4.7.5 Advanced tweaks with Scheme

Although many things are possible with the \override and \tweak commands, an even more powerful way of modifying the action of LilyPond is available through a programmable interface to the LilyPond internal operation. Code written in the Scheme programming language can be incorporated directly in the internal operation of LilyPond. Of course, at least a basic knowledge of programming in Scheme is required to do this, and an introduction is provided in the Scheme tutorial.

As an illustration of one of the many possibilities, instead of setting a property to a constant it can be set to a Scheme procedure which is then called whenever that property is accessed by LilyPond. The property can then be set dynamically to a value determined by the procedure at the time it is called. In this example we color the note head in accordance with its position on the staff.

#(define (color-notehead grob)
   "Color the notehead according to its position on the staff."
   (let ((mod-position (modulo (ly:grob-property grob 'staff-position)
     (case mod-position
       ;;   Return rainbow colors
       ((1) (x11-color 'red    ))  ; for C
       ((2) (x11-color 'orange ))  ; for D
       ((3) (x11-color 'yellow ))  ; for E
       ((4) (x11-color 'green  ))  ; for F
       ((5) (x11-color 'blue   ))  ; for G
       ((6) (x11-color 'purple ))  ; for A
       ((0) (x11-color 'violet ))  ; for B

\relative {
  % Arrange to obtain color from color-notehead procedure
  \override NoteHead.color = #color-notehead
  a2 b | c2 d | e2 f | g2 a |

[image of music]

Further examples showing the use of these programmable interfaces can be found in Callback functions.

LilyPond — Learning Manual v2.22.1 (stable-branch).