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 @}
388 By default, LilyPond will print these messages to the console along
389 with all the other messages. To split up these messages and save
390 the results of @code{\display@{STUFF@}}, redirect the output to
394 lilypond file.ly >display.txt
398 @node Using LilyPond syntax inside Scheme
399 @subsection Using LilyPond syntax inside Scheme
401 Creating music expressions in Scheme can be tedious, as they are
402 heavily nested and the resulting Scheme code is large. For some
403 simple tasks this can be avoided by using common LilyPond syntax inside
404 Scheme, with the dedicated @code{#@{ ... #@}} syntax.
406 The following two expressions give equivalent music expressions:
408 mynotes = @{ \override Stem #'thickness = #4
411 #(define mynotes #@{ \override Stem #'thickness = #4
415 The content of @code{#@{ ... #@}} is enclosed in an implicit @code{@{
416 ... @}} block, which is parsed. The resulting music expression, a
417 @code{SequentialMusic} music object, is then returned and usable in Scheme.
419 Arbitrary Scheme forms, including variables, can be used in @code{#@{ ... #@}}
420 expressions with the @code{$} character (@code{$$} can be used to
421 produce a single @code{$} character). This makes the creation of simple
422 functions straightforward. In the following example, a function
423 setting the TextScript's padding is defined:
425 @lilypond[quote,verbatim,ragged-right]
426 #(use-modules (ice-9 optargs))
427 #(define* (textpad padding #:optional once?)
428 (ly:export ; this is necessary for using the expression
429 ; directly inside a block
431 #{ \once \override TextScript #'padding = #$padding #}
432 #{ \override TextScript #'padding = #$padding #})))
436 #(textpad 3.0 #t) % only once
445 Here, the variable @code{padding} is a number; music expression
446 variables may also be used in a similar fashion, as in the following
449 @lilypond[quote,verbatim,ragged-right]
450 #(define (with-padding padding)
452 #{ \override TextScript #'padding = #$padding
454 \revert TextScript #'padding #}))
458 \applyMusic #(with-padding 3) { c'^"2" c'^"3" }
463 The function created by @code{(with-padding 3)} adds @code{\override} and
464 @code{\revert} statements around the music given as an argument, and returns
465 this new expression. Thus, this example is equivalent to:
470 @{ \override TextScript #'padding = #3
472 \revert TextScript #'padding
478 This function may also be defined as a music function:
480 @lilypond[quote,verbatim,ragged-right]
482 #(define-music-function (parser location padding music) (number? ly:music?)
483 #{ \override TextScript #'padding = #$padding
485 \revert TextScript #'padding #})
489 \withPadding #3 { c'^"2" c'^"3"}
494 Music functions can involve Scheme programming, in
495 addition to simple substitution,
497 @lilypond[quote,verbatim,ragged-right]
498 AltOn = #(define-music-function (parser location mag) (number?)
499 #{ \override Stem #'length = #$(* 7.0 mag)
500 \override NoteHead #'font-size =
501 #$(inexact->exact (* (/ 6.0 (log 2.0)) (log mag))) #})
504 \revert Stem #'length
505 \revert NoteHead #'font-size
508 { c'2 \AltOn #0.5 c'4 c'
509 \AltOn #1.5 c' c' \AltOff c'2 }
513 This example may be rewritten
515 @lilypond[quote,verbatim,ragged-right]
516 withAlt = #(define-music-function (parser location mag music) (number? ly:music?)
517 #{ \override Stem #'length = #$(* 7.0 mag)
518 \override NoteHead #'font-size =
519 #$(inexact->exact (* (/ 6.0 (log 2.0)) (log mag)))
521 \revert Stem #'length
522 \revert NoteHead #'font-size #})
524 { c'2 \withAlt #0.5 {c'4 c'}
525 \withAlt #1.5 {c' c'} c'2 }
529 @node Markup programmer interface
530 @section Markup programmer interface
532 Markups are implemented as special Scheme functions which produce a
533 Stencil object given a number of arguments.
536 * Markup construction in Scheme::
537 * How markups work internally ::
538 * New markup command definition::
542 @node Markup construction in Scheme
543 @subsection Markup construction in Scheme
545 @cindex defining markup commands
547 The @code{markup} macro builds markup expressions in Scheme while
548 providing a LilyPond-like syntax. For example,
550 (markup #:column (#:line (#:bold #:italic "hello" #:raise 0.4 "world")
551 #:bigger #:line ("foo" "bar" "baz")))
557 \markup \column @{ \line @{ \bold \italic "hello" \raise #0.4 "world" @}
558 \bigger \line @{ foo bar baz @} @}
562 This example demonstrates the main translation rules between regular
563 LilyPond markup syntax and Scheme markup syntax.
566 @multitable @columnfractions .3 .3
567 @item @b{LilyPond} @tab @b{Scheme}
568 @item @code{\markup markup1} @tab @code{(markup markup1)}
569 @item @code{\markup @{ markup1 markup2 ... @}} @tab
570 @code{(markup markup1 markup2 ... )}
571 @item @code{\command} @tab @code{#:command}
572 @item @code{\variable} @tab @code{variable}
573 @item @code{\center-align @{ ... @}} @tab @code{#:center-align ( ... )}
574 @item @code{string} @tab @code{"string"}
575 @item @code{#scheme-arg} @tab @code{scheme-arg}
579 The whole scheme language is accessible inside the
580 @code{markup} macro. For example, You may use function calls inside
581 @code{markup} in order to manipulate character strings. This is
582 useful when defining new markup commands (see
583 @ref{New markup command definition}).
587 One can not feed the @code{#:line}, @code{#:center}, or
588 @code{#:column}) commands with a variable or the result of a function
592 (markup #:line (function-that-returns-markups))
596 is invalid. One should use the @code{make-line-markup},
597 @code{make-center-markup}, or @code{make-column-markup} functions
601 (markup (make-line-markup (function-that-returns-markups)))
605 @node How markups work internally
606 @subsection How markups work internally
611 \raise #0.5 "text example"
615 @code{\raise} is actually represented by the @code{raise-markup}
616 function. The markup expression is stored as
619 (list raise-markup 0.5 (list simple-markup "text example"))
622 When the markup is converted to printable objects (Stencils), the
623 @code{raise-markup} function is called as
628 @var{list of property alists}
630 @var{the "text example" markup})
633 The @code{raise-markup} function first creates the stencil for the
634 @code{text example} string, and then it raises that Stencil by 0.5
635 staff space. This is a rather simple example; more complex examples
637 of this section, and in @file{scm/@/define@/-markup@/-commands@/.scm}.
640 @node New markup command definition
641 @subsection New markup command definition
643 New markup commands can be defined
644 with the @code{define-markup-command} scheme macro.
647 (define-markup-command (@var{command-name} @var{layout} @var{props} @var{arg1} @var{arg2} ...)
648 (@var{arg1-type?} @var{arg2-type?} ...)
656 @var{i}th command argument
658 a type predicate for the i@var{th} argument
660 the `layout' definition
662 a list of alists, containing all active properties.
665 As a simple example, we show how to add a @code{\smallcaps} command,
666 which selects a small caps font. Normally we could select the
670 \markup @{ \override #'(font-shape . caps) Text-in-caps @}
674 This selects the caps font by setting the @code{font-shape} property to
675 @code{#'caps} for interpreting @code{Text-in-caps}.
677 To make the above available as @code{\smallcaps} command, we must
678 define a function using @code{define-markup-command}. The command should
679 take a single argument of type @code{markup}. Therefore the start of the
680 definition should read
683 (define-markup-command (smallcaps layout props argument) (markup?)
688 What follows is the content of the command: we should interpret
689 the @code{argument} as a markup, i.e.,
692 (interpret-markup layout @dots{} argument)
696 This interpretation should add @code{'(font-shape . caps)} to the active
697 properties, so we substitute the following for the @dots{} in the
701 (cons (list '(font-shape . caps) ) props)
705 The variable @code{props} is a list of alists, and we prepend to it by
706 cons'ing a list with the extra setting.
709 Suppose that we are typesetting a recitative in an opera and
710 we would like to define a command that will show character names in a
711 custom manner. Names should be printed with small caps and moved a
712 bit to the left and top. We will define a @code{\character} command
713 which takes into account the necessary translation and uses the newly
714 defined @code{\smallcaps} command:
717 #(define-markup-command (character layout props name) (string?)
718 "Print the character name in small caps, translated to the left and
719 top. Syntax: \\character #\"name\""
720 (interpret-markup layout props
721 (markup #:hspace 0 #:translate (cons -3 1) #:smallcaps name)))
724 There is one complication that needs explanation: texts above and below
725 the staff are moved vertically to be at a certain distance (the
726 @code{padding} property) from the staff and the notes. To make sure
727 that this mechanism does not annihilate the vertical effect of our
728 @code{#:translate}, we add an empty string (@code{#:hspace 0}) before the
729 translated text. Now the @code{#:hspace 0} will be put above the notes,
731 @code{name} is moved in relation to that empty string. The net effect is
732 that the text is moved to the upper left.
734 The final result is as follows:
738 c''^\markup \character #"Cleopatra"
739 e'^\markup \character #"Giulio Cesare"
743 @lilypond[quote,ragged-right]
744 #(define-markup-command (smallcaps layout props str) (string?)
745 "Print the string argument in small caps. Syntax: \\smallcaps #\"string\""
746 (interpret-markup layout props
749 (if (= (string-length s) 0)
751 (markup #:large (string-upcase (substring s 0 1))
752 #:translate (cons -0.6 0)
753 #:tiny (string-upcase (substring s 1)))))
754 (string-split str #\Space)))))
756 #(define-markup-command (character layout props name) (string?)
757 "Print the character name in small caps, translated to the left and
758 top. Syntax: \\character #\"name\""
759 (interpret-markup layout props
760 (markup #:hspace 0 #:translate (cons -3 1) #:smallcaps name)))
763 c''^\markup \character #"Cleopatra" c'' c'' c''
764 e'^\markup \character #"Giulio Cesare" e' e' e'
768 We have used the @code{caps} font shape, but suppose that our font
769 does not have a small-caps variant. In that case we have to fake
770 the small caps font by setting a string in upcase with the first
771 letter a little larger:
774 #(define-markup-command (smallcaps layout props str) (string?)
775 "Print the string argument in small caps."
776 (interpret-markup layout props
779 (if (= (string-length s) 0)
781 (markup #:large (string-upcase (substring s 0 1))
782 #:translate (cons -0.6 0)
783 #:tiny (string-upcase (substring s 1)))))
784 (string-split str #\Space)))))
787 The @code{smallcaps} command first splits its string argument into
788 tokens separated by spaces (@code{(string-split str #\Space)}); for
789 each token, a markup is built with the first letter made large and
790 upcased (@code{#:large (string-upcase (substring s 0 1))}), and a
791 second markup built with the following letters made tiny and upcased
792 (@code{#:tiny (string-upcase (substring s 1))}). As LilyPond
793 introduces a space between markups on a line, the second markup is
794 translated to the left (@code{#:translate (cons -0.6 0) ...}). Then,
795 the markups built for each token are put in a line by
796 @code{(make-line-markup ...)}. Finally, the resulting markup is passed
797 to the @code{interpret-markup} function, with the @code{layout} and
798 @code{props} arguments.
800 Note: there is now an internal command @code{\smallCaps} which can
801 be used to set text in small caps. See
802 @ref{Overview of text markup commands} for details.
806 @node Contexts for programmers
807 @section Contexts for programmers
811 * Context evaluation::
812 * Running a function on all layout objects::
815 @node Context evaluation
816 @subsection Context evaluation
818 @cindex calling code during interpreting
819 @cindex @code{\applyContext}
821 Contexts can be modified during interpretation with Scheme code. The
824 \applyContext @var{function}
827 @var{function} should be a Scheme function taking a single argument,
828 being the context to apply it to. The following code will print the
829 current bar number on the standard output during the compile:
834 (format #t "\nWe were called in barnumber ~a.\n"
835 (ly:context-property x 'currentBarNumber)))
840 @node Running a function on all layout objects
841 @subsection Running a function on all layout objects
844 @cindex calling code on layout objects
845 @cindex @code{\applyOutput}
848 The most versatile way of tuning an object is @code{\applyOutput}. Its
851 \applyOutput @var{proc}
855 where @var{proc} is a Scheme function, taking three arguments.
857 When interpreted, the function @var{proc} is called for every layout
858 object found in the context, with the following arguments:
860 @item the layout object itself,
861 @item the context where the layout object was created, and
862 @item the context where @code{\applyOutput} is processed.
866 In addition, the cause of the layout object, i.e., the music
867 expression or object that was responsible for creating it, is in the
868 object property @code{cause}. For example, for a note head, this is a
869 @internalsref{NoteHead} event, and for a @internalsref{Stem} object,
870 this is a @internalsref{NoteHead} object.
872 Here is a function to use for @code{\applyOutput}; it blanks
873 note-heads on the center-line:
876 (define (blanker grob grob-origin context)
877 (if (and (memq (ly:grob-property grob 'interfaces)
879 (eq? (ly:grob-property grob 'staff-position) 0))
880 (set! (ly:grob-property grob 'transparent) #t)))