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