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