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