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