]> git.donarmstrong.com Git - lilypond.git/blob - Documentation/user/programming-interface.itely
Merge with master
[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 @ref{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 identifier,
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 identifiers 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 "place") is the "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{MarcatoEvent} 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 @code{MarcatoEvent} to its 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 @end menu
851
852
853 @node Markup construction in Scheme
854 @subsection Markup construction in Scheme
855
856 @cindex defining markup commands
857
858 The @code{markup} macro builds markup expressions in Scheme while
859 providing a LilyPond-like syntax.  For example,
860 @example
861 (markup #:column (#:line (#:bold #:italic "hello" #:raise 0.4 "world")
862                   #:bigger #:line ("foo" "bar" "baz")))
863 @end example
864
865 @noindent
866 is equivalent to:
867 @example
868 \markup \column @{ \line @{ \bold \italic "hello" \raise #0.4 "world" @}
869                   \bigger \line @{ foo bar baz @} @}
870 @end example
871
872 @noindent
873 This example demonstrates the main translation rules between regular
874 LilyPond markup syntax and Scheme markup syntax.
875
876 @quotation
877 @multitable @columnfractions .3 .3
878 @item @b{LilyPond} @tab @b{Scheme}
879 @item @code{\markup markup1} @tab @code{(markup markup1)}
880 @item @code{\markup @{ markup1 markup2 ... @}} @tab
881         @code{(markup markup1 markup2 ... )}
882 @item @code{\command} @tab @code{#:command}
883 @item @code{\variable} @tab @code{variable}
884 @item @code{\center-align @{ ... @}} @tab @code{#:center-align ( ... )}
885 @item @code{string} @tab @code{"string"}
886 @item @code{#scheme-arg} @tab @code{scheme-arg}
887 @end multitable
888 @end quotation
889
890 The whole Scheme language is accessible inside the
891 @code{markup} macro.  For example, You may use function calls inside
892 @code{markup} in order to manipulate character strings.  This is
893 useful when defining new markup commands (see
894 @ref{New markup command definition}).
895
896
897 @refbugs
898
899 The markup-list argument of commands such as @code{#:line},
900 @code{#:center}, and @code{#:column} cannot be a variable or
901 the result of a function call.
902
903 @lisp
904 (markup #:line (function-that-returns-markups))
905 @end lisp
906
907 @noindent
908 is invalid.  One should use the @code{make-line-markup},
909 @code{make-center-markup}, or @code{make-column-markup} functions
910 instead,
911
912 @lisp
913 (markup (make-line-markup (function-that-returns-markups)))
914 @end lisp
915
916
917 @node How markups work internally
918 @subsection How markups work internally
919
920 In a markup like
921
922 @example
923 \raise #0.5 "text example"
924 @end example
925
926 @noindent
927 @code{\raise} is actually represented by the @code{raise-markup}
928 function.  The markup expression is stored as
929
930 @example
931 (list raise-markup 0.5 (list simple-markup "text example"))
932 @end example
933
934 When the markup is converted to printable objects (Stencils), the
935 @code{raise-markup} function is called as
936
937 @example
938 (apply raise-markup
939        @var{\layout object}
940        @var{list of property alists}
941        0.5
942        @var{the "text example" markup})
943 @end example
944
945 The @code{raise-markup} function first creates the stencil for the
946 @code{text example} string, and then it raises that Stencil by 0.5
947 staff space.  This is a rather simple example; more complex examples
948 are in the rest
949 of this section, and in @file{scm/@/define@/-markup@/-commands@/.scm}.
950
951
952 @node New markup command definition
953 @subsection New markup command definition
954
955 New markup commands can be defined
956 with the @code{define-markup-command} Scheme macro.
957
958 @lisp
959 (define-markup-command (@var{command-name} @var{layout} @var{props} @var{arg1} @var{arg2} ...)
960             (@var{arg1-type?} @var{arg2-type?} ...)
961   ..command body..)
962 @end lisp
963
964 The arguments are
965
966 @table @var
967 @item argi
968 @var{i}th command argument
969 @item argi-type?
970 a type predicate for the i@var{th} argument
971 @item layout
972 the @q{layout} definition
973 @item props
974 a list of alists, containing all active properties.
975 @end table
976
977 As a simple example, we show how to add a @code{\smallcaps} command,
978 which selects a small caps font.  Normally we could select the
979 small caps font,
980
981 @example
982 \markup @{ \override #'(font-shape . caps) Text-in-caps @}
983 @end example
984
985 @noindent
986 This selects the caps font by setting the @code{font-shape} property to
987 @code{#'caps} for interpreting @code{Text-in-caps}.
988
989 To make the above available as @code{\smallcaps} command, we must
990 define a function using @code{define-markup-command}.  The command should
991 take a single argument of type @code{markup}.  Therefore the start of the
992 definition should read
993
994 @example
995 (define-markup-command (smallcaps layout props argument) (markup?)
996 @end example
997
998 @noindent
999
1000 What follows is the content of the command: we should interpret
1001 the @code{argument} as a markup, i.e.,
1002
1003 @example
1004 (interpret-markup layout @dots{} argument)
1005 @end example
1006
1007 @noindent
1008 This interpretation should add @code{'(font-shape . caps)} to the active
1009 properties, so we substitute the following for the @dots{} in the
1010 above example:
1011
1012 @example
1013 (cons (list '(font-shape . caps) ) props)
1014 @end example
1015
1016 @noindent
1017 The variable @code{props} is a list of alists, and we prepend to it by
1018 cons'ing a list with the extra setting.
1019
1020
1021 Suppose that we are typesetting a recitative in an opera and
1022 we would like to define a command that will show character names in a
1023 custom manner.  Names should be printed with small caps and moved a
1024 bit to the left and top.  We will define a @code{\character} command
1025 which takes into account the necessary translation and uses the newly
1026 defined @code{\smallcaps} command:
1027
1028 @example
1029 #(define-markup-command (character layout props name) (string?)
1030   "Print the character name in small caps, translated to the left and
1031   top.  Syntax: \\character #\"name\""
1032   (interpret-markup layout props
1033    (markup #:hspace 0 #:translate (cons -3 1) #:smallcaps name)))
1034 @end example
1035
1036 There is one complication that needs explanation: texts above and below
1037 the staff are moved vertically to be at a certain distance (the
1038 @code{padding} property) from the staff and the notes.  To make sure
1039 that this mechanism does not annihilate the vertical effect of our
1040 @code{#:translate}, we add an empty string (@code{#:hspace 0}) before the
1041 translated text.  Now the @code{#:hspace 0} will be put above the notes,
1042 and the
1043 @code{name} is moved in relation to that empty string.  The net effect is
1044 that the text is moved to the upper left.
1045
1046 The final result is as follows:
1047
1048 @example
1049 @{
1050   c''^\markup \character #"Cleopatra"
1051   e'^\markup \character #"Giulio Cesare"
1052 @}
1053 @end example
1054
1055 @lilypond[quote,ragged-right]
1056 #(define-markup-command (smallcaps layout props str) (string?)
1057   "Print the string argument in small caps.  Syntax: \\smallcaps #\"string\""
1058   (interpret-markup layout props
1059    (make-line-markup
1060     (map (lambda (s)
1061           (if (= (string-length s) 0)
1062               s
1063               (markup #:large (string-upcase (substring s 0 1))
1064                       #:translate (cons -0.6 0)
1065                       #:tiny (string-upcase (substring s 1)))))
1066          (string-split str #\Space)))))
1067
1068 #(define-markup-command (character layout props name) (string?)
1069   "Print the character name in small caps, translated to the left and
1070   top.  Syntax: \\character #\"name\""
1071   (interpret-markup layout props
1072    (markup #:hspace 0 #:translate (cons -3 1) #:smallcaps name)))
1073
1074 {
1075   c''^\markup \character #"Cleopatra" c'' c'' c''
1076   e'^\markup \character #"Giulio Cesare" e' e' e'
1077 }
1078 @end lilypond
1079
1080 We have used the @code{caps} font shape, but suppose that our font
1081 does not have a small-caps variant.  In that case we have to fake
1082 the small caps font by setting a string in upcase with the first
1083 letter a little larger:
1084
1085 @example
1086 #(define-markup-command (smallcaps layout props str) (string?)
1087   "Print the string argument in small caps."
1088   (interpret-markup layout props
1089    (make-line-markup
1090     (map (lambda (s)
1091           (if (= (string-length s) 0)
1092               s
1093               (markup #:large (string-upcase (substring s 0 1))
1094                       #:translate (cons -0.6 0)
1095                       #:tiny (string-upcase (substring s 1)))))
1096          (string-split str #\Space)))))
1097 @end example
1098
1099 The @code{smallcaps} command first splits its string argument into
1100 tokens separated by spaces (@code{(string-split str #\Space)}); for
1101 each token, a markup is built with the first letter made large and
1102 upcased (@code{#:large (string-upcase (substring s 0 1))}), and a
1103 second markup built with the following letters made tiny and upcased
1104 (@code{#:tiny (string-upcase (substring s 1))}).  As LilyPond
1105 introduces a space between markups on a line, the second markup is
1106 translated to the left (@code{#:translate (cons -0.6 0) ...}).  Then,
1107 the markups built for each token are put in a line by
1108 @code{(make-line-markup ...)}.  Finally, the resulting markup is passed
1109 to the @code{interpret-markup} function, with the @code{layout} and
1110 @code{props} arguments.
1111
1112 Note: there is now an internal command @code{\smallCaps} which can
1113 be used to set text in small caps.  See
1114 @ref{Overview of text markup commands} for details.
1115
1116
1117
1118 @node Contexts for programmers
1119 @section Contexts for programmers
1120
1121 @menu
1122 * Context evaluation::          
1123 * Running a function on all layout objects::  
1124 @end menu
1125
1126 @node Context evaluation
1127 @subsection Context evaluation
1128
1129 @cindex calling code during interpreting
1130 @funindex \applyContext
1131
1132 Contexts can be modified during interpretation with Scheme code.  The
1133 syntax for this is
1134 @example
1135 \applyContext @var{function}
1136 @end example
1137
1138 @var{function} should be a Scheme function taking a single argument,
1139 being the context to apply it to.  The following code will print the
1140 current bar number on the standard output during the compile:
1141
1142 @example
1143 \applyContext
1144   #(lambda (x)
1145     (format #t "\nWe were called in barnumber ~a.\n"
1146      (ly:context-property x 'currentBarNumber)))
1147 @end example
1148
1149
1150
1151 @node Running a function on all layout objects
1152 @subsection Running a function on all layout objects
1153
1154
1155 @cindex calling code on layout objects
1156 @funindex \applyOutput
1157
1158
1159 The most versatile way of tuning an object is @code{\applyOutput}.  Its
1160 syntax is
1161 @example
1162 \applyOutput @var{context} @var{proc}
1163 @end example
1164
1165 @noindent
1166 where @var{proc} is a Scheme function, taking three arguments.
1167
1168 When interpreted, the function @var{proc} is called for every layout
1169 object found in the context @var{context}, with the following
1170 arguments:
1171 @itemize @bullet
1172 @item the layout object itself,
1173 @item the context where the layout object was created, and
1174 @item the context where @code{\applyOutput} is processed.
1175 @end itemize
1176
1177
1178 In addition, the cause of the layout object, i.e., the music
1179 expression or object that was responsible for creating it, is in the
1180 object property @code{cause}.  For example, for a note head, this is a
1181 @internalsref{NoteHead} event, and for a @internalsref{Stem} object,
1182 this is a @internalsref{NoteHead} object.
1183
1184 Here is a function to use for @code{\applyOutput}; it blanks
1185 note-heads on the center-line:
1186
1187 @example
1188 (define (blanker grob grob-origin context)
1189  (if (and (memq (ly:grob-property grob 'interfaces)
1190                 note-head-interface)
1191           (eq? (ly:grob-property grob 'staff-position) 0))
1192      (set! (ly:grob-property grob 'transparent) #t)))
1193 @end example
1194
1195
1196 @node Scheme procedures as properties
1197 @section Scheme procedures as properties
1198
1199 Properties (like thickness, direction, etc.) can be set at fixed values
1200 with \override, e.g.
1201
1202 @example
1203 \override Stem #'thickness = #2.0
1204 @end example
1205
1206 Properties can also be set to a Scheme procedure,
1207
1208 @lilypond[fragment,verbatim,quote,relative=2]
1209 \override Stem #'thickness = #(lambda (grob)
1210     (if (= UP (ly:grob-property grob 'direction))
1211         2.0
1212         7.0))
1213 c b a g b a g b
1214 @end lilypond
1215
1216 @noindent
1217 In this case, the procedure is executed as soon as the value of the
1218 property is requested during the formatting process.
1219
1220 Most of the typesetting engine is driven by such callbacks.
1221 Properties that typically use callbacks include  
1222
1223 @table @code
1224 @item stencil
1225   The printing routine, that constructs a drawing for the symbol
1226 @item X-offset
1227   The routine that sets the horizontal position
1228 @item X-extent
1229   The routine that computes the width of an object
1230 @end table
1231
1232 The procedure always takes a single argument, being the grob.
1233
1234 If routines with multiple arguments must be called, the current grob
1235 can be inserted with a grob closure.  Here is a setting from
1236 @code{AccidentalSuggestion},
1237
1238 @example
1239 (X-offset .
1240   ,(ly:make-simple-closure
1241     `(,+
1242         ,(ly:make-simple-closure
1243            (list ly:self-alignment-interface::centered-on-x-parent))
1244       ,(ly:make-simple-closure
1245            (list ly:self-alignment-interface::x-aligned-on-self)))))
1246 @end example
1247
1248 @noindent
1249 In this example, both @code{ly:self-alignment-interface::x-aligned-on-self} and
1250 @code{ly:self-alignment-interface::centered-on-x-parent} are called
1251 with the grob as argument. The results are added with the @code{+}
1252 function. To ensure that this addition is properly executed, the whole
1253 thing is enclosed in @code{ly:make-simple-closure}.
1254
1255 In fact, using a single procedure as property value is equivalent to
1256
1257 @example
1258 (ly:make-simple-closure (ly:make-simple-closure (list @var{proc})))
1259 @end example
1260
1261 @noindent
1262 The inner @code{ly:make-simple-closure} supplies the grob as argument
1263 to @var{proc}, the outer ensures that result of the function is
1264 returned, rather than the @code{simple-closure} object.