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