]> git.donarmstrong.com Git - lilypond.git/blob - Documentation/user/programming-interface.itely
38dbbc0ae5e2e47795a5504d70c5d2dcba5c96ae
[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 @example
296 traLaLa = @{ c'4 d'4 @}
297
298 #(define newLa (map ly:music-deep-copy
299   (list traLaLa traLaLa)))
300 #(define twice
301   (make-sequential-music newLa))
302
303 @{ \twice @}
304 @end example
305
306 In the above example, music expressions can be `exported' from the
307 input to the Scheme interpreter.  The opposite is also possible.  By
308 wrapping a Scheme value in the function @code{ly:export}, a Scheme
309 value is interpreted as if it were entered in LilyPond syntax.  Instead
310 of defining @code{\twice}, the example above could also have been
311 written as
312 @example
313 @dots{}
314 @{ #(ly:export (make-sequential-music (list newLa))) @}
315 @end example
316
317 Scheme code is evaluated as soon as the parser encounters it.  To
318 define some Scheme code in a macro (to be called later), use
319 @ref{Void functions} or
320
321 @example
322 #(define (nopc)
323   (ly:set-option 'point-and-click #f))
324
325 ...
326 #(nopc)
327 @{ c'4 @}
328 @end example
329
330
331 @refbugs
332
333 Mixing Scheme and LilyPond identifiers is not possible with the
334 @code{--safe} option.
335
336
337 @node Internal music representation
338 @subsection Internal music representation
339
340 When a music expression is parsed, it is converted into a set of
341 Scheme music objects.  The defining property of a music object is that
342 it takes up time.  Time is a rational number that measures the length
343 of a piece of music in whole notes.
344
345 A music object has three kinds of types:
346 @itemize @bullet
347 @item
348 music name: Each music expression has a name.  For example, a note
349 leads to a @internalsref{NoteEvent}, and @code{\simultaneous} leads to
350 a @internalsref{SimultaneousMusic}.  A list of all expressions
351 available is in the Program reference manual, under
352 @internalsref{Music expressions}.
353
354 @item
355 `type' or interface: Each music name has several `types' or
356 interfaces, for example, a note is an @code{event}, but it is also a
357 @code{note-event}, a @code{rhythmic-event}, and a
358 @code{melodic-event}.  All classes of music are listed in the
359 Program reference, under
360 @internalsref{Music classes}.
361
362 @item
363 C++ object: Each music object is represented by an object of the C++
364 class @code{Music}.
365 @end itemize
366
367 The actual information of a music expression is stored in properties.
368 For example, a @internalsref{NoteEvent} has @code{pitch} and
369 @code{duration} properties that store the pitch and duration of that
370 note.  A list of all properties available is in the internals manual,
371 under @internalsref{Music properties}.
372
373 A compound music expression is a music object that contains other
374 music objects in its properties.  A list of objects can be stored in
375 the @code{elements} property of a music object, or a single `child'
376 music object in the @code{element} object.  For example,
377 @internalsref{SequentialMusic} has its children in @code{elements},
378 and @internalsref{GraceMusic} has its single argument in
379 @code{element}.  The body of a repeat is stored in the @code{element}
380 property of @internalsref{RepeatedMusic}, and the alternatives in
381 @code{elements}.
382
383
384
385 @node Building complicated functions
386 @section Building complicated functions
387
388 This section explains how to gather the information necessary
389 to create complicated music functions.
390
391 @menu
392 * Displaying music expressions::  
393 * Music properties::            
394 * Doubling a note with slurs (example)::  
395 * Adding articulation to notes (example)::  
396 @end menu
397
398
399 @node Displaying music expressions
400 @subsection Displaying music expressions
401
402 @cindex internal storage
403 @funindex \displayMusic
404 @funindex \displayLilyMusic
405
406 When writing a music function it is often instructive to inspect how
407 a music expression is stored internally.  This can be done with the
408 music function @code{\displayMusic}
409
410 @example
411 @{
412   \displayMusic @{ c'4\f @}
413 @}
414 @end example
415
416 @noindent
417 will display
418
419 @example
420 (make-music
421   'SequentialMusic
422   'elements
423   (list (make-music
424           'EventChord
425           'elements
426           (list (make-music
427                   'NoteEvent
428                   'duration
429                   (ly:make-duration 2 0 1 1)
430                   'pitch
431                   (ly:make-pitch 0 0 0))
432                 (make-music
433                   'AbsoluteDynamicEvent
434                   'text
435                   "f")))))
436 @end example
437
438 By default, LilyPond will print these messages to the console along
439 with all the other messages.  To split up these messages and save
440 the results of @code{\display@{STUFF@}}, redirect the output to
441 a file.
442
443 @example
444 lilypond file.ly >display.txt
445 @end example
446
447 With a bit of reformatting, the above information is
448 easier to read,
449
450 @example
451 (make-music 'SequentialMusic
452   'elements (list (make-music 'EventChord
453                     'elements (list (make-music 'NoteEvent
454                                       'duration (ly:make-duration 2 0 1 1)
455                                       'pitch (ly:make-pitch 0 0 0))
456                                     (make-music 'AbsoluteDynamicEvent
457                                       'text "f")))))
458 @end example
459
460 A @code{@{ ... @}} music sequence has the name @code{SequentialMusic},
461 and its inner expressions are stored as a list in its @code{'elements}
462 property.  A note is represented as an @code{EventChord} expression,
463 containing a @code{NoteEvent} object (storing the duration and
464 pitch properties) and any extra information (in this case, an
465 @code{AbsoluteDynamicEvent} with a @code{"f"} text property.
466
467
468 @node Music properties
469 @subsection Music properties
470
471 The @code{NoteEvent} object is the first object of the
472 @code{'elements} property of @code{someNote}.
473
474 @example
475 someNote = c'
476 \displayMusic \someNote
477 ===>
478 (make-music
479   'EventChord
480   'elements
481   (list (make-music
482           'NoteEvent
483           'duration
484           (ly:make-duration 2 0 1 1)
485           'pitch
486           (ly:make-pitch 0 0 0))))
487 @end example
488
489 The @code{display-scheme-music} function is the function used by
490 @code{\displayMusic} to display the Scheme representation of a music
491 expression.
492
493 @example
494 #(display-scheme-music (first (ly:music-property someNote 'elements)))
495 ===>
496 (make-music
497   'NoteEvent
498   'duration
499   (ly:make-duration 2 0 1 1)
500   'pitch
501   (ly:make-pitch 0 0 0))
502 @end example
503
504 Then the note pitch is accessed through the @code{'pitch} property
505 of the @code{NoteEvent} object,
506
507 @example
508 #(display-scheme-music
509    (ly:music-property (first (ly:music-property someNote 'elements))
510                       'pitch))
511 ===>
512 (ly:make-pitch 0 0 0)
513 @end example
514
515 The note pitch can be changed by setting this 'pitch property,
516
517 @example
518 #(set! (ly:music-property (first (ly:music-property someNote 'elements))
519                           'pitch)
520        (ly:make-pitch 0 1 0)) ;; set the pitch to d'.
521 \displayLilyMusic \someNote
522 ===>
523 d'
524 @end example
525
526
527 @node Doubling a note with slurs (example)
528 @subsection Doubling a note with slurs (example)
529
530 Suppose we want to create a function which translates
531 input like ``@code{a}'' into ``@code{a( a)}''.  We begin
532 by examining the internal representation of the music
533 we want to end up with.
534
535 @example
536 \displayMusic@{ a'( a') @}
537 ===>
538 (make-music
539   'SequentialMusic
540   'elements
541   (list (make-music
542           'EventChord
543           'elements
544           (list (make-music
545                   'NoteEvent
546                   'duration
547                   (ly:make-duration 2 0 1 1)
548                   'pitch
549                   (ly:make-pitch 0 5 0))
550                 (make-music
551                   'SlurEvent
552                   'span-direction
553                   -1)))
554         (make-music
555           'EventChord
556           'elements
557           (list (make-music
558                   'NoteEvent
559                   'duration
560                   (ly:make-duration 2 0 1 1)
561                   'pitch
562                   (ly:make-pitch 0 5 0))
563                 (make-music
564                   'SlurEvent
565                   'span-direction
566                   1)))))
567 @end example
568
569 The bad news is that the @code{SlurEvent} expressions
570 must be added ``inside'' the note (or more precisely,
571 inside the @code{EventChord} expression).
572
573 Now we examine the input,
574
575 @example
576 (make-music
577   'SequentialMusic
578   'elements
579   (list (make-music
580           'EventChord
581           'elements
582           (list (make-music
583                   'NoteEvent
584                   'duration
585                   (ly:make-duration 2 0 1 1)
586                   'pitch
587                   (ly:make-pitch 0 5 0))))))
588 @end example
589
590 So in our function, we need to clone this expression (so that we
591 have two notes to build the sequence), add @code{SlurEvents} to the
592 @code{'elements} property of each one, and finally make a
593 @code{SequentialMusic} with the two @code{EventChords}.
594
595 @example
596 doubleSlur = #(define-music-function (parser location note) (ly:music?)
597          "Return: @{ note ( note ) @}.
598          `note' is supposed to be an EventChord."
599          (let ((note2 (ly:music-deep-copy note)))
600            (set! (ly:music-property note 'elements)
601                  (cons (make-music 'SlurEvent 'span-direction -1)
602                        (ly:music-property note 'elements)))
603            (set! (ly:music-property note2 'elements)
604                  (cons (make-music 'SlurEvent 'span-direction 1)
605                        (ly:music-property note2 'elements)))
606            (make-music 'SequentialMusic 'elements (list note note2))))
607 @end example
608
609
610 @node Adding articulation to notes (example)
611 @subsection Adding articulation to notes (example)
612
613 The easy way to add articulation to notes is to merge two music
614 expressions into one context, as explained in
615 @ref{Creating contexts}.  However, suppose that we want to write
616 a music function which does this.
617
618 A @code{$variable} inside the @code{#@{...#@}} notation is like
619 using a regular @code{\variable} in classical LilyPond
620 notation.  We know that
621
622 @example
623 @{ \music -. -> @}
624 @end example
625
626 @noindent
627 will not work in LilyPond.  We could avoid this problem by attaching
628 the articulation to a fake note,
629
630 @example
631 @{ << \music s1*0-.-> @}
632 @end example
633
634 @noindent
635 but for the sake of this example, we will learn how to do this in
636 Scheme.  We begin by examining our input and desired output,
637
638 @example
639 %  input
640 \displayMusic c4
641 ===>
642 (make-music
643   'EventChord
644   'elements
645   (list (make-music
646           'NoteEvent
647           'duration
648           (ly:make-duration 2 0 1 1)
649           'pitch
650           (ly:make-pitch -1 0 0))))
651 =====
652 %  desired output
653 \displayMusic c4->
654 ===>
655 (make-music
656   'EventChord
657   'elements
658   (list (make-music
659           'NoteEvent
660           'duration
661           (ly:make-duration 2 0 1 1)
662           'pitch
663           (ly:make-pitch -1 0 0))
664         (make-music
665           'ArticulationEvent
666           'articulation-type
667           "marcato")))
668 @end example
669
670 We see that a note (@code{c4}) is represented as an @code{EventChord}
671 expression, with a @code{NoteEvent} expression in its elements list.  To
672 add a marcato articulation, an @code{ArticulationEvent} expression must
673 be added to the elements property of the @code{EventChord}
674 expression.
675
676 To build this function, we begin with
677
678 @example
679 (define (add-marcato event-chord)
680   "Add a marcato ArticulationEvent to the elements of `event-chord',
681   which is supposed to be an EventChord expression."
682   (let ((result-event-chord (ly:music-deep-copy event-chord)))
683     (set! (ly:music-property result-event-chord 'elements)
684           (cons (make-music 'ArticulationEvent
685                   'articulation-type "marcato")
686                 (ly:music-property result-event-chord 'elements)))
687     result-event-chord))
688 @end example
689
690 The first line is the way to define a function in Scheme: the function
691 name is @code{add-marcato}, and has one variable called
692 @code{event-chord}.  In Scheme, the type of variable is often clear
693 from its name.  (this is good practice in other programming languages,
694 too!)
695
696 @example
697 "Add a marcato..."
698 @end example
699
700 @noindent
701 is a description of what the function does.  This is not strictly
702 necessary, but just like clear variable names, it is good practice.
703
704 @example
705 (let ((result-event-chord (ly:music-deep-copy event-chord)))
706 @end example
707
708 `@code{let}' is used to declare local variables.  Here we use one local
709 variable, named `@code{result-event-chord}', to which we give the value
710 @code{(ly:music-deep-copy event-chord)}.  `@code{ly:music-deep-copy}' is
711 a function specific to LilyPond, like all functions prefixed by
712 `@code{ly:}'.  It is use to make a copy of a music
713 expression.  Here we copy `@code{event-chord} (the parameter of the
714 function).  Recall that our purpose is to add a marcato to an
715 @code{EventChord} expression.  It is better to not modify the
716 @code{EventChord} which was given as an argument, because it may be
717 used elsewhere.
718
719 Now we have a @code{result-event-chord}, which is a
720 @code{NoteEventChord} expression and is a copy of @code{event-chord}.  We
721 add the marcato to its elements list property.
722
723 @example
724 (set! place new-value)
725 @end example
726
727 Here, what we want to set (the "place") is the "elements" property of
728 @code{result-event-chord} expression
729
730 @example
731 (ly:music-property result-event-chord 'elements)
732 @end example
733
734 @code{ly:music-property} is the function used to access music properties
735 (the @code{'elements}, @code{'duration}, @code{'pitch}, etc, that we
736 see in the @code{\displayMusic} output above).  The new value is the
737 former elements property, with an extra item: the
738 @code{MarcatoEvent} expression, which we copy from the
739 @code{\displayMusic} output,
740
741 @example
742 (cons (make-music 'ArticulationEvent
743         'articulation-type "marcato")
744       (ly:music-property result-event-chord 'elements))
745 @end example
746
747 `@code{cons}' is used to add an element to a list without modifying the
748 original list.  This is what we
749 want: the same list as before, plus the new @code{ArticulationEvent}
750 expression.  The order inside the elements property is not important here.
751
752 Finally, once we have added the @code{MarcatoEvent} to its elements
753 property, we can return @code{result-event-chord}, hence the last line of
754 the function.
755
756 Now we transform the @code{add-marcato} function into a music
757 function,
758
759 @example
760 addMarcato = #(define-music-function (parser location event-chord)
761                                      (ly:music?)
762     "Add a marcato ArticulationEvent to the elements of `event-chord',
763     which is supposed to be an EventChord expression."
764     (let ((result-event-chord (ly:music-deep-copy event-chord)))
765       (set! (ly:music-property result-event-chord 'elements)
766             (cons (make-music 'ArticulationEvent
767                     'articulation-type "marcato")
768                   (ly:music-property result-event-chord 'elements)))
769       result-event-chord))
770 @end example
771
772 We may verify that this music function works correctly,
773
774 @example
775 \displayMusic \addMarcato c4
776 @end example
777
778
779 @node Markup programmer interface
780 @section Markup programmer interface
781
782 Markups are implemented as special Scheme functions which produce a
783 Stencil object given a number of arguments.
784
785 @menu
786 * Markup construction in Scheme::  
787 * How markups work internally::  
788 * New markup command definition::  
789 @end menu
790
791
792 @node Markup construction in Scheme
793 @subsection Markup construction in Scheme
794
795 @cindex defining markup commands
796
797 The @code{markup} macro builds markup expressions in Scheme while
798 providing a LilyPond-like syntax.  For example,
799 @example
800 (markup #:column (#:line (#:bold #:italic "hello" #:raise 0.4 "world")
801                   #:bigger #:line ("foo" "bar" "baz")))
802 @end example
803
804 @noindent
805 is equivalent to:
806 @example
807 \markup \column @{ \line @{ \bold \italic "hello" \raise #0.4 "world" @}
808                   \bigger \line @{ foo bar baz @} @}
809 @end example
810
811 @noindent
812 This example demonstrates the main translation rules between regular
813 LilyPond markup syntax and Scheme markup syntax.
814
815 @quotation
816 @multitable @columnfractions .3 .3
817 @item @b{LilyPond} @tab @b{Scheme}
818 @item @code{\markup markup1} @tab @code{(markup markup1)}
819 @item @code{\markup @{ markup1 markup2 ... @}} @tab
820         @code{(markup markup1 markup2 ... )}
821 @item @code{\command} @tab @code{#:command}
822 @item @code{\variable} @tab @code{variable}
823 @item @code{\center-align @{ ... @}} @tab @code{#:center-align ( ... )}
824 @item @code{string} @tab @code{"string"}
825 @item @code{#scheme-arg} @tab @code{scheme-arg}
826 @end multitable
827 @end quotation
828
829 The whole Scheme language is accessible inside the
830 @code{markup} macro.  For example, You may use function calls inside
831 @code{markup} in order to manipulate character strings.  This is
832 useful when defining new markup commands (see
833 @ref{New markup command definition}).
834
835
836 @refbugs
837
838 The markup-list argument of commands such as @code{#:line},
839 @code{#:center}, and @code{#:column} cannot be a variable or
840 the result of a function call.
841
842 @lisp
843 (markup #:line (function-that-returns-markups))
844 @end lisp
845
846 @noindent
847 is invalid.  One should use the @code{make-line-markup},
848 @code{make-center-markup}, or @code{make-column-markup} functions
849 instead,
850
851 @lisp
852 (markup (make-line-markup (function-that-returns-markups)))
853 @end lisp
854
855
856 @node How markups work internally
857 @subsection How markups work internally
858
859 In a markup like
860
861 @example
862 \raise #0.5 "text example"
863 @end example
864
865 @noindent
866 @code{\raise} is actually represented by the @code{raise-markup}
867 function.  The markup expression is stored as
868
869 @example
870 (list raise-markup 0.5 (list simple-markup "text example"))
871 @end example
872
873 When the markup is converted to printable objects (Stencils), the
874 @code{raise-markup} function is called as
875
876 @example
877 (apply raise-markup
878        @var{\layout object}
879        @var{list of property alists}
880        0.5
881        @var{the "text example" markup})
882 @end example
883
884 The @code{raise-markup} function first creates the stencil for the
885 @code{text example} string, and then it raises that Stencil by 0.5
886 staff space.  This is a rather simple example; more complex examples
887 are in the rest
888 of this section, and in @file{scm/@/define@/-markup@/-commands@/.scm}.
889
890
891 @node New markup command definition
892 @subsection New markup command definition
893
894 New markup commands can be defined
895 with the @code{define-markup-command} Scheme macro.
896
897 @lisp
898 (define-markup-command (@var{command-name} @var{layout} @var{props} @var{arg1} @var{arg2} ...)
899             (@var{arg1-type?} @var{arg2-type?} ...)
900   ..command body..)
901 @end lisp
902
903 The arguments are
904
905 @table @var
906 @item argi
907 @var{i}th command argument
908 @item argi-type?
909 a type predicate for the i@var{th} argument
910 @item layout
911 the `layout' definition
912 @item props
913 a list of alists, containing all active properties.
914 @end table
915
916 As a simple example, we show how to add a @code{\smallcaps} command,
917 which selects a small caps font.  Normally we could select the
918 small caps font,
919
920 @example
921 \markup @{ \override #'(font-shape . caps) Text-in-caps @}
922 @end example
923
924 @noindent
925 This selects the caps font by setting the @code{font-shape} property to
926 @code{#'caps} for interpreting @code{Text-in-caps}.
927
928 To make the above available as @code{\smallcaps} command, we must
929 define a function using @code{define-markup-command}.  The command should
930 take a single argument of type @code{markup}.  Therefore the start of the
931 definition should read
932
933 @example
934 (define-markup-command (smallcaps layout props argument) (markup?)
935 @end example
936
937 @noindent
938
939 What follows is the content of the command: we should interpret
940 the @code{argument} as a markup, i.e.,
941
942 @example
943 (interpret-markup layout @dots{} argument)
944 @end example
945
946 @noindent
947 This interpretation should add @code{'(font-shape . caps)} to the active
948 properties, so we substitute the following for the @dots{} in the
949 above example:
950
951 @example
952 (cons (list '(font-shape . caps) ) props)
953 @end example
954
955 @noindent
956 The variable @code{props} is a list of alists, and we prepend to it by
957 cons'ing a list with the extra setting.
958
959
960 Suppose that we are typesetting a recitative in an opera and
961 we would like to define a command that will show character names in a
962 custom manner.  Names should be printed with small caps and moved a
963 bit to the left and top.  We will define a @code{\character} command
964 which takes into account the necessary translation and uses the newly
965 defined @code{\smallcaps} command:
966
967 @example
968 #(define-markup-command (character layout props name) (string?)
969   "Print the character name in small caps, translated to the left and
970   top.  Syntax: \\character #\"name\""
971   (interpret-markup layout props
972    (markup #:hspace 0 #:translate (cons -3 1) #:smallcaps name)))
973 @end example
974
975 There is one complication that needs explanation: texts above and below
976 the staff are moved vertically to be at a certain distance (the
977 @code{padding} property) from the staff and the notes.  To make sure
978 that this mechanism does not annihilate the vertical effect of our
979 @code{#:translate}, we add an empty string (@code{#:hspace 0}) before the
980 translated text.  Now the @code{#:hspace 0} will be put above the notes,
981 and the
982 @code{name} is moved in relation to that empty string.  The net effect is
983 that the text is moved to the upper left.
984
985 The final result is as follows:
986
987 @example
988 @{
989   c''^\markup \character #"Cleopatra"
990   e'^\markup \character #"Giulio Cesare"
991 @}
992 @end example
993
994 @lilypond[quote,ragged-right]
995 #(define-markup-command (smallcaps layout props str) (string?)
996   "Print the string argument in small caps.  Syntax: \\smallcaps #\"string\""
997   (interpret-markup layout props
998    (make-line-markup
999     (map (lambda (s)
1000           (if (= (string-length s) 0)
1001               s
1002               (markup #:large (string-upcase (substring s 0 1))
1003                       #:translate (cons -0.6 0)
1004                       #:tiny (string-upcase (substring s 1)))))
1005          (string-split str #\Space)))))
1006
1007 #(define-markup-command (character layout props name) (string?)
1008   "Print the character name in small caps, translated to the left and
1009   top.  Syntax: \\character #\"name\""
1010   (interpret-markup layout props
1011    (markup #:hspace 0 #:translate (cons -3 1) #:smallcaps name)))
1012
1013 {
1014   c''^\markup \character #"Cleopatra" c'' c'' c''
1015   e'^\markup \character #"Giulio Cesare" e' e' e'
1016 }
1017 @end lilypond
1018
1019 We have used the @code{caps} font shape, but suppose that our font
1020 does not have a small-caps variant.  In that case we have to fake
1021 the small caps font by setting a string in upcase with the first
1022 letter a little larger:
1023
1024 @example
1025 #(define-markup-command (smallcaps layout props str) (string?)
1026   "Print the string argument in small caps."
1027   (interpret-markup layout props
1028    (make-line-markup
1029     (map (lambda (s)
1030           (if (= (string-length s) 0)
1031               s
1032               (markup #:large (string-upcase (substring s 0 1))
1033                       #:translate (cons -0.6 0)
1034                       #:tiny (string-upcase (substring s 1)))))
1035          (string-split str #\Space)))))
1036 @end example
1037
1038 The @code{smallcaps} command first splits its string argument into
1039 tokens separated by spaces (@code{(string-split str #\Space)}); for
1040 each token, a markup is built with the first letter made large and
1041 upcased (@code{#:large (string-upcase (substring s 0 1))}), and a
1042 second markup built with the following letters made tiny and upcased
1043 (@code{#:tiny (string-upcase (substring s 1))}).  As LilyPond
1044 introduces a space between markups on a line, the second markup is
1045 translated to the left (@code{#:translate (cons -0.6 0) ...}).  Then,
1046 the markups built for each token are put in a line by
1047 @code{(make-line-markup ...)}.  Finally, the resulting markup is passed
1048 to the @code{interpret-markup} function, with the @code{layout} and
1049 @code{props} arguments.
1050
1051 Note: there is now an internal command @code{\smallCaps} which can
1052 be used to set text in small caps.  See
1053 @ref{Overview of text markup commands} for details.
1054
1055
1056
1057 @node Contexts for programmers
1058 @section Contexts for programmers
1059
1060 @menu
1061 * Context evaluation::          
1062 * Running a function on all layout objects::  
1063 @end menu
1064
1065 @node Context evaluation
1066 @subsection Context evaluation
1067
1068 @cindex calling code during interpreting
1069 @funindex \applyContext
1070
1071 Contexts can be modified during interpretation with Scheme code.  The
1072 syntax for this is
1073 @example
1074 \applyContext @var{function}
1075 @end example
1076
1077 @var{function} should be a Scheme function taking a single argument,
1078 being the context to apply it to.  The following code will print the
1079 current bar number on the standard output during the compile:
1080
1081 @example
1082 \applyContext
1083   #(lambda (x)
1084     (format #t "\nWe were called in barnumber ~a.\n"
1085      (ly:context-property x 'currentBarNumber)))
1086 @end example
1087
1088
1089
1090 @node Running a function on all layout objects
1091 @subsection Running a function on all layout objects
1092
1093
1094 @cindex calling code on layout objects
1095 @funindex \applyOutput
1096
1097
1098 The most versatile way of tuning an object is @code{\applyOutput}.  Its
1099 syntax is
1100 @example
1101 \applyOutput @var{context} @var{proc}
1102 @end example
1103
1104 @noindent
1105 where @var{proc} is a Scheme function, taking three arguments.
1106
1107 When interpreted, the function @var{proc} is called for every layout
1108 object found in the context @var{context}, with the following
1109 arguments:
1110 @itemize @bullet
1111 @item the layout object itself,
1112 @item the context where the layout object was created, and
1113 @item the context where @code{\applyOutput} is processed.
1114 @end itemize
1115
1116
1117 In addition, the cause of the layout object, i.e., the music
1118 expression or object that was responsible for creating it, is in the
1119 object property @code{cause}.  For example, for a note head, this is a
1120 @internalsref{NoteHead} event, and for a @internalsref{Stem} object,
1121 this is a @internalsref{NoteHead} object.
1122
1123 Here is a function to use for @code{\applyOutput}; it blanks
1124 note-heads on the center-line:
1125
1126 @example
1127 (define (blanker grob grob-origin context)
1128  (if (and (memq (ly:grob-property grob 'interfaces)
1129                 note-head-interface)
1130           (eq? (ly:grob-property grob 'staff-position) 0))
1131      (set! (ly:grob-property grob 'transparent) #t)))
1132 @end example
1133
1134
1135 @node Scheme procedures as properties
1136 @section Scheme procedures as properties
1137
1138 Properties (like thickness, direction, etc.) can be set at fixed values
1139 with \override, e.g.
1140
1141 @example
1142 \override Stem #'thickness = #2.0
1143 @end example
1144
1145 Properties can also be set to a Scheme procedure,
1146
1147 @lilypond[fragment,verbatim,quote,relative=2]
1148 \override Stem #'thickness = #(lambda (grob)
1149     (if (= UP (ly:grob-property grob 'direction))
1150         2.0
1151         7.0))
1152 c b a g b a g b
1153 @end lilypond
1154
1155 Procedures may also be combined like that with
1156 "grob closure".  Here is a setting from
1157 @code{AccidentalSuggestion},
1158
1159 @example
1160 (X-offset .
1161   ,(ly:make-simple-closure
1162     `(,+
1163         ,(ly:make-simple-closure
1164            (list ly:self-alignment-interface::centered-on-x-parent))
1165       ,(ly:make-simple-closure
1166            (list ly:self-alignment-interface::x-aligned-on-self)))))
1167 @end example
1168
1169