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