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