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