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