Previous: Displaying music expressions, Up: Programmer interfaces for input


11.1.6 Using LilyPond syntax inside Scheme

Creating music expressions in Scheme can be tedious, as they are heavily nested and the resulting Scheme code is large. For some simple tasks, this can be avoided, using common LilyPond syntax inside Scheme, with the dedicated #{ ... #} syntax.

The following two expressions give equivalent music expressions:

mynotes = { \override Stem #'thickness = #4
            { c'8 d' } }

#(define mynotes #{ \override Stem #'thickness = #4
                    { c'8 d' } #})

The content of #{ ... #} is enclosed in an implicit { ... } block, which is parsed. The resulting music expression, a SequentialMusic music object, is then returned and usable in Scheme.

Arbitrary Scheme forms, including variables, can be used in #{ ... #} expressions with the $ character ($$ can be used to produce a single $ character). This makes the creation of simple functions straightforward. In the following example, a function setting the TextScript's padding is defined:

     
     #(use-modules (ice-9 optargs))
     #(define* (textpad padding #:optional once?)
       (ly:export   ; this is necessary for using the expression
                    ; directly inside a block
         (if once?
             #{ \once \override TextScript #'padding = #$padding #}
             #{ \override TextScript #'padding = #$padding #})))
     
      {
        c'^"1"
        #(textpad 3.0 #t) % only once
        c'^"2"
        c'^"3"
        #(textpad 5.0)
        c'^"4"
        c'^"5"
      }

[image of music]

Here, the variable padding is a number; music expression variables may also be used in a similar fashion, as in the following example:

     
     #(define (with-padding padding)
       (lambda (music)
        #{ \override TextScript #'padding = #$padding
           $music
           \revert TextScript #'padding #}))
     
     {
       c'^"1"
       \applyMusic #(with-padding 3) { c'^"2" c'^"3" }
       c'^"4"
     }

[image of music]

The function created by (with-padding 3) adds \override and \revert statements around the music given as an argument, and returns this new expression. Thus, this example is equivalent to:

{
  c'^"1"
  { \override TextScript #'padding = #3
    { c'^"2" c'^"3"}
    \revert TextScript #'padding
  }
  c'^"4"
}

This function may also be defined as a music function:

     
     withPadding =
       #(define-music-function (parser location padding music) (number? ly:music?)
         #{ \override TextScript #'padding = #$padding
            $music 
            \revert TextScript #'padding #})
     
     {
       c'^"1"
       \withPadding #3 { c'^"2" c'^"3"}
       c'^"4"
     }

[image of music]

This page is for LilyPond-2.8.8 (stable-branch).

Report errors to http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs.

Other languages: English.
Using automatic language selection.