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