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