4 @c A menu is needed before every deeper *section nesting of @nodes
5 @c Run M-x texinfo-all-menus-update
6 @c to automagically fill in these menus
7 @c before saving changes
11 @chapter Advanced Topics
14 When LilyPond is run, it reads an input file. During parsing, Music
15 objects are created. This music is interpreted, which is done by
16 contexts, that produce graphical objects. This section discusses
17 details of these three concepts, and how they are glued together with
18 the embedded Scheme interpreter.
21 * Interpretation context::
22 * Scheme integration::
23 * Music storage format::
29 @node Interpretation context
30 @section Interpretation context
35 * Context evaluation::
36 * Context properties::
37 * Engravers and performers::
38 * Changing context definitions::
39 * Defining new contexts::
43 Interpretation contexts are objects that only exist during program
44 run. During the interpretation phase (when @code{interpreting music}
45 is interpreted to standard output), the music expression in a
46 @code{\score} block is interpreted in time order, the same order in
47 which hear and play the music. During this phase, the interpretation
48 context holds the state for the current point within the music, for example
50 @item What notes are playing at this point?
52 @item What symbols will be printed at this point?
54 @item What is the current key signature, time signature, point within
58 Contexts are grouped hierarchically: A @internalsref{Voice} context is
59 contained in a @internalsref{Staff} context (because a staff can contain
60 multiple voices at any point), a @internalsref{Staff} context is contained in
61 @internalsref{Score}, @internalsref{StaffGroup}, or
62 @internalsref{ChoirStaff} context.
64 Contexts associated with sheet music output are called @emph{notation
65 contexts}, those for sound output are called @emph{performance
66 contexts}. The default definitions of the standard notation and
67 performance contexts can be found in @file{ly/engraver-init.ly} and
68 @file{ly/performer-init.ly}, respectively.
71 @node Creating contexts
72 @subsection Creating contexts
73 @cindex @code{\context}
74 @cindex context selection
76 Contexts for a music expression can be selected manually, using the
77 following music expression.
80 \context @var{contexttype} [= @var{contextname}] @var{musicexpr}
84 This means that @var{musicexpr} should be interpreted within a context
85 of type @var{contexttype} (with name @var{contextname} if specified).
86 If no such context exists, it will be created.
88 @lilypond[verbatim,singleline]
90 \notes \relative c'' {
91 c4 <d4 \context Staff = "another" e4> f
97 In this example, the @code{c} and @code{d} are printed on the
98 default staff. For the @code{e}, a context Staff called
99 @code{another} is specified; since that does not exist, a new
100 context is created. Within @code{another}, a (default) Voice context
101 is created for the @code{e4}. When all music referring to a
102 context is finished, the context is ended as well. So after the
103 third quarter, @code{another} is removed.
106 @node Default contexts
107 @subsection Default contexts
109 Most music expressions do not need an explicit @code{\context}
110 declaration: they inherit the notation context from their parent. In
111 the following example, only the sequential expression has an explicit
112 context. The notes contained therein inherit the @code{goUp} context
113 from the enclosing music expression.
115 @lilypond[verbatim,singleline]
116 \notes \context Voice = goUp { c'4 d' e' }
119 There are some quirks that you must keep in mind when dealing with
122 First, every top level music is interpreted by the Score context; in other
123 words, you may think of @code{\score} working like
127 \context Score @var{music}
131 Second, contexts are created automatically to be able to interpret the
132 music expressions. Consider the following example.
134 @lilypond[verbatim, singleline]
135 \score { \notes { c'4-( d' e'-) } }
139 The sequential music is interpreted by the Score context initially
140 (notice that the @code{\context} specification is redundant), but when a
141 note is encountered, contexts are setup to accept that note. In this
142 case, a Thread, Voice, and Staff context are created. The rest of the
143 sequential music is also interpreted with the same Thread, Voice, and
144 Staff context, putting the notes on the same staff, in the same voice.
146 @node Context evaluation
147 @subsection Context evaluation
149 Scheme code can be used to modify contexts. The syntax for this is
152 \applycontext @var{function}
155 @var{function} should be a Scheme function taking a single argument,
156 being the context to apply it with. The following code will print the
157 current bar number on the standard output during the compile.
162 (format #t "\nWe were called in barnumber ~a.\n"
163 (ly:get-context-property x 'currentBarNumber)))
167 @node Context properties
168 @subsection Context properties
171 Notation contexts have properties. These properties are from
172 the @file{.ly} file using the following expression:
173 @cindex @code{\property}
174 @cindex context properties
175 @cindex properties, context
178 \property @var{contextname}.@var{propname} = @var{value}
182 Sets the @var{propname} property of the context @var{contextname} to
183 the specified Scheme expression @var{value}. Both @var{propname} and
184 @var{contextname} are strings, which can often be written unquoted.
187 Properties that are set in one context are inherited by all of the
188 contained contexts. This means that a property valid for the
189 @internalsref{Voice} context can be set in the @internalsref{Score} context
190 (for example) and thus take effect in all @internalsref{Voice} contexts.
192 @cindex @code{Current}
193 If you do not wish to specify the name of the context in the
194 @code{\property}-expression itself, you can refer to the abstract context
195 name, @code{Current}. The @code{Current} context is the latest
196 used context. This will typically mean the @internalsref{Thread}
197 context, but you can force another context with the
198 @code{\property}-command. Hence the expressions
201 \property @var{contextname}.@var{propname} = @var{value}
208 \context @var{contextname}
209 \property Current.@var{propname} = @var{value}
213 do the same thing. The main use for this is in predefined variables.
214 This construction allows the specification of a property-setting
215 without restriction to a specific context.
217 Properties can be unset using the following statement.
219 \property @var{contextname}.@var{propname} \unset
222 @cindex properties, unsetting
223 @cindex @code{\unset}
226 This removes the definition of @var{propname} in @var{contextname}. If
227 @var{propname} was not defined in @var{contextname} (but was inherited
228 from a higher context), then this has no effect.
232 The syntax of @code{\unset} is asymmetric: @code{\property \unset} is not
233 the inverse of @code{\property \set}.
236 @node Engravers and performers
237 @subsection Engravers and performers
239 @node Changing context definitions
240 @subsection Changing context definitions
241 @cindex context definition
242 @cindex translator definition
244 The most common way to define a context is by extending an existing
245 context. You can change an existing context from the paper block by
246 first initializing a translator with an existing context identifier:
251 @var{context-identifier}
257 Every predefined context has a standard identifier. For example, the
258 @code{Staff} context can be referred to as @code{\StaffContext}.
261 The context can then be modified by setting or changing properties,
266 Stem \set #'thickness = #1.2
267 defaultBarType = #"||"
270 These assignments happen before interpretation starts, so a @code{\property}
271 command will override any predefined settings.
277 It is not possible to collect multiple property assignments in a
278 variable, and apply to one @code{\translator} definition by
279 referencing that variable.
281 @node Defining new contexts
282 @subsection Defining new contexts
287 Each context is composed of a number of building blocks, or plug-ins
288 called engravers. An engraver is a specialized C++ class that is
289 compiled into the executable. Typically, an engraver is responsible
290 for one function: the @code{Slur_engraver} creates only @code{Slur}
291 objects, and the @code{Skip_event_swallow_translator} only swallows
292 (silently gobbles) @code{SkipEvent}s.
294 An existing context definition can be changed by adding or removing an
295 engraver. The syntax for these operations is
297 \consists @var{engravername}
298 \remove @var{engravername}
305 Here @var{engravername} is a string, the name of an engraver in the
306 system. In the following example, the @code{Clef_engraver} is removed
307 from the Staff context. The result is a staff without a clef, where
308 the central C is at its default position, the center line.
310 @lilypond[verbatim,singleline]
318 \remove Clef_engraver
324 A list of all engravers is in the internal documentation,
325 @internalsref{All engravers}.
327 It is also possible to define new contexts from scratch. To do this,
328 you must define give the new context a name. In the following
329 example, a very simple Staff context is created: one that will put
330 note heads on a staff symbol.
334 \type "Engraver_group_engraver"
337 \consists "Staff_symbol_engraver"
338 \consists "Note_head_engraver"
339 \consistsend "Axis_group_engraver"
344 The argument of @code{\type} is the name for a special engraver that
345 handles cooperation between simple engravers such as
346 @code{Note_head_engraver} and @code{Staff_symbol_engraver}. This
347 should always be @code{Engraver_group_engraver} (unless you are
348 defining a Score context from scratch, in which case
349 @code{Score_engraver} must be used).
351 The complete list of context modifiers is as follows:
353 @item @code{\alias} @var{alternate-name}:
354 This specifies a different name. In the above example,
355 @code{\property Staff.X = Y} will also work on @code{SimpleStaff}s
357 @item @code{\consistsend} @var{engravername}:
358 Analogous to @code{\consists}, but makes sure that
359 @var{engravername} is always added to the end of the list of
362 Engravers that group context objects into axis groups or alignments
363 need to be at the end of the list. @code{\consistsend} insures that
364 engravers stay at the end even if a user adds or removes engravers.
366 @item @code{\accepts} @var{contextname}:
367 This context can contains @var{contextname} contexts. The first
368 @code{\accepts} is created as a default context when events (eg. notes
369 or rests) are encountered.
371 @item @code{\denies}:
372 The opposite of @code{\accepts}.
374 @item @code{\name} @var{contextname}:
375 This sets the type name of the context, e.g. @code{Staff},
376 @code{Voice}. If the name is not specified, the translator will not
381 @node Scheme integration
382 @section Scheme integration
386 @cindex Scheme, in-line code
387 @cindex accessing Scheme
388 @cindex evaluating Scheme
391 LilyPond internally uses GUILE, a Scheme-interpreter. Scheme is a
392 language from the LISP family. You can learn more about Scheme at
393 @uref{http://www.scheme.org}. It is used to represent data throughout
396 In some places of the input file, Scheme expressions also form valid
397 syntax: wherever it is allowed, GUILE can be accessed directly by
398 entering a hash-sign (@code{#}). The expression following the
399 hash-sign is evaluated as Scheme. For example, the boolean value @var{true} is
400 @code{#t} in Scheme, so for LilyPond @var{true} looks like @code{##t},
401 and can be used in property assignments:
403 \property Staff.autoBeaming = ##f
406 Scheme is a full-blown programming language, and a full discussion is
407 outside the scope of this document. Interested readers are referred to
408 the website @uref{http://www.schemers.org/} for more information on
414 * Input variables and Scheme::
419 @node Input variables and Scheme
420 @subsection Input variables and Scheme
423 The input format supports the notion of variable: in the following
424 example, a music expression is assigned to a variable with the name
427 traLaLa = \notes @{ c'4 d'4 @}
432 There is also a form of scoping: in the following example, the
433 @code{\paper} block also contains a @code{traLaLa} variable, which is
434 independent of the outer \traLaLa.
436 traLaLa = \notes @{ c'4 d'4 @}
437 \paper @{ traLaLa = 1.0 @}
440 In effect, each input file is a scope, and all @code{\header},
441 @code{\midi} and @code{\paper} blocks are scopes nested inside that
444 Both variables and scoping are implemented in the GUILE module system.
445 A anonymous Scheme module is attached to each scope. An assignment of
448 traLaLa = \notes @{ c'4 d'4 @}
452 is internally converted to a Scheme definition
454 (define traLaLa @var{Scheme value of @code{\notes ... }})
457 This means that input variables and Scheme variables may be freely
458 mixed. In the following example, a music fragment is stored in the
459 variable @code{traLaLa}, and duplicated using Scheme. The result is
460 imported in a @code{\score} by means of a second variable
463 traLaLa = \notes @{ c'4 d'4 @}
465 #(define newLa (map ly:music-deep-copy
466 (list traLaLa traLaLa)))
468 (make-sequential-music newLa))
473 In the above example, music expressions can be `exported' from the
474 input to the Scheme interpreter. The opposite is also possible. By
475 wrapping a Scheme value in the function @code{ly:export}, a Scheme
476 value is interpreted as if it were entered in LilyPond syntax: instead
477 of defining @code{\twice}, the example above could also have been
481 \score @{ #(ly:export (make-sequential-music newLa)) @}
488 @node Scheme datatypes
489 @subsection Scheme datatypes
491 Scheme is used to glue together different program modules. To aid this
492 glue function, many lilypond specific object types can be passed as
495 The following list are all lilypond specific types, that
496 can exist during parsing:
503 @item Music_output_def
510 During a run, transient objects are also created and destroyed.
513 @item Grob: short for `Graphical object'.
514 @item Scheme_hash_table
517 @item Molecule: Device-independent page output object,
518 including dimensions.
524 @item Translator: An object that produces audio objects or Grobs. This is
525 not yet user-accessible.
527 @item Font_metric: An object representing a font.
530 Many functions are defined to manipulate these data structures. They
531 are all listed and documented in @internalsref{All scheme functions}.
535 @subsection Assignments
538 Identifiers allow objects to be assigned to names during the parse
539 stage. To assign an identifier, use @var{name}@code{=}@var{value}.
540 To refer to an identifier, precede its name with a backslash:
541 `@code{\}@var{name}'. @var{value} is any valid Scheme value or any of
542 the input-types listed above. Identifier assignments can appear at top
543 level in the LilyPond file, but also in @code{\paper} blocks.
545 An identifier can be created with any string for its name, but you will
546 only be able to refer to identifiers whose names begin with a letter,
547 being entirely alphabetical. It is impossible to refer to an identifier
548 whose name is the same as the name of a keyword.
550 The right hand side of an identifier assignment is parsed completely
551 before the assignment is done, so it is allowed to redefine an
552 identifier in terms of its old value, e.g.
558 When an identifier is referenced, the information it points to is
559 copied. For this reason, an identifier reference must always be the
560 first item in a block.
565 \paperIdent % wrong and invalid
571 \paperIdent % correct
578 @node Music storage format
579 @section Music storage format
582 * Music expressions::
583 * Internal music representation::
584 * Manipulating music expressions::
587 @node Music expressions
588 @subsection Music expressions
589 @cindex music expressions
591 Music in LilyPond is entered as a music expression. Notes, rests, lyric
592 syllables are music expressions, and you can combine music expressions
593 to form new ones, for example by enclosing a list of expressions in
594 @code{\sequential @{ @}} or @code{< >}. In the following example, a
595 compound expression is formed out of the quarter note @code{c} and a
596 quarter note @code{d}:
599 \sequential @{ c4 d4 @}
602 @cindex Sequential music
603 @cindex @code{\sequential}
604 @cindex sequential music
607 @cindex Simultaneous music
608 @cindex @code{\simultaneous}
610 The two basic compound music expressions are simultaneous and
614 \sequential @code{@{} @var{musicexprlist} @code{@}}
615 \simultaneous @code{@{} @var{musicexprlist} @code{@}}
618 For both, there is a shorthand:
621 @code{@{} @var{musicexprlist} @code{@}}
628 @code{<} @var{musicexprlist} @code{>}
632 for simultaneous music.
633 In principle, the way in which you nest sequential and simultaneous to
634 produce music is not relevant. In the following example, three chords
635 are expressed in two different ways:
637 @lilypond[fragment,verbatim,center,quote]
638 \notes \context Voice {
639 <a c'> <b d'> <c' e'>
640 < { a b c' } { c' d' e' } >
643 However, using @code{<} and @code{>} for entering chords leads to
644 various peculiarities. For this reason, a special syntax
645 for chords was introduced in version 1.7: @code{<< >>}.
651 Other compound music expressions include
654 \transpose @var{from} @var{to} @var{expr}
655 \apply @var{func} @var{expr}
656 \context @var{type} = @var{id} @var{expr}
657 \times @var{fraction} @var{expr}
660 @node Internal music representation
661 @subsection Internal music representation
668 @node Manipulating music expressions
669 @subsection Manipulating music expressions
671 When a music expression is parsed, it is converted into a set of
672 Scheme music objects. The defining property of a music object is that
673 it takes up time. Time is a rational number that measures the length
674 of a piece of music, in whole notes.
676 A music object has three kinds of types
679 Music name: each music expression has a name, for example, a note
680 leads to a @internalsref{NoteEvent}, and @code{\simultaneous} leads to
681 a @internalsref{SimultaneousMusic}. A list of all expressions
682 available is in the internals manual, under @internalsref{Music
686 Each music name has several `types' or interface. For example, a
687 note is an @code{event}, but it is also a @code{note-event}, a
688 @code{rhythmic-event} and a @code{melodic-event}.
690 All classes of music are listed in the internals manual, under
691 @internalsref{Music classes}.
693 Each music object is represented by a C++ object. may be represented
694 by different C++ classes. For technical reasons, different music
695 objects may be represented by different C++ object types. For example,
696 a note is @code{Event} object, while @code{\grace} creates a
697 @code{Grace_music} object.
699 The distinctions between different C++ types will disappear in the
703 The actual information of a music expression is stored in properties.
704 For example, a @internalsref{NoteEvent} has @code{pitch} and
705 @code{duration} properties that store the pitch and duration of that
706 note. A list of all properties available is in the internals manual,
707 under @internalsref{Music properties}.
709 A compound music expresssion is a music object that contains other
710 music objects in its properties. A list of objects can be stored in
711 the @code{elements} property of a music object, or a single `child'
712 music object is stored in the @code{element} object. For example,
713 @internalsref{SequentialMusic} has its children in @code{elements},
714 and @internalsref{GraceMusic} has its single argument in
715 @code{element}. The body of a repeat is in @code{element} property of
716 @internalsref{RepeatedMusic}, and the alternatives in @code{elements}.
718 These properties and objects can be directly accessed and manipulated,
719 through the @code{\apply} mechanism. Scheme functions can read and
720 write properties using the functions @code{ly:get-music-property} and
721 @code{ly:set-music-property!}.
723 The syntax for @code{\apply}
725 \apply #@var{func} @var{music}
729 This means that the scheme function @var{func} is called with
730 @var{music} as its argument. The return value of @var{func} is the
731 result of the entire expresssion.
733 An example is a function that reverses the order of elements in
736 #(define (rev-music-1 m)
737 (ly:set-music-property! 'elements (reverse
738 (ly:get-music-property mus 'elements)))
740 \apply #rev-music-1 @{ c4 d4 @}
743 The use of such a function is very limited. The effect of this
744 function is void, when it is applied to an argument which is does not
745 have multiple children, for example
748 \apply #rev-music-1 \grace @{ c4 d4 @}
752 does not do anything: @code{\grace} is stored as
753 @internalsref{GraceMusic}, which has no @code{elements}, only a single
754 @code{element}. Every generally applicable function for @code{\apply}
755 must --like music expressions themselves-- be recursive.
757 The following example is such a recursive function: it first extracts
758 the @code{elements} of an expression, reverses them and puts them
759 back. Then it recurses, both on @code{elements} and @code{element}.
761 #(define (reverse-music music)
762 (let* ((elements (ly:get-mus-property music 'elements))
763 (child (ly:get-mus-property music 'element))
764 (reversed (reverse elements)))
767 (ly:set-mus-property! music 'elements reversed)
770 (if (ly:music? child) (reverse-music child))
771 (map reverse-music reversed)
776 A slightly more elaborate example is in
777 @inputfileref{input/test,reverse-music.ly}.
779 Some of the input syntax is also implemented as recursive music
780 functions. For example, the syntax for polyphony
786 is actually implemented as a recursive function that replaces the
787 above by the internal equivalent of
789 < \context Voice = "1" @{ \voiceOne a @}
790 \context Voice = "2" @{ \voiceTwo a @} >
793 Other applications of @code{\apply} are writing out repeats
794 automatically (@inputfileref{input/test,unfold-all-repeats.ly}),
795 saving keystrokes (@inputfileref{input/test,music-box.ly}) and
797 LilyPond input to other formats (@inputfileref{input/test,to-xml.ly})
801 @file{scm/music-functions.scm}, @file{scm/music-types.scm},
802 @inputfileref{input/test,add-staccato.ly},
803 @inputfileref{input/test,duration-check.ly}.
804 @inputfileref{input/test,unfold-all-repeats.ly},
805 @inputfileref{input/test,music-box.ly}.
807 @node Lexical details
808 @section Lexical details
819 Begins and ends with the @code{"} character. To include a @code{"}
820 character in a string write @code{\"}. Various other backslash
821 sequences have special interpretations as in the C language. A string
822 that contains no spaces can be written without the quotes. Strings can
823 be concatenated with the @code{+} operator.
828 @section Output details
830 LilyPond's default output format is @TeX{}. Using the option @option{-f}
831 (or @option{--format}) other output formats can be selected also, but
832 currently none of them reliably work.
834 At the beginning of the output file, various global parameters are defined.
835 It also contains a large @code{\special} call to define PostScript routines
836 to draw items not representable with @TeX{}, mainly slurs and ties. A DVI
837 driver must be able to understand such embedded PostScript, or the output
838 will be rendered incompletely.
840 Then the file @file{lilyponddefs.tex} is loaded to define the macros used
841 in the code which follows. @file{lilyponddefs.tex} includes various other
842 files, partially depending on the global parameters.
844 Now the music is output system by system (a `system' consists of all
845 staves belonging together). From @TeX{}'s point of view, a system is an
846 @code{\hbox} which contains a lowered @code{\vbox} so that it is centered
847 vertically on the baseline of the text. Between systems,
848 @code{\interscoreline} is inserted vertically to have stretchable space.
849 The horizontal dimension of the @code{\hbox} is given by the
850 @code{linewidth} parameter from LilyPond's @code{\paper} block.
853 After the last system LilyPond emits a stronger variant of
854 @code{\interscoreline} only if the macro
855 @code{\lilypondpaperlastpagefill} is not defined (flushing the systems
856 to the top of the page). You can avoid that by setting the variable
857 @code{lastpagefill} in LilyPond's @code{\paper} block.
859 It is possible to fine-tune the vertical offset further by defining the
860 macro @code{\lilypondscoreshift}. Example:
863 \def\lilypondscoreshift@{0.25\baselineskip@}
867 @code{\baselineskip} is the distance from one text line to the next.
869 The code produced by LilyPond should be run through La@TeX{}, not
872 Here an example how to embed a small LilyPond file @code{foo.ly} into
873 running La@TeX{} text without using the @code{lilypond-book} script
874 (@pxref{Integrating text and music with lilypond-book}).
877 \documentclass@{article@}
879 \def\lilypondpaperlastpagefill@{@}
881 \def\lilypondscoreshift@{0.25\baselineskip@}
884 This is running text which includes an example music file
890 The file @file{foo.tex} has been simply produced with
896 It is important to set the @code{indent} parameter to zero in the
897 @code{\paper} block of @file{foo.ly}.
899 The call to @code{\lineskip} assures that there is enough vertical space
900 between the LilyPond box and the surrounding text lines.