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