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