]> git.donarmstrong.com Git - lilypond.git/blob - Documentation/user/programming-interface.itely
Fix off-by-one error in constrained-breaking.
[lilypond.git] / Documentation / user / programming-interface.itely
1 @c -*- coding: utf-8; mode: texinfo; -*-
2 @node Interfaces for programmers
3 @chapter Interfaces for programmers
4
5 Advanced tweaks may be performed by using Scheme.  If you are
6 not familiar with Scheme, you may wish to read our
7 @ref{Scheme tutorial}.
8
9 @menu
10 * Music functions::             
11 * Programmer interfaces::       
12 * Building complicated functions::  
13 * Markup programmer interface::  
14 * Contexts for programmers::    
15 * Scheme procedures as properties::  
16 @end menu
17
18
19 @node Music functions
20 @section Music functions
21
22 This section discusses how to create music functions within LilyPond.
23
24 @menu
25 * Overview of music functions::  
26 * Simple substitution functions::  
27 * Paired substitution functions::  
28 * Mathematics in functions::    
29 * Void functions::              
30 * Functions without arguments::  
31 * Overview of available music functions::  
32 @end menu
33
34 @node Overview of music functions
35 @subsection Overview of music functions
36
37 Making a function which substitutes a variable into LilyPond
38 code is easy.  The general form of these functions is
39
40 @example
41 function =
42 #(define-music-function (parser location @var{var1} @var{var2}... )
43                         (@var{var1-type?} @var{var2-type?}...)
44   #@{
45     @emph{...music...}
46   #@})
47 @end example
48
49 @noindent
50 where
51
52 @multitable @columnfractions .33 .66
53 @item @var{argi}         @tab @var{i}th variable
54 @item @var{argi-type?}   @tab type of variable
55 @item @var{...music...}  @tab normal LilyPond input, using
56   variables as @code{#$var1}.
57 @end multitable
58
59 There following input types may be used as variables
60 in a music function.  This list is not exhaustive; see
61 other documentation specifically about Scheme for more
62 variable types.
63
64 @multitable @columnfractions .33 .66
65 @headitem Input type          @tab @var{argi-type?} notation
66 @item Integer                 @tab @code{integer?}
67 @item Float (decimal number)  @tab @code{number?}
68 @item Text string             @tab @code{string?}
69 @item Markup                  @tab @code{markup?}
70 @item Music expression        @tab @code{ly:music?}
71 @item A pair of variables     @tab @code{pair?}
72 @end multitable
73
74 The @code{parser} and @code{location} argument are mandatory,
75 and are used in some advanced situations.  The @code{parser}
76 argument is used to access to the value of another LilyPond
77 variable.  The @code{location} argument
78 is used to set the ``origin'' of the music expression that is built
79 by the music function, so that in case of a syntax error LilyPond
80 can tell the user an appropriate place to look in the input file.
81
82
83 @node Simple substitution functions
84 @subsection Simple substitution functions
85
86 Here is a simple example,
87
88 @lilypond[quote,verbatim,ragged-right]
89 padText = #(define-music-function (parser location padding) (number?)
90   #{
91     \once \override TextScript #'padding = #$padding
92   #})
93
94 \relative c''' {
95   c4^"piu mosso" b a b
96   \padText #1.8
97   c4^"piu mosso" d e f
98   \padText #2.6
99   c4^"piu mosso" fis a g
100 }
101 @end lilypond
102
103 Music expressions may be substituted as well,
104
105 @lilypond[quote,verbatim,ragged-right]
106 custosNote = #(define-music-function (parser location note)
107                                      (ly:music?)
108   #{
109     \once \override Voice.NoteHead #'stencil =
110       #ly:text-interface::print
111     \once \override Voice.NoteHead #'text =
112       \markup \musicglyph #"custodes.mensural.u0"
113     \once \override Voice.Stem #'stencil = ##f
114     $note
115   #})
116
117 { c' d' e' f' \custosNote g' }
118 @end lilypond
119
120 Multiple variables may be used,
121
122 @lilypond[quote,verbatim,ragged-right]
123 tempoMark = #(define-music-function (parser location padding marktext)
124                                     (number? string?)
125 #{
126   \once \override Score . RehearsalMark #'padding = $padding
127   \once \override Score . RehearsalMark #'extra-spacing-width = #'(+inf.0 . -inf.0)
128   \mark \markup { \bold $marktext }
129 #})
130
131 \relative c'' {
132 c2 e
133 \tempoMark #3.0 #"Allegro"
134 g c
135 }
136 @end lilypond
137
138
139 @node Paired substitution functions
140 @subsection Paired substitution functions
141
142 Some @code{\override} commands require a pair of numbers
143 (called a @code{cons cell} in Scheme).  To pass these numbers
144 into a function, either use a @code{pair?} variable, or
145 insert the @code{cons} into the music function.
146
147 @quotation
148 @example
149 manualBeam =
150 #(define-music-function (parser location beg-end)
151                         (pair?)
152 #@{
153   \once \override Beam #'positions = #$beg-end
154 #@})
155
156 \relative @{
157   \manualBeam #'(3 . 6) c8 d e f
158 @}
159 @end example
160 @end quotation
161
162 @noindent
163 or
164
165 @lilypond[quote,verbatim,ragged-right]
166 manualBeam =
167 #(define-music-function (parser location beg end)
168                         (number? number?)
169 #{
170   \once \override Beam #'positions = #(cons $beg $end)
171 #})
172
173 \relative {
174   \manualBeam #3 #6 c8 d e f
175 }
176 @end lilypond
177
178
179 @node Mathematics in functions
180 @subsection Mathematics in functions
181
182 Music functions can involve Scheme programming in
183 addition to simple substitution,
184
185 @lilypond[quote,verbatim,ragged-right]
186 AltOn = #(define-music-function (parser location mag) (number?)
187   #{ \override Stem #'length = #$(* 7.0 mag)
188      \override NoteHead #'font-size =
189        #$(inexact->exact (* (/ 6.0 (log 2.0)) (log mag))) #})
190
191 AltOff = {
192   \revert Stem #'length
193   \revert NoteHead #'font-size
194 }
195
196 { c'2 \AltOn #0.5 c'4 c'
197   \AltOn #1.5 c' c' \AltOff c'2 }
198 @end lilypond
199
200 @noindent
201 This example may be rewritten to pass in music expressions,
202
203 @lilypond[quote,verbatim,ragged-right]
204 withAlt = #(define-music-function (parser location mag music) (number? ly:music?)
205   #{ \override Stem #'length = #$(* 7.0 mag)
206      \override NoteHead #'font-size =
207        #$(inexact->exact (* (/ 6.0 (log 2.0)) (log mag)))
208      $music
209      \revert Stem #'length
210      \revert NoteHead #'font-size #})
211
212 { c'2 \withAlt #0.5 {c'4 c'}
213   \withAlt #1.5 {c' c'} c'2 }
214 @end lilypond
215
216 @node Void functions
217 @subsection Void functions
218
219 A music function must return a music expression, but sometimes we
220 may want to have a function which does not involve music (such as
221 turning off Point and Click).  To do this, we return a @code{void}
222 music expression.
223
224 That is why the form
225 that is returned is the @code{(make-music ...)}. With the
226 @code{'void} property set to @code{#t}, the parser is told to
227 actually disregard this returned music
228 expression.  Thus the important part of the void music function is the
229 processing done by the function, not the music expression that is
230 returned.
231
232 @example
233 noPointAndClick =
234 #(define-music-function (parser location) ()
235    (ly:set-option 'point-and-click #f)
236    (make-music 'SequentialMusic 'void #t))
237 ...
238 \noPointAndClick   % disable point and click
239 @end example
240
241
242 @node Functions without arguments
243 @subsection Functions without arguments
244
245 In most cases a function without arguments should be written
246 with an identifier,
247
248 @example
249 dolce = \markup@{ \italic \bold dolce @}
250 @end example
251
252 However, in rare cases it may be useful to create a music function
253 without arguments,
254
255 @example
256 displayBarNum =
257 #(define-music-function (parser location) ()
258    (if (eq? #t (ly:get-option display-bar-numbers))
259        #@{ \once \override Score.BarNumber #'break-visibility = ##f #@}
260        #@{#@}))
261 @end example
262
263 To actually display bar numbers where this function is called,
264 invoke lilypond with
265
266 @example
267 lilypond -d display-bar-numbers FILENAME.ly
268 @end example
269
270
271 @node Overview of available music functions
272 @subsection Overview of available music functions
273
274 @c fixme ; this should be move somewhere else?
275 The following commands are music functions
276
277 @include identifiers.tely
278
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 Due to parser lookahead
352
353 In this example, the assignment happens after parser has verified that
354 nothing interesting happens after @code{traLaLa = @{ ... @}}. Without
355 the dummy statement in the above example, the @code{newLa} definition
356 is executed before @code{traLaLa} is defined, leading to a syntax
357 error.
358
359 The above example shows how to `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 @example
366 @dots{}
367 @{ #(ly:export (make-sequential-music (list newLa))) @}
368 @end example
369
370 Scheme code is evaluated as soon as the parser encounters it.  To
371 define some Scheme code in a macro (to be called later), use
372 @ref{Void functions} or
373
374 @example
375 #(define (nopc)
376   (ly:set-option 'point-and-click #f))
377
378 ...
379 #(nopc)
380 @{ c'4 @}
381 @end example
382
383
384 @refbugs
385
386 Mixing Scheme and LilyPond identifiers is not possible with the
387 @code{--safe} option.
388
389
390 @node Internal music representation
391 @subsection Internal music representation
392
393 When a music expression is parsed, it is converted into a set of
394 Scheme music objects.  The defining property of a music object is that
395 it takes up time.  Time is a rational number that measures the length
396 of a piece of music in whole notes.
397
398 A music object has three kinds of types:
399 @itemize @bullet
400 @item
401 music name: Each music expression has a name.  For example, a note
402 leads to a @internalsref{NoteEvent}, and @code{\simultaneous} leads to
403 a @internalsref{SimultaneousMusic}.  A list of all expressions
404 available is in the Program reference manual, under
405 @internalsref{Music expressions}.
406
407 @item
408 `type' or interface: Each music name has several `types' or
409 interfaces, for example, a note is an @code{event}, but it is also a
410 @code{note-event}, a @code{rhythmic-event}, and a
411 @code{melodic-event}.  All classes of music are listed in the
412 Program reference, under
413 @internalsref{Music classes}.
414
415 @item
416 C++ object: Each music object is represented by an object of the C++
417 class @code{Music}.
418 @end itemize
419
420 The actual information of a music expression is stored in properties.
421 For example, a @internalsref{NoteEvent} has @code{pitch} and
422 @code{duration} properties that store the pitch and duration of that
423 note.  A list of all properties available is in the internals manual,
424 under @internalsref{Music properties}.
425
426 A compound music expression is a music object that contains other
427 music objects in its properties.  A list of objects can be stored in
428 the @code{elements} property of a music object, or a single `child'
429 music object in the @code{element} object.  For example,
430 @internalsref{SequentialMusic} has its children in @code{elements},
431 and @internalsref{GraceMusic} has its single argument in
432 @code{element}.  The body of a repeat is stored in the @code{element}
433 property of @internalsref{RepeatedMusic}, and the alternatives in
434 @code{elements}.
435
436
437
438 @node Building complicated functions
439 @section Building complicated functions
440
441 This section explains how to gather the information necessary
442 to create complicated music functions.
443
444 @menu
445 * Displaying music expressions::  
446 * Music properties::            
447 * Doubling a note with slurs (example)::  
448 * Adding articulation to notes (example)::  
449 @end menu
450
451
452 @node Displaying music expressions
453 @subsection Displaying music expressions
454
455 @cindex internal storage
456 @funindex \displayMusic
457 @funindex \displayLilyMusic
458
459 When writing a music function it is often instructive to inspect how
460 a music expression is stored internally.  This can be done with the
461 music function @code{\displayMusic}
462
463 @example
464 @{
465   \displayMusic @{ c'4\f @}
466 @}
467 @end example
468
469 @noindent
470 will display
471
472 @example
473 (make-music
474   'SequentialMusic
475   'elements
476   (list (make-music
477           'EventChord
478           'elements
479           (list (make-music
480                   'NoteEvent
481                   'duration
482                   (ly:make-duration 2 0 1 1)
483                   'pitch
484                   (ly:make-pitch 0 0 0))
485                 (make-music
486                   'AbsoluteDynamicEvent
487                   'text
488                   "f")))))
489 @end example
490
491 By default, LilyPond will print these messages to the console along
492 with all the other messages.  To split up these messages and save
493 the results of @code{\display@{STUFF@}}, redirect the output to
494 a file.
495
496 @example
497 lilypond file.ly >display.txt
498 @end example
499
500 With a bit of reformatting, the above information is
501 easier to read,
502
503 @example
504 (make-music 'SequentialMusic
505   'elements (list (make-music 'EventChord
506                     'elements (list (make-music 'NoteEvent
507                                       'duration (ly:make-duration 2 0 1 1)
508                                       'pitch (ly:make-pitch 0 0 0))
509                                     (make-music 'AbsoluteDynamicEvent
510                                       'text "f")))))
511 @end example
512
513 A @code{@{ ... @}} music sequence has the name @code{SequentialMusic},
514 and its inner expressions are stored as a list in its @code{'elements}
515 property.  A note is represented as an @code{EventChord} expression,
516 containing a @code{NoteEvent} object (storing the duration and
517 pitch properties) and any extra information (in this case, an
518 @code{AbsoluteDynamicEvent} with a @code{"f"} text property.
519
520
521 @node Music properties
522 @subsection Music properties
523
524 The @code{NoteEvent} object is the first object of the
525 @code{'elements} property of @code{someNote}.
526
527 @example
528 someNote = c'
529 \displayMusic \someNote
530 ===>
531 (make-music
532   'EventChord
533   'elements
534   (list (make-music
535           'NoteEvent
536           'duration
537           (ly:make-duration 2 0 1 1)
538           'pitch
539           (ly:make-pitch 0 0 0))))
540 @end example
541
542 The @code{display-scheme-music} function is the function used by
543 @code{\displayMusic} to display the Scheme representation of a music
544 expression.
545
546 @example
547 #(display-scheme-music (first (ly:music-property someNote 'elements)))
548 ===>
549 (make-music
550   'NoteEvent
551   'duration
552   (ly:make-duration 2 0 1 1)
553   'pitch
554   (ly:make-pitch 0 0 0))
555 @end example
556
557 Then the note pitch is accessed through the @code{'pitch} property
558 of the @code{NoteEvent} object,
559
560 @example
561 #(display-scheme-music
562    (ly:music-property (first (ly:music-property someNote 'elements))
563                       'pitch))
564 ===>
565 (ly:make-pitch 0 0 0)
566 @end example
567
568 The note pitch can be changed by setting this 'pitch property,
569
570 @example
571 #(set! (ly:music-property (first (ly:music-property someNote 'elements))
572                           'pitch)
573        (ly:make-pitch 0 1 0)) ;; set the pitch to d'.
574 \displayLilyMusic \someNote
575 ===>
576 d'
577 @end example
578
579
580 @node Doubling a note with slurs (example)
581 @subsection Doubling a note with slurs (example)
582
583 Suppose we want to create a function which translates
584 input like ``@code{a}'' into ``@code{a( a)}''.  We begin
585 by examining the internal representation of the music
586 we want to end up with.
587
588 @example
589 \displayMusic@{ a'( a') @}
590 ===>
591 (make-music
592   'SequentialMusic
593   'elements
594   (list (make-music
595           'EventChord
596           'elements
597           (list (make-music
598                   'NoteEvent
599                   'duration
600                   (ly:make-duration 2 0 1 1)
601                   'pitch
602                   (ly:make-pitch 0 5 0))
603                 (make-music
604                   'SlurEvent
605                   'span-direction
606                   -1)))
607         (make-music
608           'EventChord
609           'elements
610           (list (make-music
611                   'NoteEvent
612                   'duration
613                   (ly:make-duration 2 0 1 1)
614                   'pitch
615                   (ly:make-pitch 0 5 0))
616                 (make-music
617                   'SlurEvent
618                   'span-direction
619                   1)))))
620 @end example
621
622 The bad news is that the @code{SlurEvent} expressions
623 must be added ``inside'' the note (or more precisely,
624 inside the @code{EventChord} expression).
625
626 Now we examine the input,
627
628 @example
629 (make-music
630   'SequentialMusic
631   'elements
632   (list (make-music
633           'EventChord
634           'elements
635           (list (make-music
636                   'NoteEvent
637                   'duration
638                   (ly:make-duration 2 0 1 1)
639                   'pitch
640                   (ly:make-pitch 0 5 0))))))
641 @end example
642
643 So in our function, we need to clone this expression (so that we
644 have two notes to build the sequence), add @code{SlurEvents} to the
645 @code{'elements} property of each one, and finally make a
646 @code{SequentialMusic} with the two @code{EventChords}.
647
648 @example
649 doubleSlur = #(define-music-function (parser location note) (ly:music?)
650          "Return: @{ note ( note ) @}.
651          `note' is supposed to be an EventChord."
652          (let ((note2 (ly:music-deep-copy note)))
653            (set! (ly:music-property note 'elements)
654                  (cons (make-music 'SlurEvent 'span-direction -1)
655                        (ly:music-property note 'elements)))
656            (set! (ly:music-property note2 'elements)
657                  (cons (make-music 'SlurEvent 'span-direction 1)
658                        (ly:music-property note2 'elements)))
659            (make-music 'SequentialMusic 'elements (list note note2))))
660 @end example
661
662
663 @node Adding articulation to notes (example)
664 @subsection Adding articulation to notes (example)
665
666 The easy way to add articulation to notes is to merge two music
667 expressions into one context, as explained in
668 @ref{Creating contexts}.  However, suppose that we want to write
669 a music function which does this.
670
671 A @code{$variable} inside the @code{#@{...#@}} notation is like
672 using a regular @code{\variable} in classical LilyPond
673 notation.  We know that
674
675 @example
676 @{ \music -. -> @}
677 @end example
678
679 @noindent
680 will not work in LilyPond.  We could avoid this problem by attaching
681 the articulation to a fake note,
682
683 @example
684 @{ << \music s1*0-.-> @}
685 @end example
686
687 @noindent
688 but for the sake of this example, we will learn how to do this in
689 Scheme.  We begin by examining our input and desired output,
690
691 @example
692 %  input
693 \displayMusic c4
694 ===>
695 (make-music
696   'EventChord
697   'elements
698   (list (make-music
699           'NoteEvent
700           'duration
701           (ly:make-duration 2 0 1 1)
702           'pitch
703           (ly:make-pitch -1 0 0))))
704 =====
705 %  desired output
706 \displayMusic c4->
707 ===>
708 (make-music
709   'EventChord
710   'elements
711   (list (make-music
712           'NoteEvent
713           'duration
714           (ly:make-duration 2 0 1 1)
715           'pitch
716           (ly:make-pitch -1 0 0))
717         (make-music
718           'ArticulationEvent
719           'articulation-type
720           "marcato")))
721 @end example
722
723 We see that a note (@code{c4}) is represented as an @code{EventChord}
724 expression, with a @code{NoteEvent} expression in its elements list.  To
725 add a marcato articulation, an @code{ArticulationEvent} expression must
726 be added to the elements property of the @code{EventChord}
727 expression.
728
729 To build this function, we begin with
730
731 @example
732 (define (add-marcato event-chord)
733   "Add a marcato ArticulationEvent to the elements of `event-chord',
734   which is supposed to be an EventChord expression."
735   (let ((result-event-chord (ly:music-deep-copy event-chord)))
736     (set! (ly:music-property result-event-chord 'elements)
737           (cons (make-music 'ArticulationEvent
738                   'articulation-type "marcato")
739                 (ly:music-property result-event-chord 'elements)))
740     result-event-chord))
741 @end example
742
743 The first line is the way to define a function in Scheme: the function
744 name is @code{add-marcato}, and has one variable called
745 @code{event-chord}.  In Scheme, the type of variable is often clear
746 from its name.  (this is good practice in other programming languages,
747 too!)
748
749 @example
750 "Add a marcato..."
751 @end example
752
753 @noindent
754 is a description of what the function does.  This is not strictly
755 necessary, but just like clear variable names, it is good practice.
756
757 @example
758 (let ((result-event-chord (ly:music-deep-copy event-chord)))
759 @end example
760
761 `@code{let}' is used to declare local variables.  Here we use one local
762 variable, named `@code{result-event-chord}', to which we give the value
763 @code{(ly:music-deep-copy event-chord)}.  `@code{ly:music-deep-copy}' is
764 a function specific to LilyPond, like all functions prefixed by
765 `@code{ly:}'.  It is use to make a copy of a music
766 expression.  Here we copy `@code{event-chord} (the parameter of the
767 function).  Recall that our purpose is to add a marcato to an
768 @code{EventChord} expression.  It is better to not modify the
769 @code{EventChord} which was given as an argument, because it may be
770 used elsewhere.
771
772 Now we have a @code{result-event-chord}, which is a
773 @code{NoteEventChord} expression and is a copy of @code{event-chord}.  We
774 add the marcato to its elements list property.
775
776 @example
777 (set! place new-value)
778 @end example
779
780 Here, what we want to set (the "place") is the "elements" property of
781 @code{result-event-chord} expression
782
783 @example
784 (ly:music-property result-event-chord 'elements)
785 @end example
786
787 @code{ly:music-property} is the function used to access music properties
788 (the @code{'elements}, @code{'duration}, @code{'pitch}, etc, that we
789 see in the @code{\displayMusic} output above).  The new value is the
790 former elements property, with an extra item: the
791 @code{MarcatoEvent} expression, which we copy from the
792 @code{\displayMusic} output,
793
794 @example
795 (cons (make-music 'ArticulationEvent
796         'articulation-type "marcato")
797       (ly:music-property result-event-chord 'elements))
798 @end example
799
800 `@code{cons}' is used to add an element to a list without modifying the
801 original list.  This is what we
802 want: the same list as before, plus the new @code{ArticulationEvent}
803 expression.  The order inside the elements property is not important here.
804
805 Finally, once we have added the @code{MarcatoEvent} to its elements
806 property, we can return @code{result-event-chord}, hence the last line of
807 the function.
808
809 Now we transform the @code{add-marcato} function into a music
810 function,
811
812 @example
813 addMarcato = #(define-music-function (parser location event-chord)
814                                      (ly:music?)
815     "Add a marcato ArticulationEvent to the elements of `event-chord',
816     which is supposed to be an EventChord expression."
817     (let ((result-event-chord (ly:music-deep-copy event-chord)))
818       (set! (ly:music-property result-event-chord 'elements)
819             (cons (make-music 'ArticulationEvent
820                     'articulation-type "marcato")
821                   (ly:music-property result-event-chord 'elements)))
822       result-event-chord))
823 @end example
824
825 We may verify that this music function works correctly,
826
827 @example
828 \displayMusic \addMarcato c4
829 @end example
830
831
832 @node Markup programmer interface
833 @section Markup programmer interface
834
835 Markups are implemented as special Scheme functions which produce a
836 Stencil object given a number of arguments.
837
838 @menu
839 * Markup construction in Scheme::  
840 * How markups work internally::  
841 * New markup command definition::  
842 @end menu
843
844
845 @node Markup construction in Scheme
846 @subsection Markup construction in Scheme
847
848 @cindex defining markup commands
849
850 The @code{markup} macro builds markup expressions in Scheme while
851 providing a LilyPond-like syntax.  For example,
852 @example
853 (markup #:column (#:line (#:bold #:italic "hello" #:raise 0.4 "world")
854                   #:bigger #:line ("foo" "bar" "baz")))
855 @end example
856
857 @noindent
858 is equivalent to:
859 @example
860 \markup \column @{ \line @{ \bold \italic "hello" \raise #0.4 "world" @}
861                   \bigger \line @{ foo bar baz @} @}
862 @end example
863
864 @noindent
865 This example demonstrates the main translation rules between regular
866 LilyPond markup syntax and Scheme markup syntax.
867
868 @quotation
869 @multitable @columnfractions .3 .3
870 @item @b{LilyPond} @tab @b{Scheme}
871 @item @code{\markup markup1} @tab @code{(markup markup1)}
872 @item @code{\markup @{ markup1 markup2 ... @}} @tab
873         @code{(markup markup1 markup2 ... )}
874 @item @code{\command} @tab @code{#:command}
875 @item @code{\variable} @tab @code{variable}
876 @item @code{\center-align @{ ... @}} @tab @code{#:center-align ( ... )}
877 @item @code{string} @tab @code{"string"}
878 @item @code{#scheme-arg} @tab @code{scheme-arg}
879 @end multitable
880 @end quotation
881
882 The whole Scheme language is accessible inside the
883 @code{markup} macro.  For example, You may use function calls inside
884 @code{markup} in order to manipulate character strings.  This is
885 useful when defining new markup commands (see
886 @ref{New markup command definition}).
887
888
889 @refbugs
890
891 The markup-list argument of commands such as @code{#:line},
892 @code{#:center}, and @code{#:column} cannot be a variable or
893 the result of a function call.
894
895 @lisp
896 (markup #:line (function-that-returns-markups))
897 @end lisp
898
899 @noindent
900 is invalid.  One should use the @code{make-line-markup},
901 @code{make-center-markup}, or @code{make-column-markup} functions
902 instead,
903
904 @lisp
905 (markup (make-line-markup (function-that-returns-markups)))
906 @end lisp
907
908
909 @node How markups work internally
910 @subsection How markups work internally
911
912 In a markup like
913
914 @example
915 \raise #0.5 "text example"
916 @end example
917
918 @noindent
919 @code{\raise} is actually represented by the @code{raise-markup}
920 function.  The markup expression is stored as
921
922 @example
923 (list raise-markup 0.5 (list simple-markup "text example"))
924 @end example
925
926 When the markup is converted to printable objects (Stencils), the
927 @code{raise-markup} function is called as
928
929 @example
930 (apply raise-markup
931        @var{\layout object}
932        @var{list of property alists}
933        0.5
934        @var{the "text example" markup})
935 @end example
936
937 The @code{raise-markup} function first creates the stencil for the
938 @code{text example} string, and then it raises that Stencil by 0.5
939 staff space.  This is a rather simple example; more complex examples
940 are in the rest
941 of this section, and in @file{scm/@/define@/-markup@/-commands@/.scm}.
942
943
944 @node New markup command definition
945 @subsection New markup command definition
946
947 New markup commands can be defined
948 with the @code{define-markup-command} Scheme macro.
949
950 @lisp
951 (define-markup-command (@var{command-name} @var{layout} @var{props} @var{arg1} @var{arg2} ...)
952             (@var{arg1-type?} @var{arg2-type?} ...)
953   ..command body..)
954 @end lisp
955
956 The arguments are
957
958 @table @var
959 @item argi
960 @var{i}th command argument
961 @item argi-type?
962 a type predicate for the i@var{th} argument
963 @item layout
964 the `layout' definition
965 @item props
966 a list of alists, containing all active properties.
967 @end table
968
969 As a simple example, we show how to add a @code{\smallcaps} command,
970 which selects a small caps font.  Normally we could select the
971 small caps font,
972
973 @example
974 \markup @{ \override #'(font-shape . caps) Text-in-caps @}
975 @end example
976
977 @noindent
978 This selects the caps font by setting the @code{font-shape} property to
979 @code{#'caps} for interpreting @code{Text-in-caps}.
980
981 To make the above available as @code{\smallcaps} command, we must
982 define a function using @code{define-markup-command}.  The command should
983 take a single argument of type @code{markup}.  Therefore the start of the
984 definition should read
985
986 @example
987 (define-markup-command (smallcaps layout props argument) (markup?)
988 @end example
989
990 @noindent
991
992 What follows is the content of the command: we should interpret
993 the @code{argument} as a markup, i.e.,
994
995 @example
996 (interpret-markup layout @dots{} argument)
997 @end example
998
999 @noindent
1000 This interpretation should add @code{'(font-shape . caps)} to the active
1001 properties, so we substitute the following for the @dots{} in the
1002 above example:
1003
1004 @example
1005 (cons (list '(font-shape . caps) ) props)
1006 @end example
1007
1008 @noindent
1009 The variable @code{props} is a list of alists, and we prepend to it by
1010 cons'ing a list with the extra setting.
1011
1012
1013 Suppose that we are typesetting a recitative in an opera and
1014 we would like to define a command that will show character names in a
1015 custom manner.  Names should be printed with small caps and moved a
1016 bit to the left and top.  We will define a @code{\character} command
1017 which takes into account the necessary translation and uses the newly
1018 defined @code{\smallcaps} command:
1019
1020 @example
1021 #(define-markup-command (character layout props name) (string?)
1022   "Print the character name in small caps, translated to the left and
1023   top.  Syntax: \\character #\"name\""
1024   (interpret-markup layout props
1025    (markup #:hspace 0 #:translate (cons -3 1) #:smallcaps name)))
1026 @end example
1027
1028 There is one complication that needs explanation: texts above and below
1029 the staff are moved vertically to be at a certain distance (the
1030 @code{padding} property) from the staff and the notes.  To make sure
1031 that this mechanism does not annihilate the vertical effect of our
1032 @code{#:translate}, we add an empty string (@code{#:hspace 0}) before the
1033 translated text.  Now the @code{#:hspace 0} will be put above the notes,
1034 and the
1035 @code{name} is moved in relation to that empty string.  The net effect is
1036 that the text is moved to the upper left.
1037
1038 The final result is as follows:
1039
1040 @example
1041 @{
1042   c''^\markup \character #"Cleopatra"
1043   e'^\markup \character #"Giulio Cesare"
1044 @}
1045 @end example
1046
1047 @lilypond[quote,ragged-right]
1048 #(define-markup-command (smallcaps layout props str) (string?)
1049   "Print the string argument in small caps.  Syntax: \\smallcaps #\"string\""
1050   (interpret-markup layout props
1051    (make-line-markup
1052     (map (lambda (s)
1053           (if (= (string-length s) 0)
1054               s
1055               (markup #:large (string-upcase (substring s 0 1))
1056                       #:translate (cons -0.6 0)
1057                       #:tiny (string-upcase (substring s 1)))))
1058          (string-split str #\Space)))))
1059
1060 #(define-markup-command (character layout props name) (string?)
1061   "Print the character name in small caps, translated to the left and
1062   top.  Syntax: \\character #\"name\""
1063   (interpret-markup layout props
1064    (markup #:hspace 0 #:translate (cons -3 1) #:smallcaps name)))
1065
1066 {
1067   c''^\markup \character #"Cleopatra" c'' c'' c''
1068   e'^\markup \character #"Giulio Cesare" e' e' e'
1069 }
1070 @end lilypond
1071
1072 We have used the @code{caps} font shape, but suppose that our font
1073 does not have a small-caps variant.  In that case we have to fake
1074 the small caps font by setting a string in upcase with the first
1075 letter a little larger:
1076
1077 @example
1078 #(define-markup-command (smallcaps layout props str) (string?)
1079   "Print the string argument in small caps."
1080   (interpret-markup layout props
1081    (make-line-markup
1082     (map (lambda (s)
1083           (if (= (string-length s) 0)
1084               s
1085               (markup #:large (string-upcase (substring s 0 1))
1086                       #:translate (cons -0.6 0)
1087                       #:tiny (string-upcase (substring s 1)))))
1088          (string-split str #\Space)))))
1089 @end example
1090
1091 The @code{smallcaps} command first splits its string argument into
1092 tokens separated by spaces (@code{(string-split str #\Space)}); for
1093 each token, a markup is built with the first letter made large and
1094 upcased (@code{#:large (string-upcase (substring s 0 1))}), and a
1095 second markup built with the following letters made tiny and upcased
1096 (@code{#:tiny (string-upcase (substring s 1))}).  As LilyPond
1097 introduces a space between markups on a line, the second markup is
1098 translated to the left (@code{#:translate (cons -0.6 0) ...}).  Then,
1099 the markups built for each token are put in a line by
1100 @code{(make-line-markup ...)}.  Finally, the resulting markup is passed
1101 to the @code{interpret-markup} function, with the @code{layout} and
1102 @code{props} arguments.
1103
1104 Note: there is now an internal command @code{\smallCaps} which can
1105 be used to set text in small caps.  See
1106 @ref{Overview of text markup commands} for details.
1107
1108
1109
1110 @node Contexts for programmers
1111 @section Contexts for programmers
1112
1113 @menu
1114 * Context evaluation::          
1115 * Running a function on all layout objects::  
1116 @end menu
1117
1118 @node Context evaluation
1119 @subsection Context evaluation
1120
1121 @cindex calling code during interpreting
1122 @funindex \applyContext
1123
1124 Contexts can be modified during interpretation with Scheme code.  The
1125 syntax for this is
1126 @example
1127 \applyContext @var{function}
1128 @end example
1129
1130 @var{function} should be a Scheme function taking a single argument,
1131 being the context to apply it to.  The following code will print the
1132 current bar number on the standard output during the compile:
1133
1134 @example
1135 \applyContext
1136   #(lambda (x)
1137     (format #t "\nWe were called in barnumber ~a.\n"
1138      (ly:context-property x 'currentBarNumber)))
1139 @end example
1140
1141
1142
1143 @node Running a function on all layout objects
1144 @subsection Running a function on all layout objects
1145
1146
1147 @cindex calling code on layout objects
1148 @funindex \applyOutput
1149
1150
1151 The most versatile way of tuning an object is @code{\applyOutput}.  Its
1152 syntax is
1153 @example
1154 \applyOutput @var{context} @var{proc}
1155 @end example
1156
1157 @noindent
1158 where @var{proc} is a Scheme function, taking three arguments.
1159
1160 When interpreted, the function @var{proc} is called for every layout
1161 object found in the context @var{context}, with the following
1162 arguments:
1163 @itemize @bullet
1164 @item the layout object itself,
1165 @item the context where the layout object was created, and
1166 @item the context where @code{\applyOutput} is processed.
1167 @end itemize
1168
1169
1170 In addition, the cause of the layout object, i.e., the music
1171 expression or object that was responsible for creating it, is in the
1172 object property @code{cause}.  For example, for a note head, this is a
1173 @internalsref{NoteHead} event, and for a @internalsref{Stem} object,
1174 this is a @internalsref{NoteHead} object.
1175
1176 Here is a function to use for @code{\applyOutput}; it blanks
1177 note-heads on the center-line:
1178
1179 @example
1180 (define (blanker grob grob-origin context)
1181  (if (and (memq (ly:grob-property grob 'interfaces)
1182                 note-head-interface)
1183           (eq? (ly:grob-property grob 'staff-position) 0))
1184      (set! (ly:grob-property grob 'transparent) #t)))
1185 @end example
1186
1187
1188 @node Scheme procedures as properties
1189 @section Scheme procedures as properties
1190
1191 Properties (like thickness, direction, etc.) can be set at fixed values
1192 with \override, e.g.
1193
1194 @example
1195 \override Stem #'thickness = #2.0
1196 @end example
1197
1198 Properties can also be set to a Scheme procedure,
1199
1200 @lilypond[fragment,verbatim,quote,relative=2]
1201 \override Stem #'thickness = #(lambda (grob)
1202     (if (= UP (ly:grob-property grob 'direction))
1203         2.0
1204         7.0))
1205 c b a g b a g b
1206 @end lilypond
1207
1208 @noindent
1209 In this case, the procedure is executed as soon as the value of the
1210 property is requested during the formatting process.
1211
1212 Most of the typesetting engine is driven by such callbacks.
1213 Properties that typically use callbacks include  
1214
1215 @table @code
1216 @item stencil
1217   The printing routine, that constructs a drawing for the symbol
1218 @item X-offset
1219   The routine that sets the horizontal position
1220 @item X-extent
1221   The routine that computes the width of an object
1222 @end table
1223
1224 The procedure always takes a single argument, being the grob.
1225
1226 If routines with multiple arguments must be called, the current grob
1227 can be inserted with a grob closure.  Here is a setting from
1228 @code{AccidentalSuggestion},
1229
1230 @example
1231 (X-offset .
1232   ,(ly:make-simple-closure
1233     `(,+
1234         ,(ly:make-simple-closure
1235            (list ly:self-alignment-interface::centered-on-x-parent))
1236       ,(ly:make-simple-closure
1237            (list ly:self-alignment-interface::x-aligned-on-self)))))
1238 @end example
1239
1240 @noindent
1241 In this example, both @code{ly:self-alignment-interface::x-aligned-on-self} and
1242 @code{ly:self-alignment-interface::centered-on-x-parent} are called
1243 with the grob as argument. The results are added with the @code{+}
1244 function. To ensure that this addition is properly executed, the whole
1245 thing is enclosed in @code{ly:make-simple-closure}.
1246
1247 In fact, using a single procedure as property value is equivalent to
1248
1249 @example
1250 (ly:make-simple-closure (ly:make-simple-closure (list @var{proc})))
1251 @end example
1252
1253 @noindent
1254 The inner @code{ly:make-simple-closure} supplies the grob as argument
1255 to @var{proc}, the outer ensures that result of the function is
1256 returned, rather than the @code{simple-closure} object.