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