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