]> git.donarmstrong.com Git - lilypond.git/blob - Documentation/notation/programming-interface.itely
Docs: reorganize documentation directory structure
[lilypond.git] / Documentation / notation / programming-interface.itely
1 @c -*- coding: utf-8; mode: texinfo; -*-
2
3 @ignore
4     Translation of GIT committish: FILL-IN-HEAD-COMMITTISH
5
6     When revising a translation, copy the HEAD committish of the
7     version that you are working on.  See TRANSLATION for details.
8 @end ignore
9
10 @c \version "2.12.0"
11
12 @node Interfaces for programmers
13 @chapter Interfaces for programmers
14
15 Advanced tweaks may be performed by using Scheme.  If you are
16 not familiar with Scheme, you may wish to read our
17 @rlearning{Scheme tutorial}.
18
19 @menu
20 * Music functions::
21 * Programmer interfaces::
22 * Building complicated functions::
23 * Markup programmer interface::
24 * Contexts for programmers::
25 * Scheme procedures as properties::
26 * Using Scheme code instead of \tweak::
27 * Difficult tweaks::
28 @end menu
29
30
31 @node Music functions
32 @section Music functions
33
34 This section discusses how to create music functions within LilyPond.
35
36 @menu
37 * Overview of music functions::
38 * Simple substitution functions::
39 * Paired substitution functions::
40 * Mathematics in functions::
41 * Void functions::
42 * Functions without arguments::
43 * Overview of available music functions::
44 @end menu
45
46 @node Overview of music functions
47 @subsection Overview of music functions
48
49 Making a function which substitutes a variable into LilyPond
50 code is easy.  The general form of these functions is
51
52 @example
53 function =
54 #(define-music-function (parser location @var{var1} @var{var2}...@var{vari}... )
55                         (@var{var1-type?} @var{var2-type?}...@var{vari-type?}...)
56   #@{
57     @emph{...music...}
58   #@})
59 @end example
60
61 @noindent
62 where
63
64 @multitable @columnfractions .33 .66
65 @item @var{vari}         @tab @var{i}th variable
66 @item @var{vari-type?}   @tab type of @var{i}th variable
67 @item @var{...music...}  @tab normal LilyPond input, using
68  variables as @code{#$var1}, etc.
69 @end multitable
70
71 There following input types may be used as variables
72 in a music function.  This list is not exhaustive; see
73 other documentation specifically about Scheme for more
74 variable types.
75
76 @multitable @columnfractions .33 .66
77 @headitem Input type          @tab @var{vari-type?} notation
78 @item Integer                 @tab @code{integer?}
79 @item Float (decimal number)  @tab @code{number?}
80 @item Text string             @tab @code{string?}
81 @item Markup                  @tab @code{markup?}
82 @item Music expression        @tab @code{ly:music?}
83 @item A pair of variables     @tab @code{pair?}
84 @end multitable
85
86 The @code{parser} and @code{location} arguments are mandatory,
87 and are used in some advanced situations.  The @code{parser}
88 argument is used to gain access to the value of another LilyPond
89 variable.  The @code{location} argument
90 is used to set the @q{origin} of the music expression that is built
91 by the music function, so that in case of a syntax error LilyPond
92 can tell the user an appropriate place to look in the input file.
93
94
95 @node Simple substitution functions
96 @subsection Simple substitution functions
97
98 Here is a simple example,
99
100 @lilypond[quote,verbatim,ragged-right]
101 padText = #(define-music-function (parser location padding) (number?)
102   #{
103     \once \override TextScript #'padding = #$padding
104   #})
105
106 \relative c''' {
107   c4^"piu mosso" b a b
108   \padText #1.8
109   c4^"piu mosso" d e f
110   \padText #2.6
111   c4^"piu mosso" fis a g
112 }
113 @end lilypond
114
115 Music expressions may be substituted as well,
116
117 @lilypond[quote,verbatim,ragged-right]
118 custosNote = #(define-music-function (parser location note)
119                                      (ly:music?)
120   #{
121     \once \override Voice.NoteHead #'stencil =
122       #ly:text-interface::print
123     \once \override Voice.NoteHead #'text =
124       \markup \musicglyph #"custodes.mensural.u0"
125     \once \override Voice.Stem #'stencil = ##f
126     $note
127   #})
128
129 { c' d' e' f' \custosNote g' }
130 @end lilypond
131
132 Multiple variables may be used,
133
134 @lilypond[quote,verbatim,ragged-right]
135 tempoPadded = #(define-music-function (parser location padding tempotext)
136   (number? string?)
137 #{
138   \once \override Score.MetronomeMark #'padding = $padding
139   \tempo \markup { \bold $tempotext }
140 #})
141
142 \relative c'' {
143   \tempo \markup { "Low tempo" }
144   c4 d e f g1
145   \tempoPadded #4.0 #"High tempo"
146   g4 f e d c1
147 }
148 @end lilypond
149
150
151 @node Paired substitution functions
152 @subsection Paired substitution functions
153
154 Some @code{\override} commands require a pair of numbers
155 (called a @code{cons cell} in Scheme).  To pass these numbers
156 into a function, either use a @code{pair?} variable, or
157 insert the @code{cons} into the music function.
158
159 @quotation
160 @example
161 manualBeam =
162 #(define-music-function (parser location beg-end)
163                         (pair?)
164 #@{
165   \once \override Beam #'positions = #$beg-end
166 #@})
167
168 \relative @{
169   \manualBeam #'(3 . 6) c8 d e f
170 @}
171 @end example
172 @end quotation
173
174 @noindent
175 or
176
177 @lilypond[quote,verbatim,ragged-right]
178 manualBeam =
179 #(define-music-function (parser location beg end)
180                         (number? number?)
181 #{
182   \once \override Beam #'positions = #(cons $beg $end)
183 #})
184
185 \relative {
186   \manualBeam #3 #6 c8 d e f
187 }
188 @end lilypond
189
190
191 @node Mathematics in functions
192 @subsection Mathematics in functions
193
194 Music functions can involve Scheme programming in
195 addition to simple substitution,
196
197 @lilypond[quote,verbatim,ragged-right]
198 AltOn = #(define-music-function (parser location mag) (number?)
199   #{ \override Stem #'length = #$(* 7.0 mag)
200      \override NoteHead #'font-size =
201        #$(inexact->exact (* (/ 6.0 (log 2.0)) (log mag))) #})
202
203 AltOff = {
204   \revert Stem #'length
205   \revert NoteHead #'font-size
206 }
207
208 { c'2 \AltOn #0.5 c'4 c'
209   \AltOn #1.5 c' c' \AltOff c'2 }
210 @end lilypond
211
212 @noindent
213 This example may be rewritten to pass in music expressions,
214
215 @lilypond[quote,verbatim,ragged-right]
216 withAlt = #(define-music-function (parser location mag music) (number? ly:music?)
217   #{ \override Stem #'length = #$(* 7.0 mag)
218      \override NoteHead #'font-size =
219        #$(inexact->exact (* (/ 6.0 (log 2.0)) (log mag)))
220      $music
221      \revert Stem #'length
222      \revert NoteHead #'font-size #})
223
224 { c'2 \withAlt #0.5 {c'4 c'}
225   \withAlt #1.5 {c' c'} c'2 }
226 @end lilypond
227
228 @node Void functions
229 @subsection Void functions
230
231 A music function must return a music expression, but sometimes we
232 may want to have a function which does not involve music (such as
233 turning off Point and Click).  To do this, we return a @code{void}
234 music expression.
235
236 That is why the form
237 that is returned is the @code{(make-music ...)}.  With the
238 @code{'void} property set to @code{#t}, the parser is told to
239 actually disregard this returned music
240 expression.  Thus the important part of the void music function is the
241 processing done by the function, not the music expression that is
242 returned.
243
244 @example
245 noPointAndClick =
246 #(define-music-function (parser location) ()
247    (ly:set-option 'point-and-click #f)
248    (make-music 'SequentialMusic 'void #t))
249 ...
250 \noPointAndClick   % disable point and click
251 @end example
252
253
254 @node Functions without arguments
255 @subsection Functions without arguments
256
257 In most cases a function without arguments should be written
258 with an variable,
259
260 @example
261 dolce = \markup@{ \italic \bold dolce @}
262 @end example
263
264 However, in rare cases it may be useful to create a music function
265 without arguments,
266
267 @example
268 displayBarNum =
269 #(define-music-function (parser location) ()
270    (if (eq? #t (ly:get-option 'display-bar-numbers))
271        #@{ \once \override Score.BarNumber #'break-visibility = ##f #@}
272        #@{#@}))
273 @end example
274
275 To actually display bar numbers where this function is called,
276 invoke @command{lilypond} with
277
278 @example
279 lilypond -d display-bar-numbers FILENAME.ly
280 @end example
281
282
283 @node Overview of available music functions
284 @subsection Overview of available music functions
285
286 @c fixme ; this should be move somewhere else?
287 The following commands are music functions
288
289 @include identifiers.tely
290
291
292
293 @node Programmer interfaces
294 @section Programmer interfaces
295
296 This section contains information about mixing LilyPond
297 and Scheme.
298
299 @menu
300 * Input variables and Scheme::
301 * Internal music representation::
302 @end menu
303
304
305 @node Input variables and Scheme
306 @subsection Input variables and Scheme
307
308 The input format supports the notion of variables: in the following
309 example, a music expression is assigned to a variable with the name
310 @code{traLaLa}.
311
312 @example
313 traLaLa = @{ c'4 d'4 @}
314 @end example
315
316 @noindent
317
318 There is also a form of scoping: in the following example, the
319 @code{\layout} block also contains a @code{traLaLa} variable, which is
320 independent of the outer @code{\traLaLa}.
321 @example
322 traLaLa = @{ c'4 d'4 @}
323 \layout @{ traLaLa = 1.0 @}
324 @end example
325 @c
326 In effect, each input file is a scope, and all @code{\header},
327 @code{\midi}, and @code{\layout} blocks are scopes nested inside that
328 toplevel scope.
329
330 Both variables and scoping are implemented in the GUILE module system.
331 An anonymous Scheme module is attached to each scope.  An assignment of
332 the form
333 @example
334 traLaLa = @{ c'4 d'4 @}
335 @end example
336
337 @noindent
338 is internally converted to a Scheme definition
339 @example
340 (define traLaLa @var{Scheme value of `@code{... }'})
341 @end example
342
343 This means that input variables and Scheme variables may be freely
344 mixed.  In the following example, a music fragment is stored in the
345 variable @code{traLaLa}, and duplicated using Scheme.  The result is
346 imported in a @code{\score} block by means of a second variable
347 @code{twice}:
348
349 @lilypond[verbatim]
350 traLaLa = { c'4 d'4 }
351
352 %% dummy action to deal with parser lookahead
353 #(display "this needs to be here, sorry!")
354
355 #(define newLa (map ly:music-deep-copy
356   (list traLaLa traLaLa)))
357 #(define twice
358   (make-sequential-music newLa))
359
360 { \twice }
361 @end lilypond
362
363 @c Due to parser lookahead
364
365 In this example, the assignment happens after parser has verified that
366 nothing interesting happens after @code{traLaLa = @{ ... @}}.  Without
367 the dummy statement in the above example, the @code{newLa} definition
368 is executed before @code{traLaLa} is defined, leading to a syntax
369 error.
370
371 The above example shows how to @q{export} music expressions from the
372 input to the Scheme interpreter.  The opposite is also possible.  By
373 wrapping a Scheme value in the function @code{ly:export}, a Scheme
374 value is interpreted as if it were entered in LilyPond syntax.
375 Instead of defining @code{\twice}, the example above could also have
376 been written as
377
378 @example
379 ...
380 @{ #(ly:export (make-sequential-music (list newLa))) @}
381 @end example
382
383 Scheme code is evaluated as soon as the parser encounters it.  To
384 define some Scheme code in a macro (to be called later), use
385 @ref{Void functions}, or
386
387 @example
388 #(define (nopc)
389   (ly:set-option 'point-and-click #f))
390
391 ...
392 #(nopc)
393 @{ c'4 @}
394 @end example
395
396
397 @knownissues
398
399 Mixing Scheme and LilyPond variables is not possible with the
400 @code{--safe} option.
401
402
403 @node Internal music representation
404 @subsection Internal music representation
405
406 When a music expression is parsed, it is converted into a set of
407 Scheme music objects.  The defining property of a music object is that
408 it takes up time.  Time is a rational number that measures the length
409 of a piece of music in whole notes.
410
411 A music object has three kinds of types:
412 @itemize
413 @item
414 music name: Each music expression has a name.  For example, a note
415 leads to a @rinternals{NoteEvent}, and @code{\simultaneous} leads to
416 a @rinternals{SimultaneousMusic}.  A list of all expressions
417 available is in the Internals Reference manual, under
418 @rinternals{Music expressions}.
419
420 @item
421 @q{type} or interface: Each music name has several @q{types} or
422 interfaces, for example, a note is an @code{event}, but it is also a
423 @code{note-event}, a @code{rhythmic-event}, and a
424 @code{melodic-event}.  All classes of music are listed in the
425 Internals Reference, under
426 @rinternals{Music classes}.
427
428 @item
429 C++ object: Each music object is represented by an object of the C++
430 class @code{Music}.
431 @end itemize
432
433 The actual information of a music expression is stored in properties.
434 For example, a @rinternals{NoteEvent} has @code{pitch} and
435 @code{duration} properties that store the pitch and duration of that
436 note.  A list of all properties available is in the internals manual,
437 under @rinternals{Music properties}.
438
439 A compound music expression is a music object that contains other
440 music objects in its properties.  A list of objects can be stored in
441 the @code{elements} property of a music object, or a single @q{child}
442 music object in the @code{element} property.  For example,
443 @rinternals{SequentialMusic} has its children in @code{elements},
444 and @rinternals{GraceMusic} has its single argument in
445 @code{element}.  The body of a repeat is stored in the @code{element}
446 property of @rinternals{RepeatedMusic}, and the alternatives in
447 @code{elements}.
448
449
450
451 @node Building complicated functions
452 @section Building complicated functions
453
454 This section explains how to gather the information necessary
455 to create complicated music functions.
456
457 @menu
458 * Displaying music expressions::
459 * Music properties::
460 * Doubling a note with slurs (example)::
461 * Adding articulation to notes (example)::
462 @end menu
463
464
465 @node Displaying music expressions
466 @subsection Displaying music expressions
467
468 @cindex internal storage
469 @cindex displaying music expressions
470 @cindex internal representation, displaying
471 @cindex displayMusic
472 @funindex \displayMusic
473
474 When writing a music function it is often instructive to inspect how
475 a music expression is stored internally.  This can be done with the
476 music function @code{\displayMusic}
477
478 @example
479 @{
480   \displayMusic @{ c'4\f @}
481 @}
482 @end example
483
484 @noindent
485 will display
486
487 @example
488 (make-music
489   'SequentialMusic
490   'elements
491   (list (make-music
492           'EventChord
493           'elements
494           (list (make-music
495                   'NoteEvent
496                   'duration
497                   (ly:make-duration 2 0 1 1)
498                   'pitch
499                   (ly:make-pitch 0 0 0))
500                 (make-music
501                   'AbsoluteDynamicEvent
502                   'text
503                   "f")))))
504 @end example
505
506 By default, LilyPond will print these messages to the console along
507 with all the other messages.  To split up these messages and save
508 the results of @code{\display@{STUFF@}}, redirect the output to
509 a file.
510
511 @example
512 lilypond file.ly >display.txt
513 @end example
514
515 With a bit of reformatting, the above information is
516 easier to read,
517
518 @example
519 (make-music 'SequentialMusic
520   'elements (list (make-music 'EventChord
521                     'elements (list (make-music 'NoteEvent
522                                       'duration (ly:make-duration 2 0 1 1)
523                                       'pitch (ly:make-pitch 0 0 0))
524                                     (make-music 'AbsoluteDynamicEvent
525                                       'text "f")))))
526 @end example
527
528 A @code{@{ ... @}} music sequence has the name @code{SequentialMusic},
529 and its inner expressions are stored as a list in its @code{'elements}
530 property.  A note is represented as an @code{EventChord} expression,
531 containing a @code{NoteEvent} object (storing the duration and
532 pitch properties) and any extra information (in this case, an
533 @code{AbsoluteDynamicEvent} with a @code{"f"} text property.
534
535
536 @node Music properties
537 @subsection Music properties
538
539 The @code{NoteEvent} object is the first object of the
540 @code{'elements} property of @code{someNote}.
541
542 @example
543 someNote = c'
544 \displayMusic \someNote
545 ===>
546 (make-music
547   'EventChord
548   'elements
549   (list (make-music
550           'NoteEvent
551           'duration
552           (ly:make-duration 2 0 1 1)
553           'pitch
554           (ly:make-pitch 0 0 0))))
555 @end example
556
557 The @code{display-scheme-music} function is the function used by
558 @code{\displayMusic} to display the Scheme representation of a music
559 expression.
560
561 @example
562 #(display-scheme-music (first (ly:music-property someNote 'elements)))
563 ===>
564 (make-music
565   'NoteEvent
566   'duration
567   (ly:make-duration 2 0 1 1)
568   'pitch
569   (ly:make-pitch 0 0 0))
570 @end example
571
572 Then the note pitch is accessed through the @code{'pitch} property
573 of the @code{NoteEvent} object,
574
575 @example
576 #(display-scheme-music
577    (ly:music-property (first (ly:music-property someNote 'elements))
578                       'pitch))
579 ===>
580 (ly:make-pitch 0 0 0)
581 @end example
582
583 The note pitch can be changed by setting this 'pitch property,
584
585 @funindex \displayLilyMusic
586
587 @example
588 #(set! (ly:music-property (first (ly:music-property someNote 'elements))
589                           'pitch)
590        (ly:make-pitch 0 1 0)) ;; set the pitch to d'.
591 \displayLilyMusic \someNote
592 ===>
593 d'
594 @end example
595
596
597 @node Doubling a note with slurs (example)
598 @subsection Doubling a note with slurs (example)
599
600 Suppose we want to create a function which translates
601 input like @code{a} into @code{a( a)}.  We begin
602 by examining the internal representation of the music
603 we want to end up with.
604
605 @example
606 \displayMusic@{ a'( a') @}
607 ===>
608 (make-music
609   'SequentialMusic
610   'elements
611   (list (make-music
612           'EventChord
613           'elements
614           (list (make-music
615                   'NoteEvent
616                   'duration
617                   (ly:make-duration 2 0 1 1)
618                   'pitch
619                   (ly:make-pitch 0 5 0))
620                 (make-music
621                   'SlurEvent
622                   'span-direction
623                   -1)))
624         (make-music
625           'EventChord
626           'elements
627           (list (make-music
628                   'NoteEvent
629                   'duration
630                   (ly:make-duration 2 0 1 1)
631                   'pitch
632                   (ly:make-pitch 0 5 0))
633                 (make-music
634                   'SlurEvent
635                   'span-direction
636                   1)))))
637 @end example
638
639 The bad news is that the @code{SlurEvent} expressions
640 must be added @q{inside} the note (or more precisely,
641 inside the @code{EventChord} expression).
642
643 Now we examine the input,
644
645 @example
646 (make-music
647   'SequentialMusic
648   'elements
649   (list (make-music
650           'EventChord
651           'elements
652           (list (make-music
653                   'NoteEvent
654                   'duration
655                   (ly:make-duration 2 0 1 1)
656                   'pitch
657                   (ly:make-pitch 0 5 0))))))
658 @end example
659
660 So in our function, we need to clone this expression (so that we
661 have two notes to build the sequence), add @code{SlurEvents} to the
662 @code{'elements} property of each one, and finally make a
663 @code{SequentialMusic} with the two @code{EventChords}.
664
665 @example
666 doubleSlur = #(define-music-function (parser location note) (ly:music?)
667          "Return: @{ note ( note ) @}.
668          `note' is supposed to be an EventChord."
669          (let ((note2 (ly:music-deep-copy note)))
670            (set! (ly:music-property note 'elements)
671                  (cons (make-music 'SlurEvent 'span-direction -1)
672                        (ly:music-property note 'elements)))
673            (set! (ly:music-property note2 'elements)
674                  (cons (make-music 'SlurEvent 'span-direction 1)
675                        (ly:music-property note2 'elements)))
676            (make-music 'SequentialMusic 'elements (list note note2))))
677 @end example
678
679
680 @node Adding articulation to notes (example)
681 @subsection Adding articulation to notes (example)
682
683 The easy way to add articulation to notes is to merge two music
684 expressions into one context, as explained in
685 @ref{Creating contexts}.  However, suppose that we want to write
686 a music function which does this.
687
688 A @code{$variable} inside the @code{#@{...#@}} notation is like
689 using a regular @code{\variable} in classical LilyPond
690 notation.  We know that
691
692 @example
693 @{ \music -. -> @}
694 @end example
695
696 @noindent
697 will not work in LilyPond.  We could avoid this problem by attaching
698 the articulation to a fake note,
699
700 @example
701 @{ << \music s1*0-.-> @}
702 @end example
703
704 @noindent
705 but for the sake of this example, we will learn how to do this in
706 Scheme.  We begin by examining our input and desired output,
707
708 @example
709 %  input
710 \displayMusic c4
711 ===>
712 (make-music
713   'EventChord
714   'elements
715   (list (make-music
716           'NoteEvent
717           'duration
718           (ly:make-duration 2 0 1 1)
719           'pitch
720           (ly:make-pitch -1 0 0))))
721 =====
722 %  desired output
723 \displayMusic c4->
724 ===>
725 (make-music
726   'EventChord
727   'elements
728   (list (make-music
729           'NoteEvent
730           'duration
731           (ly:make-duration 2 0 1 1)
732           'pitch
733           (ly:make-pitch -1 0 0))
734         (make-music
735           'ArticulationEvent
736           'articulation-type
737           "marcato")))
738 @end example
739
740 We see that a note (@code{c4}) is represented as an @code{EventChord}
741 expression, with a @code{NoteEvent} expression in its elements list.  To
742 add a marcato articulation, an @code{ArticulationEvent} expression must
743 be added to the elements property of the @code{EventChord}
744 expression.
745
746 To build this function, we begin with
747
748 @example
749 (define (add-marcato event-chord)
750   "Add a marcato ArticulationEvent to the elements of `event-chord',
751   which is supposed to be an EventChord expression."
752   (let ((result-event-chord (ly:music-deep-copy event-chord)))
753     (set! (ly:music-property result-event-chord 'elements)
754           (cons (make-music 'ArticulationEvent
755                   'articulation-type "marcato")
756                 (ly:music-property result-event-chord 'elements)))
757     result-event-chord))
758 @end example
759
760 The first line is the way to define a function in Scheme: the function
761 name is @code{add-marcato}, and has one variable called
762 @code{event-chord}.  In Scheme, the type of variable is often clear
763 from its name.  (this is good practice in other programming languages,
764 too!)
765
766 @example
767 "Add a marcato..."
768 @end example
769
770 @noindent
771 is a description of what the function does.  This is not strictly
772 necessary, but just like clear variable names, it is good practice.
773
774 @example
775 (let ((result-event-chord (ly:music-deep-copy event-chord)))
776 @end example
777
778 @code{let} is used to declare local variables.  Here we use one local
779 variable, named @code{result-event-chord}, to which we give the value
780 @code{(ly:music-deep-copy event-chord)}.  @code{ly:music-deep-copy} is
781 a function specific to LilyPond, like all functions prefixed by
782 @code{ly:}.  It is use to make a copy of a music
783 expression.  Here we copy @code{event-chord} (the parameter of the
784 function).  Recall that our purpose is to add a marcato to an
785 @code{EventChord} expression.  It is better to not modify the
786 @code{EventChord} which was given as an argument, because it may be
787 used elsewhere.
788
789 Now we have a @code{result-event-chord}, which is a
790 @code{NoteEventChord} expression and is a copy of @code{event-chord}.  We
791 add the marcato to its elements list property.
792
793 @example
794 (set! place new-value)
795 @end example
796
797 Here, what we want to set (the @q{place}) is the @q{elements} property of
798 @code{result-event-chord} expression.
799
800 @example
801 (ly:music-property result-event-chord 'elements)
802 @end example
803
804 @code{ly:music-property} is the function used to access music properties
805 (the @code{'elements}, @code{'duration}, @code{'pitch}, etc, that we
806 see in the @code{\displayMusic} output above).  The new value is the
807 former elements property, with an extra item: the
808 @code{ArticulationEvent} expression, which we copy from the
809 @code{\displayMusic} output,
810
811 @example
812 (cons (make-music 'ArticulationEvent
813         'articulation-type "marcato")
814       (ly:music-property result-event-chord 'elements))
815 @end example
816
817 @code{cons} is used to add an element to a list without modifying the
818 original list.  This is what we
819 want: the same list as before, plus the new @code{ArticulationEvent}
820 expression.  The order inside the elements property is not important here.
821
822 Finally, once we have added the marcato articulation to its @code{elements}
823 property, we can return @code{result-event-chord}, hence the last line of
824 the function.
825
826 Now we transform the @code{add-marcato} function into a music
827 function,
828
829 @example
830 addMarcato = #(define-music-function (parser location event-chord)
831                                      (ly:music?)
832     "Add a marcato ArticulationEvent to the elements of `event-chord',
833     which is supposed to be an EventChord expression."
834     (let ((result-event-chord (ly:music-deep-copy event-chord)))
835       (set! (ly:music-property result-event-chord 'elements)
836             (cons (make-music 'ArticulationEvent
837                     'articulation-type "marcato")
838                   (ly:music-property result-event-chord 'elements)))
839       result-event-chord))
840 @end example
841
842 We may verify that this music function works correctly,
843
844 @example
845 \displayMusic \addMarcato c4
846 @end example
847
848
849 @node Markup programmer interface
850 @section Markup programmer interface
851
852 Markups are implemented as special Scheme functions which produce a
853 Stencil object given a number of arguments.
854
855 @menu
856 * Markup construction in Scheme::
857 * How markups work internally::
858 * New markup command definition::
859 * New markup list command definition::
860 @end menu
861
862
863 @node Markup construction in Scheme
864 @subsection Markup construction in Scheme
865
866 @cindex defining markup commands
867
868 The @code{markup} macro builds markup expressions in Scheme while
869 providing a LilyPond-like syntax.  For example,
870 @example
871 (markup #:column (#:line (#:bold #:italic "hello" #:raise 0.4 "world")
872                   #:larger #:line ("foo" "bar" "baz")))
873 @end example
874
875 @noindent
876 is equivalent to:
877 @example
878 \markup \column @{ \line @{ \bold \italic "hello" \raise #0.4 "world" @}
879                   \larger \line @{ foo bar baz @} @}
880 @end example
881
882 @noindent
883 This example demonstrates the main translation rules between regular
884 LilyPond markup syntax and Scheme markup syntax.
885
886 @quotation
887 @multitable @columnfractions .3 .3
888 @item @b{LilyPond} @tab @b{Scheme}
889 @item @code{\markup markup1} @tab @code{(markup markup1)}
890 @item @code{\markup @{ markup1 markup2 ... @}} @tab
891         @code{(markup markup1 markup2 ... )}
892 @item @code{\command} @tab @code{#:command}
893 @item @code{\variable} @tab @code{variable}
894 @item @code{\center-column @{ ... @}} @tab @code{#:center-column ( ... )}
895 @item @code{string} @tab @code{"string"}
896 @item @code{#scheme-arg} @tab @code{scheme-arg}
897 @end multitable
898 @end quotation
899
900 The whole Scheme language is accessible inside the
901 @code{markup} macro.  For example, You may use function calls inside
902 @code{markup} in order to manipulate character strings.  This is
903 useful when defining new markup commands (see
904 @ref{New markup command definition}).
905
906
907 @knownissues
908
909 The markup-list argument of commands such as @code{#:line},
910 @code{#:center}, and @code{#:column} cannot be a variable or
911 the result of a function call.
912
913 @lisp
914 (markup #:line (function-that-returns-markups))
915 @end lisp
916
917 @noindent
918 is invalid.  One should use the @code{make-line-markup},
919 @code{make-center-markup}, or @code{make-column-markup} functions
920 instead,
921
922 @lisp
923 (markup (make-line-markup (function-that-returns-markups)))
924 @end lisp
925
926
927 @node How markups work internally
928 @subsection How markups work internally
929
930 In a markup like
931
932 @example
933 \raise #0.5 "text example"
934 @end example
935
936 @noindent
937 @code{\raise} is actually represented by the @code{raise-markup}
938 function.  The markup expression is stored as
939
940 @example
941 (list raise-markup 0.5 (list simple-markup "text example"))
942 @end example
943
944 When the markup is converted to printable objects (Stencils), the
945 @code{raise-markup} function is called as
946
947 @example
948 (apply raise-markup
949        @var{\layout object}
950        @var{list of property alists}
951        0.5
952        @var{the "text example" markup})
953 @end example
954
955 The @code{raise-markup} function first creates the stencil for the
956 @code{text example} string, and then it raises that Stencil by 0.5
957 staff space.  This is a rather simple example; more complex examples
958 are in the rest
959 of this section, and in @file{scm/@/define@/-markup@/-commands@/.scm}.
960
961
962 @node New markup command definition
963 @subsection New markup command definition
964
965 New markup commands can be defined
966 with the @code{define-markup-command} Scheme macro.
967
968 @lisp
969 (define-markup-command (@var{command-name} @var{layout} @var{props} @var{arg1} @var{arg2} ...)
970             (@var{arg1-type?} @var{arg2-type?} ...)
971   ..command body..)
972 @end lisp
973
974 The arguments are
975
976 @table @var
977 @item argi
978 @var{i}th command argument
979 @item argi-type?
980 a type predicate for the i@var{th} argument
981 @item layout
982 the @q{layout} definition
983 @item props
984 a list of alists, containing all active properties.
985 @end table
986
987 As a simple example, we show how to add a @code{\smallcaps} command,
988 which selects a small caps font.  Normally we could select the
989 small caps font,
990
991 @example
992 \markup @{ \override #'(font-shape . caps) Text-in-caps @}
993 @end example
994
995 @noindent
996 This selects the caps font by setting the @code{font-shape} property to
997 @code{#'caps} for interpreting @code{Text-in-caps}.
998
999 To make the above available as @code{\smallcaps} command, we must
1000 define a function using @code{define-markup-command}.  The command should
1001 take a single argument of type @code{markup}.  Therefore the start of the
1002 definition should read
1003
1004 @example
1005 (define-markup-command (smallcaps layout props argument) (markup?)
1006 @end example
1007
1008 @noindent
1009
1010 What follows is the content of the command: we should interpret
1011 the @code{argument} as a markup, i.e.,
1012
1013 @example
1014 (interpret-markup layout @dots{} argument)
1015 @end example
1016
1017 @noindent
1018 This interpretation should add @code{'(font-shape . caps)} to the active
1019 properties, so we substitute the following for the @dots{} in the
1020 above example:
1021
1022 @example
1023 (cons (list '(font-shape . caps) ) props)
1024 @end example
1025
1026 @noindent
1027 The variable @code{props} is a list of alists, and we prepend to it by
1028 cons'ing a list with the extra setting.
1029
1030
1031 Suppose that we are typesetting a recitative in an opera and
1032 we would like to define a command that will show character names in a
1033 custom manner.  Names should be printed with small caps and moved a
1034 bit to the left and top.  We will define a @code{\character} command
1035 which takes into account the necessary translation and uses the newly
1036 defined @code{\smallcaps} command:
1037
1038 @example
1039 #(define-markup-command (character layout props name) (string?)
1040   "Print the character name in small caps, translated to the left and
1041   top.  Syntax: \\character #\"name\""
1042   (interpret-markup layout props
1043    (markup #:hspace 0 #:translate (cons -3 1) #:smallcaps name)))
1044 @end example
1045
1046 There is one complication that needs explanation: texts above and below
1047 the staff are moved vertically to be at a certain distance (the
1048 @code{padding} property) from the staff and the notes.  To make sure
1049 that this mechanism does not annihilate the vertical effect of our
1050 @code{#:translate}, we add an empty string (@code{#:hspace 0}) before the
1051 translated text.  Now the @code{#:hspace 0} will be put above the notes,
1052 and the
1053 @code{name} is moved in relation to that empty string.  The net effect is
1054 that the text is moved to the upper left.
1055
1056 The final result is as follows:
1057
1058 @example
1059 @{
1060   c''^\markup \character #"Cleopatra"
1061   e'^\markup \character #"Giulio Cesare"
1062 @}
1063 @end example
1064
1065 @lilypond[quote,ragged-right]
1066 #(define-markup-command (smallcaps layout props str) (string?)
1067   "Print the string argument in small caps.  Syntax: \\smallcaps #\"string\""
1068   (interpret-markup layout props
1069    (make-line-markup
1070     (map (lambda (s)
1071           (if (= (string-length s) 0)
1072               s
1073               (markup #:large (string-upcase (substring s 0 1))
1074                       #:translate (cons -0.6 0)
1075                       #:tiny (string-upcase (substring s 1)))))
1076          (string-split str #\Space)))))
1077
1078 #(define-markup-command (character layout props name) (string?)
1079   "Print the character name in small caps, translated to the left and
1080   top.  Syntax: \\character #\"name\""
1081   (interpret-markup layout props
1082    (markup #:hspace 0 #:translate (cons -3 1) #:smallcaps name)))
1083
1084 {
1085   c''^\markup \character #"Cleopatra" c'' c'' c''
1086   e'^\markup \character #"Giulio Cesare" e' e' e'
1087 }
1088 @end lilypond
1089
1090 We have used the @code{caps} font shape, but suppose that our font
1091 does not have a small-caps variant.  In that case we have to fake
1092 the small caps font by setting a string in upcase with the first
1093 letter a little larger:
1094
1095 @example
1096 #(define-markup-command (smallcaps layout props str) (string?)
1097   "Print the string argument in small caps."
1098   (interpret-markup layout props
1099    (make-line-markup
1100     (map (lambda (s)
1101           (if (= (string-length s) 0)
1102               s
1103               (markup #:large (string-upcase (substring s 0 1))
1104                       #:translate (cons -0.6 0)
1105                       #:tiny (string-upcase (substring s 1)))))
1106          (string-split str #\Space)))))
1107 @end example
1108
1109 The @code{smallcaps} command first splits its string argument into
1110 tokens separated by spaces (@code{(string-split str #\Space)}); for
1111 each token, a markup is built with the first letter made large and
1112 upcased (@code{#:large (string-upcase (substring s 0 1))}), and a
1113 second markup built with the following letters made tiny and upcased
1114 (@code{#:tiny (string-upcase (substring s 1))}).  As LilyPond
1115 introduces a space between markups on a line, the second markup is
1116 translated to the left (@code{#:translate (cons -0.6 0) ...}).  Then,
1117 the markups built for each token are put in a line by
1118 @code{(make-line-markup ...)}.  Finally, the resulting markup is passed
1119 to the @code{interpret-markup} function, with the @code{layout} and
1120 @code{props} arguments.
1121
1122 Note: there is now an internal command @code{\smallCaps} which can
1123 be used to set text in small caps.  See
1124 @ref{Text markup commands}, for details.
1125
1126 @knownissues
1127
1128 Currently, the available combinations of arguments (after the standard
1129 @var{layout} and @var{props} arguments) to a markup command defined with
1130 @code{define-markup-command} are limited as follows.
1131
1132 @table @asis
1133 @item (no argument)
1134 @itemx @var{list}
1135 @itemx @var{markup}
1136 @itemx @var{markup markup}
1137 @itemx @var{scm}
1138 @itemx @var{scm markup}
1139 @itemx @var{scm scm}
1140 @itemx @var{scm scm markup}
1141 @itemx @var{scm scm markup markup}
1142 @itemx @var{scm markup markup}
1143 @itemx @var{scm scm scm}
1144 @end table
1145
1146 @noindent
1147 In the above table, @var{scm} represents native Scheme data types like
1148 @q{number} or @q{string}.
1149
1150 As an example, it is not possible to use a markup command @code{foo} with
1151 four arguments defined as
1152
1153 @example
1154 #(define-markup-command (foo layout props
1155                          num1    str1    num2    str2)
1156                         (number? string? number? string?)
1157   ...)
1158 @end example
1159
1160 @noindent
1161 If you apply it as, say,
1162
1163 @example
1164 \markup \foo #1 #"bar" #2 #"baz"
1165 @end example
1166
1167 @cindex Scheme signature
1168 @cindex signature, Scheme
1169 @noindent
1170 @command{lilypond} complains that it cannot parse @code{foo} due to its
1171 unknown Scheme signature.
1172
1173
1174 @node New markup list command definition
1175 @subsection New markup list command definition
1176 Markup list commands are defined with the
1177 @code{define-markup-list-command} Scheme macro, which is similar to the
1178 @code{define-markup-command} macro described in
1179 @ref{New markup command definition}, except that where the latter returns
1180 a single stencil, the former returns a list stencils.
1181
1182 In the following example, a @code{\paragraph} markup list command is
1183 defined, which returns a list of justified lines, the first one being
1184 indented.  The indent width is taken from the @code{props} argument.
1185 @example
1186 #(define-markup-list-command (paragraph layout props args) (markup-list?)
1187    (let ((indent (chain-assoc-get 'par-indent props 2)))
1188      (interpret-markup-list layout props
1189        (make-justified-lines-markup-list (cons (make-hspace-markup indent)
1190                                                args)))))
1191 @end example
1192
1193 Besides the usual @code{layout} and @code{props} arguments, the
1194 @code{paragraph} markup list command takes a markup list argument, named
1195 @code{args}.  The predicate for markup lists is @code{markup-list?}.
1196
1197 First, the function gets the indent width, a property here named
1198 @code{par-indent}, from the property list @code{props} If the property
1199 is not found, the default value is @code{2}.  Then, a list of justified
1200 lines is made using the @code{make-justified-lines-markup-list}
1201 function, which is related to the @code{\justified-lines}
1202 built-in markup list command.  An horizontal space is added at the
1203 beginning using the @code{make-hspace-markup} function.  Finally, the
1204 markup list is interpreted using the @code{interpret-markup-list}
1205 function.
1206
1207 This new markup list command can be used as follows:
1208 @example
1209 \markuplines @{
1210   \paragraph @{
1211     The art of music typography is called \italic @{(plate) engraving.@}
1212     The term derives from the traditional process of music printing.
1213     Just a few decades ago, sheet music was made by cutting and stamping
1214     the music into a zinc or pewter plate in mirror image.
1215   @}
1216   \override-lines #'(par-indent . 4) \paragraph @{
1217     The plate would be inked, the depressions caused by the cutting
1218     and stamping would hold ink.  An image was formed by pressing paper
1219     to the plate.  The stamping and cutting was completely done by
1220     hand.
1221   @}
1222 @}
1223 @end example
1224
1225 @node Contexts for programmers
1226 @section Contexts for programmers
1227
1228 @menu
1229 * Context evaluation::
1230 * Running a function on all layout objects::
1231 @end menu
1232
1233 @node Context evaluation
1234 @subsection Context evaluation
1235
1236 @cindex calling code during interpreting
1237 @funindex \applyContext
1238
1239 Contexts can be modified during interpretation with Scheme code.  The
1240 syntax for this is
1241 @example
1242 \applyContext @var{function}
1243 @end example
1244
1245 @var{function} should be a Scheme function taking a single argument,
1246 being the context to apply it to.  The following code will print the
1247 current bar number on the standard output during the compile:
1248
1249 @example
1250 \applyContext
1251   #(lambda (x)
1252     (format #t "\nWe were called in barnumber ~a.\n"
1253      (ly:context-property x 'currentBarNumber)))
1254 @end example
1255
1256
1257
1258 @node Running a function on all layout objects
1259 @subsection Running a function on all layout objects
1260
1261
1262 @cindex calling code on layout objects
1263 @funindex \applyOutput
1264
1265
1266 The most versatile way of tuning an object is @code{\applyOutput}.  Its
1267 syntax is
1268 @example
1269 \applyOutput @var{context} @var{proc}
1270 @end example
1271
1272 @noindent
1273 where @var{proc} is a Scheme function, taking three arguments.
1274
1275 When interpreted, the function @var{proc} is called for every layout
1276 object found in the context @var{context}, with the following
1277 arguments:
1278 @itemize
1279 @item the layout object itself,
1280 @item the context where the layout object was created, and
1281 @item the context where @code{\applyOutput} is processed.
1282 @end itemize
1283
1284
1285 In addition, the cause of the layout object, i.e., the music
1286 expression or object that was responsible for creating it, is in the
1287 object property @code{cause}.  For example, for a note head, this is a
1288 @rinternals{NoteHead} event, and for a @rinternals{Stem} object,
1289 this is a @rinternals{NoteHead} object.
1290
1291 Here is a function to use for @code{\applyOutput}; it blanks
1292 note-heads on the center-line:
1293
1294 @lilypond[quote,verbatim,ragged-right]
1295 #(define (blanker grob grob-origin context)
1296    (if (and (memq 'note-head-interface (ly:grob-interfaces grob))
1297             (eq? (ly:grob-property grob 'staff-position) 0))
1298        (set! (ly:grob-property grob 'transparent) #t)))
1299
1300 \relative {
1301   e4 g8 \applyOutput #'Voice #blanker b d2
1302 }
1303 @end lilypond
1304
1305
1306 @node Scheme procedures as properties
1307 @section Scheme procedures as properties
1308
1309 Properties (like thickness, direction, etc.) can be set at fixed values
1310 with \override, e.g.
1311
1312 @example
1313 \override Stem #'thickness = #2.0
1314 @end example
1315
1316 Properties can also be set to a Scheme procedure,
1317
1318 @lilypond[fragment,verbatim,quote,relative=2]
1319 \override Stem #'thickness = #(lambda (grob)
1320     (if (= UP (ly:grob-property grob 'direction))
1321         2.0
1322         7.0))
1323 c b a g b a g b
1324 @end lilypond
1325
1326 @noindent
1327 In this case, the procedure is executed as soon as the value of the
1328 property is requested during the formatting process.
1329
1330 Most of the typesetting engine is driven by such callbacks.
1331 Properties that typically use callbacks include
1332
1333 @table @code
1334 @item stencil
1335   The printing routine, that constructs a drawing for the symbol
1336 @item X-offset
1337   The routine that sets the horizontal position
1338 @item X-extent
1339   The routine that computes the width of an object
1340 @end table
1341
1342 The procedure always takes a single argument, being the grob.
1343
1344 If routines with multiple arguments must be called, the current grob
1345 can be inserted with a grob closure.  Here is a setting from
1346 @code{AccidentalSuggestion},
1347
1348 @example
1349 (X-offset .
1350   ,(ly:make-simple-closure
1351     `(,+
1352         ,(ly:make-simple-closure
1353            (list ly:self-alignment-interface::centered-on-x-parent))
1354       ,(ly:make-simple-closure
1355            (list ly:self-alignment-interface::x-aligned-on-self)))))
1356 @end example
1357
1358 @noindent
1359 In this example, both @code{ly:self-alignment-interface::x-aligned-on-self} and
1360 @code{ly:self-alignment-interface::centered-on-x-parent} are called
1361 with the grob as argument.  The results are added with the @code{+}
1362 function.  To ensure that this addition is properly executed, the whole
1363 thing is enclosed in @code{ly:make-simple-closure}.
1364
1365 In fact, using a single procedure as property value is equivalent to
1366
1367 @example
1368 (ly:make-simple-closure (ly:make-simple-closure (list @var{proc})))
1369 @end example
1370
1371 @noindent
1372 The inner @code{ly:make-simple-closure} supplies the grob as argument
1373 to @var{proc}, the outer ensures that result of the function is
1374 returned, rather than the @code{simple-closure} object.
1375
1376
1377 @node Using Scheme code instead of \tweak
1378 @section Using Scheme code instead of @code{\tweak}
1379
1380 The main disadvantage of @code{\tweak} is its syntactical
1381 inflexibility.  For example, the following produces a syntax error.
1382
1383 @example
1384 F = \tweak #'font-size #-3 -\flageolet
1385
1386 \relative c'' @{
1387   c4^\F c4_\F
1388 @}
1389 @end example
1390
1391 @noindent
1392 With other words, @code{\tweak} doesn't behave like an articulation
1393 regarding the syntax; in particular, it can't be attached with
1394 @code{^} and @code{_}.
1395
1396 Using Scheme, this problem can be circumvented.  The route to the
1397 result is given in @ref{Adding articulation to notes (example)},
1398 especially how to use @code{\displayMusic} as a helping guide.
1399
1400 @example
1401 F = #(let ((m (make-music 'ArticulationEvent
1402                           'articulation-type "flageolet")))
1403        (set! (ly:music-property m 'tweaks)
1404              (acons 'font-size -3
1405                     (ly:music-property m 'tweaks)))
1406        m)
1407
1408 \relative c'' @{
1409   c4^\F c4_\F
1410 @}
1411 @end example
1412
1413 @noindent
1414 Here, the @code{tweaks} properties of the flageolet object
1415 @code{m} (created with @code{make-music}) are extracted with
1416 @code{ly:music-property}, a new key-value pair to change the
1417 font size is prepended to the property list with the
1418 @code{acons} Scheme function, and the result is finally
1419 written back with @code{set!}.  The last element of the
1420 @code{let} block is the return value, @code{m} itself.
1421
1422
1423
1424 @node Difficult tweaks
1425 @section Difficult tweaks
1426
1427 There are a few classes of difficult adjustments.
1428
1429 @itemize
1430
1431
1432 @item
1433 One type of difficult adjustment is the appearance of spanner objects,
1434 such as slur and tie.  Initially, only one of these objects is created,
1435 and they can be adjusted with the normal mechanism.  However, in some
1436 cases the spanners cross line breaks.  If this happens, these objects
1437 are cloned.  A separate object is created for every system that it is
1438 in.  These are clones of the original object and inherit all
1439 properties, including @code{\override}s.
1440
1441
1442 In other words, an @code{\override} always affects all pieces of a
1443 broken spanner.  To change only one part of a spanner at a line break,
1444 it is necessary to hook into the formatting process.  The
1445 @code{after-line-breaking} callback contains the Scheme procedure that
1446 is called after the line breaks have been determined, and layout
1447 objects have been split over different systems.
1448
1449 In the following example, we define a procedure
1450 @code{my-callback}.  This procedure
1451
1452 @itemize
1453 @item
1454 determines if we have been split across line breaks
1455 @item
1456 if yes, retrieves all the split objects
1457 @item
1458 checks if we are the last of the split objects
1459 @item
1460 if yes, it sets @code{extra-offset}.
1461 @end itemize
1462
1463 This procedure is installed into @rinternals{Tie}, so the last part
1464 of the broken tie is translated up.
1465
1466 @lilypond[quote,verbatim,ragged-right]
1467 #(define (my-callback grob)
1468   (let* (
1469          ; have we been split?
1470          (orig (ly:grob-original grob))
1471
1472          ; if yes, get the split pieces (our siblings)
1473          (siblings (if (ly:grob? orig)
1474                      (ly:spanner-broken-into orig) '() )))
1475
1476    (if (and (>= (length siblings) 2)
1477              (eq? (car (last-pair siblings)) grob))
1478      (ly:grob-set-property! grob 'extra-offset '(-2 . 5)))))
1479
1480 \relative c'' {
1481   \override Tie #'after-line-breaking =
1482   #my-callback
1483   c1 ~ \break c2 ~ c
1484 }
1485 @end lilypond
1486
1487 @noindent
1488 When applying this trick, the new @code{after-line-breaking} callback
1489 should also call the old one @code{after-line-breaking}, if there is
1490 one.  For example, if using this with @code{Hairpin},
1491 @code{ly:hairpin::after-line-breaking} should also be called.
1492
1493
1494 @item Some objects cannot be changed with @code{\override} for
1495 technical reasons.  Examples of those are @code{NonMusicalPaperColumn}
1496 and @code{PaperColumn}.  They can be changed with the
1497 @code{\overrideProperty} function, which works similar to @code{\once
1498 \override}, but uses a different syntax.
1499
1500 @example
1501 \overrideProperty
1502 #"Score.NonMusicalPaperColumn"  % Grob name
1503 #'line-break-system-details     % Property name
1504 #'((next-padding . 20))         % Value
1505 @end example
1506
1507 Note, however, that @code{\override}, applied to
1508 @code{NonMusicalPaperColumn} and @code{PaperColumn}, still works as
1509 expected within @code{\context} blocks.
1510
1511 @end itemize
1512
1513
1514
1515
1516