]> git.donarmstrong.com Git - lilypond.git/blob - Documentation/user/programming-interface.itely
Major new docs, some reorg, some info from Nicolas.
[lilypond.git] / Documentation / user / programming-interface.itely
1 @c -*- coding: utf-8; mode: texinfo; -*-
2 @node Interfaces for programmers
3 @chapter Interfaces for programmers
4
5 Advanced tweaks may be performed by using Scheme.  If you are
6 not familiar with Scheme, you may wish to read our
7 @ref{Scheme tutorial}.
8
9 @menu
10 * Music functions::             
11 * Programmer interfaces::       
12 * Building complicated functions::  
13 * Markup programmer interface::  
14 * Contexts for programmers::    
15 * OLD STUFF::                   
16 @end menu
17
18
19 @node Music functions
20 @section Music functions
21
22 This section discusses how to create music functions within LilyPond.
23
24 @menu
25 * Overview of music functions::  
26 * Simple substitution functions::  
27 * Paired substition functions::  
28 * Mathematics in functions::    
29 @end menu
30
31 @node Overview of music functions
32 @subsection Overview of music functions 
33
34 Making a funcion which substitutes a variable into LilyPond
35 code is easy.  The general form of these functions is
36
37 @example
38 function =
39 #(define-music-function (parser location @var{var1} @var{var2}... )
40                         (@var{var1-type?} @var{var2-type?}...)
41   #@{
42     @emph{...music...}
43   #@})
44 @end example
45
46 @noindent
47 where
48
49 @multitable @columnfractions .33 .66
50 @item @var{argi}         @tab @var{i}th variable
51 @item @var{argi-type?}   @tab type of variable
52 @item @var{...music...}  @tab normal LilyPond input, using
53   variables as @code{#$var1}.
54 @end multitable
55
56 The following input types may be used as variables
57 in a music function.
58
59 @multitable @columnfractions .33 .66
60 @headitem Input type          @tab @var{argi-type?} notation
61 @item Integer                 @tab @code{integer?}
62 @item Float (decimal number)  @tab @code{number?}
63 @item Text string             @tab @code{string?}
64 @item Markup                  @tab @code{markup?}
65 @item Music expression        @tab @code{ly:music?}
66 @item A pair of numbers       @tab @code{pair?}
67 @end multitable
68
69
70 @node Simple substitution functions
71 @subsection Simple substitution functions
72
73 Here is a simple example,
74
75 @lilypond[quote,verbatim,ragged-right]
76 padText = #(define-music-function (parser location padding) (number?)
77   #{
78     \once \override TextScript #'padding = #$padding
79   #})
80
81 \relative c''' {
82   c4^"piu mosso" b a b
83   \padText #1.8
84   c4^"piu mosso" d e f
85   \padText #2.6
86   c4^"piu mosso" fis a g
87
88 @end lilypond
89
90 Music expressions may be substituted as well,
91
92 @lilypond[quote,verbatim,ragged-right]
93 custosNote = #(define-music-function (parser location note)
94                                      (ly:music?)
95   #{ 
96     \once \override Voice.NoteHead #'stencil = 
97       #ly:text-interface::print
98     \once \override Voice.NoteHead #'text = 
99       \markup \musicglyph #"custodes.mensural.u0"
100     \once \override Voice.Stem #'stencil = ##f 
101     $note
102   #})
103
104 { c' d' e' f' \custosNote g' }
105 @end lilypond
106
107 Multiple variables may be used,
108
109 @lilypond[quote,verbatim,ragged-right]
110 tempoMark = #(define-music-function (parser location marktext padding)
111                                     (string? number?)
112 #{
113   \once \override Score . RehearsalMark #'padding = $padding
114   \once \override Score . RehearsalMark #'no-spacing-rods = ##t
115   \mark \markup { \bold $marktext }
116 #})
117
118 \relative c'' {
119 c2 e
120 \tempoMark #"Allegro" #3.0
121 g c
122 }
123 @end lilypond
124
125
126 @node Paired substition functions
127 @subsection Paired substition functions
128
129 Some @code{\override} commands require a pair of numbers
130 (called a @code{cons cell} in Scheme).  To pass these numbers
131 into a function, either use a @code{pair?} variable, or
132 insert the @code{cons} into the music function.
133
134 @quotation
135 @example
136 manualBeam =
137 #(define-music-function (parser location beg-end)
138                         (pair?)
139 #@{
140   \once \override Beam #'positions = #$beg-end
141 #@})
142
143 \relative @{
144   \manualBeam #'(3 . 6) c8 d e f
145 @}
146 @end example
147 @end quotation
148
149 @noindent
150 or
151
152 @lilypond[quote,verbatim,ragged-right]
153 manualBeam =
154 #(define-music-function (parser location beg end)
155                         (number? number?)
156 #{
157   \once \override Beam #'positions = #(cons $beg $end)
158 #}) 
159
160 \relative {
161   \manualBeam #3 #6 c8 d e f
162 }
163 @end lilypond  
164
165
166 @node Mathematics in functions
167 @subsection Mathematics in functions
168
169 Music functions can involve Scheme programming in
170 addition to simple substitution,
171
172 @lilypond[quote,verbatim,ragged-right]
173 AltOn = #(define-music-function (parser location mag) (number?) 
174   #{ \override Stem #'length = #$(* 7.0 mag)
175      \override NoteHead #'font-size = 
176        #$(inexact->exact (* (/ 6.0 (log 2.0)) (log mag))) #})
177
178 AltOff = {
179   \revert Stem #'length
180   \revert NoteHead #'font-size 
181 }
182
183 { c'2 \AltOn #0.5 c'4 c'
184   \AltOn #1.5 c' c' \AltOff c'2 }
185 @end lilypond
186
187 @noindent
188 This example may be rewritten to pass in music expressions,
189
190 @lilypond[quote,verbatim,ragged-right]
191 withAlt = #(define-music-function (parser location mag music) (number? ly:music?) 
192   #{ \override Stem #'length = #$(* 7.0 mag)
193      \override NoteHead #'font-size = 
194        #$(inexact->exact (* (/ 6.0 (log 2.0)) (log mag)))
195      $music
196      \revert Stem #'length
197      \revert NoteHead #'font-size #})
198
199 { c'2 \withAlt #0.5 {c'4 c'}
200   \withAlt #1.5 {c' c'} c'2 }
201 @end lilypond
202
203
204
205 @node Programmer interfaces
206 @section Programmer interfaces
207
208 This section contains information about mixing LilyPond
209 and Scheme.
210
211 @menu
212 * Input variables and Scheme::  
213 * Internal music representation::  
214 @end menu
215
216
217 @node Input variables and Scheme
218 @subsection Input variables and Scheme
219
220 The input format supports the notion of variables: in the following
221 example, a music expression is assigned to a variable with the name
222 @code{traLaLa}.
223
224 @example
225 traLaLa = @{ c'4 d'4 @}
226 @end example
227
228 @noindent
229
230 There is also a form of scoping: in the following example, the
231 @code{\layout} block also contains a @code{traLaLa} variable, which is
232 independent of the outer @code{\traLaLa}.
233 @example
234 traLaLa = @{ c'4 d'4 @}
235 \layout @{ traLaLa = 1.0 @}
236 @end example
237 @c
238 In effect, each input file is a scope, and all @code{\header},
239 @code{\midi}, and @code{\layout} blocks are scopes nested inside that
240 toplevel scope.
241
242 Both variables and scoping are implemented in the GUILE module system.
243 An anonymous Scheme module is attached to each scope.  An assignment of
244 the form
245 @example
246 traLaLa = @{ c'4 d'4 @}
247 @end example
248
249 @noindent
250 is internally converted to a Scheme definition
251 @example
252 (define traLaLa @var{Scheme value of ``@code{... }''})
253 @end example
254
255 This means that input variables and Scheme variables may be freely
256 mixed.  In the following example, a music fragment is stored in the
257 variable @code{traLaLa}, and duplicated using Scheme.  The result is
258 imported in a @code{\score} block by means of a second variable
259 @code{twice}:
260 @example
261 traLaLa = @{ c'4 d'4 @}
262
263 #(define newLa (map ly:music-deep-copy
264   (list traLaLa traLaLa)))
265 #(define twice
266   (make-sequential-music newLa))
267
268 @{ \twice @}
269 @end example
270
271 In the above example, music expressions can be `exported' from the
272 input to the Scheme interpreter.  The opposite is also possible.  By
273 wrapping a Scheme value in the function @code{ly:export}, a Scheme
274 value is interpreted as if it were entered in LilyPond syntax.  Instead
275 of defining @code{\twice}, the example above could also have been
276 written as
277 @example
278 @dots{}
279 @{ #(ly:export (make-sequential-music (list newLa))) @}
280 @end example
281
282 Scheme code is evaluated as soon as the parser encounters it.  To
283 define some scheme code in a macro (to be called later), use
284
285 @example
286 #(define (nopc)
287   (ly:set-option 'point-and-click #f))
288
289 ...
290 #(nopc)
291 @{ c'4 @}
292 @end example
293
294
295 @refbugs
296
297 Mixing Scheme and LilyPond identifiers is not possible with the
298 @code{--safe} option.
299
300
301 @node Internal music representation
302 @subsection Internal music representation
303
304 When a music expression is parsed, it is converted into a set of
305 Scheme music objects.  The defining property of a music object is that
306 it takes up time.  Time is a rational number that measures the length
307 of a piece of music in whole notes.
308
309 A music object has three kinds of types:
310 @itemize @bullet
311 @item
312 music name: Each music expression has a name.  For example, a note
313 leads to a @internalsref{NoteEvent}, and @code{\simultaneous} leads to
314 a @internalsref{SimultaneousMusic}.  A list of all expressions
315 available is in the Program reference manual, under
316 @internalsref{Music expressions}.
317
318 @item
319 `type' or interface: Each music name has several `types' or
320 interfaces, for example, a note is an @code{event}, but it is also a
321 @code{note-event}, a @code{rhythmic-event}, and a
322 @code{melodic-event}.  All classes of music are listed in the
323 Profram reference, under
324 @internalsref{Music classes}.
325
326 @item
327 C++ object: Each music object is represented by an object of the C++
328 class @code{Music}.
329 @end itemize
330
331 The actual information of a music expression is stored in properties.
332 For example, a @internalsref{NoteEvent} has @code{pitch} and
333 @code{duration} properties that store the pitch and duration of that
334 note.  A list of all properties available is in the internals manual,
335 under @internalsref{Music properties}.
336
337 A compound music expression is a music object that contains other
338 music objects in its properties.  A list of objects can be stored in
339 the @code{elements} property of a music object, or a single `child'
340 music object in the @code{element} object.  For example,
341 @internalsref{SequentialMusic} has its children in @code{elements},
342 and @internalsref{GraceMusic} has its single argument in
343 @code{element}.  The body of a repeat is stored in the @code{element}
344 property of @internalsref{RepeatedMusic}, and the alternatives in
345 @code{elements}.
346
347
348
349 @node Building complicated functions
350 @section Building complicated functions
351
352 This section explains how to gather the information necessary
353 to create complicated music functions.
354
355 @menu
356 * Displaying music expressions::  
357 * Doubling a note with slurs (example)::  
358 * Adding articulation to notes (example)::  
359 @end menu
360
361
362 @node Displaying music expressions
363 @subsection Displaying music expressions
364
365 @cindex internal storage
366 @cindex @code{\displayMusic}
367 @cindex @code{\displayLilyMusic}
368
369 When writing a music function it is often instructive to inspect how
370 a music expression is stored internally.  This can be done with the
371 music function @code{\displayMusic}
372
373 @example
374 @{
375   \displayMusic @{ c'4\f @}
376 @}
377 @end example
378
379 @noindent
380 will display
381
382 @example
383 (make-music
384   'SequentialMusic
385   'elements
386   (list (make-music
387           'EventChord
388           'elements
389           (list (make-music
390                   'NoteEvent
391                   'duration
392                   (ly:make-duration 2 0 1 1)
393                   'pitch
394                   (ly:make-pitch 0 0 0))
395                 (make-music
396                   'AbsoluteDynamicEvent
397                   'text
398                   "f")))))
399 @end example
400
401 By default, LilyPond will print these messages to the console along
402 with all the other messages.  To split up these messages and save
403 the results of @code{\display@{STUFF@}}, redirect the output to
404 a file.
405
406 @example
407 lilypond file.ly >display.txt
408 @end example
409
410
411 @node Doubling a note with slurs (example)
412 @subsection Doubling a note with slurs (example)
413
414 Suppose we want to create a function which translates
415 input like ``@code{a}'' into ``@code{a( a)}''.  We begin
416 by examining the internal representation of the music
417 we want to end up with.
418
419 @example
420 \displayMusic@{ a'( a') @}
421 ===>
422 (make-music
423   'SequentialMusic
424   'elements
425   (list (make-music
426           'EventChord
427           'elements
428           (list (make-music
429                   'NoteEvent
430                   'duration
431                   (ly:make-duration 2 0 1 1)
432                   'pitch
433                   (ly:make-pitch 0 5 0))
434                 (make-music
435                   'SlurEvent
436                   'span-direction
437                   -1)))
438         (make-music
439           'EventChord
440           'elements
441           (list (make-music
442                   'NoteEvent
443                   'duration
444                   (ly:make-duration 2 0 1 1)
445                   'pitch
446                   (ly:make-pitch 0 5 0))
447                 (make-music
448                   'SlurEvent
449                   'span-direction
450                   1)))))
451 @end example
452
453 The bad news is that the @code{SlurEvent} expressions
454 must be added ``inside'' the note (or more precisely,
455 inside the @code{EventChord} expression).
456
457 Now we examine the input,
458
459 @example
460 (make-music
461   'SequentialMusic
462   'elements
463   (list (make-music
464           'EventChord
465           'elements
466           (list (make-music
467                   'NoteEvent
468                   'duration
469                   (ly:make-duration 2 0 1 1)
470                   'pitch
471                   (ly:make-pitch 0 5 0))))))
472 @end example
473
474 So in our function, we need to clone this expression (so that we
475 have two notes to build the sequence), add @code{SlurEvents} to the
476 @code{'elements} property of each one, and finally make a
477 @code{SequentialMusic} with the two @code{EventChords}.
478
479 @example
480 doubleSlur = #(def-music-function (parser location note) (ly:music?)
481          "Return: @{ note ( note ) @}.
482          `note' is supposed to be an EventChord."
483          (let ((note2 (ly:music-deep-copy note)))
484            (set! (ly:music-property note 'elements)
485                  (cons (make-music 'SlurEvent 'span-direction -1)
486                        (ly:music-property note 'elements)))
487            (set! (ly:music-property note2 'elements)
488                  (cons (make-music 'SlurEvent 'span-direction 1)
489                        (ly:music-property note2 'elements)))
490            (make-music 'SequentialMusic 'elements (list note note2))))
491 @end example
492
493
494 @node Adding articulation to notes (example)
495 @subsection Adding articulation to notes (example)
496
497 The easy way to add articulation to notes is to merge two music
498 expressions into one context, as explained in
499 @ref{Creating contexts}.  However, suppose that we want to write
500 a music function which does this.
501
502 A @code{$variable} inside the @code{#@{...#@}} notation is like
503 using a regular @code{\variable} in classical LilyPond
504 notation.  We know that
505
506 @example
507 @{ \music -. -> @}
508 @end example
509
510 @noindent
511 will not work in LilyPond.  We could avoid this problem by attaching
512 the articulation to a fake note,
513
514 @example
515 @{ << \music s1*0-.-> @}
516 @end example
517
518 @noindent
519 but for the sake of this example, we will learn how to do this in
520 Scheme.  We begin by examining our input and desired output,
521
522 @example
523 %  input
524 \displayMusic c4
525 ===>
526 (make-music
527   'EventChord
528   'elements
529   (list (make-music
530           'NoteEvent
531           'duration
532           (ly:make-duration 2 0 1 1)
533           'pitch
534           (ly:make-pitch -1 0 0))))
535 =====
536 %  desired output
537 \displayMusic c4->
538 ===>
539 (make-music
540   'EventChord
541   'elements
542   (list (make-music
543           'NoteEvent
544           'duration
545           (ly:make-duration 2 0 1 1)
546           'pitch
547           (ly:make-pitch -1 0 0))
548         (make-music
549           'ArticulationEvent
550           'articulation-type
551           "marcato")))
552 @end example
553
554 We see that a note (@code{c4}) is represented as an @code{EventChord}
555 expression, with a @code{NoteEvent} expression in its elements list.  To
556 add a marcato articulation, an @code{ArticulationEvent} expression must
557 be added to the elements property of the @code{EventChord}
558 expression.
559
560 To build this function, we begin with
561
562 @example
563 (define (add-marcato event-chord)
564   "Add a marcato ArticulationEvent to the elements of `event-chord',
565   which is supposed to be an EventChord expression."
566   (let ((result-event-chord (ly:music-deep-copy event-chord)))
567     (set! (ly:music-property result-event-chord 'elements)
568           (cons (make-music 'ArticulationEvent
569                   'articulation-type "marcato")
570                 (ly:music-property result-event-chord 'elements)))
571     result-event-chord))
572 @end example
573
574 The first line is the way to define a function in Scheme: the function
575 name is @code{add-marcato}, and has one variable called
576 @code{event-chord}.  In Scheme, the type of variable is often clear
577 from its name.  (this is good practice in other programming languages,
578 too!)
579
580 @example
581 "Add a marcato..."
582 @end example
583
584 @noindent
585 is a description of what the function does.  This is not strictly
586 necessary, but just like clear variable names, it is good practice.
587
588 @example
589 (let ((result-event-chord (ly:music-deep-copy event-chord)))
590 @end example
591
592 `@code{let}' is used to declare local variables.  Here we use one local
593 variable, named `@code{result-event-chord}', to which we give the value 
594 @code{(ly:music-deep-copy event-chord)}.  `@code{ly:music-deep-copy}' is
595 a function specific to LilyPond, like all functions prefixed by
596 `@code{ly:}'.  It is use to make a copy of a music
597 expression.  Here we copy `@code{event-chord} (the parameter of the
598 function).  Recall that our purpose is to add a marcato to an
599 @code{EventChord} expression.  It is better to not modify the
600 @code{EventChord} which was given as an argument, because it may be
601 used elsewhere.
602
603 Now we have a @code{result-event-chord}, which is a 
604 @code{oteEventChord} expression and is a copy of @code{event-chord}.  We
605 add the marcato to its elements list property.
606
607 @example
608 (set! place new-value)
609 @end example
610
611 Here, what we want to set (the "place") is the "elements" property of
612 @code{result-event-chord} expression
613
614 @example
615 (ly:music-property result-event-chord 'elements)
616 @end example
617
618 @code{ly:music-property} is the function used to access music properties
619 (the @code{'elements}, @code{'duration}, @code{'pitch}, etc, that we
620 see in the @code{\displayMusic} output above).  The new value is the
621 former elements property, with an extra item: the
622 @code{MarcatoEvent} expression, which we copy from the
623 @code{\displayMusic} output,
624
625 @example
626 (cons (make-music 'ArticulationEvent
627         'articulation-type "marcato")
628       (ly:music-property result-event-chord 'elements))
629 @end example
630
631 `@code{cons}' is used to add an element to a list.  This is what we
632 want: the same list as before, plus the new @code{ArticulationEvent}
633 expression.  The order inside the elements property is not important here.
634
635 Finally, once we have added the @code{MarcatoEvent} to its elements
636 property, we can return @code{result-event-chord}, hence the last line of
637 the function.
638
639 Now we transform the @code{add-marcato} function into a music
640 function,
641
642 @example
643 addMarcato = #(define-music-function (parser location event-chord)
644                                      (ly:music?)
645     "Add a marcato ArticulationEvent to the elements of `event-chord',
646     which is supposed to be an EventChord expression."
647     (let ((result-event-chord (ly:music-deep-copy event-chord)))
648       (set! (ly:music-property result-event-chord 'elements)
649             (cons (make-music 'ArticulationEvent
650                     'articulation-type "marcato")
651                   (ly:music-property result-event-chord 'elements)))
652       result-event-chord))
653 @end example
654
655 We may verify that this music function works correctly,
656
657 @example
658 \displayMusic \addMarcato c4
659 @end example
660
661
662 @node Markup programmer interface
663 @section Markup programmer interface
664
665 Markups are implemented as special Scheme functions which produce a
666 Stencil object given a number of arguments.
667
668 @menu
669 * Markup construction in Scheme::  
670 * How markups work internally::  
671 * New markup command definition::  
672 @end menu
673
674
675 @node Markup construction in Scheme
676 @subsection Markup construction in Scheme
677
678 @cindex defining markup commands 
679
680 The @code{markup} macro builds markup expressions in Scheme while
681 providing a LilyPond-like syntax.  For example,
682 @example
683 (markup #:column (#:line (#:bold #:italic "hello" #:raise 0.4 "world")
684                   #:bigger #:line ("foo" "bar" "baz")))
685 @end example
686
687 @noindent
688 is equivalent to:
689 @example
690 \markup \column @{ \line @{ \bold \italic "hello" \raise #0.4 "world" @}
691                   \bigger \line @{ foo bar baz @} @}
692 @end example
693
694 @noindent
695 This example demonstrates the main translation rules between regular
696 LilyPond markup syntax and Scheme markup syntax.
697
698 @quotation
699 @multitable @columnfractions .3 .3
700 @item @b{LilyPond} @tab @b{Scheme}
701 @item @code{\markup markup1} @tab @code{(markup markup1)}
702 @item @code{\markup @{ markup1 markup2 ... @}} @tab 
703         @code{(markup markup1 markup2 ... )}
704 @item @code{\command} @tab @code{#:command}
705 @item @code{\variable} @tab @code{variable}
706 @item @code{\center-align @{ ... @}} @tab @code{#:center-align ( ... )}
707 @item @code{string} @tab @code{"string"}
708 @item @code{#scheme-arg} @tab @code{scheme-arg}
709 @end multitable
710 @end quotation
711
712 The whole scheme language is accessible inside the
713 @code{markup} macro.  For example, You may use function calls inside
714 @code{markup} in order to manipulate character strings.  This is
715 useful when defining new markup commands (see
716 @ref{New markup command definition}).
717
718 @refbugs
719
720 One can not feed the @code{#:line}, @code{#:center}, or
721 @code{#:column}) commands with a variable or the result of a function
722 call.  Example:
723
724 @lisp
725 (markup #:line (function-that-returns-markups))
726 @end lisp
727
728 @noindent
729 is invalid.  One should use the @code{make-line-markup},
730 @code{make-center-markup}, or @code{make-column-markup} functions
731 instead,
732
733 @lisp
734 (markup (make-line-markup (function-that-returns-markups)))
735 @end lisp
736
737
738 @node How markups work internally
739 @subsection How markups work internally
740
741 In a markup like
742
743 @example
744 \raise #0.5 "text example"
745 @end example
746
747 @noindent
748 @code{\raise} is actually represented by the @code{raise-markup}
749 function.  The markup expression is stored as
750
751 @example
752 (list raise-markup 0.5 (list simple-markup "text example"))
753 @end example
754
755 When the markup is converted to printable objects (Stencils), the
756 @code{raise-markup} function is called as
757
758 @example
759 (apply raise-markup
760        @var{\layout object}
761        @var{list of property alists}
762        0.5
763        @var{the "text example" markup})
764 @end example
765
766 The @code{raise-markup} function first creates the stencil for the
767 @code{text example} string, and then it raises that Stencil by 0.5
768 staff space.  This is a rather simple example; more complex examples
769 are in the rest
770 of this section, and in @file{scm/@/define@/-markup@/-commands@/.scm}.
771
772
773 @node New markup command definition
774 @subsection New markup command definition
775
776 New markup commands can be defined
777 with the @code{define-markup-command} scheme macro.
778
779 @lisp
780 (define-markup-command (@var{command-name} @var{layout} @var{props} @var{arg1} @var{arg2} ...)
781             (@var{arg1-type?} @var{arg2-type?} ...)
782   ..command body..)
783 @end lisp
784
785 The arguments are
786
787 @table @var
788 @item argi
789 @var{i}th command argument
790 @item argi-type?
791 a type predicate for the i@var{th} argument
792 @item layout
793 the `layout' definition
794 @item props
795 a list of alists, containing all active properties. 
796 @end table
797
798 As a simple example, we show how to add a @code{\smallcaps} command,
799 which selects a small caps font.  Normally we could select the
800 small caps font,
801
802 @example
803 \markup @{ \override #'(font-shape . caps) Text-in-caps @}
804 @end example
805
806 @noindent
807 This selects the caps font by setting the @code{font-shape} property to
808 @code{#'caps} for interpreting @code{Text-in-caps}.
809
810 To make the above available as @code{\smallcaps} command, we must
811 define a function using @code{define-markup-command}.  The command should
812 take a single argument of type @code{markup}.  Therefore the start of the
813 definition should read
814
815 @example
816 (define-markup-command (smallcaps layout props argument) (markup?)
817 @end example
818
819 @noindent
820
821 What follows is the content of the command: we should interpret
822 the @code{argument} as a markup, i.e.,
823
824 @example
825 (interpret-markup layout @dots{} argument)
826 @end example
827
828 @noindent
829 This interpretation should add @code{'(font-shape . caps)} to the active
830 properties, so we substitute the following for the @dots{} in the
831 above example:
832
833 @example
834 (cons (list '(font-shape . caps) ) props)
835 @end example
836
837 @noindent
838 The variable @code{props} is a list of alists, and we prepend to it by
839 cons'ing a list with the extra setting.
840
841
842 Suppose that we are typesetting a recitative in an opera and
843 we would like to define a command that will show character names in a
844 custom manner.  Names should be printed with small caps and moved a
845 bit to the left and top.  We will define a @code{\character} command
846 which takes into account the necessary translation and uses the newly
847 defined @code{\smallcaps} command:
848
849 @example
850 #(define-markup-command (character layout props name) (string?)
851   "Print the character name in small caps, translated to the left and
852   top.  Syntax: \\character #\"name\""
853   (interpret-markup layout props 
854    (markup #:hspace 0 #:translate (cons -3 1) #:smallcaps name)))
855 @end example
856
857 There is one complication that needs explanation: texts above and below
858 the staff are moved vertically to be at a certain distance (the
859 @code{padding} property) from the staff and the notes.  To make sure
860 that this mechanism does not annihilate the vertical effect of our
861 @code{#:translate}, we add an empty string (@code{#:hspace 0}) before the
862 translated text.  Now the @code{#:hspace 0} will be put above the notes,
863 and the
864 @code{name} is moved in relation to that empty string.  The net effect is
865 that the text is moved to the upper left.
866
867 The final result is as follows:
868
869 @example
870 @{
871   c''^\markup \character #"Cleopatra"
872   e'^\markup \character #"Giulio Cesare"
873 @}
874 @end example
875
876 @lilypond[quote,ragged-right]
877 #(define-markup-command (smallcaps layout props str) (string?)
878   "Print the string argument in small caps.  Syntax: \\smallcaps #\"string\""
879   (interpret-markup layout props
880    (make-line-markup
881     (map (lambda (s)
882           (if (= (string-length s) 0)
883               s
884               (markup #:large (string-upcase (substring s 0 1))
885                       #:translate (cons -0.6 0)
886                       #:tiny (string-upcase (substring s 1)))))
887          (string-split str #\Space)))))
888
889 #(define-markup-command (character layout props name) (string?)
890   "Print the character name in small caps, translated to the left and
891   top.  Syntax: \\character #\"name\""
892   (interpret-markup layout props 
893    (markup #:hspace 0 #:translate (cons -3 1) #:smallcaps name)))
894
895 {
896   c''^\markup \character #"Cleopatra" c'' c'' c''
897   e'^\markup \character #"Giulio Cesare" e' e' e'
898 }
899 @end lilypond
900
901 We have used the @code{caps} font shape, but suppose that our font
902 does not have a small-caps variant.  In that case we have to fake
903 the small caps font by setting a string in upcase with the first
904 letter a little larger:
905
906 @example
907 #(define-markup-command (smallcaps layout props str) (string?)
908   "Print the string argument in small caps."
909   (interpret-markup layout props
910    (make-line-markup
911     (map (lambda (s)
912           (if (= (string-length s) 0)
913               s
914               (markup #:large (string-upcase (substring s 0 1))
915                       #:translate (cons -0.6 0)
916                       #:tiny (string-upcase (substring s 1)))))
917          (string-split str #\Space)))))
918 @end example
919
920 The @code{smallcaps} command first splits its string argument into
921 tokens separated by spaces (@code{(string-split str #\Space)}); for
922 each token, a markup is built with the first letter made large and
923 upcased (@code{#:large (string-upcase (substring s 0 1))}), and a
924 second markup built with the following letters made tiny and upcased
925 (@code{#:tiny (string-upcase (substring s 1))}).  As LilyPond
926 introduces a space between markups on a line, the second markup is
927 translated to the left (@code{#:translate (cons -0.6 0) ...}).  Then,
928 the markups built for each token are put in a line by
929 @code{(make-line-markup ...)}.  Finally, the resulting markup is passed
930 to the @code{interpret-markup} function, with the @code{layout} and
931 @code{props} arguments.
932
933 Note: there is now an internal command @code{\smallCaps} which can
934 be used to set text in small caps.  See
935 @ref{Overview of text markup commands} for details.
936
937
938
939 @node Contexts for programmers
940 @section Contexts for programmers
941
942 @menu
943 * Context evaluation::          
944 * Running a function on all layout objects::  
945 @end menu
946
947 @node Context evaluation
948 @subsection Context evaluation
949
950 @cindex calling code during interpreting
951 @cindex @code{\applyContext}
952
953 Contexts can be modified during interpretation with Scheme code.  The
954 syntax for this is
955 @example
956 \applyContext @var{function}
957 @end example
958
959 @var{function} should be a Scheme function taking a single argument,
960 being the context to apply it to.  The following code will print the
961 current bar number on the standard output during the compile:
962
963 @example
964 \applyContext
965   #(lambda (x)
966     (format #t "\nWe were called in barnumber ~a.\n"
967      (ly:context-property x 'currentBarNumber)))
968 @end example
969
970
971
972 @node Running a function on all layout objects
973 @subsection Running a function on all layout objects
974
975
976 @cindex calling code on layout objects
977 @cindex @code{\applyOutput}
978
979
980 The most versatile way of tuning an object is @code{\applyOutput}.  Its
981 syntax is
982 @example
983 \applyOutput @var{proc}
984 @end example
985
986 @noindent
987 where @var{proc} is a Scheme function, taking three arguments.
988
989 When interpreted, the function @var{proc} is called for every layout
990 object found in the context, with the following arguments:
991 @itemize @bullet
992 @item the layout object itself,
993 @item the context where the layout object was created, and
994 @item the context where @code{\applyOutput} is processed.
995 @end itemize
996
997
998 In addition, the cause of the layout object, i.e., the music
999 expression or object that was responsible for creating it, is in the
1000 object property @code{cause}.  For example, for a note head, this is a
1001 @internalsref{NoteHead} event, and for a @internalsref{Stem} object,
1002 this is a @internalsref{NoteHead} object.
1003
1004 Here is a function to use for @code{\applyOutput}; it blanks
1005 note-heads on the center-line:
1006
1007 @example
1008 (define (blanker grob grob-origin context)
1009  (if (and (memq (ly:grob-property grob 'interfaces)
1010                 note-head-interface)
1011           (eq? (ly:grob-property grob 'staff-position) 0))
1012      (set! (ly:grob-property grob 'transparent) #t)))
1013 @end example
1014
1015
1016 @node OLD STUFF
1017 @section OLD STUFF
1018
1019 This stuff is slated for deletion or merger into the earlier sections.
1020
1021 @menu
1022 * Extending music syntax::      
1023 * Manipulating music expressions::  
1024 * Using LilyPond syntax inside Scheme::  
1025 @end menu
1026
1027
1028 @node Extending music syntax
1029 @subsection Extending music syntax
1030
1031 @c TODO: rewrite example.
1032 @c The use of FUNC as example  argument is rather confusing.
1033
1034 The syntax of composite music expressions, like @code{\repeat},
1035 @code{\transpose}, and @code{\context} follows the general form of
1036
1037 @example
1038 \@code{keyword} @var{non-music-arguments} @var{music-arguments}
1039 @end example
1040
1041 Such syntax can also be defined as user code.  To do this it is
1042 necessary to create a @emph{music function}.  This is a specially marked
1043 Scheme function.  For example, the music function @code{\applyMusic} applies
1044 a user-defined function to a music expression.  Its syntax is
1045
1046 @example
1047 \applyMusic #@var{func} @var{music}
1048 @end example
1049
1050 A music function is created with @code{ly:make-music-function},
1051
1052 @example
1053 (ly:make-music-function
1054 @end example
1055
1056 @code{\applyMusic} takes a Scheme function and a Music expression as
1057 arguments.  This is encoded in its parameter list,
1058
1059 @example
1060 (list procedure? ly:music?)
1061 @end example
1062
1063 The function itself takes another argument: an Input location
1064 object.  That object is used to provide error messages with file names
1065 and line numbers.  The definition is the second argument of
1066 @code{ly:make-music-function}.  The body simply calls the function
1067
1068 @example
1069 (lambda (where func music)
1070  (func music))
1071 @end example
1072
1073 The above Scheme code only defines the functionality.  The tag
1074 @code{\applyMusic} is selected by defining
1075
1076 @example
1077 applyMusic = #(ly:make-music-function
1078                 (list procedure? ly:music?)
1079                 (lambda (parser location func music)
1080                   (func music)))
1081 @end example
1082
1083 A @code{define-music-function} macro is introduced on top of
1084 @code{ly:make-music-function} to ease the definition of music
1085 functions:
1086
1087 @example
1088 applyMusic = #(define-music-function (parser location func music)
1089                 (procedure? ly:music?)
1090                 (func music))
1091 @end example
1092
1093 Examples of the use of @code{\applyMusic} are in the next section.
1094
1095 @seealso
1096 @file{ly/@/music@/-functions@/-init@/.ly}.
1097
1098
1099 @node Manipulating music expressions
1100 @subsection Manipulating music expressions
1101
1102 Music objects and their properties can be accessed and manipulated
1103 directly through the @code{\applyMusic} mechanism.
1104 The syntax for @code{\applyMusic} is
1105
1106 @example
1107 \applyMusic #@var{func} @var{music}
1108 @end example
1109
1110 @noindent
1111 This means that the Scheme function @var{func} is called with
1112 @var{music} as its argument.  The return value of @var{func} is the
1113 result of the entire expression.  @var{func} may read and write music
1114 properties using the functions @code{ly:music-property} and
1115 @code{ly:music-set-property!}.
1116
1117 An example is a function that reverses the order of elements in
1118 its argument,
1119 @lilypond[quote,verbatim,ragged-right]
1120 #(define (rev-music-1 m)
1121   (ly:music-set-property! m 'elements 
1122     (reverse (ly:music-property m 'elements)))
1123   m)
1124
1125 \applyMusic #rev-music-1 { c'4 d'4 } 
1126 @end lilypond
1127
1128 The use of such a function is very limited.  The effect of this
1129 function is void when applied to an argument that does not have
1130 multiple children.  The following function application has no effect
1131
1132 @example
1133 \applyMusic #rev-music-1 \grace @{ c4 d4 @}
1134 @end example
1135
1136 @noindent
1137 In this case, @code{\grace} is stored as @internalsref{GraceMusic}, which
1138 has no @code{elements}, only a single @code{element}.  Every generally
1139 applicable function for @code{\applyMusic} must -- like music expressions
1140 themselves -- be recursive.
1141
1142 The following example is such a recursive function: It first extracts
1143 the @code{elements} of an expression, reverses them and puts them
1144 back.  Then it recurses, both on @code{elements} and @code{element}
1145 children.
1146
1147 @example
1148 #(define (reverse-music music)
1149   (let* ((elements (ly:music-property music 'elements))
1150          (child (ly:music-property music 'element))
1151          (reversed (reverse elements)))
1152
1153     ; set children
1154     (ly:music-set-property! music 'elements reversed)
1155
1156     ; recurse
1157     (if (ly:music? child) (reverse-music child))
1158     (map reverse-music reversed)
1159
1160     music))
1161 @end example
1162
1163 A slightly more elaborate example is in
1164 @inputfileref{input/@/test,reverse@/-music@/.ly}.
1165
1166 Some of the input syntax is also implemented as recursive music
1167 functions.  For example, the syntax for polyphony
1168 @example
1169 <<a \\ b>>
1170 @end example
1171
1172 @noindent
1173 is actually implemented as a recursive function that replaces the
1174 above by the internal equivalent of
1175 @example
1176 << \context Voice = "1" @{ \voiceOne a @}
1177    \context Voice = "2" @{ \voiceTwo b @} >>
1178 @end example
1179
1180 Other applications of @code{\applyMusic} are writing out repeats
1181 automatically (@inputfileref{input/@/test,unfold@/-all@/-repeats@/.ly}),
1182 saving keystrokes (@inputfileref{input/@/test,music@/-box@/.ly}) and
1183 exporting LilyPond input to other formats
1184 @c no @inputfileref{} here 
1185 (eg. @file{input/@/no@/-notation/@/to@/-xml@/.ly}).
1186
1187 @seealso
1188
1189 @file{scm/@/music@/-functions@/.scm}, @file{scm/@/music@/-types@/.scm},
1190 @inputfileref{input/@/test,add@/-staccato@/.ly},
1191 @inputfileref{input/@/test,unfold@/-all@/-repeats@/.ly}, and
1192 @inputfileref{input/@/test,music@/-box@/.ly}.
1193
1194
1195 @node Using LilyPond syntax inside Scheme
1196 @subsection Using LilyPond syntax inside Scheme
1197
1198 Creating music expressions in Scheme can be tedious, as they are
1199 heavily nested and the resulting Scheme code is large.  For some
1200 simple tasks this can be avoided by using common LilyPond syntax inside
1201 Scheme, with the dedicated @code{#@{ ... #@}} syntax.
1202
1203 The following two expressions give equivalent music expressions:
1204 @example
1205 mynotes = @{ \override Stem #'thickness = #4
1206             @{ c'8 d' @} @}
1207   
1208 #(define mynotes #@{ \override Stem #'thickness = #4
1209                     @{ c'8 d' @} #@})
1210 @end example
1211
1212 The content of @code{#@{ ... #@}} is enclosed in an implicit @code{@{
1213 ... @}} block, which is parsed.  The resulting music expression, a
1214 @code{SequentialMusic} music object, is then returned and usable in Scheme.
1215
1216 Arbitrary Scheme forms, including variables, can be used in @code{#@{ ... #@}}
1217 expressions with the @code{$} character (@code{$$} can be used to
1218 produce a single @code{$} character).  This makes the creation of simple
1219 functions straightforward.  In the following example, a function
1220 setting the TextScript's padding is defined:
1221
1222 @lilypond[quote,verbatim,ragged-right]
1223 #(use-modules (ice-9 optargs))
1224 #(define* (textpad padding #:optional once?)
1225   (ly:export   ; this is necessary for using the expression
1226                ; directly inside a block
1227     (if once?
1228         #{ \once \override TextScript #'padding = #$padding #}
1229         #{ \override TextScript #'padding = #$padding #})))
1230
1231  {
1232    c'^"1"
1233    #(textpad 3.0 #t) % only once
1234    c'^"2"
1235    c'^"3"
1236    #(textpad 5.0)
1237    c'^"4"
1238    c'^"5"
1239  }
1240 @end lilypond
1241
1242 Here, the variable @code{padding} is a number; music expression
1243 variables may also be used in a similar fashion, as in the following
1244 example:
1245
1246 @lilypond[quote,verbatim,ragged-right]
1247 #(define (with-padding padding)
1248   (lambda (music)
1249    #{ \override TextScript #'padding = #$padding
1250       $music
1251       \revert TextScript #'padding #}))
1252
1253 {
1254   c'^"1"
1255   \applyMusic #(with-padding 3) { c'^"2" c'^"3" }
1256   c'^"4"
1257 }
1258 @end lilypond
1259
1260 The function created by @code{(with-padding 3)} adds @code{\override} and
1261 @code{\revert} statements around the music given as an argument, and returns
1262 this new expression.  Thus, this example is equivalent to:
1263
1264 @example
1265 @{
1266   c'^"1"
1267   @{ \override TextScript #'padding = #3
1268     @{ c'^"2" c'^"3"@}
1269     \revert TextScript #'padding
1270   @}
1271   c'^"4"
1272 @}
1273 @end example
1274
1275
1276