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