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::
30 @node Interpretation context
31 @section Interpretation context
36 * Context evaluation::
37 * Context properties::
38 * Engravers and performers::
39 * Changing context definitions::
40 * Defining new contexts::
44 Interpretation contexts are objects that only exist during program
45 run. During the interpretation phase (when @code{interpreting music}
46 is interpreted to standard output), the music expression in a
47 @code{\score} block is interpreted in time order, the same order in
48 which hear and play the music. During this phase, the interpretation
49 context holds the state for the current point within the music, for example
51 @item What notes are playing at this point?
53 @item What symbols will be printed at this point?
55 @item What is the current key signature, time signature, point within
59 Contexts are grouped hierarchically: A @internalsref{Voice} context is
60 contained in a @internalsref{Staff} context (because a staff can contain
61 multiple voices at any point), a @internalsref{Staff} context is contained in
62 @internalsref{Score}, @internalsref{StaffGroup}, or
63 @internalsref{ChoirStaff} context.
65 Contexts associated with sheet music output are called @emph{notation
66 contexts}, those for sound output are called @emph{performance
67 contexts}. The default definitions of the standard notation and
68 performance contexts can be found in @file{ly/engraver-init.ly} and
69 @file{ly/performer-init.ly}, respectively.
72 @node Creating contexts
73 @subsection Creating contexts
74 @cindex @code{\context}
75 @cindex context selection
77 Contexts for a music expression can be selected manually, using the
78 following music expression.
81 \context @var{contexttype} [= @var{contextname}] @var{musicexpr}
85 This means that @var{musicexpr} should be interpreted within a context
86 of type @var{contexttype} (with name @var{contextname} if specified).
87 If no such context exists, it will be created.
89 @lilypond[verbatim,singleline]
91 \notes \relative c'' {
92 c4 <d4 \context Staff = "another" e4> f
98 In this example, the @code{c} and @code{d} are printed on the
99 default staff. For the @code{e}, a context Staff called
100 @code{another} is specified; since that does not exist, a new
101 context is created. Within @code{another}, a (default) Voice context
102 is created for the @code{e4}. When all music referring to a
103 context is finished, the context is ended as well. So after the
104 third quarter, @code{another} is removed.
107 @node Default contexts
108 @subsection Default contexts
110 Most music expressions do not need an explicit @code{\context}
111 declaration: they inherit the notation context from their parent. In
112 the following example, only the sequential expression has an explicit
113 context. The notes contained therein inherit the @code{goUp} context
114 from the enclosing music expression.
116 @lilypond[verbatim,singleline]
117 \notes \context Voice = goUp { c'4 d' e' }
120 There are some quirks that you must keep in mind when dealing with
123 First, every top level music is interpreted by the Score context; in other
124 words, you may think of @code{\score} working like
128 \context Score @var{music}
132 Second, contexts are created automatically to be able to interpret the
133 music expressions. Consider the following example.
135 @lilypond[verbatim, singleline]
136 \score { \notes { c'4-( d' e'-) } }
140 The sequential music is interpreted by the Score context initially
141 (notice that the @code{\context} specification is redundant), but when a
142 note is encountered, contexts are setup to accept that note. In this
143 case, a Thread, Voice, and Staff context are created. The rest of the
144 sequential music is also interpreted with the same Thread, Voice, and
145 Staff context, putting the notes on the same staff, in the same voice.
147 @node Context evaluation
148 @subsection Context evaluation
150 Scheme code can be used to modify contexts. The syntax for this is
153 \applycontext @var{function}
156 @var{function} should be a Scheme function taking a single argument,
157 being the context to apply it with. The following code will print the
158 current bar number on the standard output during the compile.
163 (format #t "\nWe were called in barnumber ~a.\n"
164 (ly:get-context-property x 'currentBarNumber)))
168 @node Context properties
169 @subsection Context properties
172 Notation contexts have properties. These properties are from
173 the @file{.ly} file using the following expression:
174 @cindex @code{\property}
175 @cindex context properties
176 @cindex properties, context
179 \property @var{contextname}.@var{propname} = @var{value}
183 Sets the @var{propname} property of the context @var{contextname} to
184 the specified Scheme expression @var{value}. Both @var{propname} and
185 @var{contextname} are strings, which can often be written unquoted.
188 Properties that are set in one context are inherited by all of the
189 contained contexts. This means that a property valid for the
190 @internalsref{Voice} context can be set in the @internalsref{Score} context
191 (for example) and thus take effect in all @internalsref{Voice} contexts.
193 @cindex @code{Current}
194 If you do not wish to specify the name of the context in the
195 @code{\property}-expression itself, you can refer to the abstract context
196 name, @code{Current}. The @code{Current} context is the latest
197 used context. This will typically mean the @internalsref{Thread}
198 context, but you can force another context with the
199 @code{\property}-command. Hence the expressions
202 \property @var{contextname}.@var{propname} = @var{value}
209 \context @var{contextname}
210 \property Current.@var{propname} = @var{value}
214 do the same thing. The main use for this is in predefined variables.
215 This construction allows the specification of a property-setting
216 without restriction to a specific context.
218 Properties can be unset using the following statement.
220 \property @var{contextname}.@var{propname} \unset
223 @cindex properties, unsetting
224 @cindex @code{\unset}
227 This removes the definition of @var{propname} in @var{contextname}. If
228 @var{propname} was not defined in @var{contextname} (but was inherited
229 from a higher context), then this has no effect.
233 The syntax of @code{\unset} is asymmetric: @code{\property \unset} is not
234 the inverse of @code{\property \set}.
237 @node Engravers and performers
238 @subsection Engravers and performers
240 @node Changing context definitions
241 @subsection Changing context definitions
242 @cindex context definition
243 @cindex translator definition
245 The most common way to define a context is by extending an existing
246 context. You can change an existing context from the paper block by
247 first initializing a translator with an existing context identifier:
252 @var{context-identifier}
258 Every predefined context has a standard identifier. For example, the
259 @code{Staff} context can be referred to as @code{\StaffContext}.
262 The context can then be modified by setting or changing properties,
267 Stem \set #'thickness = #1.2
268 defaultBarType = #"||"
271 These assignments happen before interpretation starts, so a @code{\property}
272 command will override any predefined settings.
278 It is not possible to collect multiple property assignments in a
279 variable, and apply to one @code{\translator} definition by
280 referencing that variable.
282 @node Defining new contexts
283 @subsection Defining new contexts
288 Each context is composed of a number of building blocks, or plug-ins
289 called engravers. An engraver is a specialized C++ class that is
290 compiled into the executable. Typically, an engraver is responsible
291 for one function: the @code{Slur_engraver} creates only @code{Slur}
292 objects, and the @code{Skip_event_swallow_translator} only swallows
293 (silently gobbles) @code{SkipEvent}s.
295 An existing context definition can be changed by adding or removing an
296 engraver. The syntax for these operations is
298 \consists @var{engravername}
299 \remove @var{engravername}
306 Here @var{engravername} is a string, the name of an engraver in the
307 system. In the following example, the @code{Clef_engraver} is removed
308 from the Staff context. The result is a staff without a clef, where
309 the central C is at its default position, the center line.
311 @lilypond[verbatim,singleline]
319 \remove Clef_engraver
325 A list of all engravers is in the internal documentation,
326 @internalsref{All engravers}.
328 It is also possible to define new contexts from scratch. To do this,
329 you must define give the new context a name. In the following
330 example, a very simple Staff context is created: one that will put
331 note heads on a staff symbol.
335 \type "Engraver_group_engraver"
338 \consists "Staff_symbol_engraver"
339 \consists "Note_head_engraver"
340 \consistsend "Axis_group_engraver"
345 The argument of @code{\type} is the name for a special engraver that
346 handles cooperation between simple engravers such as
347 @code{Note_head_engraver} and @code{Staff_symbol_engraver}. This
348 should always be @code{Engraver_group_engraver} (unless you are
349 defining a Score context from scratch, in which case
350 @code{Score_engraver} must be used).
352 The complete list of context modifiers is as follows:
354 @item @code{\alias} @var{alternate-name}:
355 This specifies a different name. In the above example,
356 @code{\property Staff.X = Y} will also work on @code{SimpleStaff}s
358 @item @code{\consistsend} @var{engravername}:
359 Analogous to @code{\consists}, but makes sure that
360 @var{engravername} is always added to the end of the list of
363 Engravers that group context objects into axis groups or alignments
364 need to be at the end of the list. @code{\consistsend} insures that
365 engravers stay at the end even if a user adds or removes engravers.
367 @item @code{\accepts} @var{contextname}:
368 This context can contains @var{contextname} contexts. The first
369 @code{\accepts} is created as a default context when events (eg. notes
370 or rests) are encountered.
372 @item @code{\denies}:
373 The opposite of @code{\accepts}.
375 @item @code{\name} @var{contextname}:
376 This sets the type name of the context, e.g. @code{Staff},
377 @code{Voice}. If the name is not specified, the translator will not
382 @node Scheme integration
383 @section Scheme integration
387 @cindex Scheme, in-line code
388 @cindex accessing Scheme
389 @cindex evaluating Scheme
392 LilyPond internally uses GUILE, a Scheme-interpreter. Scheme is a
393 language from the LISP family. You can learn more about Scheme at
394 @uref{http://www.scheme.org}. It is used to represent data throughout
397 In some places of the input file, Scheme expressions also form valid
398 syntax: wherever it is allowed, GUILE can be accessed directly by
399 entering a hash-sign (@code{#}). The expression following the
400 hash-sign is evaluated as Scheme. For example, the boolean value @var{true} is
401 @code{#t} in Scheme, so for LilyPond @var{true} looks like @code{##t},
402 and can be used in property assignments:
404 \property Staff.autoBeaming = ##f
407 Scheme is a full-blown programming language, and a full discussion is
408 outside the scope of this document. Interested readers are referred to
409 the website @uref{http://www.schemers.org/} for more information on
415 * Input variables and Scheme::
420 @node Input variables and Scheme
421 @subsection Input variables and Scheme
424 The input format supports the notion of variable: in the following
425 example, a music expression is assigned to a variable with the name
428 traLaLa = \notes @{ c'4 d'4 @}
433 There is also a form of scoping: in the following example, the
434 @code{\paper} block also contains a @code{traLaLa} variable, which is
435 independent of the outer \traLaLa.
437 traLaLa = \notes @{ c'4 d'4 @}
438 \paper @{ traLaLa = 1.0 @}
441 In effect, each input file is a scope, and all @code{\header},
442 @code{\midi} and @code{\paper} blocks are scopes nested inside that
445 Both variables and scoping are implemented in the GUILE module system.
446 A anonymous Scheme module is attached to each scope. An assignment of
449 traLaLa = \notes @{ c'4 d'4 @}
453 is internally converted to a Scheme definition
455 (define traLaLa @var{Scheme value of @code{\notes ... }})
458 This means that input variables and Scheme variables may be freely
459 mixed. In the following example, a music fragment is stored in the
460 variable @code{traLaLa}, and duplicated using Scheme. The result is
461 imported in a @code{\score} by means of a second variable
464 traLaLa = \notes @{ c'4 d'4 @}
466 #(define newLa (map ly:music-deep-copy
467 (list traLaLa traLaLa)))
469 (make-sequential-music newLa))
474 In the above example, music expressions can be `exported' from the
475 input to the Scheme interpreter. The opposite is also possible. By
476 wrapping a Scheme value in the function @code{ly:export}, a Scheme
477 value is interpreted as if it were entered in LilyPond syntax: instead
478 of defining @code{\twice}, the example above could also have been
482 \score @{ #(ly:export (make-sequential-music newLa)) @}
489 @node Scheme datatypes
490 @subsection Scheme datatypes
492 Scheme is used to glue together different program modules. To aid this
493 glue function, many lilypond specific object types can be passed as
496 The following list are all lilypond specific types, that
497 can exist during parsing:
504 @item Music_output_def
511 During a run, transient objects are also created and destroyed.
514 @item Grob: short for `Graphical object'.
515 @item Scheme_hash_table
518 @item Molecule: Device-independent page output object,
519 including dimensions.
525 @item Translator: An object that produces audio objects or Grobs. This is
526 not yet user-accessible.
528 @item Font_metric: An object representing a font.
531 Many functions are defined to manipulate these data structures. They
532 are all listed and documented in @internalsref{All scheme functions}.
536 @subsection Assignments
539 Identifiers allow objects to be assigned to names during the parse
540 stage. To assign an identifier, use @var{name}@code{=}@var{value}.
541 To refer to an identifier, precede its name with a backslash:
542 `@code{\}@var{name}'. @var{value} is any valid Scheme value or any of
543 the input-types listed above. Identifier assignments can appear at top
544 level in the LilyPond file, but also in @code{\paper} blocks.
546 An identifier can be created with any string for its name, but you will
547 only be able to refer to identifiers whose names begin with a letter,
548 being entirely alphabetical. It is impossible to refer to an identifier
549 whose name is the same as the name of a keyword.
551 The right hand side of an identifier assignment is parsed completely
552 before the assignment is done, so it is allowed to redefine an
553 identifier in terms of its old value, e.g.
559 When an identifier is referenced, the information it points to is
560 copied. For this reason, an identifier reference must always be the
561 first item in a block.
566 \paperIdent % wrong and invalid
572 \paperIdent % correct
579 @node Music storage format
580 @section Music storage format
583 * Music expressions::
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}
661 @c . {Manipulating music expressions}
662 @node Manipulating music expressions
663 @subsection Manipulating music expressions
665 The @code{\apply} mechanism gives you access to the internal
666 representation of music. You can write Scheme-functions that operate
667 directly on it. The syntax is
670 \apply #@var{func} @var{music}
674 This means that @var{func} is applied to @var{music}. The function
675 @var{func} should return a music expression.
677 This example replaces the text string of a script. It also shows a dump
678 of the music it processes, which is useful if you want to know more
679 about how music is stored.
681 @lilypond[verbatim,singleline]
682 #(define (testfunc x)
683 (if (equal? (ly:get-mus-property x 'text) (make-simple-markup "foo"))
684 (ly:set-mus-property! x 'text (make-simple-markup "bar")))
686 (ly:set-mus-property! x 'elements
687 (map testfunc (ly:get-mus-property x 'elements)))
693 \apply #testfunc { c'4_"foo" }
697 A final example is a function that reverses a piece of music in time:
699 @lilypond[verbatim,singleline]
700 #(define (reverse-music music)
701 (let* ((elements (ly:get-mus-property music 'elements))
702 (reversed (reverse elements))
703 (span-dir (ly:get-mus-property music 'span-direction)))
704 (ly:set-mus-property! music 'elements reversed)
705 (if (ly:dir? span-dir)
706 (ly:set-mus-property! music 'span-direction (- span-dir)))
707 (map reverse-music reversed)
710 music = \notes { c'4 d'4( e'4 f'4 }
715 \apply #reverse-music \music
722 More examples are given in the distributed example files in
728 Directly accessing internal representations is dangerous: The
729 implementation is subject to changes, so you should avoid this feature
733 @node Syntactic details
734 @section Syntactic details
735 @cindex Syntactic details
737 This section describes details that were too boring to be put elsewhere.
747 @subsection Lexical modes
748 @cindex Lexical modes
751 @cindex @code{\notes}
752 @cindex @code{\chords}
753 @cindex @code{\lyrics}
755 To simplify entering notes, lyrics, and chords, LilyPond has three
756 special input modes in addition to the default mode: note, lyrics, and
757 chords mode. These input modes change the way that normal, unquoted
758 words are interpreted: For example, the word @code{cis} may be
759 interpreted as a C-sharp, as a lyric syllable `cis' or as a C-sharp
760 major triad respectively.
762 A mode switch is entered as a compound music expression
765 @code{\notes} @var{musicexpr}
766 @code{\chords} @var{musicexpr}
767 @code{\lyrics} @var{musicexpr}
768 @code{\figures} @var{musicexpr}
769 @code{\markup} @var{markupexpr}
773 In each of these cases, these expressions do not add anything to the
774 meaning of their arguments. They just instruct the parser in what mode
775 to parse their arguments.
777 Different input modes for music expressions may be nested.
782 @subsection Ambiguities
786 The grammar contains two ambiguities.
796 is interpreted as the string identifier assignment. However,
797 it can also be interpreted as making a string identifier @code{\foo}
798 containing @code{"bar"}, or a music identifier @code{\foo} containing
799 the syllable `bar'. The former interpretation is chosen.
801 @item If you do a nested repeat like
810 then it is ambiguous to which @code{\repeat} the
811 @code{\alternative} belongs. This is the classic if-then-else
812 dilemma. It may be solved by using braces.
816 @c . {Lexical details}
817 @node Lexical details
818 @section Lexical details
829 Begins and ends with the @code{"} character. To include a @code{"}
830 character in a string write @code{\"}. Various other backslash
831 sequences have special interpretations as in the C language. A string
832 that contains no spaces can be written without the quotes. Strings can
833 be concatenated with the @code{+} operator.
836 @c . {Output details}
838 @section Output details
840 LilyPond's default output format is @TeX{}. Using the option @option{-f}
841 (or @option{--format}) other output formats can be selected also, but
842 currently none of them reliably work.
844 At the beginning of the output file, various global parameters are defined.
845 It also contains a large @code{\special} call to define PostScript routines
846 to draw items not representable with @TeX{}, mainly slurs and ties. A DVI
847 driver must be able to understand such embedded PostScript, or the output
848 will be rendered incompletely.
850 Then the file @file{lilyponddefs.tex} is loaded to define the macros used
851 in the code which follows. @file{lilyponddefs.tex} includes various other
852 files, partially depending on the global parameters.
854 Now the music is output system by system (a `system' consists of all
855 staves belonging together). From @TeX{}'s point of view, a system is an
856 @code{\hbox} which contains a lowered @code{\vbox} so that it is centered
857 vertically on the baseline of the text. Between systems,
858 @code{\interscoreline} is inserted vertically to have stretchable space.
859 The horizontal dimension of the @code{\hbox} is given by the
860 @code{linewidth} parameter from LilyPond's @code{\paper} block.
863 After the last system LilyPond emits a stronger variant of
864 @code{\interscoreline} only if the macro
865 @code{\lilypondpaperlastpagefill} is not defined (flushing the systems
866 to the top of the page). You can avoid that by setting the variable
867 @code{lastpagefill} in LilyPond's @code{\paper} block.
869 It is possible to fine-tune the vertical offset further by defining the
870 macro @code{\lilypondscoreshift}. Example:
873 \def\lilypondscoreshift@{0.25\baselineskip@}
877 @code{\baselineskip} is the distance from one text line to the next.
879 The code produced by LilyPond should be run through La@TeX{}, not
882 Here an example how to embed a small LilyPond file @code{foo.ly} into
883 running La@TeX{} text without using the @code{lilypond-book} script
884 (@pxref{Integrating text and music with lilypond-book}).
887 \documentclass@{article@}
889 \def\lilypondpaperlastpagefill@{@}
891 \def\lilypondscoreshift@{0.25\baselineskip@}
894 This is running text which includes an example music file
900 The file @file{foo.tex} has been simply produced with
906 It is important to set the @code{indent} parameter to zero in the
907 @code{\paper} block of @file{foo.ly}.
909 The call to @code{\lineskip} assures that there is enough vertical space
910 between the LilyPond box and the surrounding text lines.