]> git.donarmstrong.com Git - lilypond.git/blob - Documentation/user/programming-interface.itely
* Documentation/user/tutorial.itely (Integrating text and music):
[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 = @{ 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 = @{ 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 = @{ 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{... }''})
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 = @{ 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   @{ \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   @{ #(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   \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               @{ c'8 d' @} @}
318   
319   #(define mynotes #@{ \override Stem #'thickness = #4
320                       @{ 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 block
338       (if once?
339           #{ \once \override TextScript #'padding = #$padding #}
340           #{ \override TextScript #'padding = #$padding #})))
341   
342       {
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 @end lilypond
353
354 Here, the variable @code{padding} is a number; music expression
355 variables may also be used in a similar fashion, as in the following
356 example:
357
358 @lilypond[verbatim,raggedright]
359   #(define (with-padding padding)
360      (lambda (music)
361        #{ \override TextScript #'padding = #$padding
362           $music
363           \revert TextScript #'padding #}))
364   
365       {
366           c'^"1"
367           \applymusic #(with-padding 3)
368             { c'^"2" c'^"3"}
369           c'^"4"
370       }
371 @end lilypond
372
373 The function created by @code{(with-padding 3)} adds @code{\override} and
374 @code{\revert} statements around the music given as an argument, and returns
375 this new expression. Thus, this example is equivalent to:
376
377 @example
378       @{
379           c'^"1"
380           @{ \override TextScript #'padding = #3
381             @{ c'^"2" c'^"3"@}
382             \revert TextScript #'padding
383           @}
384           c'^"4"
385       @}
386 @end example
387
388 This function may also be defined as a music function:
389
390 @lilypond[verbatim,raggedright]
391   withPadding = #(def-music-function (location padding music) (number? ly:music?)
392                    #{ \override TextScript #'padding = #$padding
393                       $music 
394                       \revert TextScript #'padding #})
395   
396       {
397           c'^"1"
398           \withPadding #3
399             { c'^"2" c'^"3"}
400           c'^"4"
401       }
402 @end lilypond
403
404
405 @node Markup programmer interface
406 @section Markup programmer interface
407
408
409 @menu
410 * Markup construction in scheme::  
411 * Markup command definition::   
412 @end menu
413
414 @node Markup construction in scheme
415 @subsection Markup construction in scheme
416
417 @cindex defining markup commands 
418
419 The @code{markup} macro builds markup expressions in Scheme while
420 providing a LilyPond-like syntax. For example,
421 @example
422 (markup #:column (#:line (#:bold #:italic "hello" #:raise 0.4 "world")
423                   #:bigger #:line ("foo" "bar" "baz")))
424 @end example
425
426 @noindent
427 is equivalent to:
428 @example
429 \markup \column < @{ \bold \italic "hello" \raise #0.4 "world" @}
430                   \bigger @{ foo bar baz @} >
431 @end example
432
433 @noindent
434 This example exposes the main translation rules between regular
435 LilyPond markup syntax and scheme markup syntax, which are summed up
436 is this table:
437 @multitable @columnfractions .5 .5
438 @item @b{LilyPond} @tab @b{Scheme}
439 @item @code{\command} @tab @code{#:command}
440 @item @code{\variable} @tab @code{variable}
441 @item @code{@{ ... @}} @tab @code{#:line ( ... )}
442 @item @code{\center-align < ... >} @tab @code{#:center ( ... )}
443 @item @code{string} @tab @code{"string"}
444 @item @code{#scheme-arg} @tab @code{scheme-arg}
445 @end multitable
446
447 Besides, the whole scheme language is accessible inside the
448 @code{markup} macro: thus, one may use function calls inside
449 @code{markup} in order to manipulate character strings for
450 instance. This proves useful when defining new markup commands (see
451 @ref{Markup command definition}).
452
453 @refbugs
454
455 One can not feed the @code{#:line} (resp @code{#:center},
456 @code{#:column}) command with a variable or the result of a function
457 call. E.g.:
458 @lisp
459 (markup #:line (fun-that-returns-markups))
460 @end lisp
461 is illegal. One should use the @code{make-line-markup} (resp
462 @code{make-center-markup}, @code{make-column-markup}) function
463 instead:
464 @lisp
465 (markup (make-line-markup (fun-that-returns-markups)))
466 @end lisp
467
468 @node Markup command definition
469 @subsection Markup command definition
470
471 New markup commands can be defined
472 with  the @code{def-markup-command} scheme macro.
473 @lisp
474 (def-markup-command (@var{command-name} @var{paper} @var{props} @var{arg1} @var{arg2} ...)
475             (@var{arg1-type?} @var{arg2-type?} ...)
476   ..command body..)
477 @end lisp
478
479 The arguments signify
480
481 @table @var
482 @item argi
483 @var{i}th command argument
484 @item argi-type?
485 a type predicate for the i@var{th} argument
486 @item paper
487 the `paper' definition
488 @item props
489 a list of alists, containing all active properties. 
490 @end table
491
492 As a simple example, we show how to add a @code{\smallcaps} command,
493 which selects @TeX{}'s small caps font.  Normally, we could select the
494 small caps font as follows:
495
496 @verbatim
497   \markup { \override #'(font-shape . caps)  Text-in-caps }
498 @end verbatim
499
500 This selects the caps font by setting the @code{font-shape} property to
501 @code{#'caps} for interpreting @code{Text-in-caps}.
502
503 To make the above available as @code{\smallcaps} command, we have to
504 define a function using @code{def-markup-command}. The command should
505 take a single argument, of markup type. Therefore, the start of the
506 definition should read
507 @example
508   (def-markup-command (smallcaps paper props argument) (markup?)
509 @end example
510
511 @noindent
512
513 What follows is the content of the command: we should interpret
514 the @code{argument} as a markup, i.e.
515
516 @example
517     (interpret-markup paper  @dots{} argument)
518 @end example
519
520 @noindent
521 This interpretation should add @code{'(font-shape . caps)} to the active
522 properties, so we substitute the  following for the @dots{} in the
523 above example:
524
525 @example
526  (cons (list '(font-shape . caps) ) props)
527 @end example
528
529 @noindent
530 The variable @code{props} is a list of alists, and we prepend to it by
531 consing a list with the extra setting.
532
533
534 Suppose that we are typesetting a recitative in an opera, and
535 we would like to define a command that will show character names in a
536 custom manner. Names should be printed with small caps and translated a
537 bit to the left and top.  We will define a @code{\character} command
538 that takes into account the needed translation, and uses the newly
539 defined @code{\smallcaps} command:
540
541 @verbatim
542 #(def-markup-command (character paper props name) (string?)
543    "Print the character name in small caps, translated to the left and
544    top. Syntax: \\character #\"name\""
545    (interpret-markup paper props 
546     (markup "" #:translate (cons -4 2) #:smallcaps name)))
547 @end verbatim
548
549 There is one complication that needs explanation: texts above and below
550 the staff are moved vertically to be at a certain distance (the
551 @code{padding} property) from the staff and the notes. To make sure
552 that this mechanism does not annihilate the vertical effect of our
553 @code{#:translate}, we add an empty string (@code{""}) before the
554 translated text.  Now the @code{""} will be put above the notes, and the
555 @code{name} is moved in relation to that empty string. The net effect is
556 that the text is moved to the upper left.
557
558 The final result is as follows:
559 @verbatim
560     { \fatText
561         c''^\markup \character #"Cleopatra"
562         e'^\markup \character #"Giulio Cesare"
563     }
564 @end verbatim
565
566 @lilypond[raggedright]
567 #(def-markup-command (smallcaps paper props str) (string?)
568    "Print the string argument in small caps. Syntax: \\smallcaps #\"string\""
569    (interpret-markup paper props
570     (make-line-markup
571      (map (lambda (s)
572             (if (= (string-length s) 0)
573                 s
574                 (markup #:large (string-upcase (substring s 0 1))
575                         #:translate (cons -0.6 0)
576                         #:tiny (string-upcase (substring s 1)))))
577           (string-split str #\Space)))))
578
579 #(def-markup-command (character paper props name) (string?)
580    "Print the character name in small caps, translated to the left and
581    top. Syntax: \\character #\"name\""
582    (interpret-markup paper props 
583     (markup "" #:translate (cons -4 0) #:smallcaps name)))
584
585     { \fatText
586         c''^\markup \character #"Cleopatra"
587         e'^\markup \character #"Giulio Cesare"
588     }
589 @end lilypond
590
591 We have used the @code{caps} font shape, but suppose that our font
592 that does not have a small-caps variant. In that case, we have to fake
593 the small caps font, by setting a string in upcase, with the first
594 letter a little larger:
595
596 @example
597 #(def-markup-command (smallcaps paper props str) (string?)
598    "Print the string argument in small caps."
599    (interpret-markup paper props
600     (make-line-markup
601      (map (lambda (s)
602             (if (= (string-length s) 0)
603                 s
604                 (markup #:large (string-upcase (substring s 0 1))
605                         #:translate (cons -0.6 0)
606                         #:tiny (string-upcase (substring s 1)))))
607           (string-split str #\Space)))))
608 @end example
609
610 The @code{smallcaps} command first splits its string argument into
611 tokens separated by spaces (@code{(string-split str #\Space)}); for
612 each token, a markup is built with the first letter made large and
613 upcased (@code{#:large (string-upcase (substring s 0 1))}), and a
614 second markup built with the following letters made tiny and upcased
615 (@code{#:tiny (string-upcase (substring s 1))}). As LilyPond
616 introduces a space between markups on a line, the second markup is
617 translated to the left (@code{#:translate (cons -0.6 0) ...}). Then,
618 the markups built for each token are put in a line by
619 @code{(make-line-markup ...)}. Finally, the resulting markup is passed
620 to the @code{interpret-markup} function, with the @code{paper} and
621 @code{props} arguments.
622
623
624
625 @node Contexts for programmers
626 @section Contexts for programmers
627
628
629 @menu
630 * Context evaluation::          
631 * Running a function on all layout objects::  
632 @end menu
633
634 @node Context evaluation
635 @subsection Context evaluation
636
637 @cindex calling code during interpreting
638 @cindex @code{\applycontext}
639
640 Contexts can be modified during interpretation with Scheme code. The
641 syntax for this is
642 @example
643   \applycontext @var{function}
644 @end example
645
646 @var{function} should be a Scheme function taking a single argument,
647 being the context to apply it to. The following code will print the
648 current bar number on the standard output during the compile:
649
650 @example
651     \applycontext
652       #(lambda (x)
653          (format #t "\nWe were called in barnumber ~a.\n"
654           (ly:context-property x 'currentBarNumber)))
655 @end example
656
657
658
659 @node Running a function on all layout objects
660 @subsection Running a function on all layout objects
661
662
663 @cindex calling code on layout objects
664 @cindex @code{\applyoutput}
665
666
667 The most versatile way of tuning an object is @code{\applyoutput}. Its
668 syntax is
669 @example
670 \applyoutput @var{proc}
671 @end example
672
673 @noindent
674 where @var{proc} is a Scheme function, taking three arguments.
675
676 When interpreted, the function @var{proc} is called for every layout
677 object found in the context, with the following arguments:
678 @itemize @bullet
679 @item the layout object itself,
680 @item the context where the layout object was created, and
681 @item the context where @code{\applyoutput} is processed.
682 @end itemize
683
684
685 In addition, the cause of the layout object, i.e.  the music
686 expression or object that was responsible for creating it, is in the
687 object property @code{cause}.  For example, for a note head, this is a
688 @internalsref{NoteHead} event, and for a @internalsref{Stem} object,
689 this is a @internalsref{NoteHead} object.
690
691 Here is a function to use for @code{\applyoutput}; it blanks
692 note-heads on the center-line:
693
694 @example
695 (define (blanker grob grob-origin context)
696   (if (and (memq (ly:grob-property grob 'interfaces)
697                  note-head-interface)
698            (eq? (ly:grob-property grob 'staff-position) 0))
699
700            (set! (ly:grob-property grob 'transparent) #t)))
701 @end example
702