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