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