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