]> git.donarmstrong.com Git - lilypond.git/blob - Documentation/user/programming-interface.itely
* Documentation/user/changing-defaults.itely (Changing defaults):
[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 @node Manipulating music expressions
137 @appendixsubsec Manipulating music expressions
138
139 Music objects and their properties can be accessed and manipulated
140 directly, through the @code{\apply} mechanism.
141 The syntax for @code{\apply} is
142 @example
143 \apply #@var{func} @var{music}
144 @end example
145
146 @noindent
147 This means that the scheme function @var{func} is called with
148 @var{music} as its argument.  The return value of @var{func} is the
149 result of the entire expression.  @var{func} may read and write music
150 properties using the functions @code{ly:music-property} and
151 @code{ly:music-set-property!}.
152
153 An example is a function that reverses the order of elements in
154 its argument:
155 @lilypond[verbatim,raggedright]
156   #(define (rev-music-1 m)
157      (ly:music-set-property! m 'elements (reverse
158        (ly:music-property m 'elements)))
159      m)
160   \score { \notes \apply #rev-music-1 { c4 d4 } }
161 @end lilypond
162
163 The use of such a function is very limited. The effect of this
164 function is void when applied to an argument which is does not have
165 multiple children.  The following function application has no effect:
166
167 @example
168   \apply #rev-music-1 \grace @{ c4 d4 @}
169 @end example
170
171 @noindent
172 In this case, @code{\grace} is stored as @internalsref{GraceMusic}, which has no
173 @code{elements}, only a single @code{element}. Every generally
174 applicable function for @code{\apply} must -- like music expressions
175 themselves -- be recursive.
176
177 The following example is such a recursive function: It first extracts
178 the @code{elements} of an expression, reverses them and puts them
179 back. Then it recurses, both on @code{elements} and @code{element}
180 children.
181 @example
182 #(define (reverse-music music)
183   (let* ((elements (ly:music-property music 'elements))
184          (child (ly:music-property music 'element))
185          (reversed (reverse elements)))
186
187     ; set children
188     (ly:music-set-property! music 'elements reversed)
189
190     ; recurse
191     (if (ly:music? child) (reverse-music child))
192     (map reverse-music reversed)
193
194     music))
195 @end example
196
197 A slightly more elaborate example is in
198 @inputfileref{input/test,reverse-music.ly}.
199
200 Some of the input syntax is also implemented as recursive music
201 functions. For example, the syntax for polyphony
202 @example
203   <<a \\ b>>
204 @end example
205
206 @noindent
207 is actually  implemented as a recursive function that replaces the
208 above by the internal equivalent of
209 @example
210   << \context Voice = "1" @{ \voiceOne a @}
211     \context Voice = "2" @{ \voiceTwo b @} >>
212 @end example
213
214 Other applications of @code{\apply} are writing out repeats
215 automatically (@inputfileref{input/test,unfold-all-repeats.ly}),
216 saving keystrokes (@inputfileref{input/test,music-box.ly}) and
217 exporting
218 LilyPond input to other formats  (@inputfileref{input/test,to-xml.ly})
219
220 @seealso
221
222 @file{scm/music-functions.scm}, @file{scm/music-types.scm},
223 @inputfileref{input/test,add-staccato.ly},
224 @inputfileref{input/test,unfold-all-repeats.ly}, and
225 @inputfileref{input/test,music-box.ly}.
226
227
228
229 @node Markup programmer interface
230 @appendixsec Markup programmer interface
231
232
233 @menu
234 * Markup construction in scheme::  
235 * Markup command definition::   
236 @end menu
237
238 @node Markup construction in scheme
239 @appendixsubsec Markup construction in scheme
240
241 @cindex defining markup commands 
242
243 The @code{markup} macro builds markup expressions in Scheme while
244 providing a LilyPond-like syntax. For example,
245 @example
246 (markup #:column (#:line (#:bold #:italic "hello" #:raise 0.4 "world")
247                   #:bigger #:line ("foo" "bar" "baz")))
248 @end example
249
250 @noindent
251 is equivalent to:
252 @example
253 \markup \column < @{ \bold \italic "hello" \raise #0.4 "world" @}
254                   \bigger @{ foo bar baz @} >
255 @end example
256
257 @noindent
258 This example exposes the main translation rules between regular
259 LilyPond markup syntax and scheme markup syntax, which are summed up
260 is this table:
261 @multitable @columnfractions .5 .5
262 @item @b{LilyPond} @tab @b{Scheme}
263 @item @code{\command} @tab @code{#:command}
264 @item @code{\variable} @tab @code{variable}
265 @item @code{@{ ... @}} @tab @code{#:line ( ... )}
266 @item @code{\center-align < ... >} @tab @code{#:center ( ... )}
267 @item @code{string} @tab @code{"string"}
268 @item @code{#scheme-arg} @tab @code{scheme-arg}
269 @end multitable
270
271 Besides, the whole scheme language is accessible inside the
272 @code{markup} macro: thus, one may use function calls inside
273 @code{markup} in order to manipulate character strings for
274 instance. This proves useful when defining new markup commands (see
275 @ref{Markup command definition}).
276
277 @refbugs
278
279 One can not feed the @code{#:line} (resp @code{#:center},
280 @code{#:column}) command with a variable or the result of a function
281 call. Eg:
282 @lisp
283 (markup #:line (fun-that-returns-markups))
284 @end lisp
285 is illegal. One should use the @code{make-line-markup} (resp
286 @code{make-center-markup}, @code{make-column-markup}) function
287 instead:
288 @lisp
289 (markup (make-line-markup (fun-that-returns-markups)))
290 @end lisp
291
292 @node Markup command definition
293 @appendixsubsec Markup command definition
294
295 New markup commands can be defined thanks to the @code{def-markup-command} scheme macro.
296 @lisp
297 (def-markup-command (@var{command-name} @var{paper} @var{props} @var{arg1} @var{arg2} ...)
298             (@var{arg1-type?} @var{arg2-type?} ...)
299   ..command body..)
300
301     @var{argi}: i@var{th} command argument
302     @var{argi-type?}: a type predicate for the i@var{th} argument
303     @var{paper}: the `paper' definition
304     @var{props}: a list of alists, containing all active properties. 
305 @end lisp
306
307 As a simple example, we show how to add a @code{\smallcaps} command,
308 which selects @TeX{}'s small caps font.  Normally, we could select the
309 small caps font as follows:
310
311 @verbatim
312   \markup { \override #'(font-shape . caps)  Text-in-caps }
313 @end verbatim
314
315 This selects the caps font by setting the @code{font-shape} property to
316 @code{#'caps} for interpreting @code{Text-in-caps}.
317
318 To make the above available as @code{\smallcaps} command, we have to
319 define a function using @code{def-markup-command}. The command should
320 take a single argument, of markup type. Therefore, the start of the
321 definition should read
322 @example
323   (def-markup-command (smallcaps paper props argument) (markup?)
324 @end example
325
326 @noindent
327
328 What follows is the content of the command: we should interpret
329 the @code{argument} as a markup, i.e.
330
331 @example
332     (interpret-markup paper  @dots{} argument)
333 @end example
334
335 @noindent
336 This interpretation should add @code{'(font-shape . caps)} to the active
337 properties, so we substitute the the following for the @dots{} in the
338 above example:
339
340 @example
341  (cons (list '(font-shape . caps) ) props)
342 @end example
343
344 @noindent
345 The variable @code{props} is a list of alists, and we prepend to it by
346 consing a list with the extra setting.
347
348 However, suppose that we are using a font that does not have a
349 small-caps variant. In that case, we have to fake the small caps font,
350 by setting a string in upcase, with the first letter a little larger:
351
352 @example
353 #(def-markup-command (smallcaps paper props str) (string?)
354    "Print the string argument in small caps. Syntax: \\smallcaps #\"string\""
355    (interpret-markup paper props
356     (make-line-markup
357      (map (lambda (s)
358             (if (= (string-length s) 0)
359                 s
360                 (markup #:large (string-upcase (substring s 0 1))
361                         #:translate (cons -0.6 0)
362                         #:tiny (string-upcase (substring s 1)))))
363           (string-split str #\Space)))))
364 @end example
365
366 The @code{smallcaps} command first splits its string argument into
367 tokens separated by spaces (@code{(string-split str #\Space)}); for
368 each token, a markup is built with the first letter made large and
369 upcased (@code{#:large (string-upcase (substring s 0 1))}), and a
370 second markup built with the following letters made tiny and upcased
371 (@code{#:tiny (string-upcase (substring s 1))}). As LilyPond
372 introduces a space between markups on a line, the second markup is
373 translated to the left (@code{#:translate (cons -0.6 0) ...}). Then,
374 the markups built for each token are put in a line
375 (@code{(make-line-markup ...)}). Finally, the resulting markup is
376 passed to the @code{interpret-markup} function, with the @code{paper}
377 and @code{props} arguments.
378
379 Finally, suppose that we are typesetting a recitative in an opera, and
380 we would like to define a command that will show character names in a
381 custom manner. Names should be printed with small caps and translated a
382 bit to the left and top.  We will define a @code{\character} command
383 that takes into account the needed translation, and uses the newly
384 defined @code{\smallcaps} command:
385
386 @verbatim
387 #(def-markup-command (character paper props name) (string?)
388    "Print the character name in small caps, translated to the left and
389    top. Syntax: \\character #\"name\""
390    (interpret-markup paper props 
391     (markup "" #:translate (cons -4 2) #:smallcaps name)))
392 @end verbatim
393
394 There is one complication that needs explanation: texts above and below
395 the staff are moved vertically to be at a certain distance (the
396 @code{padding} property) from the staff and the notes. To make sure
397 that this mechanism does not annihilate the vertical effect of our
398 @code{#:translate}, we add an empty string (@code{""}) before the
399 translated text.  Now the @code{""} will be put above the notes, and the
400 @code{name} is moved in relation to that empty string. The net effect is
401 that the text is moved to the upper left.
402
403 The final result is as follows:
404 @verbatim
405 \score {
406     \notes { \fatText
407         c''^\markup \character #"Cleopatra"
408         e'^\markup \character #"Giulio Cesare"
409     }
410 }
411 @end verbatim
412
413 @lilypond[raggedright]
414 #(def-markup-command (smallcaps paper props str) (string?)
415    "Print the string argument in small caps. Syntax: \\smallcaps #\"string\""
416    (interpret-markup paper props
417     (make-line-markup
418      (map (lambda (s)
419             (if (= (string-length s) 0)
420                 s
421                 (markup #:large (string-upcase (substring s 0 1))
422                         #:translate (cons -0.6 0)
423                         #:tiny (string-upcase (substring s 1)))))
424           (string-split str #\Space)))))
425
426 #(def-markup-command (character paper props name) (string?)
427    "Print the character name in small caps, translated to the left and
428    top. Syntax: \\character #\"name\""
429    (interpret-markup paper props 
430     (markup "" #:translate (cons -4 0) #:smallcaps name)))
431
432 \score {
433     \notes { \fatText
434         c''^\markup \character #"Cleopatra"
435         e'^\markup \character #"Giulio Cesare"
436     }
437 }
438 @end lilypond
439
440
441
442 @node Contexts for programmers
443 @appendixsec Contexts for programmers
444
445
446 @menu
447 * Context evaluation::          
448 * Applyoutput::                 
449 @end menu
450
451 @node Context evaluation
452 @appendixsubsec Context evaluation
453
454 Contexts can be modified during interpretation with Scheme code. The
455 syntax for this is
456 @example
457   \applycontext @var{function}
458 @end example
459
460 @var{function} should be a Scheme function taking a single argument,
461 being the context to apply it to. The following code will print the
462 current bar number on the standard output during the compile:
463
464 @example
465     \applycontext
466       #(lambda (x)
467          (format #t "\nWe were called in barnumber ~a.\n"
468           (ly:context-property x 'currentBarNumber)))
469 @end example
470
471
472
473 @node Applyoutput
474 @appendixsubsec Applyoutput
475
476 The most versatile way of tuning an object is @code{\applyoutput}. Its
477 syntax is
478 @example
479 \applyoutput @var{proc}
480 @end example
481
482 @noindent
483 where @var{proc} is a Scheme function, taking three arguments.
484
485 When interpreted, the function @var{proc} is called for every layout
486 object found in the context, with the following arguments:
487 @itemize @bullet
488 @item the layout object itself,
489 @item the context where the layout object was created, and
490 @item the context where @code{\applyoutput} is processed.
491 @end itemize
492
493
494 In addition, the cause of the layout object, i.e.  the music
495 expression or object that was responsible for creating it, is in the
496 object property @code{cause}.  For example, for a note head, this is a
497 @internalsref{NoteHead} event, and for a @internalsref{Stem} object,
498 this is a @internalsref{NoteHead} object.
499
500 Here is a simple example of @code{\applyoutput}; it blanks note-heads on the
501 center-line:
502 @example
503 (define (blanker grob grob-origin context)
504   (if (and (memq (ly:grob-property grob 'interfaces)
505                  note-head-interface)
506            (eq? (ly:grob-property grob 'staff-position) 0))
507
508            (ly:grob-set-property! grob 'transparent #t)))
509 @end example
510