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