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