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