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