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