]> git.donarmstrong.com Git - lilypond.git/blob - Documentation/user/programming-interface.itely
remove split around-space hack.
[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. E.g.:
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
296 with  the @code{def-markup-command} scheme macro.
297 @lisp
298 (def-markup-command (@var{command-name} @var{paper} @var{props} @var{arg1} @var{arg2} ...)
299             (@var{arg1-type?} @var{arg2-type?} ...)
300   ..command body..)
301 @end lisp
302
303 The arguments signify
304
305 @table @var
306 @item argi
307 @var{i}th command argument
308 @item argi-type?
309 a type predicate for the i@var{th} argument
310 @item paper
311 the `paper' definition
312 @item props
313 a list of alists, containing all active properties. 
314 @end table
315
316 As a simple example, we show how to add a @code{\smallcaps} command,
317 which selects @TeX{}'s small caps font.  Normally, we could select the
318 small caps font as follows:
319
320 @verbatim
321   \markup { \override #'(font-shape . caps)  Text-in-caps }
322 @end verbatim
323
324 This selects the caps font by setting the @code{font-shape} property to
325 @code{#'caps} for interpreting @code{Text-in-caps}.
326
327 To make the above available as @code{\smallcaps} command, we have to
328 define a function using @code{def-markup-command}. The command should
329 take a single argument, of markup type. Therefore, the start of the
330 definition should read
331 @example
332   (def-markup-command (smallcaps paper props argument) (markup?)
333 @end example
334
335 @noindent
336
337 What follows is the content of the command: we should interpret
338 the @code{argument} as a markup, i.e.
339
340 @example
341     (interpret-markup paper  @dots{} argument)
342 @end example
343
344 @noindent
345 This interpretation should add @code{'(font-shape . caps)} to the active
346 properties, so we substitute the  following for the @dots{} in the
347 above example:
348
349 @example
350  (cons (list '(font-shape . caps) ) props)
351 @end example
352
353 @noindent
354 The variable @code{props} is a list of alists, and we prepend to it by
355 consing a list with the extra setting.
356
357
358 Suppose that we are typesetting a recitative in an opera, and
359 we would like to define a command that will show character names in a
360 custom manner. Names should be printed with small caps and translated a
361 bit to the left and top.  We will define a @code{\character} command
362 that takes into account the needed translation, and uses the newly
363 defined @code{\smallcaps} command:
364
365 @verbatim
366 #(def-markup-command (character paper props name) (string?)
367    "Print the character name in small caps, translated to the left and
368    top. Syntax: \\character #\"name\""
369    (interpret-markup paper props 
370     (markup "" #:translate (cons -4 2) #:smallcaps name)))
371 @end verbatim
372
373 There is one complication that needs explanation: texts above and below
374 the staff are moved vertically to be at a certain distance (the
375 @code{padding} property) from the staff and the notes. To make sure
376 that this mechanism does not annihilate the vertical effect of our
377 @code{#:translate}, we add an empty string (@code{""}) before the
378 translated text.  Now the @code{""} will be put above the notes, and the
379 @code{name} is moved in relation to that empty string. The net effect is
380 that the text is moved to the upper left.
381
382 The final result is as follows:
383 @verbatim
384 \score {
385     \notes { \fatText
386         c''^\markup \character #"Cleopatra"
387         e'^\markup \character #"Giulio Cesare"
388     }
389 }
390 @end verbatim
391
392 @lilypond[raggedright]
393 #(def-markup-command (smallcaps paper props str) (string?)
394    "Print the string argument in small caps. Syntax: \\smallcaps #\"string\""
395    (interpret-markup paper props
396     (make-line-markup
397      (map (lambda (s)
398             (if (= (string-length s) 0)
399                 s
400                 (markup #:large (string-upcase (substring s 0 1))
401                         #:translate (cons -0.6 0)
402                         #:tiny (string-upcase (substring s 1)))))
403           (string-split str #\Space)))))
404
405 #(def-markup-command (character paper props name) (string?)
406    "Print the character name in small caps, translated to the left and
407    top. Syntax: \\character #\"name\""
408    (interpret-markup paper props 
409     (markup "" #:translate (cons -4 0) #:smallcaps name)))
410
411 \score {
412     \notes { \fatText
413         c''^\markup \character #"Cleopatra"
414         e'^\markup \character #"Giulio Cesare"
415     }
416 }
417 @end lilypond
418
419 We have used the @code{caps} font shape, but suppose that our font
420 that does not have a small-caps variant. In that case, we have to fake
421 the small caps font, by setting a string in upcase, with the first
422 letter a little larger:
423
424 @example
425 #(def-markup-command (smallcaps paper props str) (string?)
426    "Print the string argument in small caps."
427    (interpret-markup paper props
428     (make-line-markup
429      (map (lambda (s)
430             (if (= (string-length s) 0)
431                 s
432                 (markup #:large (string-upcase (substring s 0 1))
433                         #:translate (cons -0.6 0)
434                         #:tiny (string-upcase (substring s 1)))))
435           (string-split str #\Space)))))
436 @end example
437
438 The @code{smallcaps} command first splits its string argument into
439 tokens separated by spaces (@code{(string-split str #\Space)}); for
440 each token, a markup is built with the first letter made large and
441 upcased (@code{#:large (string-upcase (substring s 0 1))}), and a
442 second markup built with the following letters made tiny and upcased
443 (@code{#:tiny (string-upcase (substring s 1))}). As LilyPond
444 introduces a space between markups on a line, the second markup is
445 translated to the left (@code{#:translate (cons -0.6 0) ...}). Then,
446 the markups built for each token are put in a line by
447 @code{(make-line-markup ...)}. Finally, the resulting markup is passed
448 to the @code{interpret-markup} function, with the @code{paper} and
449 @code{props} arguments.
450
451
452
453 @node Contexts for programmers
454 @appendixsec Contexts for programmers
455
456
457 @menu
458 * Context evaluation::          
459 * Running a function on all layout objects::  
460 @end menu
461
462 @node Context evaluation
463 @appendixsubsec Context evaluation
464
465 Contexts can be modified during interpretation with Scheme code. The
466 syntax for this is
467 @example
468   \applycontext @var{function}
469 @end example
470
471 @var{function} should be a Scheme function taking a single argument,
472 being the context to apply it to. The following code will print the
473 current bar number on the standard output during the compile:
474
475 @example
476     \applycontext
477       #(lambda (x)
478          (format #t "\nWe were called in barnumber ~a.\n"
479           (ly:context-property x 'currentBarNumber)))
480 @end example
481
482
483
484 @node Running a function on all layout objects
485 @appendixsubsec Running a function on all layout objects
486
487 The most versatile way of tuning an object is @code{\applyoutput}. Its
488 syntax is
489 @example
490 \applyoutput @var{proc}
491 @end example
492
493 @noindent
494 where @var{proc} is a Scheme function, taking three arguments.
495
496 When interpreted, the function @var{proc} is called for every layout
497 object found in the context, with the following arguments:
498 @itemize @bullet
499 @item the layout object itself,
500 @item the context where the layout object was created, and
501 @item the context where @code{\applyoutput} is processed.
502 @end itemize
503
504
505 In addition, the cause of the layout object, i.e.  the music
506 expression or object that was responsible for creating it, is in the
507 object property @code{cause}.  For example, for a note head, this is a
508 @internalsref{NoteHead} event, and for a @internalsref{Stem} object,
509 this is a @internalsref{NoteHead} object.
510
511 Here is a function to use for @code{\applyoutput}; it blanks
512 note-heads on the center-line:
513
514 @example
515 (define (blanker grob grob-origin context)
516   (if (and (memq (ly:grob-property grob 'interfaces)
517                  note-head-interface)
518            (eq? (ly:grob-property grob 'staff-position) 0))
519
520            (set! (ly:grob-property grob 'transparent) #t)))
521 @end example
522