1 @c -*- coding: utf-8; mode: texinfo; -*-
2 @node Interfaces for programmers
3 @chapter Interfaces for programmers
5 Advanced tweaks may be performed by using Scheme. If you are
6 not familiar with Scheme, you may wish to read our
10 * Programmer interfaces for input::
11 * Markup programmer interface::
12 * Contexts for programmers::
16 @node Programmer interfaces for input
17 @section Programmer interfaces for input
19 This section discusses how to create functions within LilyPond.
22 * Input variables and Scheme::
23 * Internal music representation::
24 * Extending music syntax::
25 * Manipulating music expressions::
26 * Displaying music expressions::
27 * Using LilyPond syntax inside Scheme::
30 @node Input variables and Scheme
31 @subsection Input variables and Scheme
34 The input format supports the notion of variables: in the following
35 example, a music expression is assigned to a variable with the name
38 traLaLa = @{ c'4 d'4 @}
43 There is also a form of scoping: in the following example, the
44 @code{\layout} block also contains a @code{traLaLa} variable, which is
45 independent of the outer @code{\traLaLa}.
47 traLaLa = @{ c'4 d'4 @}
48 \layout @{ traLaLa = 1.0 @}
51 In effect, each input file is a scope, and all @code{\header},
52 @code{\midi}, and @code{\layout} blocks are scopes nested inside that
55 Both variables and scoping are implemented in the GUILE module system.
56 An anonymous Scheme module is attached to each scope. An assignment of
59 traLaLa = @{ c'4 d'4 @}
63 is internally converted to a Scheme definition
65 (define traLaLa @var{Scheme value of ``@code{... }''})
68 This means that input variables and Scheme variables may be freely
69 mixed. In the following example, a music fragment is stored in the
70 variable @code{traLaLa}, and duplicated using Scheme. The result is
71 imported in a @code{\score} block by means of a second variable
74 traLaLa = @{ c'4 d'4 @}
76 #(define newLa (map ly:music-deep-copy
77 (list traLaLa traLaLa)))
79 (make-sequential-music newLa))
84 In the above example, music expressions can be `exported' from the
85 input to the Scheme interpreter. The opposite is also possible. By
86 wrapping a Scheme value in the function @code{ly:export}, a Scheme
87 value is interpreted as if it were entered in LilyPond syntax. Instead
88 of defining @code{\twice}, the example above could also have been
92 @{ #(ly:export (make-sequential-music (list newLa))) @}
95 Scheme code is evaluated as soon as the parser encounters it. To
96 define some scheme code in a macro (to be called later), use
100 (ly:set-option 'point-and-click #f))
110 Mixing Scheme and LilyPond identifiers is not possible with the
111 @code{--safe} option.
114 @node Internal music representation
115 @subsection Internal music representation
117 When a music expression is parsed, it is converted into a set of
118 Scheme music objects. The defining property of a music object is that
119 it takes up time. Time is a rational number that measures the length
120 of a piece of music in whole notes.
122 A music object has three kinds of types:
125 music name: Each music expression has a name. For example, a note
126 leads to a @internalsref{NoteEvent}, and @code{\simultaneous} leads to
127 a @internalsref{SimultaneousMusic}. A list of all expressions
128 available is in the Program reference manual, under
129 @internalsref{Music expressions}.
132 `type' or interface: Each music name has several `types' or
133 interfaces, for example, a note is an @code{event}, but it is also a
134 @code{note-event}, a @code{rhythmic-event}, and a
135 @code{melodic-event}. All classes of music are listed in the
136 Profram reference, under
137 @internalsref{Music classes}.
140 C++ object: Each music object is represented by a C++ object. For
141 technical reasons, different music objects may be represented by
142 different C++ object types. For example, a note is @code{Event}
143 object, while @code{\grace} creates a @code{Grace_music} object. We
144 expect that distinctions between different C++ types will disappear
148 The actual information of a music expression is stored in properties.
149 For example, a @internalsref{NoteEvent} has @code{pitch} and
150 @code{duration} properties that store the pitch and duration of that
151 note. A list of all properties available is in the internals manual,
152 under @internalsref{Music properties}.
154 A compound music expression is a music object that contains other
155 music objects in its properties. A list of objects can be stored in
156 the @code{elements} property of a music object, or a single `child'
157 music object in the @code{element} object. For example,
158 @internalsref{SequentialMusic} has its children in @code{elements},
159 and @internalsref{GraceMusic} has its single argument in
160 @code{element}. The body of a repeat is stored in the @code{element}
161 property of @internalsref{RepeatedMusic}, and the alternatives in
167 @node Extending music syntax
168 @subsection Extending music syntax
170 @c TODO: rewrite example.
171 @c The use of FUNC as example argument is rather confusing.
173 The syntax of composite music expressions, like @code{\repeat},
174 @code{\transpose}, and @code{\context} follows the general form of
177 \@code{keyword} @var{non-music-arguments} @var{music-arguments}
180 Such syntax can also be defined as user code. To do this it is
181 necessary to create a @emph{music function}. This is a specially marked
182 Scheme function. For example, the music function @code{\applyMusic} applies
183 a user-defined function to a music expression. Its syntax is
186 \applyMusic #@var{func} @var{music}
189 A music function is created with @code{ly:make-music-function},
192 (ly:make-music-function
195 @code{\applyMusic} takes a Scheme function and a Music expression as
196 arguments. This is encoded in its parameter list,
199 (list procedure? ly:music?)
202 The function itself takes another argument: an Input location
203 object. That object is used to provide error messages with file names
204 and line numbers. The definition is the second argument of
205 @code{ly:make-music-function}. The body simply calls the function
208 (lambda (where func music)
212 The above Scheme code only defines the functionality. The tag
213 @code{\applyMusic} is selected by defining
216 applyMusic = #(ly:make-music-function
217 (list procedure? ly:music?)
218 (lambda (parser location func music)
222 A @code{define-music-function} macro is introduced on top of
223 @code{ly:make-music-function} to ease the definition of music
227 applyMusic = #(define-music-function (parser location func music)
228 (procedure? ly:music?)
232 Examples of the use of @code{\applyMusic} are in the next section.
235 @file{ly/@/music@/-functions@/-init@/.ly}.
238 @node Manipulating music expressions
239 @subsection Manipulating music expressions
241 Music objects and their properties can be accessed and manipulated
242 directly through the @code{\applyMusic} mechanism.
243 The syntax for @code{\applyMusic} is
246 \applyMusic #@var{func} @var{music}
250 This means that the Scheme function @var{func} is called with
251 @var{music} as its argument. The return value of @var{func} is the
252 result of the entire expression. @var{func} may read and write music
253 properties using the functions @code{ly:music-property} and
254 @code{ly:music-set-property!}.
256 An example is a function that reverses the order of elements in
258 @lilypond[quote,verbatim,ragged-right]
259 #(define (rev-music-1 m)
260 (ly:music-set-property! m 'elements
261 (reverse (ly:music-property m 'elements)))
264 \applyMusic #rev-music-1 { c'4 d'4 }
267 The use of such a function is very limited. The effect of this
268 function is void when applied to an argument that does not have
269 multiple children. The following function application has no effect
272 \applyMusic #rev-music-1 \grace @{ c4 d4 @}
276 In this case, @code{\grace} is stored as @internalsref{GraceMusic}, which
277 has no @code{elements}, only a single @code{element}. Every generally
278 applicable function for @code{\applyMusic} must -- like music expressions
279 themselves -- be recursive.
281 The following example is such a recursive function: It first extracts
282 the @code{elements} of an expression, reverses them and puts them
283 back. Then it recurses, both on @code{elements} and @code{element}
287 #(define (reverse-music music)
288 (let* ((elements (ly:music-property music 'elements))
289 (child (ly:music-property music 'element))
290 (reversed (reverse elements)))
293 (ly:music-set-property! music 'elements reversed)
296 (if (ly:music? child) (reverse-music child))
297 (map reverse-music reversed)
302 A slightly more elaborate example is in
303 @inputfileref{input/@/test,reverse@/-music@/.ly}.
305 Some of the input syntax is also implemented as recursive music
306 functions. For example, the syntax for polyphony
312 is actually implemented as a recursive function that replaces the
313 above by the internal equivalent of
315 << \context Voice = "1" @{ \voiceOne a @}
316 \context Voice = "2" @{ \voiceTwo b @} >>
319 Other applications of @code{\applyMusic} are writing out repeats
320 automatically (@inputfileref{input/@/test,unfold@/-all@/-repeats@/.ly}),
321 saving keystrokes (@inputfileref{input/@/test,music@/-box@/.ly}) and
322 exporting LilyPond input to other formats
323 @c no @inputfileref{} here
324 (eg. @file{input/@/no@/-notation/@/to@/-xml@/.ly}).
328 @file{scm/@/music@/-functions@/.scm}, @file{scm/@/music@/-types@/.scm},
329 @inputfileref{input/@/test,add@/-staccato@/.ly},
330 @inputfileref{input/@/test,unfold@/-all@/-repeats@/.ly}, and
331 @inputfileref{input/@/test,music@/-box@/.ly}.
334 @node Displaying music expressions
335 @subsection Displaying music expressions
337 @cindex internal storage
338 @cindex @code{\displayMusic}
339 @cindex @code{\displayLilyMusic}
341 When writing a music function it is often instructive to inspect how
342 a music expression is stored internally. This can be done with the
343 music function @code{\displayMusic}
347 \displayMusic @{ c'4\f @}
364 (ly:make-duration 2 0 1 1)
366 (ly:make-pitch 0 0 0))
368 'AbsoluteDynamicEvent
373 Displaying a music expression in LilyPond notation can be
374 done using the music function @code{\displayLilyMusic}. For example,
378 \displayLilyMusic \transpose c a, @{ c e g a bes @}
389 @node Using LilyPond syntax inside Scheme
390 @subsection Using LilyPond syntax inside Scheme
392 Creating music expressions in Scheme can be tedious, as they are
393 heavily nested and the resulting Scheme code is large. For some
394 simple tasks this can be avoided by using common LilyPond syntax inside
395 Scheme, with the dedicated @code{#@{ ... #@}} syntax.
397 The following two expressions give equivalent music expressions:
399 mynotes = @{ \override Stem #'thickness = #4
402 #(define mynotes #@{ \override Stem #'thickness = #4
406 The content of @code{#@{ ... #@}} is enclosed in an implicit @code{@{
407 ... @}} block, which is parsed. The resulting music expression, a
408 @code{SequentialMusic} music object, is then returned and usable in Scheme.
410 Arbitrary Scheme forms, including variables, can be used in @code{#@{ ... #@}}
411 expressions with the @code{$} character (@code{$$} can be used to
412 produce a single @code{$} character). This makes the creation of simple
413 functions straightforward. In the following example, a function
414 setting the TextScript's padding is defined:
416 @lilypond[quote,verbatim,ragged-right]
417 #(use-modules (ice-9 optargs))
418 #(define* (textpad padding #:optional once?)
419 (ly:export ; this is necessary for using the expression
420 ; directly inside a block
422 #{ \once \override TextScript #'padding = #$padding #}
423 #{ \override TextScript #'padding = #$padding #})))
427 #(textpad 3.0 #t) % only once
436 Here, the variable @code{padding} is a number; music expression
437 variables may also be used in a similar fashion, as in the following
440 @lilypond[quote,verbatim,ragged-right]
441 #(define (with-padding padding)
443 #{ \override TextScript #'padding = #$padding
445 \revert TextScript #'padding #}))
449 \applyMusic #(with-padding 3) { c'^"2" c'^"3" }
454 The function created by @code{(with-padding 3)} adds @code{\override} and
455 @code{\revert} statements around the music given as an argument, and returns
456 this new expression. Thus, this example is equivalent to:
461 @{ \override TextScript #'padding = #3
463 \revert TextScript #'padding
469 This function may also be defined as a music function:
471 @lilypond[quote,verbatim,ragged-right]
473 #(define-music-function (parser location padding music) (number? ly:music?)
474 #{ \override TextScript #'padding = #$padding
476 \revert TextScript #'padding #})
480 \withPadding #3 { c'^"2" c'^"3"}
485 Music functions can involve Scheme programming, in
486 addition to simple substitution,
488 @lilypond[quote,verbatim,ragged-right]
489 AltOn = #(define-music-function (parser location mag) (number?)
490 #{ \override Stem #'length = #$(* 7.0 mag)
491 \override NoteHead #'font-size =
492 #$(inexact->exact (* (/ 6.0 (log 2.0)) (log mag))) #})
495 \revert Stem #'length
496 \revert NoteHead #'font-size
499 { c'2 \AltOn #0.5 c'4 c'
500 \AltOn #1.5 c' c' \AltOff c'2 }
504 This example may be rewritten
506 @lilypond[quote,verbatim,ragged-right]
507 withAlt = #(define-music-function (parser location mag music) (number? ly:music?)
508 #{ \override Stem #'length = #$(* 7.0 mag)
509 \override NoteHead #'font-size =
510 #$(inexact->exact (* (/ 6.0 (log 2.0)) (log mag)))
512 \revert Stem #'length
513 \revert NoteHead #'font-size #})
515 { c'2 \withAlt #0.5 {c'4 c'}
516 \withAlt #1.5 {c' c'} c'2 }
520 @node Markup programmer interface
521 @section Markup programmer interface
523 @c Please rewrite the second sentence; I don't understand its meaning. AS
525 Markups are implemented as special Scheme functions. When applied
526 with as arguments an output definition (@code{\layout} or
527 @code{\paper}), and a list of properties and other arguments, produce
531 * Markup construction in Scheme::
532 * How markups work internally ::
533 * New markup command definition::
537 @node Markup construction in Scheme
538 @subsection Markup construction in Scheme
540 @cindex defining markup commands
542 The @code{markup} macro builds markup expressions in Scheme while
543 providing a LilyPond-like syntax. For example,
545 (markup #:column (#:line (#:bold #:italic "hello" #:raise 0.4 "world")
546 #:bigger #:line ("foo" "bar" "baz")))
552 \markup \column @{ \line @{ \bold \italic "hello" \raise #0.4 "world" @}
553 \bigger \line @{ foo bar baz @} @}
557 This example demonstrates the main translation rules between regular
558 LilyPond markup syntax and Scheme markup syntax.
561 @multitable @columnfractions .3 .3
562 @item @b{LilyPond} @tab @b{Scheme}
563 @item @code{\markup markup1} @tab @code{(markup markup1)}
564 @item @code{\markup @{ markup1 markup2 ... @}} @tab
565 @code{(markup markup1 markup2 ... )}
566 @item @code{\command} @tab @code{#:command}
567 @item @code{\variable} @tab @code{variable}
568 @item @code{\center-align @{ ... @}} @tab @code{#:center-align ( ... )}
569 @item @code{string} @tab @code{"string"}
570 @item @code{#scheme-arg} @tab @code{scheme-arg}
574 The whole scheme language is accessible inside the
575 @code{markup} macro. For example, You may use function calls inside
576 @code{markup} in order to manipulate character strings. This is
577 useful when defining new markup commands (see
578 @ref{New markup command definition}).
582 One can not feed the @code{#:line}, @code{#:center}, or
583 @code{#:column}) commands with a variable or the result of a function
587 (markup #:line (function-that-returns-markups))
591 is invalid. One should use the @code{make-line-markup},
592 @code{make-center-markup}, or @code{make-column-markup} functions
596 (markup (make-line-markup (function-that-returns-markups)))
600 @node How markups work internally
601 @subsection How markups work internally
606 \raise #0.5 "text example"
610 @code{\raise} is actually represented by the @code{raise-markup}
611 function. The markup expression is stored as
614 (list raise-markup 0.5 (list simple-markup "text example"))
617 When the markup is converted to printable objects (Stencils), the
618 @code{raise-markup} function is called as
623 @var{list of property alists}
625 @var{the "text example" markup})
628 The @code{raise-markup} function first creates the stencil for the
629 @code{text example} string, and then it raises that Stencil by 0.5
630 staff space. This is a rather simple example; more complex examples
632 of this section, and in @file{scm/@/define@/-markup@/-commands@/.scm}.
635 @node New markup command definition
636 @subsection New markup command definition
638 New markup commands can be defined
639 with the @code{define-markup-command} scheme macro.
642 (define-markup-command (@var{command-name} @var{layout} @var{props} @var{arg1} @var{arg2} ...)
643 (@var{arg1-type?} @var{arg2-type?} ...)
651 @var{i}th command argument
653 a type predicate for the i@var{th} argument
655 the `layout' definition
657 a list of alists, containing all active properties.
660 As a simple example, we show how to add a @code{\smallcaps} command,
661 which selects a small caps font. Normally we could select the
665 \markup @{ \override #'(font-shape . caps) Text-in-caps @}
669 This selects the caps font by setting the @code{font-shape} property to
670 @code{#'caps} for interpreting @code{Text-in-caps}.
672 To make the above available as @code{\smallcaps} command, we must
673 define a function using @code{define-markup-command}. The command should
674 take a single argument of type @code{markup}. Therefore the start of the
675 definition should read
678 (define-markup-command (smallcaps layout props argument) (markup?)
683 What follows is the content of the command: we should interpret
684 the @code{argument} as a markup, i.e.,
687 (interpret-markup layout @dots{} argument)
691 This interpretation should add @code{'(font-shape . caps)} to the active
692 properties, so we substitute the following for the @dots{} in the
696 (cons (list '(font-shape . caps) ) props)
700 The variable @code{props} is a list of alists, and we prepend to it by
701 cons'ing a list with the extra setting.
704 Suppose that we are typesetting a recitative in an opera and
705 we would like to define a command that will show character names in a
706 custom manner. Names should be printed with small caps and moved a
707 bit to the left and top. We will define a @code{\character} command
708 which takes into account the necessary translation and uses the newly
709 defined @code{\smallcaps} command:
712 #(define-markup-command (character layout props name) (string?)
713 "Print the character name in small caps, translated to the left and
714 top. Syntax: \\character #\"name\""
715 (interpret-markup layout props
716 (markup #:hspace 0 #:translate (cons -3 1) #:smallcaps name)))
719 There is one complication that needs explanation: texts above and below
720 the staff are moved vertically to be at a certain distance (the
721 @code{padding} property) from the staff and the notes. To make sure
722 that this mechanism does not annihilate the vertical effect of our
723 @code{#:translate}, we add an empty string (@code{#:hspace 0}) before the
724 translated text. Now the @code{#:hspace 0} will be put above the notes,
726 @code{name} is moved in relation to that empty string. The net effect is
727 that the text is moved to the upper left.
729 The final result is as follows:
733 c''^\markup \character #"Cleopatra"
734 e'^\markup \character #"Giulio Cesare"
738 @lilypond[quote,ragged-right]
739 #(define-markup-command (smallcaps layout props str) (string?)
740 "Print the string argument in small caps. Syntax: \\smallcaps #\"string\""
741 (interpret-markup layout props
744 (if (= (string-length s) 0)
746 (markup #:large (string-upcase (substring s 0 1))
747 #:translate (cons -0.6 0)
748 #:tiny (string-upcase (substring s 1)))))
749 (string-split str #\Space)))))
751 #(define-markup-command (character layout props name) (string?)
752 "Print the character name in small caps, translated to the left and
753 top. Syntax: \\character #\"name\""
754 (interpret-markup layout props
755 (markup #:hspace 0 #:translate (cons -3 1) #:smallcaps name)))
758 c''^\markup \character #"Cleopatra" c'' c'' c''
759 e'^\markup \character #"Giulio Cesare" e' e' e'
763 We have used the @code{caps} font shape, but suppose that our font
764 does not have a small-caps variant. In that case we have to fake
765 the small caps font by setting a string in upcase with the first
766 letter a little larger:
769 #(define-markup-command (smallcaps layout props str) (string?)
770 "Print the string argument in small caps."
771 (interpret-markup layout props
774 (if (= (string-length s) 0)
776 (markup #:large (string-upcase (substring s 0 1))
777 #:translate (cons -0.6 0)
778 #:tiny (string-upcase (substring s 1)))))
779 (string-split str #\Space)))))
782 The @code{smallcaps} command first splits its string argument into
783 tokens separated by spaces (@code{(string-split str #\Space)}); for
784 each token, a markup is built with the first letter made large and
785 upcased (@code{#:large (string-upcase (substring s 0 1))}), and a
786 second markup built with the following letters made tiny and upcased
787 (@code{#:tiny (string-upcase (substring s 1))}). As LilyPond
788 introduces a space between markups on a line, the second markup is
789 translated to the left (@code{#:translate (cons -0.6 0) ...}). Then,
790 the markups built for each token are put in a line by
791 @code{(make-line-markup ...)}. Finally, the resulting markup is passed
792 to the @code{interpret-markup} function, with the @code{layout} and
793 @code{props} arguments.
795 Note: there is now an internal command @code{\smallCaps} which can
796 be used to set text in small caps. See
797 @ref{Overview of text markup commands} for details.
801 @node Contexts for programmers
802 @section Contexts for programmers
806 * Context evaluation::
807 * Running a function on all layout objects::
810 @node Context evaluation
811 @subsection Context evaluation
813 @cindex calling code during interpreting
814 @cindex @code{\applyContext}
816 Contexts can be modified during interpretation with Scheme code. The
819 \applyContext @var{function}
822 @var{function} should be a Scheme function taking a single argument,
823 being the context to apply it to. The following code will print the
824 current bar number on the standard output during the compile:
829 (format #t "\nWe were called in barnumber ~a.\n"
830 (ly:context-property x 'currentBarNumber)))
835 @node Running a function on all layout objects
836 @subsection Running a function on all layout objects
839 @cindex calling code on layout objects
840 @cindex @code{\applyOutput}
843 The most versatile way of tuning an object is @code{\applyOutput}. Its
846 \applyOutput @var{proc}
850 where @var{proc} is a Scheme function, taking three arguments.
852 When interpreted, the function @var{proc} is called for every layout
853 object found in the context, with the following arguments:
855 @item the layout object itself,
856 @item the context where the layout object was created, and
857 @item the context where @code{\applyOutput} is processed.
861 In addition, the cause of the layout object, i.e., the music
862 expression or object that was responsible for creating it, is in the
863 object property @code{cause}. For example, for a note head, this is a
864 @internalsref{NoteHead} event, and for a @internalsref{Stem} object,
865 this is a @internalsref{NoteHead} object.
867 Here is a function to use for @code{\applyOutput}; it blanks
868 note-heads on the center-line:
871 (define (blanker grob grob-origin context)
872 (if (and (memq (ly:grob-property grob 'interfaces)
874 (eq? (ly:grob-property grob 'staff-position) 0))
875 (set! (ly:grob-property grob 'transparent) #t)))