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