]> git.donarmstrong.com Git - lilypond.git/blob - Documentation/user/programming-interface.itely
a29c1f2e5debec9d3ab3e876ccdacdf5b81afc14
[lilypond.git] / Documentation / user / programming-interface.itely
1 @c -*-texinfo-*-
2 @node Interfaces for programmers
3 @appendix Interfaces for programmers
4
5
6
7 @menu
8 * Programmer interfaces for input ::  
9 * Markup programmer interface::  
10 * Contexts for programmers::    
11 @end menu
12
13 @node Programmer interfaces for input 
14 @appendixsec Programmer interfaces for input 
15
16 @menu
17 * Input variables and Scheme::  
18 * Internal music representation::  
19 * Extending music syntax::      
20 * Manipulating music expressions:: 
21 * Using LilyPond syntax inside Scheme::   
22 @end menu
23
24 @node Input variables and Scheme
25 @appendixsubsec Input variables and Scheme
26
27
28 The input format supports the notion of variable: in the following
29 example, a music expression is assigned to a variable with the name
30 @code{traLaLa}.
31 @example
32   traLaLa = \notes @{ c'4 d'4 @}
33 @end example
34
35 @noindent
36
37 There is also a form of scoping: in the following example, the
38 @code{\paper} block also contains a @code{traLaLa} variable, which is
39 independent of the outer @code{\traLaLa}.
40 @example
41   traLaLa = \notes @{ c'4 d'4 @}
42   \paper @{ traLaLa = 1.0 @}
43 @end example
44 @c
45 In effect, each input file is a scope, and all @code{\header},
46 @code{\midi} and @code{\paper} blocks are scopes nested inside that
47 toplevel scope.
48
49 Both variables and scoping are implemented in the GUILE module system.
50 An anonymous Scheme module is attached to each scope. An assignment of
51 the form
52 @example
53  traLaLa = \notes @{ c'4 d'4 @}
54 @end example
55
56 @noindent
57 is internally converted to a Scheme definition
58 @example
59  (define traLaLa @var{Scheme value of ``@code{\notes ... }''})
60 @end example
61
62 This means that input variables and Scheme variables may be freely
63 mixed.  In the following example, a music fragment is stored in the
64 variable @code{traLaLa}, and duplicated using Scheme. The result is
65 imported in a @code{\score} by means of a second variable
66 @code{twice}:
67 @example
68   traLaLa = \notes @{ c'4 d'4 @}
69
70   #(define newLa (map ly:music-deep-copy
71     (list traLaLa traLaLa)))
72   #(define twice
73     (make-sequential-music newLa))
74
75   \score @{ \twice @}
76 @end example
77
78 In the above example, music expressions can be `exported' from the
79 input to the Scheme interpreter. The opposite is also possible. By
80 wrapping a Scheme value in the function @code{ly:export}, a Scheme
81 value is interpreted as if it were entered in LilyPond syntax: instead
82 of defining @code{\twice}, the example above could also have been
83 written as
84 @example
85   @dots{}
86   \score @{ #(ly:export (make-sequential-music newLa)) @}
87 @end example
88
89 @refbugs
90
91 Mixing Scheme and lily identifiers is not possible with @code{--safe}.
92
93 @node Internal music representation
94 @appendixsubsec Internal music representation
95
96 When a music expression is parsed, it is converted into a set of
97 Scheme music objects. The defining property of a music object is that
98 it takes up time. Time is a rational number that measures the length
99 of a piece of music, in whole notes.
100
101 A music object has three kinds of types:
102 @itemize @bullet
103 @item
104   music name: Each music expression has a name, for example, a note
105 leads to a @internalsref{NoteEvent}, and @code{\simultaneous} leads to
106 a @internalsref{SimultaneousMusic}. A list of all expressions
107 available is in the internals manual, under @internalsref{Music
108 expressions}.
109
110 @item
111   `type' or interface: Each music name has several `types' or interface,
112   for example, a note is an @code{event}, but it is also a @code{note-event},
113   a @code{rhythmic-event} and a @code{melodic-event}.
114
115   All classes of music are listed in the internals manual, under
116   @internalsref{Music classes}.
117 @item
118 C++ object: Each music object is represented by a C++ object. For technical
119 reasons, different music objects may be represented by different C++
120 object types. For example, a note is @code{Event} object, while
121 @code{\grace} creates a @code{Grace_music} object.
122
123 We expect that distinctions between different C++ types will disappear
124 in the future.
125 @end itemize
126
127 The actual information of a music expression is stored in properties.
128 For example, a @internalsref{NoteEvent} has @code{pitch} and
129 @code{duration} properties that store the pitch and duration of that
130 note.  A list of all properties available is in the internals manual,
131 under @internalsref{Music properties}.
132
133 A compound music expression is a music object that contains other
134 music objects in its properties. A list of objects can be stored in
135 the @code{elements} property of a music object, or a single `child'
136 music object in the @code{element} object. For example,
137 @internalsref{SequentialMusic} has its children in @code{elements},
138 and @internalsref{GraceMusic} has its single argument in
139 @code{element}. The body of a repeat is in @code{element} property of
140 @internalsref{RepeatedMusic}, and the alternatives in @code{elements}.
141
142
143
144
145 @node Extending music syntax
146 @appendixsubsec Extending music syntax
147
148 The syntax of composite music expressions, like
149 @code{\repeat}, @code{\transpose} and @code{\context}
150 follows the general form of
151
152 @example
153   \@code{keyword} @var{non-music-arguments} @var{music-arguments}
154 @end example
155
156 Such syntax can also be defined as user code. To do this, it is
157 necessary to create a @emph{music function}. This is a specially marked
158 Scheme function. For example, the music function @code{\applymusic} applies
159 a user-defined function to a music expression.  Its syntax is
160
161 @example
162 \applymusic #@var{func} @var{music}
163 @end example
164
165 A music function is created with @code{ly:make-music-function},
166
167 @example
168   (ly:make-music-function
169 @end example
170
171 @code{\applymusic} takes a Scheme function and a Music expression as
172 argument. This is encoded in its first argument,
173
174 @example
175    (list procedure? ly:music?)
176 @end example
177
178 The function itself takes another argument, an Input location
179 object. That object is used to provide error messages with file names
180 and line numbers.  The definition is the second argument of
181 @code{ly:make-music-function}. The body is function simply calls the
182 function
183
184 @example
185   (lambda (where func music)
186    (func music))
187 @end example
188
189 The above Scheme code only defines the functionality. The tag
190 @code{\applymusic} is selected by defining
191
192 @example
193   applymusic = #(ly:make-music-function
194                   (list procedure? ly:music?)
195                   (lambda (location func music)
196                     (func music)))
197 @end example
198
199 A @code{def-music-function} macro is introduced on top of
200 @code{ly:make-music-function} to ease the definition of music
201 functions:
202
203 @example
204   applymusic = #(def-music-function (location func music) (procedure? ly:music?)
205                   (func music))
206 @end example
207
208 Examples of the use of @code{\applymusic} are in the next section.
209
210 @seealso
211 @file{ly/music-functions-init.ly}.
212
213 @node Manipulating music expressions
214 @appendixsubsec Manipulating music expressions
215
216 Music objects and their properties can be accessed and manipulated
217 directly, through the @code{\applymusic} mechanism.
218 The syntax for @code{\applymusic} is
219 @example
220 \applymusic #@var{func} @var{music}
221 @end example
222
223 @noindent
224 This means that the scheme function @var{func} is called with
225 @var{music} as its argument.  The return value of @var{func} is the
226 result of the entire expression.  @var{func} may read and write music
227 properties using the functions @code{ly:music-property} and
228 @code{ly:music-set-property!}.
229
230 An example is a function that reverses the order of elements in
231 its argument:
232 @lilypond[verbatim,raggedright]
233   #(define (rev-music-1 m)
234      (ly:music-set-property! m 'elements (reverse
235        (ly:music-property m 'elements)))
236      m)
237   \score { \notes \applymusic #rev-music-1 { c4 d4 } }
238 @end lilypond
239
240 The use of such a function is very limited. The effect of this
241 function is void when applied to an argument which is does not have
242 multiple children.  The following function application has no effect:
243
244 @example
245   \applymusic #rev-music-1 \grace @{ c4 d4 @}
246 @end example
247
248 @noindent
249 In this case, @code{\grace} is stored as @internalsref{GraceMusic}, which has no
250 @code{elements}, only a single @code{element}. Every generally
251 applicable function for @code{\applymusic} must -- like music expressions
252 themselves -- be recursive.
253
254 The following example is such a recursive function: It first extracts
255 the @code{elements} of an expression, reverses them and puts them
256 back. Then it recurses, both on @code{elements} and @code{element}
257 children.
258 @example
259 #(define (reverse-music music)
260   (let* ((elements (ly:music-property music 'elements))
261          (child (ly:music-property music 'element))
262          (reversed (reverse elements)))
263
264     ; set children
265     (ly:music-set-property! music 'elements reversed)
266
267     ; recurse
268     (if (ly:music? child) (reverse-music child))
269     (map reverse-music reversed)
270
271     music))
272 @end example
273
274 A slightly more elaborate example is in
275 @inputfileref{input/test,reverse-music.ly}.
276
277 Some of the input syntax is also implemented as recursive music
278 functions. For example, the syntax for polyphony
279 @example
280   <<a \\ b>>
281 @end example
282
283 @noindent
284 is actually  implemented as a recursive function that replaces the
285 above by the internal equivalent of
286 @example
287   << \context Voice = "1" @{ \voiceOne a @}
288     \context Voice = "2" @{ \voiceTwo b @} >>
289 @end example
290
291 Other applications of @code{\applymusic} are writing out repeats
292 automatically (@inputfileref{input/test,unfold-all-repeats.ly}),
293 saving keystrokes (@inputfileref{input/test,music-box.ly}) and
294 exporting
295 LilyPond input to other formats  (@inputfileref{input/test,to-xml.ly})
296
297 @seealso
298
299 @file{scm/music-functions.scm}, @file{scm/music-types.scm},
300 @inputfileref{input/test,add-staccato.ly},
301 @inputfileref{input/test,unfold-all-repeats.ly}, and
302 @inputfileref{input/test,music-box.ly}.
303
304
305 @node Using LilyPond syntax inside Scheme
306 @appendixsubsec Using LilyPond syntax inside Scheme
307
308 Creating music expressions in scheme can be tedious, as they are
309 heavily nested and the resulting scheme code is large. For some
310 simple tasks, this can be avoided, using LilyPond usual syntax inside
311 scheme, with the dedicated @code{#@{ ... #@}} syntax.
312
313 The following two expressions give equivalent music expressions:
314 @example
315   mynotes = @{ \override Stem #'thickness = #4
316               \notes @{ c'8 d' @} @}
317   
318   #(define mynotes #@{ \override Stem #'thickness = #4
319                       \notes @{ c'8 d' @} #@})
320 @end example
321
322 The content of @code{#@{ ... #@}} is enclosed in an implicit @code{@{
323 ... @}} block, which is parsed. The resulting music expression, a
324 @code{SequentialMusic} music object, is then returned and usable in scheme.
325
326 Arbitrary scheme forms, including variables, can be used in @code{#@{ ... #@}}
327 expressions with the @code{$} character (@code{$$} can be used to
328 produce a single $ character). This makes the creation of simple
329 functions straightforward. In the following example, a function
330 setting the TextScript's padding is defined:
331
332 @lilypond[verbatim,raggedright]
333   #(use-modules (ice-9 optargs))
334   #(define* (textpad padding #:optional once?)
335     (ly:export   ; this is necessary for using the expression
336                  ; directly inside a \notes block
337       (if once?
338           #{ \once \override TextScript #'padding = #$padding #}
339           #{ \override TextScript #'padding = #$padding #})))
340   
341   \score {
342       \notes {
343           c'^"1"
344           #(textpad 3.0 #t) % only once
345           c'^"2"
346           c'^"3"
347           #(textpad 5.0)
348           c'^"4"
349           c'^"5"
350           
351       }
352   }
353 @end lilypond
354
355 Here, the variable @code{padding} is a number; music expression
356 variables may also be used in a similar fashion, as in the following
357 example:
358
359 @lilypond[verbatim,raggedright]
360   #(define (with-padding padding)
361      (lambda (music)
362        #{ \override TextScript #'padding = #$padding
363           $music
364           \revert TextScript #'padding #}))
365   
366   \score {
367       \notes {
368           c'^"1"
369           \applymusic #(with-padding 3)
370             { c'^"2" c'^"3"}
371           c'^"4"
372       }
373   }
374 @end lilypond
375
376 The function created by @code{(with-padding 3)} adds @code{\override} and
377 @code{\revert} statements around the music given as an argument, and returns
378 this new expression. Thus, this example is equivalent to:
379
380 @example
381   \score @{
382       \notes @{
383           c'^"1"
384           @{ \override TextScript #'padding = #3
385             @{ c'^"2" c'^"3"@}
386             \revert TextScript #'padding
387           @}
388           c'^"4"
389       @}
390   @}
391 @end example
392
393 This function may also be defined as a music function:
394
395 @lilypond[verbatim,raggedright]
396   withPadding = #(def-music-function (location padding music) (number? ly:music?)
397                    #{ \override TextScript #'padding = #$padding
398                       $music 
399                       \revert TextScript #'padding #})
400   
401   \score {
402       \notes {
403           c'^"1"
404           \withPadding #3
405             { c'^"2" c'^"3"}
406           c'^"4"
407       }
408   }
409 @end lilypond
410
411
412 @node Markup programmer interface
413 @appendixsec Markup programmer interface
414
415
416 @menu
417 * Markup construction in scheme::  
418 * Markup command definition::   
419 @end menu
420
421 @node Markup construction in scheme
422 @appendixsubsec Markup construction in scheme
423
424 @cindex defining markup commands 
425
426 The @code{markup} macro builds markup expressions in Scheme while
427 providing a LilyPond-like syntax. For example,
428 @example
429 (markup #:column (#:line (#:bold #:italic "hello" #:raise 0.4 "world")
430                   #:bigger #:line ("foo" "bar" "baz")))
431 @end example
432
433 @noindent
434 is equivalent to:
435 @example
436 \markup \column < @{ \bold \italic "hello" \raise #0.4 "world" @}
437                   \bigger @{ foo bar baz @} >
438 @end example
439
440 @noindent
441 This example exposes the main translation rules between regular
442 LilyPond markup syntax and scheme markup syntax, which are summed up
443 is this table:
444 @multitable @columnfractions .5 .5
445 @item @b{LilyPond} @tab @b{Scheme}
446 @item @code{\command} @tab @code{#:command}
447 @item @code{\variable} @tab @code{variable}
448 @item @code{@{ ... @}} @tab @code{#:line ( ... )}
449 @item @code{\center-align < ... >} @tab @code{#:center ( ... )}
450 @item @code{string} @tab @code{"string"}
451 @item @code{#scheme-arg} @tab @code{scheme-arg}
452 @end multitable
453
454 Besides, the whole scheme language is accessible inside the
455 @code{markup} macro: thus, one may use function calls inside
456 @code{markup} in order to manipulate character strings for
457 instance. This proves useful when defining new markup commands (see
458 @ref{Markup command definition}).
459
460 @refbugs
461
462 One can not feed the @code{#:line} (resp @code{#:center},
463 @code{#:column}) command with a variable or the result of a function
464 call. E.g.:
465 @lisp
466 (markup #:line (fun-that-returns-markups))
467 @end lisp
468 is illegal. One should use the @code{make-line-markup} (resp
469 @code{make-center-markup}, @code{make-column-markup}) function
470 instead:
471 @lisp
472 (markup (make-line-markup (fun-that-returns-markups)))
473 @end lisp
474
475 @node Markup command definition
476 @appendixsubsec Markup command definition
477
478 New markup commands can be defined
479 with  the @code{def-markup-command} scheme macro.
480 @lisp
481 (def-markup-command (@var{command-name} @var{paper} @var{props} @var{arg1} @var{arg2} ...)
482             (@var{arg1-type?} @var{arg2-type?} ...)
483   ..command body..)
484 @end lisp
485
486 The arguments signify
487
488 @table @var
489 @item argi
490 @var{i}th command argument
491 @item argi-type?
492 a type predicate for the i@var{th} argument
493 @item paper
494 the `paper' definition
495 @item props
496 a list of alists, containing all active properties. 
497 @end table
498
499 As a simple example, we show how to add a @code{\smallcaps} command,
500 which selects @TeX{}'s small caps font.  Normally, we could select the
501 small caps font as follows:
502
503 @verbatim
504   \markup { \override #'(font-shape . caps)  Text-in-caps }
505 @end verbatim
506
507 This selects the caps font by setting the @code{font-shape} property to
508 @code{#'caps} for interpreting @code{Text-in-caps}.
509
510 To make the above available as @code{\smallcaps} command, we have to
511 define a function using @code{def-markup-command}. The command should
512 take a single argument, of markup type. Therefore, the start of the
513 definition should read
514 @example
515   (def-markup-command (smallcaps paper props argument) (markup?)
516 @end example
517
518 @noindent
519
520 What follows is the content of the command: we should interpret
521 the @code{argument} as a markup, i.e.
522
523 @example
524     (interpret-markup paper  @dots{} argument)
525 @end example
526
527 @noindent
528 This interpretation should add @code{'(font-shape . caps)} to the active
529 properties, so we substitute the  following for the @dots{} in the
530 above example:
531
532 @example
533  (cons (list '(font-shape . caps) ) props)
534 @end example
535
536 @noindent
537 The variable @code{props} is a list of alists, and we prepend to it by
538 consing a list with the extra setting.
539
540
541 Suppose that we are typesetting a recitative in an opera, and
542 we would like to define a command that will show character names in a
543 custom manner. Names should be printed with small caps and translated a
544 bit to the left and top.  We will define a @code{\character} command
545 that takes into account the needed translation, and uses the newly
546 defined @code{\smallcaps} command:
547
548 @verbatim
549 #(def-markup-command (character paper props name) (string?)
550    "Print the character name in small caps, translated to the left and
551    top. Syntax: \\character #\"name\""
552    (interpret-markup paper props 
553     (markup "" #:translate (cons -4 2) #:smallcaps name)))
554 @end verbatim
555
556 There is one complication that needs explanation: texts above and below
557 the staff are moved vertically to be at a certain distance (the
558 @code{padding} property) from the staff and the notes. To make sure
559 that this mechanism does not annihilate the vertical effect of our
560 @code{#:translate}, we add an empty string (@code{""}) before the
561 translated text.  Now the @code{""} will be put above the notes, and the
562 @code{name} is moved in relation to that empty string. The net effect is
563 that the text is moved to the upper left.
564
565 The final result is as follows:
566 @verbatim
567 \score {
568     \notes { \fatText
569         c''^\markup \character #"Cleopatra"
570         e'^\markup \character #"Giulio Cesare"
571     }
572 }
573 @end verbatim
574
575 @lilypond[raggedright]
576 #(def-markup-command (smallcaps paper props str) (string?)
577    "Print the string argument in small caps. Syntax: \\smallcaps #\"string\""
578    (interpret-markup paper props
579     (make-line-markup
580      (map (lambda (s)
581             (if (= (string-length s) 0)
582                 s
583                 (markup #:large (string-upcase (substring s 0 1))
584                         #:translate (cons -0.6 0)
585                         #:tiny (string-upcase (substring s 1)))))
586           (string-split str #\Space)))))
587
588 #(def-markup-command (character paper props name) (string?)
589    "Print the character name in small caps, translated to the left and
590    top. Syntax: \\character #\"name\""
591    (interpret-markup paper props 
592     (markup "" #:translate (cons -4 0) #:smallcaps name)))
593
594 \score {
595     \notes { \fatText
596         c''^\markup \character #"Cleopatra"
597         e'^\markup \character #"Giulio Cesare"
598     }
599 }
600 @end lilypond
601
602 We have used the @code{caps} font shape, but suppose that our font
603 that does not have a small-caps variant. In that case, we have to fake
604 the small caps font, by setting a string in upcase, with the first
605 letter a little larger:
606
607 @example
608 #(def-markup-command (smallcaps paper props str) (string?)
609    "Print the string argument in small caps."
610    (interpret-markup paper props
611     (make-line-markup
612      (map (lambda (s)
613             (if (= (string-length s) 0)
614                 s
615                 (markup #:large (string-upcase (substring s 0 1))
616                         #:translate (cons -0.6 0)
617                         #:tiny (string-upcase (substring s 1)))))
618           (string-split str #\Space)))))
619 @end example
620
621 The @code{smallcaps} command first splits its string argument into
622 tokens separated by spaces (@code{(string-split str #\Space)}); for
623 each token, a markup is built with the first letter made large and
624 upcased (@code{#:large (string-upcase (substring s 0 1))}), and a
625 second markup built with the following letters made tiny and upcased
626 (@code{#:tiny (string-upcase (substring s 1))}). As LilyPond
627 introduces a space between markups on a line, the second markup is
628 translated to the left (@code{#:translate (cons -0.6 0) ...}). Then,
629 the markups built for each token are put in a line by
630 @code{(make-line-markup ...)}. Finally, the resulting markup is passed
631 to the @code{interpret-markup} function, with the @code{paper} and
632 @code{props} arguments.
633
634
635
636 @node Contexts for programmers
637 @appendixsec Contexts for programmers
638
639
640 @menu
641 * Context evaluation::          
642 * Running a function on all layout objects::  
643 @end menu
644
645 @node Context evaluation
646 @appendixsubsec Context evaluation
647
648 @cindex calling code during interpreting
649 @cindex @code{\applycontext}
650
651 Contexts can be modified during interpretation with Scheme code. The
652 syntax for this is
653 @example
654   \applycontext @var{function}
655 @end example
656
657 @var{function} should be a Scheme function taking a single argument,
658 being the context to apply it to. The following code will print the
659 current bar number on the standard output during the compile:
660
661 @example
662     \applycontext
663       #(lambda (x)
664          (format #t "\nWe were called in barnumber ~a.\n"
665           (ly:context-property x 'currentBarNumber)))
666 @end example
667
668
669
670 @node Running a function on all layout objects
671 @appendixsubsec Running a function on all layout objects
672
673
674 @cindex calling code on layout objects
675 @cindex @code{\applyoutput}
676
677
678 The most versatile way of tuning an object is @code{\applyoutput}. Its
679 syntax is
680 @example
681 \applyoutput @var{proc}
682 @end example
683
684 @noindent
685 where @var{proc} is a Scheme function, taking three arguments.
686
687 When interpreted, the function @var{proc} is called for every layout
688 object found in the context, with the following arguments:
689 @itemize @bullet
690 @item the layout object itself,
691 @item the context where the layout object was created, and
692 @item the context where @code{\applyoutput} is processed.
693 @end itemize
694
695
696 In addition, the cause of the layout object, i.e.  the music
697 expression or object that was responsible for creating it, is in the
698 object property @code{cause}.  For example, for a note head, this is a
699 @internalsref{NoteHead} event, and for a @internalsref{Stem} object,
700 this is a @internalsref{NoteHead} object.
701
702 Here is a function to use for @code{\applyoutput}; it blanks
703 note-heads on the center-line:
704
705 @example
706 (define (blanker grob grob-origin context)
707   (if (and (memq (ly:grob-property grob 'interfaces)
708                  note-head-interface)
709            (eq? (ly:grob-property grob 'staff-position) 0))
710
711            (set! (ly:grob-property grob 'transparent) #t)))
712 @end example
713