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