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