]> git.donarmstrong.com Git - lilypond.git/blob - Documentation/extending/programming-interface.itely
7c8b287552fede93f24346adeaf14aca550302f8
[lilypond.git] / Documentation / extending / programming-interface.itely
1 @c -*- coding: utf-8; mode: texinfo; -*-
2
3 @ignore
4     Translation of GIT committish: FILL-IN-HEAD-COMMITTISH
5
6     When revising a translation, copy the HEAD committish of the
7     version that you are working on.  For details, see the Contributors'
8     Guide, node Updating translation committishes..
9 @end ignore
10
11 @c \version "2.12.0"
12
13 @node Interfaces for programmers
14 @chapter Interfaces for programmers
15
16 Advanced tweaks may be performed by using Scheme.  If you are
17 not familiar with Scheme, you may wish to read our
18 @ref{Scheme tutorial}.
19
20 @menu
21 * Music functions::
22 * Markup functions::
23 * Contexts for programmers::
24 * Callback functions::
25 * Inline Scheme code::
26 * Difficult tweaks::
27 @end menu
28
29
30 @node Music functions
31 @section Music functions
32
33 @emph{Music functions} are scheme procedures that can create music
34 expressions automatically, and can be used to greatly simplify the
35 input file.
36
37 @menu
38 * Music function syntax::
39 * Simple substitution functions::
40 * Intermediate substitution functions::
41 * Mathematics in functions::
42 * Functions without arguments::
43 * Void functions::
44 @end menu
45
46
47 @node Music function syntax
48 @subsection Music function syntax
49
50 The general form for music functions is:
51
52 @example
53 function =
54 #(define-music-function
55      (parser location @var{arg1} @var{arg2} @dots{})
56      (@var{type1?} @var{type2?} @dots{})
57    @var{music})
58 @end example
59
60 @noindent
61 where
62
63 @multitable @columnfractions .33 .66
64 @item @code{@var{argN}}
65 @tab @var{n}th argument
66
67 @item @code{@var{typeN?}}
68 @tab a scheme @emph{type predicate} for which @code{@var{argN}}
69 must return @code{#t}.
70
71 @item @code{@var{music}}
72 @tab A music expression, optionally written in scheme, with any
73 LilyPond code enclosed in hashed braces
74 (@tie{}@w{@code{#@{@dots{}#@}}}@tie{}).  Within LilyPond code
75 blocks, use @code{$} to reference function arguments (eg.,
76 @samp{$arg1}) or to start an inline scheme expression containing
77 function arguments (eg., @w{@samp{$(cons arg1 arg2)}}).
78
79 @end multitable
80
81 @noindent
82 For a list of available type predicates, see
83 @ruser{Predefined type predicates}.  User-defined type predicates
84 are also allowed.
85
86
87 @seealso
88
89 Notation Reference:
90 @ruser{Predefined type predicates}.
91
92 Installed Files:
93 @file{lily/music-scheme.cc},
94 @file{scm/c++.scm},
95 @file{scm/lily.scm}.
96
97
98 @node Simple substitution functions
99 @subsection Simple substitution functions
100
101 Simple substitution functions are music functions whose output
102 music expression is written in LilyPond format and contains
103 function arguments in the output expression.  They are described
104 in @ruser{Substitution function examples}.
105
106
107 @node Intermediate substitution functions
108 @subsection Intermediate substitution functions
109
110 Intermediate substitution functions involve a mix of Scheme code
111 and LilyPond code in the music expression to be returned.
112
113 Some @code{\override} commands require an argument consisting of
114 a pair of numbers (called a @code{cons cell} in Scheme).
115
116 The pair can be directly passed into the music function,
117 using a @code{pair?} variable:
118
119 @example
120 manualBeam =
121 #(define-music-function
122      (parser location beg-end)
123      (pair?)
124    #@{
125      \once \override Beam #'positions = $beg-end
126    #@})
127
128 \relative c' @{
129   \manualBeam #'(3 . 6) c8 d e f
130 @}
131 @end example
132
133 Alternatively, the numbers making up the pair can be
134 passed as separate arguments, and the Scheme code
135 used to create the pair can be included in the
136 music expression:
137
138 @lilypond[quote,verbatim,ragged-right]
139 manualBeam =
140 #(define-music-function
141      (parser location beg end)
142      (number? number?)
143    #{
144      \once \override Beam #'positions = $(cons beg end)
145    #})
146
147 \relative c' {
148   \manualBeam #3 #6 c8 d e f
149 }
150 @end lilypond
151
152
153 @node Mathematics in functions
154 @subsection Mathematics in functions
155
156 Music functions can involve Scheme programming in
157 addition to simple substitution,
158
159 @lilypond[quote,verbatim,ragged-right]
160 AltOn =
161 #(define-music-function
162      (parser location mag)
163      (number?)
164    #{
165      \override Stem #'length = $(* 7.0 mag)
166      \override NoteHead #'font-size =
167        $(inexact->exact (* (/ 6.0 (log 2.0)) (log mag)))
168    #})
169
170 AltOff = {
171   \revert Stem #'length
172   \revert NoteHead #'font-size
173 }
174
175 \relative c' {
176   c2 \AltOn #0.5 c4 c
177   \AltOn #1.5 c c \AltOff c2
178 }
179 @end lilypond
180
181 @noindent
182 This example may be rewritten to pass in music expressions,
183
184 @lilypond[quote,verbatim,ragged-right]
185 withAlt =
186 #(define-music-function
187      (parser location mag music)
188      (number? ly:music?)
189    #{
190      \override Stem #'length = $(* 7.0 mag)
191      \override NoteHead #'font-size =
192        $(inexact->exact (* (/ 6.0 (log 2.0)) (log mag)))
193      $music
194      \revert Stem #'length
195      \revert NoteHead #'font-size
196    #})
197
198 \relative c' {
199   c2 \withAlt #0.5 { c4 c }
200   \withAlt #1.5 { c c } c2
201 }
202 @end lilypond
203
204
205 @node Functions without arguments
206 @subsection Functions without arguments
207
208 In most cases a function without arguments should be written
209 with a variable,
210
211 @example
212 dolce = \markup@{ \italic \bold dolce @}
213 @end example
214
215 However, in rare cases it may be useful to create a music function
216 without arguments,
217
218 @example
219 displayBarNum =
220 #(define-music-function
221      (parser location)
222      ()
223    (if (eq? #t (ly:get-option 'display-bar-numbers))
224        #@{ \once \override Score.BarNumber #'break-visibility = ##f #@}
225        #@{#@}))
226 @end example
227
228 To actually display bar numbers where this function is called,
229 invoke @command{lilypond} with
230
231 @example
232 lilypond -d display-bar-numbers FILENAME.ly
233 @end example
234
235
236 @node Void functions
237 @subsection Void functions
238
239 A music function must return a music expression, but sometimes we
240 may want to have a function that does not involve music (such as
241 turning off Point and Click).  To do this, we return a @code{void}
242 music expression.
243
244 That is why the form that is returned is the
245 @w{@code{(make-music @dots{})}}.  With the @code{'void} property
246 set to @code{#t}, the parser is told to actually disregard this
247 returned music expression.  Thus the important part of the void
248 music function is the processing done by the function, not the
249 music expression that is returned.
250
251 @example
252 noPointAndClick =
253 #(define-music-function
254      (parser location)
255      ()
256    (ly:set-option 'point-and-click #f)
257    (make-music 'SequentialMusic 'void #t))
258 ...
259 \noPointAndClick   % disable point and click
260 @end example
261
262
263 @node Markup functions
264 @section Markup functions
265
266 Markups are implemented as special Scheme functions which produce a
267 @code{Stencil} object given a number of arguments.
268
269 @menu
270 * Markup construction in Scheme::
271 * How markups work internally::
272 * New markup command definition::
273 * New markup list command definition::
274 @end menu
275
276
277 @node Markup construction in Scheme
278 @subsection Markup construction in Scheme
279
280 @cindex defining markup commands
281
282 The @code{markup} macro builds markup expressions in Scheme while
283 providing a LilyPond-like syntax.  For example,
284 @example
285 (markup #:column (#:line (#:bold #:italic "hello" #:raise 0.4 "world")
286                   #:larger #:line ("foo" "bar" "baz")))
287 @end example
288
289 @noindent
290 is equivalent to:
291 @example
292 \markup \column @{ \line @{ \bold \italic "hello" \raise #0.4 "world" @}
293                   \larger \line @{ foo bar baz @} @}
294 @end example
295
296 @noindent
297 This example demonstrates the main translation rules between regular
298 LilyPond markup syntax and Scheme markup syntax.
299
300 @quotation
301 @multitable @columnfractions .3 .3
302 @item @b{LilyPond} @tab @b{Scheme}
303 @item @code{\markup markup1} @tab @code{(markup markup1)}
304 @item @code{\markup @{ markup1 markup2 ... @}} @tab
305         @code{(markup markup1 markup2 ... )}
306 @item @code{\markup-command} @tab @code{#:markup-command}
307 @item @code{\variable} @tab @code{variable}
308 @item @code{\center-column @{ ... @}} @tab @code{#:center-column ( ... )}
309 @item @code{string} @tab @code{"string"}
310 @item @code{#scheme-arg} @tab @code{scheme-arg}
311 @end multitable
312 @end quotation
313
314 The whole Scheme language is accessible inside the
315 @code{markup} macro.  For example, You may use function calls inside
316 @code{markup} in order to manipulate character strings.  This is
317 useful when defining new markup commands (see
318 @ref{New markup command definition}).
319
320
321 @knownissues
322
323 The markup-list argument of commands such as @code{#:line},
324 @code{#:center}, and @code{#:column} cannot be a variable or
325 the result of a function call.
326
327 @lisp
328 (markup #:line (function-that-returns-markups))
329 @end lisp
330
331 @noindent
332 is invalid.  One should use the @code{make-line-markup},
333 @code{make-center-markup}, or @code{make-column-markup} functions
334 instead,
335
336 @lisp
337 (markup (make-line-markup (function-that-returns-markups)))
338 @end lisp
339
340
341 @node How markups work internally
342 @subsection How markups work internally
343
344 In a markup like
345
346 @example
347 \raise #0.5 "text example"
348 @end example
349
350 @noindent
351 @code{\raise} is actually represented by the @code{raise-markup}
352 function.  The markup expression is stored as
353
354 @example
355 (list raise-markup 0.5 (list simple-markup "text example"))
356 @end example
357
358 When the markup is converted to printable objects (Stencils), the
359 @code{raise-markup} function is called as
360
361 @example
362 (apply raise-markup
363        @var{\layout object}
364        @var{list of property alists}
365        0.5
366        @var{the "text example" markup})
367 @end example
368
369 The @code{raise-markup} function first creates the stencil for the
370 @code{text example} string, and then it raises that Stencil by 0.5
371 staff space.  This is a rather simple example; more complex examples
372 are in the rest
373 of this section, and in @file{scm/@/define@/-markup@/-commands@/.scm}.
374
375
376 @node New markup command definition
377 @subsection New markup command definition
378
379 This section discusses the definition of new markup commands.
380
381 @menu
382 * Markup command definition syntax::
383 * On properties::
384 * A complete example::
385 * Adapting builtin commands::
386 @end menu
387
388 @node Markup command definition syntax
389 @unnumberedsubsubsec Markup command definition syntax
390
391 New markup commands can be defined using the
392 @code{define-markup-command} Scheme macro, at top-level.
393
394 @lisp
395 (define-markup-command (@var{command-name} @var{layout} @var{props} @var{arg1} @var{arg2} ...)
396     (@var{arg1-type?} @var{arg2-type?} ...)
397     [ #:properties ((@var{property1} @var{default-value1})
398                     ...) ]
399   ..command body..)
400 @end lisp
401
402 The arguments are
403
404 @table @var
405 @item command-name
406 the markup command name
407 @item layout
408 the @q{layout} definition.
409 @item props
410 a list of associative lists, containing all active properties.
411 @item argi
412 @var{i}th command argument
413 @item argi-type?
414 a type predicate for the i@var{th} argument
415 @end table
416
417 If the command uses properties from the @var{props} arguments, the
418 @code{#:properties} keyword can be used, to specify which properties are
419 used, and their default values.
420
421 @knownissues
422 There are restrictions on the possible arguments to a markup command.
423
424 Arguments are distingued according to their type:
425 @itemize
426 @item a markup, corresponding to type predicate @code{markup?};
427 @item a list of markup, corresponding to type predicate
428 @code{markup-list?};
429 @item any other scheme object, corresponding to type predicates such as
430 @code{list?}, @code{number?}, @code{boolean?}, etc.
431 @end itemize
432
433 The available combinations of arguments (after the standard @var{layout}
434 and @var{props} arguments) to a markup command defined with
435 @code{define-markup-command} are limited as follows.
436
437 @table @asis
438 @item (no argument)
439 @itemx @var{markup-list}
440 @itemx @var{markup}
441 @itemx @var{markup markup}
442 @itemx @var{scheme}
443 @itemx @var{scheme markup}
444 @itemx @var{scheme scheme}
445 @itemx @var{scheme scheme markup}
446 @itemx @var{scheme scheme markup markup}
447 @itemx @var{scheme markup markup}
448 @itemx @var{scheme scheme scheme}
449 @end table
450
451 @noindent
452 This means that it is not possible to define with e.g. three scheme
453 arguments and a markup arguments, like:
454
455 @example
456 #(define-markup-command (foo layout props
457                          num1    num2    a-list a-markup)
458                         (number? number? list?  markup?)
459   ...)
460 @end example
461
462 @noindent
463 If you apply it as, say,
464
465 @example
466 \markup \foo #1 #2 #'(bar baz) Blah
467 @end example
468
469 @cindex Scheme signature
470 @cindex signature, Scheme
471 @noindent
472 @command{lilypond} complains that it cannot parse @code{foo} due to its
473 unknown Scheme signature.
474
475 @node On properties
476 @unnumberedsubsubsec On properties
477
478 The @code{layout} and @code{props} arguments of markup commands bring a
479 context for the markup interpretation: font size, line width, etc.
480
481 The @code{layout} argument allows access to properties defined in
482 @code{paper} blocks, using the @code{ly:output-def-lookup} function.
483 For instance, the line width (the same as the one used in scores) is
484 read using:
485
486 @example
487 (ly:output-def-lookup layout 'line-width)
488 @end example
489
490 The @code{props} argument makes some properties accessible to markup
491 commands.  For instance, when a book title markup is interpreted, all
492 the variables defined in the @code{\header} block are automatically
493 added to @code{props}, so that the book title markup can access the book
494 title, composer, etc.  It is also a way to configure the behaviour of a
495 markup command: for example, when a command uses font size during
496 processing, the font size is read from @code{props} rather than having a
497 @code{font-size} argument.  The caller of a markup command may change
498 the value of the font size property in order to change the behaviour.
499 Use the @code{#:properties} keyword of @code{define-markup-command} to
500 specify which properties shall be read from the @code{props} arguments.
501
502 The example in next section illustrates how to access and override
503 properties in a markup command.
504
505 @node A complete example
506 @unnumberedsubsubsec A complete example
507
508 The following example defines a markup command to draw a double box
509 around a piece of text.
510
511 Firstly, we need to build an approximative result using markups.
512 Consulting the @ruser{Text markup commands} shows us the @code{\box}
513 command is useful:
514
515 @lilypond[quote,verbatim,ragged-right]
516 \markup \box \box HELLO
517 @end lilypond
518
519 Now, we consider that more padding between the text and the boxes is
520 preferable.  According to the @code{\box} documentation, this command
521 uses a @code{box-padding} property, which defaults to 0.2.  The
522 documentation also mentions how to override it:
523
524 @lilypond[quote,verbatim,ragged-right]
525 \markup \box \override #'(box-padding . 0.6) \box A
526 @end lilypond
527
528 Then, the padding between the two boxes is considered too small, so we
529 override it too:
530
531 @lilypond[quote,verbatim,ragged-right]
532 \markup \override #'(box-padding . 0.4) \box \override #'(box-padding . 0.6) \box A
533 @end lilypond
534
535 Repeating this lengthy markup would be painful.  This is where a markup
536 command is needed.  Thus, we write a @code{double-box} markup command,
537 taking one argument (the text).  This draws the two boxes, with some
538 padding.
539
540 @lisp
541 #(define-markup-command (double-box layout props text) (markup?)
542   "Draw a double box around text."
543   (interpret-markup layout props
544     (markup #:override '(box-padding . 0.4) #:box
545             #:override '(box-padding . 0.6) #:box text)))
546 @end lisp
547
548 @code{text} is the name of the command argument, and @code{markup?} its
549 type: it identifies it as a markup.  The @code{interpret-markup}
550 function is used in most of markup commands: it builds a stencil, using
551 @code{layout}, @code{props}, and a markup.  Here, this markup is built
552 using the @code{markup} scheme macro, see @ref{Markup construction in Scheme}.
553 The transformation from @code{\markup} expression to scheme
554 markup expression is straight-forward.
555
556 The new command can be used as follow:
557
558 @example
559 \markup \double-box A
560 @end example
561
562 It would be nice to make the @code{double-box} command customizable:
563 here, the @code{box-padding} values are hard coded, and cannot be
564 changed by the user.  Also, it would be better to distinguish the
565 padding between the two boxes, from the padding between the inner box
566 and the text. So we will introduce a new property,
567 @code{inter-box-padding}, for the padding between the two boxes. The
568 @code{box-padding} will be used for the inner padding.  The new code is
569 now as follows:
570
571 @lisp
572 #(define-markup-command (double-box layout props text) (markup?)
573   #:properties ((inter-box-padding 0.4)
574                 (box-padding 0.6))
575   "Draw a double box around text."
576   (interpret-markup layout props
577     (markup #:override `(box-padding . ,inter-box-padding) #:box
578             #:override `(box-padding . ,box-padding) #:box text)))
579 @end lisp
580
581 Here, the @code{#:properties} keyword is used so that the
582 @code{inter-box-padding} and @code{box-padding} properties are read from
583 the @code{props} argument, and default values are given to them if the
584 properties are not defined.
585
586 Then, these values are used to override the @code{box-padding}
587 properties used by the two @code{\box} commands.  Note the backquote and
588 the comma in the @code{\override} argument: they allow you to introduce
589 a variable value into a literal expression.
590
591 Now, the command can be used in a markup, and the boxes padding be
592 customized:
593
594 @lilypond[quote,verbatim,ragged-right]
595 #(define-markup-command (double-box layout props text) (markup?)
596   #:properties ((inter-box-padding 0.4)
597                 (box-padding 0.6))
598   "Draw a double box around text."
599   (interpret-markup layout props
600     (markup #:override `(box-padding . ,inter-box-padding) #:box
601             #:override `(box-padding . ,box-padding) #:box text)))
602
603 \markup \double-box A
604 \markup \override #'(inter-box-padding . 0.8) \double-box A
605 \markup \override #'(box-padding . 1.0) \double-box A
606 @end lilypond
607
608 @node Adapting builtin commands
609 @unnumberedsubsubsec Adapting builtin commands
610
611 A good way to start writing a new markup command, is to take example on
612 a builtin one.  Most of the markup commands provided with LilyPond can be
613 found in file @file{scm/@/define@/-markup@/-commands@/.scm}.
614
615 For instance, we would like to adapt the @code{\draw-line} command, to
616 draw a double line instead.  The @code{\draw-line} command is defined as
617 follow (documentation stripped):
618
619 @lisp
620 (define-markup-command (draw-line layout props dest)
621   (number-pair?)
622   #:category graphic
623   #:properties ((thickness 1))
624   "..documentation.."
625   (let ((th (* (ly:output-def-lookup layout 'line-thickness)
626                thickness))
627         (x (car dest))
628         (y (cdr dest)))
629     (make-line-stencil th 0 0 x y)))
630 @end lisp
631
632 To define a new command based on an existing one, copy the definition,
633 and change the command name.  The @code{#:category} keyword can be
634 safely removed, as it is only used for generating LilyPond
635 documentation, and is of no use for user-defined markup commands.
636
637 @lisp
638 (define-markup-command (draw-double-line layout props dest)
639   (number-pair?)
640   #:properties ((thickness 1))
641   "..documentation.."
642   (let ((th (* (ly:output-def-lookup layout 'line-thickness)
643                thickness))
644         (x (car dest))
645         (y (cdr dest)))
646     (make-line-stencil th 0 0 x y)))
647 @end lisp
648
649 Then, a property for setting the gap between two lines is added, called
650 @code{line-gap}, defaulting e.g. to 0.6:
651
652 @lisp
653 (define-markup-command (draw-double-line layout props dest)
654   (number-pair?)
655   #:properties ((thickness 1)
656                 (line-gap 0.6))
657   "..documentation.."
658   ...
659 @end lisp
660
661 Finally, the code for drawing two lines is added.  Two calls to
662 @code{make-line-stencil} are used to draw the lines, and the resulting
663 stencils are combined using @code{ly:stencil-add}:
664
665 @lilypond[quote,verbatim,ragged-right]
666 #(define-markup-command (my-draw-line layout props dest)
667   (number-pair?)
668   #:properties ((thickness 1)
669                 (line-gap 0.6))
670   "..documentation.."
671   (let* ((th (* (ly:output-def-lookup layout 'line-thickness)
672                 thickness))
673          (dx (car dest))
674          (dy (cdr dest))
675          (w (/ line-gap 2.0))
676          (x (cond ((= dx 0) w)
677                   ((= dy 0) 0)
678                   (else (/ w (sqrt (+ 1 (* (/ dx dy) (/ dx dy))))))))
679          (y (* (if (< (* dx dy) 0) 1 -1)
680                (cond ((= dy 0) w)
681                      ((= dx 0) 0)
682                      (else (/ w (sqrt (+ 1 (* (/ dy dx) (/ dy dx))))))))))
683      (ly:stencil-add (make-line-stencil th x y (+ dx x) (+ dy y))
684                      (make-line-stencil th (- x) (- y) (- dx x) (- dy y)))))
685
686 \markup \my-draw-line #'(4 . 3)
687 \markup \override #'(line-gap . 1.2) \my-draw-line #'(4 . 3)
688 @end lilypond
689
690
691 @node New markup list command definition
692 @subsection New markup list command definition
693 Markup list commands are defined with the
694 @code{define-markup-list-command} Scheme macro, which is similar to the
695 @code{define-markup-command} macro described in
696 @ref{New markup command definition}, except that where the latter returns
697 a single stencil, the former returns a list of stencils.
698
699 In the following example, a @code{\paragraph} markup list command is
700 defined, which returns a list of justified lines, the first one being
701 indented.  The indent width is taken from the @code{props} argument.
702 @example
703 #(define-markup-list-command (paragraph layout props args) (markup-list?)
704    #:properties ((par-indent 2))
705    (interpret-markup-list layout props
706      (make-justified-lines-markup-list (cons (make-hspace-markup par-indent)
707                                              args))))
708 @end example
709
710 Besides the usual @code{layout} and @code{props} arguments, the
711 @code{paragraph} markup list command takes a markup list argument, named
712 @code{args}.  The predicate for markup lists is @code{markup-list?}.
713
714 First, the function gets the indent width, a property here named
715 @code{par-indent}, from the property list @code{props}.  If the
716 property is not found, the default value is @code{2}.  Then, a
717 list of justified lines is made using the
718 @code{make-justified-lines-markup-list} function, which is related
719 to the @code{\justified-lines} built-in markup list command.  A
720 horizontal space is added at the beginning using the
721 @code{make-hspace-markup} function.  Finally, the markup list is
722 interpreted using the @code{interpret-markup-list} function.
723
724 This new markup list command can be used as follows:
725 @example
726 \markuplines @{
727   \paragraph @{
728     The art of music typography is called \italic @{(plate) engraving.@}
729     The term derives from the traditional process of music printing.
730     Just a few decades ago, sheet music was made by cutting and stamping
731     the music into a zinc or pewter plate in mirror image.
732   @}
733   \override-lines #'(par-indent . 4) \paragraph @{
734     The plate would be inked, the depressions caused by the cutting
735     and stamping would hold ink.  An image was formed by pressing paper
736     to the plate.  The stamping and cutting was completely done by
737     hand.
738   @}
739 @}
740 @end example
741
742 @node Contexts for programmers
743 @section Contexts for programmers
744
745 @menu
746 * Context evaluation::
747 * Running a function on all layout objects::
748 @end menu
749
750 @node Context evaluation
751 @subsection Context evaluation
752
753 @cindex calling code during interpreting
754 @funindex \applyContext
755
756 Contexts can be modified during interpretation with Scheme code.  The
757 syntax for this is
758 @example
759 \applyContext @var{function}
760 @end example
761
762 @var{function} should be a Scheme function that takes a single
763 argument: the context in which the @code{\applyContext} command is
764 being called.  The following code will print the current bar
765 number on the standard output during the compile:
766
767 @example
768 \applyContext
769   #(lambda (x)
770     (format #t "\nWe were called in barnumber ~a.\n"
771      (ly:context-property x 'currentBarNumber)))
772 @end example
773
774
775
776 @node Running a function on all layout objects
777 @subsection Running a function on all layout objects
778
779
780 @cindex calling code on layout objects
781 @funindex \applyOutput
782
783
784 The most versatile way of tuning an object is @code{\applyOutput}.  Its
785 syntax is
786 @example
787 \applyOutput @var{context} @var{proc}
788 @end example
789
790 @noindent
791 where @var{proc} is a Scheme function, taking three arguments.
792
793 When interpreted, the function @var{proc} is called for every layout
794 object found in the context @var{context}, with the following
795 arguments:
796 @itemize
797 @item the layout object itself,
798 @item the context where the layout object was created, and
799 @item the context where @code{\applyOutput} is processed.
800 @end itemize
801
802
803 In addition, the cause of the layout object, i.e., the music
804 expression or object that was responsible for creating it, is in the
805 object property @code{cause}.  For example, for a note head, this is a
806 @rinternals{NoteHead} event, and for a @rinternals{Stem} object,
807 this is a @rinternals{NoteHead} object.
808
809 Here is a function to use for @code{\applyOutput}; it blanks
810 note-heads on the center-line:
811
812 @lilypond[quote,verbatim,ragged-right]
813 #(define (blanker grob grob-origin context)
814    (if (and (memq 'note-head-interface (ly:grob-interfaces grob))
815             (eq? (ly:grob-property grob 'staff-position) 0))
816        (set! (ly:grob-property grob 'transparent) #t)))
817
818 \relative c' {
819   e4 g8 \applyOutput #'Voice #blanker b d2
820 }
821 @end lilypond
822
823
824 @node Callback functions
825 @section Callback functions
826
827 Properties (like @code{thickness}, @code{direction}, etc.) can be
828 set at fixed values with @code{\override}, e.g.
829
830 @example
831 \override Stem #'thickness = #2.0
832 @end example
833
834 Properties can also be set to a Scheme procedure,
835
836 @lilypond[fragment,verbatim,quote,relative=2]
837 \override Stem #'thickness = #(lambda (grob)
838     (if (= UP (ly:grob-property grob 'direction))
839         2.0
840         7.0))
841 c b a g b a g b
842 @end lilypond
843
844 @noindent
845 In this case, the procedure is executed as soon as the value of the
846 property is requested during the formatting process.
847
848 Most of the typesetting engine is driven by such callbacks.
849 Properties that typically use callbacks include
850
851 @table @code
852 @item stencil
853   The printing routine, that constructs a drawing for the symbol
854 @item X-offset
855   The routine that sets the horizontal position
856 @item X-extent
857   The routine that computes the width of an object
858 @end table
859
860 The procedure always takes a single argument, being the grob.
861
862 If routines with multiple arguments must be called, the current grob
863 can be inserted with a grob closure.  Here is a setting from
864 @code{AccidentalSuggestion},
865
866 @example
867 `(X-offset .
868   ,(ly:make-simple-closure
869     `(,+
870         ,(ly:make-simple-closure
871            (list ly:self-alignment-interface::centered-on-x-parent))
872       ,(ly:make-simple-closure
873            (list ly:self-alignment-interface::x-aligned-on-self)))))
874 @end example
875
876 @noindent
877 In this example, both @code{ly:self-alignment-interface::x-aligned-on-self} and
878 @code{ly:self-alignment-interface::centered-on-x-parent} are called
879 with the grob as argument.  The results are added with the @code{+}
880 function.  To ensure that this addition is properly executed, the whole
881 thing is enclosed in @code{ly:make-simple-closure}.
882
883 In fact, using a single procedure as property value is equivalent to
884
885 @example
886 (ly:make-simple-closure (ly:make-simple-closure (list @var{proc})))
887 @end example
888
889 @noindent
890 The inner @code{ly:make-simple-closure} supplies the grob as argument
891 to @var{proc}, the outer ensures that result of the function is
892 returned, rather than the @code{simple-closure} object.
893
894 From within a callback, the easiest method for evaluating a markup is
895 to use grob-interpret-markup.  For example:
896
897 @example
898 my-callback = #(lambda (grob)
899                  (grob-interpret-markup grob (markup "foo")))
900 @end example
901
902 @node Inline Scheme code
903 @section Inline Scheme code
904
905 The main disadvantage of @code{\tweak} is its syntactical
906 inflexibility.  For example, the following produces a syntax error.
907
908 @example
909 F = \tweak #'font-size #-3 -\flageolet
910
911 \relative c'' @{
912   c4^\F c4_\F
913 @}
914 @end example
915
916 @noindent
917 In other words, @code{\tweak} doesn't behave like an articulation
918 regarding the syntax; in particular, it can't be attached with
919 @code{^} and @code{_}.
920
921 Using Scheme, this problem can be avoided.  The route to the
922 result is given in @ref{Adding articulation to notes (example)},
923 especially how to use @code{\displayMusic} as a helping guide.
924
925 @example
926 F = #(let ((m (make-music 'ArticulationEvent
927                           'articulation-type "flageolet")))
928        (set! (ly:music-property m 'tweaks)
929              (acons 'font-size -3
930                     (ly:music-property m 'tweaks)))
931        m)
932
933 \relative c'' @{
934   c4^\F c4_\F
935 @}
936 @end example
937
938 @noindent
939 Here, the @code{tweaks} properties of the flageolet object
940 @code{m} (created with @code{make-music}) are extracted with
941 @code{ly:music-property}, a new key-value pair to change the
942 font size is prepended to the property list with the
943 @code{acons} Scheme function, and the result is finally
944 written back with @code{set!}.  The last element of the
945 @code{let} block is the return value, @code{m} itself.
946
947
948
949 @node Difficult tweaks
950 @section Difficult tweaks
951
952 There are a few classes of difficult adjustments.
953
954 @itemize
955
956
957 @item
958 One type of difficult adjustment involves the appearance of
959 spanner objects, such as slurs and ties.  Usually, only one
960 spanner object is created at a time, and it can be adjusted with
961 the normal mechanism.  However, occasionally a spanner crosses a
962 line break.  When this happens, the object is cloned.  A separate
963 object is created for every system in which the spanner appears.
964 The new objects are clones of the original object and inherit all
965 properties, including @code{\override}s.
966
967
968 In other words, an @code{\override} always affects all pieces of a
969 broken spanner.  To change only one part of a spanner at a line break,
970 it is necessary to hook into the formatting process.  The
971 @code{after-line-breaking} callback contains the Scheme procedure that
972 is called after the line breaks have been determined and layout
973 objects have been split over different systems.
974
975 In the following example, we define a procedure
976 @code{my-callback}.  This procedure
977
978 @itemize
979 @item
980 determines if the spanner has been split across line breaks
981 @item
982 if yes, retrieves all the split objects
983 @item
984 checks if this grob is the last of the split objects
985 @item
986 if yes, it sets @code{extra-offset}.
987 @end itemize
988
989 This procedure is installed into @rinternals{Tie}, so the last part
990 of the broken tie is repositioned.
991
992 @lilypond[quote,verbatim,ragged-right]
993 #(define (my-callback grob)
994   (let* (
995          ; have we been split?
996          (orig (ly:grob-original grob))
997
998          ; if yes, get the split pieces (our siblings)
999          (siblings (if (ly:grob? orig)
1000                      (ly:spanner-broken-into orig) '() )))
1001
1002    (if (and (>= (length siblings) 2)
1003              (eq? (car (last-pair siblings)) grob))
1004      (ly:grob-set-property! grob 'extra-offset '(-2 . 5)))))
1005
1006 \relative c'' {
1007   \override Tie #'after-line-breaking =
1008   #my-callback
1009   c1 ~ \break c2 ~ c
1010 }
1011 @end lilypond
1012
1013 @noindent
1014 When applying this trick, the new @code{after-line-breaking} callback
1015 should also call the old one @code{after-line-breaking}, if there is
1016 one.  For example, if using this with @code{Hairpin},
1017 @code{ly:hairpin::after-line-breaking} should also be called.
1018
1019
1020 @item Some objects cannot be changed with @code{\override} for
1021 technical reasons.  Examples of those are @code{NonMusicalPaperColumn}
1022 and @code{PaperColumn}.  They can be changed with the
1023 @code{\overrideProperty} function, which works similar to @code{\once
1024 \override}, but uses a different syntax.
1025
1026 @example
1027 \overrideProperty
1028 #"Score.NonMusicalPaperColumn"  % Grob name
1029 #'line-break-system-details     % Property name
1030 #'((next-padding . 20))         % Value
1031 @end example
1032
1033 Note, however, that @code{\override}, applied to
1034 @code{NonMusicalPaperColumn} and @code{PaperColumn}, still works as
1035 expected within @code{\context} blocks.
1036
1037 @end itemize
1038
1039 @node LilyPond Scheme interfaces
1040 @chapter LilyPond Scheme interfaces
1041
1042 This chapter covers the various tools provided by LilyPond to help
1043 Scheme programmers get information into and out of the music streams.
1044
1045 TODO -- figure out what goes in here and how to organize it
1046