]> git.donarmstrong.com Git - lilypond.git/blob - Documentation/user/programming-interface.itely
Split WWW target in two stages WWW-1 and WWW-2
[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.38"
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 @funindex \displayLilyMusic
469
470 When writing a music function it is often instructive to inspect how
471 a music expression is stored internally.  This can be done with the
472 music function @code{\displayMusic}
473
474 @example
475 @{
476   \displayMusic @{ c'4\f @}
477 @}
478 @end example
479
480 @noindent
481 will display
482
483 @example
484 (make-music
485   'SequentialMusic
486   'elements
487   (list (make-music
488           'EventChord
489           'elements
490           (list (make-music
491                   'NoteEvent
492                   'duration
493                   (ly:make-duration 2 0 1 1)
494                   'pitch
495                   (ly:make-pitch 0 0 0))
496                 (make-music
497                   'AbsoluteDynamicEvent
498                   'text
499                   "f")))))
500 @end example
501
502 By default, LilyPond will print these messages to the console along
503 with all the other messages.  To split up these messages and save
504 the results of @code{\display@{STUFF@}}, redirect the output to
505 a file.
506
507 @example
508 lilypond file.ly >display.txt
509 @end example
510
511 With a bit of reformatting, the above information is
512 easier to read,
513
514 @example
515 (make-music 'SequentialMusic
516   'elements (list (make-music 'EventChord
517                     'elements (list (make-music 'NoteEvent
518                                       'duration (ly:make-duration 2 0 1 1)
519                                       'pitch (ly:make-pitch 0 0 0))
520                                     (make-music 'AbsoluteDynamicEvent
521                                       'text "f")))))
522 @end example
523
524 A @code{@{ ... @}} music sequence has the name @code{SequentialMusic},
525 and its inner expressions are stored as a list in its @code{'elements}
526 property.  A note is represented as an @code{EventChord} expression,
527 containing a @code{NoteEvent} object (storing the duration and
528 pitch properties) and any extra information (in this case, an
529 @code{AbsoluteDynamicEvent} with a @code{"f"} text property.
530
531
532 @node Music properties
533 @subsection Music properties
534
535 The @code{NoteEvent} object is the first object of the
536 @code{'elements} property of @code{someNote}.
537
538 @example
539 someNote = c'
540 \displayMusic \someNote
541 ===>
542 (make-music
543   'EventChord
544   'elements
545   (list (make-music
546           'NoteEvent
547           'duration
548           (ly:make-duration 2 0 1 1)
549           'pitch
550           (ly:make-pitch 0 0 0))))
551 @end example
552
553 The @code{display-scheme-music} function is the function used by
554 @code{\displayMusic} to display the Scheme representation of a music
555 expression.
556
557 @example
558 #(display-scheme-music (first (ly:music-property someNote 'elements)))
559 ===>
560 (make-music
561   'NoteEvent
562   'duration
563   (ly:make-duration 2 0 1 1)
564   'pitch
565   (ly:make-pitch 0 0 0))
566 @end example
567
568 Then the note pitch is accessed through the @code{'pitch} property
569 of the @code{NoteEvent} object,
570
571 @example
572 #(display-scheme-music
573    (ly:music-property (first (ly:music-property someNote 'elements))
574                       'pitch))
575 ===>
576 (ly:make-pitch 0 0 0)
577 @end example
578
579 The note pitch can be changed by setting this 'pitch property,
580
581 @example
582 #(set! (ly:music-property (first (ly:music-property someNote 'elements))
583                           'pitch)
584        (ly:make-pitch 0 1 0)) ;; set the pitch to d'.
585 \displayLilyMusic \someNote
586 ===>
587 d'
588 @end example
589
590
591 @node Doubling a note with slurs (example)
592 @subsection Doubling a note with slurs (example)
593
594 Suppose we want to create a function which translates
595 input like @code{a} into @code{a( a)}.  We begin
596 by examining the internal representation of the music
597 we want to end up with.
598
599 @example
600 \displayMusic@{ a'( a') @}
601 ===>
602 (make-music
603   'SequentialMusic
604   'elements
605   (list (make-music
606           'EventChord
607           'elements
608           (list (make-music
609                   'NoteEvent
610                   'duration
611                   (ly:make-duration 2 0 1 1)
612                   'pitch
613                   (ly:make-pitch 0 5 0))
614                 (make-music
615                   'SlurEvent
616                   'span-direction
617                   -1)))
618         (make-music
619           'EventChord
620           'elements
621           (list (make-music
622                   'NoteEvent
623                   'duration
624                   (ly:make-duration 2 0 1 1)
625                   'pitch
626                   (ly:make-pitch 0 5 0))
627                 (make-music
628                   'SlurEvent
629                   'span-direction
630                   1)))))
631 @end example
632
633 The bad news is that the @code{SlurEvent} expressions
634 must be added @q{inside} the note (or more precisely,
635 inside the @code{EventChord} expression).
636
637 Now we examine the input,
638
639 @example
640 (make-music
641   'SequentialMusic
642   'elements
643   (list (make-music
644           'EventChord
645           'elements
646           (list (make-music
647                   'NoteEvent
648                   'duration
649                   (ly:make-duration 2 0 1 1)
650                   'pitch
651                   (ly:make-pitch 0 5 0))))))
652 @end example
653
654 So in our function, we need to clone this expression (so that we
655 have two notes to build the sequence), add @code{SlurEvents} to the
656 @code{'elements} property of each one, and finally make a
657 @code{SequentialMusic} with the two @code{EventChords}.
658
659 @example
660 doubleSlur = #(define-music-function (parser location note) (ly:music?)
661          "Return: @{ note ( note ) @}.
662          `note' is supposed to be an EventChord."
663          (let ((note2 (ly:music-deep-copy note)))
664            (set! (ly:music-property note 'elements)
665                  (cons (make-music 'SlurEvent 'span-direction -1)
666                        (ly:music-property note 'elements)))
667            (set! (ly:music-property note2 'elements)
668                  (cons (make-music 'SlurEvent 'span-direction 1)
669                        (ly:music-property note2 'elements)))
670            (make-music 'SequentialMusic 'elements (list note note2))))
671 @end example
672
673
674 @node Adding articulation to notes (example)
675 @subsection Adding articulation to notes (example)
676
677 The easy way to add articulation to notes is to merge two music
678 expressions into one context, as explained in
679 @ref{Creating contexts}.  However, suppose that we want to write
680 a music function which does this.
681
682 A @code{$variable} inside the @code{#@{...#@}} notation is like
683 using a regular @code{\variable} in classical LilyPond
684 notation.  We know that
685
686 @example
687 @{ \music -. -> @}
688 @end example
689
690 @noindent
691 will not work in LilyPond.  We could avoid this problem by attaching
692 the articulation to a fake note,
693
694 @example
695 @{ << \music s1*0-.-> @}
696 @end example
697
698 @noindent
699 but for the sake of this example, we will learn how to do this in
700 Scheme.  We begin by examining our input and desired output,
701
702 @example
703 %  input
704 \displayMusic c4
705 ===>
706 (make-music
707   'EventChord
708   'elements
709   (list (make-music
710           'NoteEvent
711           'duration
712           (ly:make-duration 2 0 1 1)
713           'pitch
714           (ly:make-pitch -1 0 0))))
715 =====
716 %  desired output
717 \displayMusic c4->
718 ===>
719 (make-music
720   'EventChord
721   'elements
722   (list (make-music
723           'NoteEvent
724           'duration
725           (ly:make-duration 2 0 1 1)
726           'pitch
727           (ly:make-pitch -1 0 0))
728         (make-music
729           'ArticulationEvent
730           'articulation-type
731           "marcato")))
732 @end example
733
734 We see that a note (@code{c4}) is represented as an @code{EventChord}
735 expression, with a @code{NoteEvent} expression in its elements list.  To
736 add a marcato articulation, an @code{ArticulationEvent} expression must
737 be added to the elements property of the @code{EventChord}
738 expression.
739
740 To build this function, we begin with
741
742 @example
743 (define (add-marcato event-chord)
744   "Add a marcato ArticulationEvent to the elements of `event-chord',
745   which is supposed to be an EventChord expression."
746   (let ((result-event-chord (ly:music-deep-copy event-chord)))
747     (set! (ly:music-property result-event-chord 'elements)
748           (cons (make-music 'ArticulationEvent
749                   'articulation-type "marcato")
750                 (ly:music-property result-event-chord 'elements)))
751     result-event-chord))
752 @end example
753
754 The first line is the way to define a function in Scheme: the function
755 name is @code{add-marcato}, and has one variable called
756 @code{event-chord}.  In Scheme, the type of variable is often clear
757 from its name.  (this is good practice in other programming languages,
758 too!)
759
760 @example
761 "Add a marcato..."
762 @end example
763
764 @noindent
765 is a description of what the function does.  This is not strictly
766 necessary, but just like clear variable names, it is good practice.
767
768 @example
769 (let ((result-event-chord (ly:music-deep-copy event-chord)))
770 @end example
771
772 @code{let} is used to declare local variables.  Here we use one local
773 variable, named @code{result-event-chord}, to which we give the value
774 @code{(ly:music-deep-copy event-chord)}.  @code{ly:music-deep-copy} is
775 a function specific to LilyPond, like all functions prefixed by
776 @code{ly:}.  It is use to make a copy of a music
777 expression.  Here we copy @code{event-chord} (the parameter of the
778 function).  Recall that our purpose is to add a marcato to an
779 @code{EventChord} expression.  It is better to not modify the
780 @code{EventChord} which was given as an argument, because it may be
781 used elsewhere.
782
783 Now we have a @code{result-event-chord}, which is a
784 @code{NoteEventChord} expression and is a copy of @code{event-chord}.  We
785 add the marcato to its elements list property.
786
787 @example
788 (set! place new-value)
789 @end example
790
791 Here, what we want to set (the @q{place}) is the @q{elements} property of
792 @code{result-event-chord} expression.
793
794 @example
795 (ly:music-property result-event-chord 'elements)
796 @end example
797
798 @code{ly:music-property} is the function used to access music properties
799 (the @code{'elements}, @code{'duration}, @code{'pitch}, etc, that we
800 see in the @code{\displayMusic} output above).  The new value is the
801 former elements property, with an extra item: the
802 @code{ArticulationEvent} expression, which we copy from the
803 @code{\displayMusic} output,
804
805 @example
806 (cons (make-music 'ArticulationEvent
807         'articulation-type "marcato")
808       (ly:music-property result-event-chord 'elements))
809 @end example
810
811 @code{cons} is used to add an element to a list without modifying the
812 original list.  This is what we
813 want: the same list as before, plus the new @code{ArticulationEvent}
814 expression.  The order inside the elements property is not important here.
815
816 Finally, once we have added the marcato articulation to its @code{elements}
817 property, we can return @code{result-event-chord}, hence the last line of
818 the function.
819
820 Now we transform the @code{add-marcato} function into a music
821 function,
822
823 @example
824 addMarcato = #(define-music-function (parser location event-chord)
825                                      (ly:music?)
826     "Add a marcato ArticulationEvent to the elements of `event-chord',
827     which is supposed to be an EventChord expression."
828     (let ((result-event-chord (ly:music-deep-copy event-chord)))
829       (set! (ly:music-property result-event-chord 'elements)
830             (cons (make-music 'ArticulationEvent
831                     'articulation-type "marcato")
832                   (ly:music-property result-event-chord 'elements)))
833       result-event-chord))
834 @end example
835
836 We may verify that this music function works correctly,
837
838 @example
839 \displayMusic \addMarcato c4
840 @end example
841
842
843 @node Markup programmer interface
844 @section Markup programmer interface
845
846 Markups are implemented as special Scheme functions which produce a
847 Stencil object given a number of arguments.
848
849 @menu
850 * Markup construction in Scheme::  
851 * How markups work internally::  
852 * New markup command definition::  
853 * New markup list command definition::  
854 @end menu
855
856
857 @node Markup construction in Scheme
858 @subsection Markup construction in Scheme
859
860 @cindex defining markup commands
861
862 The @code{markup} macro builds markup expressions in Scheme while
863 providing a LilyPond-like syntax.  For example,
864 @example
865 (markup #:column (#:line (#:bold #:italic "hello" #:raise 0.4 "world")
866                   #:bigger #:line ("foo" "bar" "baz")))
867 @end example
868
869 @noindent
870 is equivalent to:
871 @example
872 \markup \column @{ \line @{ \bold \italic "hello" \raise #0.4 "world" @}
873                   \bigger \line @{ foo bar baz @} @}
874 @end example
875
876 @noindent
877 This example demonstrates the main translation rules between regular
878 LilyPond markup syntax and Scheme markup syntax.
879
880 @quotation
881 @multitable @columnfractions .3 .3
882 @item @b{LilyPond} @tab @b{Scheme}
883 @item @code{\markup markup1} @tab @code{(markup markup1)}
884 @item @code{\markup @{ markup1 markup2 ... @}} @tab
885         @code{(markup markup1 markup2 ... )}
886 @item @code{\command} @tab @code{#:command}
887 @item @code{\variable} @tab @code{variable}
888 @item @code{\center-align @{ ... @}} @tab @code{#:center-align ( ... )}
889 @item @code{string} @tab @code{"string"}
890 @item @code{#scheme-arg} @tab @code{scheme-arg}
891 @end multitable
892 @end quotation
893
894 The whole Scheme language is accessible inside the
895 @code{markup} macro.  For example, You may use function calls inside
896 @code{markup} in order to manipulate character strings.  This is
897 useful when defining new markup commands (see
898 @ref{New markup command definition}).
899
900
901 @knownissues
902
903 The markup-list argument of commands such as @code{#:line},
904 @code{#:center}, and @code{#:column} cannot be a variable or
905 the result of a function call.
906
907 @lisp
908 (markup #:line (function-that-returns-markups))
909 @end lisp
910
911 @noindent
912 is invalid.  One should use the @code{make-line-markup},
913 @code{make-center-markup}, or @code{make-column-markup} functions
914 instead,
915
916 @lisp
917 (markup (make-line-markup (function-that-returns-markups)))
918 @end lisp
919
920
921 @node How markups work internally
922 @subsection How markups work internally
923
924 In a markup like
925
926 @example
927 \raise #0.5 "text example"
928 @end example
929
930 @noindent
931 @code{\raise} is actually represented by the @code{raise-markup}
932 function.  The markup expression is stored as
933
934 @example
935 (list raise-markup 0.5 (list simple-markup "text example"))
936 @end example
937
938 When the markup is converted to printable objects (Stencils), the
939 @code{raise-markup} function is called as
940
941 @example
942 (apply raise-markup
943        @var{\layout object}
944        @var{list of property alists}
945        0.5
946        @var{the "text example" markup})
947 @end example
948
949 The @code{raise-markup} function first creates the stencil for the
950 @code{text example} string, and then it raises that Stencil by 0.5
951 staff space.  This is a rather simple example; more complex examples
952 are in the rest
953 of this section, and in @file{scm/@/define@/-markup@/-commands@/.scm}.
954
955
956 @node New markup command definition
957 @subsection New markup command definition
958
959 New markup commands can be defined
960 with the @code{define-markup-command} Scheme macro.
961
962 @lisp
963 (define-markup-command (@var{command-name} @var{layout} @var{props} @var{arg1} @var{arg2} ...)
964             (@var{arg1-type?} @var{arg2-type?} ...)
965   ..command body..)
966 @end lisp
967
968 The arguments are
969
970 @table @var
971 @item argi
972 @var{i}th command argument
973 @item argi-type?
974 a type predicate for the i@var{th} argument
975 @item layout
976 the @q{layout} definition
977 @item props
978 a list of alists, containing all active properties.
979 @end table
980
981 As a simple example, we show how to add a @code{\smallcaps} command,
982 which selects a small caps font.  Normally we could select the
983 small caps font,
984
985 @example
986 \markup @{ \override #'(font-shape . caps) Text-in-caps @}
987 @end example
988
989 @noindent
990 This selects the caps font by setting the @code{font-shape} property to
991 @code{#'caps} for interpreting @code{Text-in-caps}.
992
993 To make the above available as @code{\smallcaps} command, we must
994 define a function using @code{define-markup-command}.  The command should
995 take a single argument of type @code{markup}.  Therefore the start of the
996 definition should read
997
998 @example
999 (define-markup-command (smallcaps layout props argument) (markup?)
1000 @end example
1001
1002 @noindent
1003
1004 What follows is the content of the command: we should interpret
1005 the @code{argument} as a markup, i.e.,
1006
1007 @example
1008 (interpret-markup layout @dots{} argument)
1009 @end example
1010
1011 @noindent
1012 This interpretation should add @code{'(font-shape . caps)} to the active
1013 properties, so we substitute the following for the @dots{} in the
1014 above example:
1015
1016 @example
1017 (cons (list '(font-shape . caps) ) props)
1018 @end example
1019
1020 @noindent
1021 The variable @code{props} is a list of alists, and we prepend to it by
1022 cons'ing a list with the extra setting.
1023
1024
1025 Suppose that we are typesetting a recitative in an opera and
1026 we would like to define a command that will show character names in a
1027 custom manner.  Names should be printed with small caps and moved a
1028 bit to the left and top.  We will define a @code{\character} command
1029 which takes into account the necessary translation and uses the newly
1030 defined @code{\smallcaps} command:
1031
1032 @example
1033 #(define-markup-command (character layout props name) (string?)
1034   "Print the character name in small caps, translated to the left and
1035   top.  Syntax: \\character #\"name\""
1036   (interpret-markup layout props
1037    (markup #:hspace 0 #:translate (cons -3 1) #:smallcaps name)))
1038 @end example
1039
1040 There is one complication that needs explanation: texts above and below
1041 the staff are moved vertically to be at a certain distance (the
1042 @code{padding} property) from the staff and the notes.  To make sure
1043 that this mechanism does not annihilate the vertical effect of our
1044 @code{#:translate}, we add an empty string (@code{#:hspace 0}) before the
1045 translated text.  Now the @code{#:hspace 0} will be put above the notes,
1046 and the
1047 @code{name} is moved in relation to that empty string.  The net effect is
1048 that the text is moved to the upper left.
1049
1050 The final result is as follows:
1051
1052 @example
1053 @{
1054   c''^\markup \character #"Cleopatra"
1055   e'^\markup \character #"Giulio Cesare"
1056 @}
1057 @end example
1058
1059 @lilypond[quote,ragged-right]
1060 #(define-markup-command (smallcaps layout props str) (string?)
1061   "Print the string argument in small caps.  Syntax: \\smallcaps #\"string\""
1062   (interpret-markup layout props
1063    (make-line-markup
1064     (map (lambda (s)
1065           (if (= (string-length s) 0)
1066               s
1067               (markup #:large (string-upcase (substring s 0 1))
1068                       #:translate (cons -0.6 0)
1069                       #:tiny (string-upcase (substring s 1)))))
1070          (string-split str #\Space)))))
1071
1072 #(define-markup-command (character layout props name) (string?)
1073   "Print the character name in small caps, translated to the left and
1074   top.  Syntax: \\character #\"name\""
1075   (interpret-markup layout props
1076    (markup #:hspace 0 #:translate (cons -3 1) #:smallcaps name)))
1077
1078 {
1079   c''^\markup \character #"Cleopatra" c'' c'' c''
1080   e'^\markup \character #"Giulio Cesare" e' e' e'
1081 }
1082 @end lilypond
1083
1084 We have used the @code{caps} font shape, but suppose that our font
1085 does not have a small-caps variant.  In that case we have to fake
1086 the small caps font by setting a string in upcase with the first
1087 letter a little larger:
1088
1089 @example
1090 #(define-markup-command (smallcaps layout props str) (string?)
1091   "Print the string argument in small caps."
1092   (interpret-markup layout props
1093    (make-line-markup
1094     (map (lambda (s)
1095           (if (= (string-length s) 0)
1096               s
1097               (markup #:large (string-upcase (substring s 0 1))
1098                       #:translate (cons -0.6 0)
1099                       #:tiny (string-upcase (substring s 1)))))
1100          (string-split str #\Space)))))
1101 @end example
1102
1103 The @code{smallcaps} command first splits its string argument into
1104 tokens separated by spaces (@code{(string-split str #\Space)}); for
1105 each token, a markup is built with the first letter made large and
1106 upcased (@code{#:large (string-upcase (substring s 0 1))}), and a
1107 second markup built with the following letters made tiny and upcased
1108 (@code{#:tiny (string-upcase (substring s 1))}).  As LilyPond
1109 introduces a space between markups on a line, the second markup is
1110 translated to the left (@code{#:translate (cons -0.6 0) ...}).  Then,
1111 the markups built for each token are put in a line by
1112 @code{(make-line-markup ...)}.  Finally, the resulting markup is passed
1113 to the @code{interpret-markup} function, with the @code{layout} and
1114 @code{props} arguments.
1115
1116 Note: there is now an internal command @code{\smallCaps} which can
1117 be used to set text in small caps.  See
1118 @ref{Text markup commands}, for details.
1119
1120 @knownissues
1121
1122 Currently, the available combinations of arguments (after the standard
1123 @var{layout} and @var{props} arguments) to a markup command defined with
1124 @code{define-markup-command} are limited as follows.
1125
1126 @table @asis
1127 @item (no argument)
1128 @itemx @var{list}
1129 @itemx @var{markup}
1130 @itemx @var{markup markup}
1131 @itemx @var{scm}
1132 @itemx @var{scm markup}
1133 @itemx @var{scm scm}
1134 @itemx @var{scm scm markup}
1135 @itemx @var{scm markup markup}
1136 @itemx @var{scm scm scm}
1137 @end table
1138
1139 @noindent
1140 In the above table, @var{scm} represents native Scheme data types like
1141 @q{number} or @q{string}.
1142
1143 As an example, it is not possible to use a markup command @code{foo} with
1144 four arguments defined as
1145
1146 @example
1147 #(define-markup-command (foo layout props
1148                          num1    str1    num2    str2)
1149                         (number? string? number? string?)
1150   ...)
1151 @end example
1152
1153 @noindent
1154 If you apply it as, say,
1155
1156 @example
1157 \markup \foo #1 #"bar" #2 #"baz"
1158 @end example
1159
1160 @cindex Scheme signature
1161 @cindex signature, Scheme
1162 @noindent
1163 @command{lilypond} complains that it cannot parse @code{foo} due to its
1164 unknown Scheme signature.
1165
1166
1167 @node New markup list command definition
1168 @subsection New markup list command definition
1169 Markup list commands are defined with the
1170 @code{define-markup-list-command} Scheme macro, which is similar to the
1171 @code{define-markup-command} macro described in
1172 @ref{New markup command definition}, except that where the latter returns
1173 a single stencil, the former returns a list stencils.
1174
1175 In the following example, a @code{\paragraph} markup list command is
1176 defined, which returns a list of justified lines, the first one being
1177 indented.  The indent width is taken from the @code{props} argument.
1178 @example
1179 #(define-markup-list-command (paragraph layout props args) (markup-list?)
1180    (let ((indent (chain-assoc-get 'par-indent props 2)))
1181      (interpret-markup-list layout props 
1182        (make-justified-lines-markup-list (cons (make-hspace-markup indent)
1183                                                args)))))
1184 @end example
1185
1186 Besides the usual @code{layout} and @code{props} arguments, the
1187 @code{paragraph} markup list command takes a markup list argument, named
1188 @code{args}.  The predicate for markup lists is @code{markup-list?}.
1189
1190 First, the function gets the indent width, a property here named
1191 @code{par-indent}, from the property list @code{props} If the property
1192 is not found, the default value is @code{2}.  Then, a list of justified
1193 lines is made using the @code{make-justified-lines-markup-list}
1194 function, which is related to the @code{\justified-lines}
1195 built-in markup list command.  An horizontal space is added at the
1196 beginning using the @code{make-hspace-markup} function.  Finally, the
1197 markup list is interpreted using the @code{interpret-markup-list}
1198 function.
1199
1200 This new markup list command can be used as follows:
1201 @example
1202 \markuplines @{
1203   \paragraph @{
1204     The art of music typography is called \italic @{(plate) engraving.@}
1205     The term derives from the traditional process of music printing.
1206     Just a few decades ago, sheet music was made by cutting and stamping
1207     the music into a zinc or pewter plate in mirror image.
1208   @}
1209   \override-lines #'(par-indent . 4) \paragraph @{
1210     The plate would be inked, the depressions caused by the cutting
1211     and stamping would hold ink.  An image was formed by pressing paper
1212     to the plate.  The stamping and cutting was completely done by
1213     hand.
1214   @}
1215 @}
1216 @end example
1217
1218 @node Contexts for programmers
1219 @section Contexts for programmers
1220
1221 @menu
1222 * Context evaluation::          
1223 * Running a function on all layout objects::  
1224 @end menu
1225
1226 @node Context evaluation
1227 @subsection Context evaluation
1228
1229 @cindex calling code during interpreting
1230 @funindex \applyContext
1231
1232 Contexts can be modified during interpretation with Scheme code.  The
1233 syntax for this is
1234 @example
1235 \applyContext @var{function}
1236 @end example
1237
1238 @var{function} should be a Scheme function taking a single argument,
1239 being the context to apply it to.  The following code will print the
1240 current bar number on the standard output during the compile:
1241
1242 @example
1243 \applyContext
1244   #(lambda (x)
1245     (format #t "\nWe were called in barnumber ~a.\n"
1246      (ly:context-property x 'currentBarNumber)))
1247 @end example
1248
1249
1250
1251 @node Running a function on all layout objects
1252 @subsection Running a function on all layout objects
1253
1254
1255 @cindex calling code on layout objects
1256 @funindex \applyOutput
1257
1258
1259 The most versatile way of tuning an object is @code{\applyOutput}.  Its
1260 syntax is
1261 @example
1262 \applyOutput @var{context} @var{proc}
1263 @end example
1264
1265 @noindent
1266 where @var{proc} is a Scheme function, taking three arguments.
1267
1268 When interpreted, the function @var{proc} is called for every layout
1269 object found in the context @var{context}, with the following
1270 arguments:
1271 @itemize
1272 @item the layout object itself,
1273 @item the context where the layout object was created, and
1274 @item the context where @code{\applyOutput} is processed.
1275 @end itemize
1276
1277
1278 In addition, the cause of the layout object, i.e., the music
1279 expression or object that was responsible for creating it, is in the
1280 object property @code{cause}.  For example, for a note head, this is a
1281 @rinternals{NoteHead} event, and for a @rinternals{Stem} object,
1282 this is a @rinternals{NoteHead} object.
1283
1284 Here is a function to use for @code{\applyOutput}; it blanks
1285 note-heads on the center-line:
1286
1287 @example
1288 (define (blanker grob grob-origin context)
1289  (if (and (memq (ly:grob-property grob 'interfaces)
1290                 note-head-interface)
1291           (eq? (ly:grob-property grob 'staff-position) 0))
1292      (set! (ly:grob-property grob 'transparent) #t)))
1293 @end example
1294
1295
1296 @node Scheme procedures as properties
1297 @section Scheme procedures as properties
1298
1299 Properties (like thickness, direction, etc.) can be set at fixed values
1300 with \override, e.g.
1301
1302 @example
1303 \override Stem #'thickness = #2.0
1304 @end example
1305
1306 Properties can also be set to a Scheme procedure,
1307
1308 @lilypond[fragment,verbatim,quote,relative=2]
1309 \override Stem #'thickness = #(lambda (grob)
1310     (if (= UP (ly:grob-property grob 'direction))
1311         2.0
1312         7.0))
1313 c b a g b a g b
1314 @end lilypond
1315
1316 @noindent
1317 In this case, the procedure is executed as soon as the value of the
1318 property is requested during the formatting process.
1319
1320 Most of the typesetting engine is driven by such callbacks.
1321 Properties that typically use callbacks include  
1322
1323 @table @code
1324 @item stencil
1325   The printing routine, that constructs a drawing for the symbol
1326 @item X-offset
1327   The routine that sets the horizontal position
1328 @item X-extent
1329   The routine that computes the width of an object
1330 @end table
1331
1332 The procedure always takes a single argument, being the grob.
1333
1334 If routines with multiple arguments must be called, the current grob
1335 can be inserted with a grob closure.  Here is a setting from
1336 @code{AccidentalSuggestion},
1337
1338 @example
1339 (X-offset .
1340   ,(ly:make-simple-closure
1341     `(,+
1342         ,(ly:make-simple-closure
1343            (list ly:self-alignment-interface::centered-on-x-parent))
1344       ,(ly:make-simple-closure
1345            (list ly:self-alignment-interface::x-aligned-on-self)))))
1346 @end example
1347
1348 @noindent
1349 In this example, both @code{ly:self-alignment-interface::x-aligned-on-self} and
1350 @code{ly:self-alignment-interface::centered-on-x-parent} are called
1351 with the grob as argument.  The results are added with the @code{+}
1352 function.  To ensure that this addition is properly executed, the whole
1353 thing is enclosed in @code{ly:make-simple-closure}.
1354
1355 In fact, using a single procedure as property value is equivalent to
1356
1357 @example
1358 (ly:make-simple-closure (ly:make-simple-closure (list @var{proc})))
1359 @end example
1360
1361 @noindent
1362 The inner @code{ly:make-simple-closure} supplies the grob as argument
1363 to @var{proc}, the outer ensures that result of the function is
1364 returned, rather than the @code{simple-closure} object.
1365
1366
1367 @node TODO moved into scheme
1368 @section TODO moved into scheme
1369
1370 @menu
1371 * Using Scheme code instead of \tweak::  
1372 * Difficult tweaks::            
1373 @end menu
1374
1375 @node Using Scheme code instead of \tweak
1376 @subsection Using Scheme code instead of @code{\tweak}
1377
1378 The main disadvantage of @code{\tweak} is its syntactical
1379 inflexibility.  For example, the following produces a syntax error.
1380
1381 @example
1382 F = \tweak #'font-size #-3 -\flageolet
1383
1384 \relative c'' @{
1385   c4^\F c4_\F
1386 @}
1387 @end example
1388
1389 @noindent
1390 With other words, @code{\tweak} doesn't behave like an articulation
1391 regarding the syntax; in particular, it can't be attached with
1392 @code{^} and @code{_}.
1393
1394 Using Scheme, this problem can be circumvented.  The route to the
1395 result is given in @ref{Adding articulation to notes (example)},
1396 especially how to use @code{\displayMusic} as a helping guide.
1397
1398 @example
1399 F = #(let ((m (make-music 'ArticulationEvent
1400                           'articulation-type "flageolet")))
1401        (set! (ly:music-property m 'tweaks)
1402              (acons 'font-size -3
1403                     (ly:music-property m 'tweaks)))
1404        m)
1405  
1406 \relative c'' @{
1407   c4^\F c4_\F
1408 @}
1409 @end example
1410
1411 @noindent
1412 Here, the @code{tweaks} properties of the flageolet object
1413 @code{m} (created with @code{make-music}) are extracted with
1414 @code{ly:music-property}, a new key-value pair to change the
1415 font size is prepended to the property list with the
1416 @code{acons} Scheme function, and the result is finally
1417 written back with @code{set!}.  The last element of the
1418 @code{let} block is the return value, @code{m} itself.
1419
1420
1421
1422 @node Difficult tweaks
1423 @subsection Difficult tweaks
1424
1425 There are a few classes of difficult adjustments.
1426
1427 @itemize
1428
1429
1430 @item
1431 One type of difficult adjustment is the appearance of spanner objects,
1432 such as slur and tie.  Initially, only one of these objects is created,
1433 and they can be adjusted with the normal mechanism.  However, in some
1434 cases the spanners cross line breaks.  If this happens, these objects
1435 are cloned.  A separate object is created for every system that it is
1436 in.  These are clones of the original object and inherit all
1437 properties, including @code{\override}s.
1438
1439
1440 In other words, an @code{\override} always affects all pieces of a
1441 broken spanner.  To change only one part of a spanner at a line break,
1442 it is necessary to hook into the formatting process.  The
1443 @code{after-line-breaking} callback contains the Scheme procedure that
1444 is called after the line breaks have been determined, and layout
1445 objects have been split over different systems.
1446
1447 In the following example, we define a procedure
1448 @code{my-callback}.  This procedure
1449
1450 @itemize
1451 @item
1452 determines if we have been split across line breaks
1453 @item
1454 if yes, retrieves all the split objects
1455 @item
1456 checks if we are the last of the split objects
1457 @item
1458 if yes, it sets @code{extra-offset}.
1459 @end itemize
1460
1461 This procedure is installed into @rinternals{Tie}, so the last part
1462 of the broken tie is translated up.
1463
1464 @lilypond[quote,verbatim,ragged-right]
1465 #(define (my-callback grob)
1466   (let* (
1467          ; have we been split?
1468          (orig (ly:grob-original grob))
1469
1470          ; if yes, get the split pieces (our siblings)
1471          (siblings (if (ly:grob? orig)
1472                      (ly:spanner-broken-into orig) '() )))
1473
1474    (if (and (>= (length siblings) 2)
1475              (eq? (car (last-pair siblings)) grob))
1476      (ly:grob-set-property! grob 'extra-offset '(-2 . 5)))))
1477
1478 \relative c'' {
1479   \override Tie #'after-line-breaking =
1480   #my-callback
1481   c1 ~ \break c2 ~ c
1482 }
1483 @end lilypond
1484
1485 @noindent
1486 When applying this trick, the new @code{after-line-breaking} callback
1487 should also call the old one @code{after-line-breaking}, if there is
1488 one.  For example, if using this with @code{Hairpin},
1489 @code{ly:hairpin::after-line-breaking} should also be called.
1490
1491
1492 @item Some objects cannot be changed with @code{\override} for
1493 technical reasons.  Examples of those are @code{NonMusicalPaperColumn}
1494 and @code{PaperColumn}.  They can be changed with the
1495 @code{\overrideProperty} function, which works similar to @code{\once
1496 \override}, but uses a different syntax.
1497
1498 @example
1499 \overrideProperty
1500 #"Score.NonMusicalPaperColumn"  % Grob name
1501 #'line-break-system-details     % Property name
1502 #'((next-padding . 20))         % Value
1503 @end example
1504
1505 Note, however, that @code{\override}, applied to
1506 @code{NoteMusicalPaperColumn} and @code{PaperColumn}, still works as
1507 expected within @code{\context} blocks.
1508
1509 @end itemize
1510
1511
1512
1513
1514