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