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