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