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