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