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