1@c -*- coding: utf-8; mode: texinfo; fill-column: 60 -*-
2
3@ignore
4    Translation of GIT committish: 12c6693055728e69dce5c4e5a4a2b5f71180a5e2
5
6    When revising a translation, copy the HEAD committish of the
7    version that you are working on.  For details, see the Contributors'
8    Guide, node Updating translation committishes..
9@end ignore
10
11@c Translator: Jan Nieuwenhuizen
12@c Translation checker:
13@c Translation checker committish:
14
15@c \version "2.19.22"
16
17@node Fundamentele concepten
18@translationof Fundamental concepts
19@chapter Fundamentele concepten
20
21In het Leerboek hebben we gezien hoe je prachtig geprinte
22muziek maakt van een eenvoudig tekstbestand.  Dit hoofdstuk
23introduceert de achterliggende concepten en benodigde
24technieken voor het maken van ingewikkeldere partituren die
25er net zo mooi uitzien.
26
27@menu
28* Hoe LilyPond-invoerbestanden werken::
29* Voices contain music::
30* Contexts and engravers::
31* Extending the templates::
32@end menu
33
34
35@node Hoe LilyPond-invoerbestanden werken
36@translationof How LilyPond input files work
37@section Hoe LilyPond-invoerbestanden werken
38
39Het LilyPond invoerformaat is tamelijk vrij, wat ervaren
40gebruikers veel flexibiliteit geeft hun bestanden te
41structureren zoals ze dat wensen.  Deze flexibiliteit kan
42verwarrend zijn voor nieuwe gebruikers.  Deze paragraaf legt
43het een en ander uit over deze structuur.  Om het leesbaar
44te houden worden details weggelaten.  Een complete
45beschrijving van het invoerformaat is te vinden in
46@ruser{File structure}.
47
48@menu
49* Inleiding in de LilyPond-bestandsstructuur::
50* Score is a (single) compound musical expression::
51* Nesting music expressions::
52* On the un-nestedness of brackets and ties::
53@end menu
54
55@node Inleiding in de LilyPond-bestandsstructuur
56@translationof Introduction to the LilyPond file structure
57@subsection Inleiding in de LilyPond-bestandsstructuur
58
59@cindex invoerformaat
60@cindex bestandsstructuur
61
62Een basisvoorbeeld van een LilyPond-invoerbestand is
63
64@example
65\version @w{"@version{}"}
66
67\header @{ @}
68
69\score @{
70  @var{...samengestelde muziekuitdrukking...}  % alle muziek komt hier!
71  \layout @{ @}
72  \midi @{ @}
73@}
74@end example
75
76@noindent
77Er zijn veel variaties op dit basispatroon maar dit
78voorbeeld dient als een handig beginpunt.
79
80@funindex \book
81@funindex boek
82@funindex \score
83@funindex partituur
84@cindex boek
85@cindex partituur
86
87Tot nu toe heeft geen van de voorbeelden het
88@code{\score@{@}}-commando gebruikt.  Dit kan omdat LilyPond
89automatisch de extra commando's toevoegt die benodigt zijn
90als je het eenvoudige invoer geeft.  LilyPond behandelt invoer
91zoals dit:
92
93@example
94\relative @{
95  c''4 a d c
96@}
97@end example
98
99@noindent
100als een afkorting voor dit:
101
102@example
103\book @{
104  \score @{
105    \new Staff @{
106      \new Voice @{
107        \relative @{
108          c''4 a b c
109        @}
110      @}
111    @}
112    \layout @{ @}
113  @}
114@}
115@end example
116
117Anders gezegd, als de invoer een enkelvoudige
118muziekuitdrukking bevat, interpreteert LilyPond het bestand
119alsof die muziekuitdrukking ingepakt is in bovenstaande
120commando's.
121
122@cindex impliciete contexten
123@cindex contexten, impliciet
124
125@strong{Een kleine waarschuwing!} In veel van de voorbeelden
126in de LilyPond-documentatie worden de @code{\new Staff}- en
127@code{\new Voice}-commando's weggelaten en worden ze
128impliciet aangemaakt.  Voor eenvoudige voorbeelden werkt dat
129goed, maar voor ingewikkelde voorbeelden, vooral wanneer
130additionele commando's worden gebruikt, kan het impliciete
131aanmaken van contexten verrassende resultaten opleveren,
132zoals extra ongewenste notebalken.  Hoe je contexten
133expliciet specificeert, wordt uitgelegd in @ref{Contexts and
134engravers}.
135
136@warning{Voor het invoeren van meer dan enkele regels muziek
137wordt aangeraden altijd notenbalken en stemmen expliciet te
138specificeren.}
139
140Laten we terugkeren naar het eerste voorbeeld en het
141@code{\score}-commando beter bekijken.
142
143Een @code{\score}-blok moet altijd precies één
144muziekuitdrukking bevatten, en die moet direct na het
145@code{\score}-commando staan.  Herrinner je dat een
146muziekuitdrukking alles kan zijn van een enkele noot
147tot een enorme samengestelde uitdrukking zoals
148
149@example
150@{
151  \new StaffGroup <<
152    @var{...vul de volledige partituur van een Wagner opera hier in...}
153  >>
154@}
155@end example
156
157@noindent
158Omdat alles tussen @code{@{ ... @}} staat, telt het als één
159muziekuitdrukking.
160
161Zoals we eerder al zagen, kan het @code{\score}-blok
162allerlei andere dingen bevatten, zoals
163
164@example
165\score @{
166  @{ c'4 a b c' @}
167  \header @{ @}
168  \layout @{ @}
169  \midi @{ @}
170@}
171@end example
172
173@funindex \header
174@funindex kop
175@funindex \layout
176@funindex \midi
177@cindex kop
178@cindex opmaak
179@cindex midi
180
181@noindent
182Merk op dat deze drie commando's -- @code{\header},
183@code{\layout} en @code{\midi} -- speciaal zijn: in
184tegenstelling tot veel andere commando's die met een
185backslash (@code{\}) beginnen zijn het @emph{geen}
186muziekuitdrukkingen en ze zijn ook geen onderdeel van een
187muziekuitdrukking.  Ze kunnen zowel binnen als buiten het
188@code{\score}-blok worden geplaatst.  Deze commando's worden
189gewoonlijk dan ook buiten het @code{\score}-blok gezet
190-- bijvoorbeeld, @code{\header} staat meestal boven het
191@code{\score}-commando, zoals het in eerste voorbeeld van
192deze paragraaf.
193
194De twee andere commando's die je niet eerder hebt gezien
195zijn @code{\layout @{ @}} en @code{\midi @{@}}.  Als deze
196gebruikt worden als hierboven laten ze LilyPond
197respectievelijk geprinte- en MIDI-uitvoer genereren.  Een
198volledige beschrijving van deze commando's is te vinden in
199de Notatiehandleiding -- @ruser{Score layout}, en
200@ruser{Creating MIDI files}.
201
202@cindex partituren, verscheidene
203@cindex boek blok, impliciet
204@cindex impliciet boek blok
205@funindex \book
206@funindex boek
207
208Je kunt meer dan een @code{\score}-blok gebruiken.  Elk
209wordt behandeld als een afzonderlijke partituur en ze worden
210allemaal samengevoegd in een enkel uitvoerbestand.  Een
211@code{\book}-commando is niet nodig -- die wordt impliciet
212aangemaakt.  Echter, als je afzonderlijke uitvoerbestanden
213vanuit een @file{.ly}-bestand wil maken, dan moet het
214@code{\book}-commando worden gebruikt om de verschillende
215secties aan te geven: elk @code{\book}-blok produceert
216een apart uitvoerbestand.
217
218Samengevat:
219
220Elk @code{\book}-blok geeft een apart uitvoerbestand (bijv.,
221een PDF-bestand).  Als je er geen expliciet toevoegt, stopt
222LilyPond je gehele invoercode impliciet in een
223@code{\book}-blok.
224
225Elk @code{\score}-blok is een apart brok muziek binnen een
226@code{\book}-blok.
227
228@cindex opmaakblok, effect van locatie
229
230Elk @code{\layout}-blok beïnvloedt het @code{\score}- of
231@code{\book}-blok waarin het voorkomt -- d.w.z., een
232@code{\layout}-blok binnen een @code{\score}-blok heeft
233uitsluitend invloed op dat @code{\score}-blok, maar een
234@code{\layout}-blok buiten een @code{\score}-blok (en dus
235binnen een @code{\book}-blok, expliciet danwel impliciet)
236beïnvloedt elke @code{\score} in dat @code{\book}.
237
238Voor details zie @ruser{Multiple scores in a book}.
239
240@cindex variabelen
241
242Een andere manier van afkorten is het gebruik van
243variabelen, zoals getoond in @ref{Stukken organiseren met
244variabelen}.  Alle sjablonen gebruiken dat:
245
246@example
247melodie = \relative @{
248  c'4 a b c
249@}
250
251\score @{
252  \melodie
253@}
254@end example
255
256Als LilyPond naar dit bestand kijkt, neemt het de waarde van
257@code{melodie} (alles na het isgelijkteken) en voegt die in
258zodra ergens @code{\melody} staat.  De naam van de variable
259heeft verder geen speciale betekenis -- het kan net zo goed
260@code{melodie}, @code{globaal}, @code{TijdSleutel},
261@code{pianorechterhand}, of iets anders zijn.  Bedenk dat je
262vrijwel elke naam kunt gebruiken die je wilt, zolang die
263maar bestaat uit letters en het niet de naam is van een
264LilyPond-commando.  Voor meer details, zie @ref{Saving
265typing with variables and functions}.  De precieze
266beperkingen van variabelenamen staan beschreven in
267@ruser{File structure}.
268
269
270@morerefs
271Voor een volledige definitie van het invoerformaat, zie
272@ruser{File structure}.
273
274
275@node Score is a (single) compound musical expression
276@subsection Score is a (single) compound musical expression
277
278@funindex \score
279@cindex score
280@cindex contents of a score block
281@cindex score block, contents of
282@cindex compound music expression
283@cindex music expression, compound
284
285We saw the general organization of LilyPond input files in the
286previous section, @ref{Introduction to the LilyPond file structure}.
287But we seemed to skip over the most important part: how do we figure
288out what to write after @code{\score}?
289
290We didn't skip over it at all.  The big mystery is simply that
291there @emph{is} no mystery.  This line explains it all:
292
293@quotation
294@emph{A @code{\score} block must begin with a compound music expression.}
295@end quotation
296
297@noindent
298To understand what is meant by a music expression and a compound
299music expression, you may find it useful to review the tutorial,
300@ref{Music expressions explained}.  In that section, we saw how to
301build big music expressions from small pieces -- we started from
302notes, then chords, etc.  Now we're going to start from a big
303music expression and work our way down.  For simplicity, we'll use
304just a singer and piano in our example.  We don't need a
305@code{StaffGroup} for this ensemble, which simply groups a number
306of staves together with a bracket at the left, but we do need
307staves for a singer and a piano, though.
308
309@example
310\score @{
311  <<
312    \new Staff = "singer" <<
313    >>
314    \new PianoStaff = "piano" <<
315    >>
316  >>
317  \layout @{ @}
318@}
319@end example
320
321Here we have given names to the staves -- @qq{singer} and
322@qq{piano}.  This is not essential here, but it is a useful habit
323to cultivate so that you can see at a glance what each stave is
324for.
325
326Remember that we use @code{<< ... >>} instead of @code{@{ ... @}} to
327show simultaneous music.  This causes the vocal part and piano part
328to appear one above the other in the score.  The @code{<< ... >>}
329construct would not be necessary for the Singer staff in the example
330above if it were going to contain only one sequential music
331expression, but @code{<< ... >>} rather than braces is necessary if
332the music in the Staff is to contain two or more simultaneous
333expressions, e.g. two simultaneous Voices, or a Voice with lyrics.
334We're going to have a voice with lyrics, so angle brackets are
335required.  We'll add some real music later; for now let's just put
336in some dummy notes and lyrics.  If you've forgotten how to add lyrics
337you may wish to review @code{\addlyrics} in @ref{Setting simple songs}.
338
339@lilypond[verbatim,quote,ragged-right]
340\score {
341  <<
342    \new Staff = "singer" <<
343      \new Voice = "vocal" { c'1 }
344      \addlyrics { And }
345    >>
346    \new PianoStaff = "piano" <<
347      \new Staff = "upper" { c'1 }
348      \new Staff = "lower" { c'1 }
349    >>
350  >>
351  \layout { }
352}
353@end lilypond
354
355Now we have a lot more details.  We have the singer's staff: it
356contains a @code{Voice} (in LilyPond, this term refers to a set of
357notes, not necessarily vocal notes -- for example, a violin
358generally plays one voice) and some lyrics.  We also have a piano
359staff: it contains an upper staff (right hand) and a lower staff
360(left hand), although the lower staff has yet to be given a bass
361clef.
362
363At this stage, we could start filling in notes.  Inside the curly
364braces next to @code{\new Voice = "vocal"}, we could start writing
365
366@example
367\relative @{
368  r4 d''8\noBeam g, c4 r
369@}
370@end example
371
372But if we did that, the @code{\score} section would get pretty
373long, and it would be harder to understand what was happening.  So
374let's use variables instead.  These were introduced at the end
375of the previous section, remember?  To ensure the contents of the
376@code{text} variable are interpreted as lyrics we preface them with
377@code{\lyricmode}.  Like @code{\addlyrics}, this switches the input
378mode to lyrics.  Without that, LilyPond would try to interpret the
379contents as notes, which would generate errors.  (Several other
380input modes are available, see @ruser{Input modes}.)
381
382So, adding a few notes and a bass clef for the left hand, we now
383have a piece of real music:
384
385@lilypond[verbatim,quote,ragged-right]
386melody = \relative { r4 d''8\noBeam g, c4 r }
387text   = \lyricmode { And God said, }
388upper  = \relative { <g' d g,>2~ <g d g,> }
389lower  = \relative { b,2 e }
390
391\score {
392  <<
393    \new Staff = "singer" <<
394      \new Voice = "vocal" { \melody }
395      \addlyrics { \text }
396    >>
397    \new PianoStaff = "piano" <<
398      \new Staff = "upper" { \upper }
399      \new Staff = "lower" {
400        \clef "bass"
401        \lower
402      }
403    >>
404  >>
405  \layout { }
406}
407@end lilypond
408
409When writing (or reading) a @code{\score} section, just take it
410slowly and carefully.  Start with the outer level, then work on
411each smaller level.  It also really helps to be strict with
412indentation -- make sure that each item on the same level starts
413on the same horizontal position in your text editor.
414
415
416@morerefs
417Notation Reference: @ruser{Structure of a score}.
418
419
420@node Nesting music expressions
421@subsection Nesting music expressions
422
423@cindex staves, temporary
424@cindex temporary staves
425@cindex ossias
426
427It is not essential to declare all staves at the beginning; they may
428be introduced temporarily at any point.  This is particularly useful
429for creating ossia sections -- see @rglos{ossia}.  Here is a simple
430example showing how to introduce a new staff temporarily for the
431duration of three notes:
432
433@lilypond[verbatim,quote,ragged-right]
434\new Staff {
435  \relative {
436    r4 g'8 g c4 c8 d |
437    e4 r8
438    <<
439      { f8 c c }
440      \new Staff {
441        f8 f c
442      }
443    >>
444    r4 |
445  }
446}
447@end lilypond
448
449@noindent
450Note that the size of the clef is the same as a clef printed
451following a clef change -- slightly smaller than the clef
452at the beginning of the line.  This is usual for clefs printed
453in the middle of a line.
454
455@cindex staff, positioning
456
457The ossia section may be placed above the staff
458as follows:
459
460@lilypond[verbatim,quote,ragged-right]
461\new Staff = "main" {
462  \relative {
463    r4 g'8 g c4 c8 d |
464    e4 r8
465    <<
466      { f8 c c }
467      \new Staff \with {
468        alignAboveContext = "main"
469      } { f8 f c }
470    >>
471    r4 |
472  }
473}
474@end lilypond
475
476This example uses @code{\with}, which will be explained more
477fully later.  It is a means of modifying the default behavior
478of a single Staff.  Here it says that the new staff should be
479placed above the staff called @qq{main} instead of the default
480position which is below.
481
482
483@morerefs
484Ossia are often written without clef and without
485time signature and are usually in a smaller font.
486These require further commands which
487have not yet been introduced.  See @ref{Size of objects},
488and @ruser{Ossia staves}.
489
490
491@node On the un-nestedness of brackets and ties
492@subsection On the un-nestedness of brackets and ties
493
494@cindex brackets, nesting
495@cindex bracket types
496@cindex brackets, enclosing vs. marking
497
498You have already met a number of different types of bracket and
499bracket-like constructs in writing the input file to LilyPond.
500These obey different rules which can be confusing at first.
501Let's first review the different types of brackets and bracket-like
502constructs.
503
504@c attempt to force this onto a new page
505@need 50
506@multitable @columnfractions .3 .7
507@headitem Bracket Type
508  @tab Function
509@item @code{@{ .. @}}
510  @tab Encloses a sequential segment of music
511@item @code{< .. >}
512  @tab Encloses the notes of a chord
513@item @code{<< .. >>}
514  @tab Encloses simultaneous music expressions
515@item @code{( .. )}
516  @tab Marks the start and end of a slur
517@item @code{\( .. \)}
518  @tab Marks the start and end of a phrasing slur
519@item @code{[ .. ]}
520  @tab Marks the start and end of a manual beam
521@end multitable
522
523To these we should add other constructs which generate lines
524between or across notes: ties (marked by a tilde, @code{~}),
525tuplets written as @code{\times x/y @{..@}}, and grace notes
526written as @code{\grace@{..@}}.
527
528Outside LilyPond, the conventional use of brackets requires the
529different types to be properly nested, like this, @code{<< [ @{ ( .. )
530@} ] >>}, with the closing brackets being encountered in exactly the
531opposite order to the opening brackets.  This @strong{is} a
532requirement for the three types of bracket described by the word
533@q{Encloses} in the table above -- they must nest properly.  However,
534the remaining bracket-like constructs, described with the word
535@q{Marks} in the table above together with ties and tuplets, do
536@strong{not} have to nest properly with any of the brackets or
537bracket-like constructs.  In fact, these are not brackets in
538the sense that they enclose something -- they are simply markers to
539indicate where something starts and ends.
540
541So, for example, a phrasing slur can start before a manually
542inserted beam and end before the end of the beam -- not very
543musical, perhaps, but possible:
544
545@lilypond[quote,verbatim,ragged-right]
546\relative { g'8\( a b[ c b\) a] g4 }
547@end lilypond
548
549In general, different kinds of brackets, bracket-like constructs,
550and those implied by tuplets, ties and grace notes, may be mixed
551freely.  This example shows a beam extending into a tuplet (line 1),
552a slur extending into a tuplet (line 2), a beam and a slur
553extending into a tuplet, a tie crossing two tuplets, and a
554phrasing slur extending out of a tuplet (lines 3 and 4).
555
556@lilypond[quote,verbatim,ragged-right]
557\relative {
558  r16[ g' \tuplet 3/2 { r16 e'8] }
559  g,16( a \tuplet 3/2 { b16 d) e }
560  g,8[( a \tuplet 3/2 { b8 d) e~] } |
561  \tuplet 5/4 { e32\( a, b d e } a4.\)
562}
563@end lilypond
564
565
566@node Voices contain music
567@section Voices contain music
568
569Singers need voices to sing, and so does LilyPond.
570The actual music for all instruments in a score
571is contained in Voices -- the most fundamental
572of all LilyPond's concepts.
573
574@menu
575* I'm hearing Voices::
576* Explicitly instantiating voices::
577* Voices and vocals::
578@end menu
579
580@node I'm hearing Voices
581@subsection I'm hearing Voices
582
583@cindex polyphony
584@cindex layers
585@cindex multiple voices
586@cindex voices, multiple
587@cindex Voice context
588@cindex context, Voice
589@cindex simultaneous music
590@cindex music, simultaneous
591@cindex concurrent music
592@cindex music, concurrent
593@cindex voices vs. chords
594@cindex chords vs. voices
595
596The lowest, most fundamental or innermost layers in a LilyPond
597score are called @q{Voice contexts} or just @q{Voices} for short.
598Voices are sometimes called @q{layers} in other notation
599packages.
600
601In fact, a Voice layer or context is the only one which can contain
602music.  If a Voice context is not explicitly declared one is created
603automatically, as we saw at the beginning of this chapter.  Some
604instruments such as an Oboe can play only one note at a time.  Music
605written for such instruments requires just a single voice.  Instruments
606which can play more than one note at a time like the piano will often
607require multiple voices to encode the different concurrent notes and
608rhythms they are capable of playing.
609
610A single voice can contain many notes in a chord, of course,
611so when exactly are multiple voices needed?  Look first at
612this example of four chords:
613
614@lilypond[quote,verbatim,ragged-right]
615\relative {
616  \key g \major
617  <d' g>4 <d fis> <d a'> <d g>
618}
619@end lilypond
620
621This can be expressed using just the single angle bracket chord
622symbols, @code{< ... >}, and for this just a single voice is
623needed.  But suppose the F-sharp were actually an eighth-note
624followed by an eighth-note G, a passing note on the way to the A?
625Now we have two notes which start at the same time but have
626different durations: the quarter-note D and the eighth-note
627F-sharp.  How are these to be coded?  They cannot be written as
628a chord because all the notes in a chord must have the same
629duration.  And they cannot be written as two sequential notes
630as they need to start at the same time.  This is when two
631voices are required.
632
633Let us see how this is done in LilyPond input syntax.
634
635@funindex << \\ >>
636@funindex \\
637
638The easiest way to enter fragments with more than one voice on a
639staff is to enter each voice as a sequence (with @code{@{...@}}),
640and combine them simultaneously with angle brackets, @code{<<...>>}.
641The fragments must also be separated with double backward slashes,
642@code{\\}, to place them in separate voices.  Without these, the
643notes would be entered into a single voice, which would usually
644cause errors.  This technique is particularly suited to pieces of
645music which are largely homophonic with occasional short sections
646of polyphony.
647
648Here's how we split the chords above into two voices and add both
649the passing note and a slur:
650
651@lilypond[quote,verbatim,ragged-right]
652\relative {
653  \key g \major
654  %    Voice = "1"             Voice = "2"
655  << { g'4 fis8( g) a4 g } \\ { d4 d d d }  >>
656}
657@end lilypond
658
659Notice how the stems of the second voice now point down.
660
661Here's another simple example:
662
663@lilypond[quote,verbatim,ragged-right]
664\relative {
665  \key d \minor
666  %    Voice = "1"           Voice = "2"
667  << { r4 g' g4. a8 }   \\ { d,2 d4 g }       >> |
668  << { bes4 bes c bes } \\ { g4 g g8( a) g4 } >> |
669  << { a2. r4 }         \\ { fis2. s4 }       >> |
670}
671@end lilypond
672
673It is not necessary to use a separate @code{<< \\ >>} construct
674for each bar.  For music with few notes in each bar this layout
675can help the legibility of the code, but if there are many
676notes in each bar it may be better to split out each voice
677separately, like this:
678
679@lilypond[quote,verbatim,ragged-right]
680<<
681  \key d \minor
682  \relative { % Voice = "1"
683    r4 g' g4. a8 |
684    bes4 bes c bes |
685    a2. r4 |
686  } \\
687  \relative { % Voice = "2"
688    d'2 d4 g |
689    g4 g g8( a) g4 |
690    fis2. s4 |
691  }
692>>
693@end lilypond
694
695
696@cindex voices, naming
697@cindex voices crossing brackets
698@cindex slurs crossing brackets
699@cindex ties crossing brackets
700
701This example has just two voices, but the same construct may be
702used to encode three or more voices by adding more back-slash
703separators.
704
705The Voice contexts bear the names @code{"1"}, @code{"2"}, etc.
706The first contexts set the @emph{outer} voices, the highest
707voice in context @code{"1"} and the lowest voice in context
708@code{"2"}.  The inner voices go in contexts @code{"3"} and
709@code{"4"}.  In each of these contexts, the vertical direction
710of slurs, stems, ties, dynamics etc., is set appropriately.
711
712@lilypond[quote,verbatim]
713\new Staff \relative {
714  % Main voice
715  c'16 d e f
716  %    Voice = "1"   Voice = "2"              Voice = "3"
717  << { g4 f e } \\ { r8 e4 d c8~ } >> |
718  << { d2 e }   \\ { c8 b16 a b8 g~ 2 } \\ { s4 b c2 } >> |
719}
720@end lilypond
721
722These voices are all separate from the main voice that contains
723the notes just outside the @code{<< .. >>} construct.  Let's call
724this the @emph{simultaneous construct}.  Slurs and ties may only
725connect notes within the same voice, so slurs and ties cannot go
726into or out of a simultaneous construct.  Conversely,
727parallel voices from separate simultaneous constructs on the same
728staff are the same voice.  Other voice-related properties also
729carry across simultaneous constructs.  Here is the same example,
730with different colors and note heads for each voice.  Note that
731changes in one voice do not affect other voices, but they do
732persist in the same voice later.  Note also that tied notes may be
733split across the same voices in two constructs, shown here in the
734blue triangle voice.
735
736@lilypond[quote,verbatim]
737\new Staff \relative {
738  % Main voice
739  c'16 d e f
740  <<  % Bar 1
741    {
742      \voiceOneStyle
743      g4 f e
744    }
745  \\
746    {
747      \voiceTwoStyle
748      r8 e4 d c8~
749    }
750  >> |
751  <<  % Bar 2
752     % Voice 1 continues
753    { d2 e }
754  \\
755     % Voice 2 continues
756    { c8 b16 a b8 g~ 2 }
757  \\
758    {
759      \voiceThreeStyle
760      s4 b c2
761    }
762  >> |
763}
764@end lilypond
765
766@funindex \voiceOneStyle
767@funindex \voiceTwoStyle
768@funindex \voiceThreeStyle
769@funindex \voiceFourStyle
770@funindex \voiceNeutralStyle
771
772The commands @code{\voiceXXXStyle} are mainly intended for use in
773educational documents such as this one.  They modify the color
774of the note head, the stem and the beams, and the style of the
775note head, so that the voices may be easily distinguished.
776Voice one is set to red diamonds, voice two to blue triangles,
777voice three to green crossed circles, and voice four (not used
778here) to magenta crosses;  @code{\voiceNeutralStyle} (also not
779used here) reverts the style back to the default.
780We shall see later how commands like these may be created by the
781user.
782See @ref{Visibility and color of objects} and
783@ref{Using variables for tweaks}.
784
785@cindex polyphony and relative note entry
786@cindex relative note entry and polyphony
787
788Polyphony does not change the relationship of notes within a
789@code{\relative} block.  Each note is still calculated relative to
790the note immediately preceding it, or to the first note of the
791preceding chord.  So in
792
793@example
794\relative c' @{ noteA << < noteB noteC > \\ noteD >> noteE @}
795@end example
796
797@noindent
798@code{noteB} is relative to @code{noteA}                      @*
799@code{noteC} is relative to @code{noteB}, not @code{noteA};   @*
800@code{noteD} is relative to @code{noteB}, not @code{noteA} or
801@code{noteC};                                                 @*
802@code{noteE} is relative to @code{noteD}, not @code{noteA}.
803
804An alternative way, which may be clearer if the notes in the
805voices are widely separated, is to place a @code{\relative}
806command at the start of each voice:
807
808@example
809\relative c' @{ noteA ... @}
810<<
811  \relative c'' @{ < noteB noteC > ... @}
812\\
813  \relative g' @{ noteD ... @}
814>>
815\relative c' @{ noteE ... @}
816@end example
817
818Let us finally analyze the voices in a more complex piece of music.
819Here are the notes from the first two bars of the second of Chopin's
820Deux Nocturnes, Op 32.  This example will be used at later stages in
821this and the next chapter to illustrate several techniques for
822producing notation, so please ignore for now anything in the
823underlying code which looks mysterious and concentrate just on the
824music and the voices -- the complications will all be explained in
825later sections.
826
827@c The following should appear as music without code
828@lilypond[quote,ragged-right]
829\new Staff \relative {
830  \key aes \major
831  <<  % Voice one
832    { c''2 aes4. bes8 }
833  \\  % Voice two
834    {
835      % Ignore these for now - they are explained in Ch 4
836      \once \override NoteColumn.ignore-collision = ##t
837      <ees, c>2
838      \once \override NoteColumn.force-hshift = #0.5
839      des2
840    }
841  \\  % No voice three
842  \\  % Voice four
843    {
844      \override NoteColumn.force-hshift = #0
845      aes'2 f4 fes
846    }
847  >> |
848  <c ees aes c>1 |
849}
850@end lilypond
851
852The direction of the stems is often used to indicate the continuity of
853two simultaneous melodic lines.  Here the stems of the highest notes
854are all pointing up and the stems of the lower notes are all pointing
855down.  This is the first indication that more than one voice is
856required.
857
858But the real need for multiple voices arises when notes
859which start at the same time have different durations.
860Look at the notes which start at beat three in the first
861bar.  The A-flat is a dotted quarter note, the F is a
862quarter note and the D-flat is a half note.  These
863cannot be written as a chord as all the notes in a chord
864must have the same duration.  Neither can they be written
865as sequential notes, as they must start at the same time.
866This section of the bar requires three voices, and the
867normal practice would be to write the whole bar as three
868voices, as shown below, where we have used different note heads
869and colors for the three voices.  Again, the code behind this
870example will be explained later, so ignore anything you do
871not understand.
872
873@c The following should appear as music without code
874@c The three voice styles should be defined in -init
875@lilypond[quote,ragged-right]
876\new Staff \relative {
877  \key aes \major
878  <<
879    {  % Voice one
880      \voiceOneStyle
881      c''2 aes4. bes8
882    }
883  \\  % Voice two
884    { \voiceTwoStyle
885      % Ignore these for now - they are explained in Ch 4
886      \once \override NoteColumn.ignore-collision = ##t
887      <ees, c>2
888      \once \override NoteColumn.force-hshift = #0.5
889      des2
890    }
891  \\  % No Voice three (we want stems down)
892  \\  % Voice four
893    { \voiceThreeStyle
894      \override NoteColumn.force-hshift = #0
895      aes'2 f4 fes
896    }
897  >> |
898  <c ees aes c>1 |
899}
900@end lilypond
901
902
903Let us try to encode this music from scratch.  As we
904shall see, this encounters some difficulties.  We begin as
905we have learnt, using the @code{<< \\  >>} construct to
906enter the music of the first bar in three voices:
907
908@lilypond[quote,verbatim,ragged-right]
909\new Staff \relative {
910  \key aes \major
911  <<
912    { c''2 aes4. bes8 } \\ { <ees, c>2 des } \\ { aes'2 f4 fes }
913  >> |
914  <c ees aes c>1 |
915}
916@end lilypond
917
918@cindex stem down
919@cindex voices and stem directions
920@cindex stem directions and voices
921@cindex stem up
922
923The stem directions are automatically assigned with the
924odd-numbered voices taking upward stems and the even-numbered
925voices downward ones.  The stems for voices 1 and 2 are right,
926but the stems in voice 3 should go down in this particular piece
927of music.  We can correct this by skipping voice three
928and placing the music in voice four.  This is done by simply
929adding another pair of @code{\\}.
930
931@lilypond[quote,verbatim,ragged-right]
932\new Staff \relative {
933  \key aes \major
934  <<  % Voice one
935    { c''2 aes4. bes8 }
936  \\  % Voice two
937    { <ees, c>2 des }
938  \\  % Omit Voice three
939  \\  % Voice four
940    { aes'2 f4 fes }
941  >> |
942  <c ees aes c>1 |
943}
944@end lilypond
945
946@noindent
947We see that this fixes the stem direction, but the horizontal
948placement of notes is not what we want.  LilyPond shifts the
949inner notes when they or their stems would collide with outer
950voices, but this is not appropriate for piano music.  In other
951situations, the shifts LilyPond applies might fail to clear
952the collisions.  LilyPond provides several ways to adjust the
953horizontal placing of notes.  We are not quite ready yet to see
954how to correct this, so we shall leave this problem until a
955later section --- see the @code{force-hshift} property in
956@ref{Fixing overlapping notation}.
957
958@warning{Lyrics, spanners (such as slurs, ties, hairpins etc.) cannot be
959created @q{across} voices.}
960
961
962@morerefs
963Notation Reference: @ruser{Multiple voices}.
964
965
966@node Explicitly instantiating voices
967@subsection Explicitly instantiating voices
968
969@funindex \voiceOne
970@funindex \voiceTwo
971@funindex \voiceThree
972@funindex \voiceFour
973@funindex \oneVoice
974@funindex \new Voice
975@cindex voice contexts, creating
976
977Voice contexts can also be created manually
978inside a @code{<< >>} block to create polyphonic music, using
979@code{\voiceOne} @dots{} @code{\voiceFour} to indicate the required
980directions of stems, slurs, etc.  In longer scores this method
981is clearer, as it permits the voices to be separated and to be
982given more descriptive names.
983
984Specifically, the construct @code{<< \\ >>} which we used in
985the previous section:
986
987@example
988\new Staff @{
989  \relative @{
990    << @{ e'4 f g a @} \\ @{ c,4 d e f @} >>
991  @}
992@}
993@end example
994
995@noindent
996is equivalent to
997
998@example
999\new Staff <<
1000  \new Voice = "1" @{ \voiceOne \relative @{ e'4 f g a @} @}
1001  \new Voice = "2" @{ \voiceTwo \relative @{ c'4 d e f @} @}
1002>>
1003@end example
1004
1005Both of the above would produce
1006
1007@c The following example should not display the code
1008@lilypond[ragged-right,quote]
1009\new Staff <<
1010  \new Voice = "1" { \voiceOne \relative { e'4 f g a } }
1011  \new Voice = "2" { \voiceTwo \relative { c'4 d e f } }
1012>>
1013@end lilypond
1014
1015@cindex voices, reverting to single
1016@cindex reverting to a single voice
1017
1018The @code{\voiceXXX} commands set the direction of stems, slurs,
1019ties, articulations, text annotations, augmentation dots of dotted
1020notes, and fingerings.  @code{\voiceOne} and @code{\voiceThree}
1021make these objects point upwards, while @code{\voiceTwo} and
1022@code{\voiceFour} make them point downwards.  These commands also
1023generate a horizontal shift for each voice when this is required
1024to avoid clashes of note heads.  The command @code{\oneVoice}
1025reverts the settings back to the normal values for a single voice.
1026
1027Let us see in some simple examples exactly what effect
1028@code{\oneVoice}, @code{\voiceOne} and @code{voiceTwo} have on
1029markup, ties, slurs, and dynamics:
1030
1031@lilypond[quote,ragged-right,verbatim]
1032\relative {
1033  % Default behavior or behavior after \oneVoice
1034  c'4 d8~ 8 e4( f | g4 a) b-> c |
1035}
1036@end lilypond
1037
1038@lilypond[quote,ragged-right,verbatim]
1039\relative {
1040  \voiceOne
1041  c'4 d8~ 8 e4( f | g4 a) b-> c |
1042  \oneVoice
1043  c,4 d8~ 8 e4( f | g4 a) b-> c |
1044}
1045@end lilypond
1046
1047@lilypond[quote,ragged-right,verbatim]
1048\relative {
1049  \voiceTwo
1050  c'4 d8~ 8 e4( f | g4 a) b-> c |
1051  \oneVoice
1052  c,4 d8~ 8 e4( f | g4 a) b-> c |
1053}
1054@end lilypond
1055
1056Now let's look at three different ways to notate the same passage of
1057polyphonic music, each of which is advantageous in different
1058circumstances, using the example from the previous section.
1059
1060An expression that appears directly inside a @code{<< >>} belongs to the
1061main voice (but, note, @strong{not} in a @code{<< \\ >>} construct).
1062This is useful when extra voices appear while the main voice is playing.
1063Here is a more correct rendition of our example.  The red diamond-shaped
1064notes demonstrate that the main melody is now in a single voice context,
1065permitting a phrasing slur to be drawn over them.
1066
1067@lilypond[quote,ragged-right,verbatim]
1068\new Staff \relative {
1069  \voiceOneStyle
1070  % This section is homophonic
1071  c'16^( d e f
1072  % Start simultaneous section of three voices
1073  <<
1074    % Continue the main voice in parallel
1075    { g4 f e | d2 e) | }
1076    % Initiate second voice
1077    \new Voice {
1078      % Set stems, etc., down
1079      \voiceTwo
1080      r8 e4 d c8~ | 8 b16 a b8 g~ 2 |
1081    }
1082    % Initiate third voice
1083    \new Voice {
1084      % Set stems, etc, up
1085      \voiceThree
1086      s2. | s4 b c2 |
1087    }
1088  >>
1089}
1090@end lilypond
1091
1092@cindex nesting music expressions
1093@cindex nesting simultaneous constructs
1094@cindex nesting voices
1095@cindex voices, temporary
1096@cindex voices, nesting
1097
1098More deeply nested polyphony constructs are possible, and if a
1099voice appears only briefly this might be a more natural way to
1100typeset the music:
1101
1102@lilypond[quote,ragged-right,verbatim]
1103\new Staff \relative {
1104  c'16^( d e f
1105  <<
1106    { g4 f e | d2 e) | }
1107    \new Voice {
1108      \voiceTwo
1109      r8 e4 d c8~ |
1110      <<
1111        { c8 b16 a b8 g~ 2 | }
1112        \new Voice {
1113          \voiceThree
1114          s4 b c2 |
1115        }
1116      >>
1117    }
1118  >>
1119}
1120@end lilypond
1121
1122@cindex spacing notes
1123
1124This method of nesting new voices briefly is useful
1125when only small sections of the music
1126are polyphonic, but when the whole staff is largely polyphonic
1127it can be clearer to use multiple voices throughout, using
1128spacing notes to step over sections where the voice is silent,
1129as here:
1130
1131@lilypond[quote,ragged-right,verbatim]
1132\new Staff \relative <<
1133  % Initiate first voice
1134  \new Voice {
1135    \voiceOne
1136    c'16^( d e f g4 f e | d2 e) |
1137  }
1138  % Initiate second voice
1139  \new Voice {
1140    % Set stems, etc, down
1141    \voiceTwo
1142    s4 r8 e4 d c8~ | 8 b16 a b8 g~ 2 |
1143  }
1144  % Initiate third voice
1145  \new Voice {
1146    % Set stems, etc, up
1147    \voiceThree
1148    s1 | s4 b c2 |
1149  }
1150>>
1151@end lilypond
1152
1153@subsubheading Note columns
1154
1155@cindex note column
1156@cindex note collisions
1157@cindex collisions, notes
1158@cindex shift commands
1159@funindex \shiftOff
1160@funindex \shiftOn
1161@funindex \shiftOnn
1162@funindex \shiftOnnn
1163
1164Closely spaced notes in a chord, or notes occurring at the same
1165time in different voices, are arranged in two, occasionally more,
1166columns to prevent the note heads overlapping.  These are called
1167note columns.  There are separate columns for each voice, and
1168the currently specified voice-dependent shift is applied to the
1169note column if there would otherwise be a collision.  This can
1170be seen in the example above.  In bar 2 the C in voice two is
1171shifted to the right relative to the D in voice one, and in the
1172final chord the C in voice three is also shifted to the right
1173relative to the other notes.
1174
1175The @code{\shiftOn}, @code{\shiftOnn}, @code{\shiftOnnn}, and
1176@code{\shiftOff} commands specify the degree to which notes and
1177chords of the voice should be shifted if a collision
1178would otherwise occur.  By default, the outer voices (normally
1179voices one and two) have @code{\shiftOff} specified, while the
1180inner voices (three and four) have @code{\shiftOn} specified.
1181When a shift is applied, voices one and three are shifted to
1182the right and voices two and four to the left.
1183
1184@code{\shiftOnn} and @code{\shiftOnnn} define further shift
1185levels which may be specified temporarily to resolve collisions
1186in complex situations -- see @ref{Real music example}.
1187
1188A note column can contain just one note (or chord) from a voice
1189with stems up and one note (or chord) from a voice with stems
1190down.  If notes from two voices which have their stems in the
1191same direction are placed at the same position and both voices
1192have no shift or the same shift specified, the error message
1193@qq{Too many clashing note columns} will be produced.
1194
1195
1196@morerefs
1197Notation Reference: @ruser{Multiple voices}.
1198
1199
1200@node Voices and vocals
1201@subsection Voices and vocals
1202
1203Vocal music presents a special difficulty: we need to combine two
1204expressions -- notes and lyrics.
1205
1206@funindex \new Lyrics
1207@funindex \lyricsto
1208@funindex Lyrics
1209@cindex Lyrics context, creating
1210@cindex lyrics, linking to voice
1211
1212You have already seen the @code{\addlyrics@{@}} command, which
1213handles simple scores well.  However, this technique is
1214quite limited.  For more complex music, you must introduce the
1215lyrics in a @code{Lyrics} context using @code{\new Lyrics} and
1216explicitly link
1217the lyrics to the notes with @code{\lyricsto@{@}}, using the
1218name assigned to the Voice.
1219
1220@lilypond[quote,verbatim]
1221<<
1222  \new Voice = "one" {
1223    \relative {
1224      \autoBeamOff
1225      \time 2/4
1226      c''4 b8. a16 | g4. f8 | e4 d | c2 |
1227    }
1228  }
1229  \new Lyrics \lyricsto "one" {
1230    No more let | sins and | sor -- rows | grow. |
1231  }
1232>>
1233@end lilypond
1234
1235Note that the lyrics must be linked to a @code{Voice} context,
1236@emph{not} a @code{Staff} context.  This is a case where it is
1237necessary to create @code{Staff} and @code{Voice} contexts
1238explicitly.
1239
1240@cindex lyrics and beaming
1241@cindex beaming and lyrics
1242@funindex \autoBeamOff
1243
1244The automatic beaming which LilyPond uses by default works well
1245for instrumental music, but not so well for music with lyrics,
1246where beaming is either not required at all or is used to indicate
1247melismata in the lyrics.  In the example above we use the command
1248@code{\autoBeamOff} to turn off the automatic beaming.
1249
1250@funindex \new ChoirStaff
1251@funindex ChoirStaff
1252@funindex \lyricmode
1253@cindex vocal score structure
1254@cindex choir staff
1255
1256Let us reuse the earlier example from Judas Maccabæus to
1257illustrate this more flexible technique.  We first recast
1258it to use variables so the music and lyrics can be separated
1259from the staff structure.  We also introduce a ChoirStaff
1260bracket.  The lyrics themselves must be introduced with
1261@code{\lyricmode} to ensure they are interpreted as lyrics
1262rather than music.
1263
1264@lilypond[quote,verbatim]
1265global = { \key f \major \time 6/8 \partial 8 }
1266
1267SopOneMusic = \relative {
1268  c''8 | c8([ bes)] a a([ g)] f | f'4. b, | c4.~ 4
1269}
1270SopOneLyrics = \lyricmode {
1271  Let | flee -- cy flocks the | hills a -- dorn, __
1272}
1273SopTwoMusic = \relative {
1274  r8 | r4. r4 c'8 | a'8([ g)] f f([ e)] d | e8([ d)] c bes'
1275}
1276SopTwoLyrics = \lyricmode {
1277  Let | flee -- cy flocks the | hills a -- dorn,
1278}
1279
1280\score {
1281  \new ChoirStaff <<
1282    \new Staff <<
1283      \new Voice = "SopOne" {
1284        \global
1285        \SopOneMusic
1286      }
1287      \new Lyrics \lyricsto "SopOne" {
1288        \SopOneLyrics
1289      }
1290    >>
1291    \new Staff <<
1292      \new Voice = "SopTwo" {
1293        \global
1294        \SopTwoMusic
1295      }
1296      \new Lyrics \lyricsto "SopTwo" {
1297        \SopTwoLyrics
1298      }
1299    >>
1300  >>
1301}
1302@end lilypond
1303
1304This is the basic structure of all vocal scores.  More staves may be
1305added as required, more voices may be added to the staves, more verses
1306may be added to the lyrics, and the variables containing the music can
1307easily be placed in separate files should they become too long.
1308
1309@cindex hymn structure
1310@cindex SATB structure
1311@cindex vocal scores with multiple verses
1312@cindex multiple vocal verses
1313@cindex verses, multiple vocal
1314
1315Here is an example of the first line of a hymn with four
1316verses, set for SATB.  In this case the words for all four
1317parts are the same.  Note how we use variables to separate the
1318music notation and words from the staff structure.  See too
1319how a variable, which we have chosen to call @q{keyTime}, is used
1320to hold several commands for use within the two staves.  In other
1321examples this is often called @q{global}.
1322
1323@lilypond[quote,verbatim]
1324keyTime = { \key c \major \time 4/4 \partial 4 }
1325
1326SopMusic   = \relative { c'4 | e4. e8 g4  g    | a4   a   g  }
1327AltoMusic  = \relative { c'4 | c4. c8 e4  e    | f4   f   e  }
1328TenorMusic = \relative  { e4 | g4. g8 c4.   b8 | a8 b c d e4 }
1329BassMusic  = \relative  { c4 | c4. c8 c4  c    | f8 g a b c4 }
1330
1331VerseOne =
1332  \lyricmode { E -- | ter -- nal fa -- ther, | strong to save, }
1333VerseTwo   =
1334  \lyricmode { O | Christ, whose voice the | wa -- ters heard, }
1335VerseThree =
1336  \lyricmode { O | Ho -- ly Spi -- rit, | who didst brood }
1337VerseFour  =
1338  \lyricmode { O | Tri -- ni -- ty of | love and pow'r }
1339
1340\score {
1341  \new ChoirStaff <<
1342    \new Staff <<
1343      \clef "treble"
1344      \new Voice = "Sop"  { \voiceOne \keyTime \SopMusic }
1345      \new Voice = "Alto" { \voiceTwo \AltoMusic }
1346      \new Lyrics \lyricsto "Sop" { \VerseOne   }
1347      \new Lyrics \lyricsto "Sop" { \VerseTwo   }
1348      \new Lyrics \lyricsto "Sop" { \VerseThree }
1349      \new Lyrics \lyricsto "Sop" { \VerseFour  }
1350    >>
1351    \new Staff <<
1352      \clef "bass"
1353      \new Voice = "Tenor" { \voiceOne \keyTime \TenorMusic }
1354      \new Voice = "Bass"  { \voiceTwo \BassMusic }
1355    >>
1356  >>
1357}
1358@end lilypond
1359
1360
1361@morerefs
1362Notation Reference: @ruser{Vocal music}.
1363
1364
1365@node Contexts and engravers
1366@section Contexts and engravers
1367
1368Contexts and engravers have been mentioned informally
1369in earlier sections; we now must look at
1370these concepts in more detail, as they are important
1371in the fine-tuning of LilyPond output.
1372
1373
1374@menu
1375* Contexts explained::
1376* Creating contexts::
1377* Engravers explained::
1378* Modifying context properties::
1379* Adding and removing engravers::
1380@end menu
1381
1382@node Contexts explained
1383@subsection Contexts explained
1384
1385@cindex contexts explained
1386
1387When music is printed, many notational elements which do not
1388appear explicitly in the input file must be added to the
1389output.  For example, compare the input and output of the
1390following example:
1391
1392@lilypond[quote,verbatim]
1393\relative { cis''4 cis2. | a4 a2. | }
1394@end lilypond
1395
1396The input is rather sparse, but in the output, bar lines,
1397accidentals, clef, and time signature have been added.  When
1398LilyPond @emph{interprets} the input the musical information
1399is parsed from left to right, similar to the way a performer
1400reads the score.  While reading the input, the program remembers
1401where measure boundaries are, and which pitches require explicit
1402accidentals.  This information must be held on several levels.
1403For example, an accidental affects only a single staff, while
1404a bar line must be synchronized across the entire score.
1405
1406Within LilyPond, these rules and bits of information are grouped in
1407@emph{Contexts}.  We have already introduced the @code{Voice} context.
1408Others are the @code{Staff} and @code{Score} contexts.  Contexts are
1409hierarchical to reflect the hierarchical nature of a musical score.
1410For example: a @code{Staff} context can contain many @code{Voice}
1411contexts, and a @code{Score} context can contain many @code{Staff}
1412contexts.
1413
1414@quotation
1415@sourceimage{context-example,5cm,,}
1416@end quotation
1417
1418Each context has the responsibility for enforcing some notation rules,
1419creating some notation objects and maintaining the associated
1420properties.  For example, the @code{Voice} context may introduce an
1421accidental and then the @code{Staff} context maintains the rule to
1422show or suppress the accidental for the remainder of the measure.
1423
1424As another example, the synchronization of bar lines is, by default,
1425handled in the @code{Score} context.
1426However, in some music we may not want the bar lines to be
1427synchronized -- consider a polymetric score in 4/4 and 3/4 time.
1428In such cases, we must modify the default settings of the
1429@code{Score} and @code{Staff} contexts.
1430
1431For very simple scores, contexts are created implicitly, and you need
1432not be aware of them.  For larger pieces, such as anything with more
1433than one staff, they must be
1434created explicitly to make sure that you get as many staves as you
1435need, and that they are in the correct order.  For typesetting pieces
1436with specialized notation, it is usual to modify existing, or
1437even to define totally new, contexts.
1438
1439In addition to the @code{Score,} @code{Staff} and
1440@code{Voice} contexts there are contexts which fit between
1441the score and staff levels to control staff groups, such as the
1442@code{PianoStaff} and @code{ChoirStaff} contexts.  There
1443are also alternative staff and voice contexts, and contexts for
1444lyrics, percussion, fret boards, figured bass, etc.
1445
1446The names of all context types are formed from one or more
1447words, each word being capitalized and joined immediately to the
1448preceding word with no hyphen or underscore, e.g.,
1449@code{GregorianTranscriptionStaff}.
1450
1451
1452@morerefs
1453Notation Reference: @ruser{Contexts explained}.
1454
1455
1456@node Creating contexts
1457@subsection Creating contexts
1458
1459@funindex \new
1460@cindex new contexts
1461@cindex creating contexts
1462@cindex contexts, creating
1463
1464In an input file a score block, introduced with a @code{\score}
1465command, contains a single music expression and an associated
1466output definition (either a @code{\layout} or a @code{\midi} block).
1467The @code{Score} context is usually left to be created automatically
1468when the interpretation of that music expression starts.
1469
1470For scores with only one voice and one staff, the @code{Voice} and
1471@code{Staff} contexts may also be left to be created automatically,
1472but for more complex scores it is necessary to create them by hand.
1473The simplest command that does this is @code{\new}.  It is prepended
1474to a music expression, for example
1475
1476@example
1477\new @var{type} @var{music-expression}
1478@end example
1479
1480@noindent
1481where @var{type} is a context name (like @code{Staff} or
1482@code{Voice}).  This command creates a new context, and starts
1483interpreting the @var{music-expression} within that context.
1484
1485@warning{@bs{}@code{new Score} should not be used as the essential
1486top-level @code{Score} context is created automatically when the music
1487expression within the @bs{}@code{score} block is interpreted.  Score-wide
1488default values of context properties can be changed within the
1489@bs{}@code{layout} block.  See @ref{Modifying context properties}}
1490
1491You have seen many practical examples which created new
1492@code{Staff} and @code{Voice} contexts in earlier sections, but
1493to remind you how these commands are used in practice, here's an
1494annotated real-music example:
1495
1496@lilypond[quote,verbatim,ragged-right]
1497\score {  % start of single compound music expression
1498  <<  % start of simultaneous staves section
1499    \time 2/4
1500    \new Staff {  % create RH staff
1501      \clef "treble"
1502      \key g \minor
1503      \new Voice {  % create voice for RH notes
1504        \relative {  % start of RH notes
1505          d''4 ees16 c8. |
1506          d4 ees16 c8. |
1507        }  % end of RH notes
1508      }  % end of RH voice
1509    }  % end of RH staff
1510    \new Staff <<  % create LH staff; needs two simultaneous voices
1511      \clef "bass"
1512      \key g \minor
1513      \new Voice {  % create LH voice one
1514        \voiceOne
1515        \relative {  % start of LH voice one notes
1516          g8 <bes d> ees, <g c> |
1517          g8 <bes d> ees, <g c> |
1518        }  % end of LH voice one notes
1519      }  % end of LH voice one
1520      \new Voice {  % create LH voice two
1521        \voiceTwo
1522        \relative {  % start of LH voice two notes
1523          g4 ees |
1524          g4 ees |
1525        }  % end of LH voice two notes
1526      }  % end of LH voice two
1527    >>  % end of LH staff
1528  >>  % end of simultaneous staves section
1529}  % end of single compound music expression
1530@end lilypond
1531
1532(Note how all the statements which open a block with either a
1533curly bracket, @code{@{}, or double angle brackets, @code{<<},
1534are indented by two further spaces, and the corresponding
1535closing bracket is indented by exactly the same amount.  While
1536this is not required, following this practice will greatly
1537reduce the number of @q{unmatched bracket} errors, and is
1538strongly recommended.  It enables the structure of the music to
1539be seen at a glance, and any unmatched brackets will be obvious.
1540Note too how the LH staff is created using double angle brackets
1541because it requires two voices for its music, whereas the RH staff
1542is created with a single music expression surrounded by curly
1543brackets because it requires only one voice.)
1544
1545@cindex contexts, naming
1546@cindex naming contexts
1547
1548The @code{\new} command may also give an identifying name to the
1549context to distinguish it from other contexts of the same type,
1550
1551@example
1552\new @var{type} = @var{id} @var{music-expression}
1553@end example
1554
1555Note the distinction between the name of the context type,
1556@code{Staff}, @code{Voice}, etc, and the identifying name of a
1557particular instance of that type, which can be any sequence of letters
1558invented by the user.  Digits and spaces can also be used in the
1559identifying name, but then it has to be placed in quotes,
1560i.e. @code{\new Staff = "MyStaff 1" @var{music-expression}}.
1561The identifying name is used to
1562refer back to that particular instance of a context.  We saw this in
1563use in the section on lyrics, see @ref{Voices and vocals}.
1564
1565
1566@morerefs
1567Notation Reference: @ruser{Creating contexts}.
1568
1569
1570@node Engravers explained
1571@subsection Engravers explained
1572
1573@cindex engravers
1574
1575Every mark on the printed output of a score produced by LilyPond
1576is produced by an @code{Engraver}.  Thus there is an engraver
1577to print staves, one to print note heads, one for stems, one for
1578beams, etc, etc.  In total there are over 120 such engravers!
1579Fortunately, for most scores it is not necessary to know about
1580more than a few, and for simple scores you do not need to know
1581about any.
1582
1583Engravers live and operate in Contexts.  Engravers such as the
1584@code{Metronome_mark_engraver}, whose action and output apply to the
1585score as a whole, operate in the highest level context -- the
1586@code{Score} context.
1587
1588The @code{Clef_engraver} and @code{Key_engraver} are to be
1589found in every @code{Staff} Context, as different staves may require
1590different clefs and keys.
1591
1592The @code{Note_heads_engraver} and @code{Stem_engraver} live
1593in every @code{Voice} context, the lowest level context of all.
1594
1595Each engraver processes the particular objects associated
1596with its function, and maintains the properties that relate
1597to that function.  These properties, like the properties
1598associated with contexts, may be modified to change the
1599operation of the engraver or the appearance of those elements
1600in the printed score.
1601
1602Engravers all have compound names formed from words which
1603describe their function.  Just the first word is capitalized,
1604and the remainder are joined to it with underscores.  Thus
1605the @code{Staff_symbol_engraver} is responsible for creating the
1606lines of the staff, the @code{Clef_engraver} determines and sets
1607the pitch reference point on the staff by drawing a clef symbol.
1608
1609Here are some of the most common engravers together with their
1610function.  You will see it is usually easy to guess the function
1611from the name, or vice versa.
1612
1613@multitable @columnfractions .3 .7
1614@headitem Engraver
1615  @tab Function
1616@item Accidental_engraver
1617  @tab Makes accidentals, cautionary and suggested accidentals
1618@item Beam_engraver
1619  @tab Engraves beams
1620@item Clef_engraver
1621  @tab Engraves clefs
1622@item Completion_heads_engraver
1623  @tab Splits notes which cross bar lines
1624@item Dynamic_engraver
1625  @tab Creates hairpins and dynamic texts
1626@item Forbid_line_break_engraver
1627  @tab Prevents line breaks if a musical element is still active
1628@item Key_engraver
1629  @tab Creates the key signature
1630@item Metronome_mark_engraver
1631  @tab Engraves metronome marking
1632@item Note_heads_engraver
1633  @tab Engraves note heads
1634@item Rest_engraver
1635  @tab Engraves rests
1636@item Staff_symbol_engraver
1637  @tab Engraves the five (by default) lines of the staff
1638@item Stem_engraver
1639  @tab Creates stems and single-stem tremolos
1640@item Time_signature_engraver
1641  @tab Creates time signatures
1642@end multitable
1643
1644@smallspace
1645
1646We shall see later how the output of LilyPond can be changed
1647by modifying the action of Engravers.
1648
1649
1650@morerefs
1651Internals reference: @rinternals{Engravers and Performers}.
1652
1653
1654@node Modifying context properties
1655@subsection Modifying context properties
1656
1657@cindex context properties
1658@cindex context properties, modifying
1659@cindex modifying context properties
1660@funindex \set
1661@funindex \unset
1662
1663Contexts are responsible for holding the values of a number of
1664context @emph{properties}.  Many of them can be changed to
1665influence the interpretation of the input and so change the
1666appearance of the output.  They are changed by the
1667@code{\set} command.  This takes the form
1668
1669@example
1670\set @emph{ContextName}.@emph{propertyName} = #@emph{value}
1671@end example
1672
1673Where the @emph{ContextName} is usually @code{Score},
1674@code{Staff} or @code{Voice}.  It may be omitted,
1675in which case the current context (typically @code{Voice}) is assumed.
1676
1677The names of context properties consist of words joined
1678together with no hyphens or underscores, all except the
1679first having a capital letter.  Here are a few examples
1680of some commonly used ones.  There are many more.
1681
1682@c attempt to force this onto a new page
1683@need 50
1684@multitable @columnfractions .25 .15 .45 .15
1685@headitem propertyName
1686  @tab Type
1687  @tab Function
1688  @tab Example Value
1689@item extraNatural
1690  @tab Boolean
1691  @tab If true, set extra natural signs before accidentals
1692  @tab @code{#t}, @code{#f}
1693@item currentBarNumber
1694  @tab Integer
1695  @tab Set the current bar number
1696  @tab @code{50}
1697@item doubleSlurs
1698  @tab Boolean
1699  @tab If true, print slurs both above and below notes
1700  @tab @code{#t}, @code{#f}
1701@item instrumentName
1702  @tab Text
1703  @tab Set the name to be placed at the start of the staff
1704  @tab @code{"Cello I"}
1705@item fontSize
1706  @tab Real
1707  @tab Increase or decrease the font size
1708  @tab @code{2.4}
1709@item stanza
1710  @tab Text
1711  @tab Set the text to print before the start of a verse
1712  @tab @code{"2"}
1713@end multitable
1714
1715@noindent
1716where a Boolean is either True (@code{#t}) or False (@code{#f}),
1717an Integer is a positive whole number, a Real is a positive
1718or negative decimal number, and text is enclosed in double
1719apostrophes.  Note the occurrence of hash signs,
1720(@code{#}), in two different places -- as part of the Boolean
1721value before the @code{t} or @code{f}, and before @emph{value}
1722in the @code{\set} statement.  So when a Boolean is being
1723entered you need to code two hash signs, e.g., @code{##t}.
1724
1725@cindex properties operating in contexts
1726@cindex setting properties within contexts
1727
1728Before we can set any of these properties we need to know
1729in which context they operate.  Sometimes this is obvious,
1730but occasionally it can be tricky.  If the wrong context
1731is specified, no error message is produced, but the expected
1732action will not take place.  For example, the
1733@code{instrumentName} clearly lives in the @code{Staff} context, since
1734it is the staff that is to be named.
1735In this example the first staff is labeled, but not the second,
1736because we omitted the context name.
1737
1738@lilypond[quote,verbatim,ragged-right]
1739<<
1740  \new Staff \relative {
1741    \set Staff.instrumentName = "Soprano"
1742    c''2 c
1743  }
1744  \new Staff \relative {
1745    \set instrumentName = "Alto"  % Wrong!
1746    d'2 d
1747  }
1748>>
1749@end lilypond
1750
1751Remember the default context name is @code{Voice}, so the second
1752@code{\set} command set the property @code{instrumentName} in the
1753@code{Voice} context to @qq{Alto}, but as LilyPond does not look
1754for any such property in the @code{Voice} context, no
1755further action took place.  This is not an error, and no error
1756message is logged in the log file.
1757
1758Similarly, if the property name is mis-spelt no error message is
1759produced, and clearly the expected action cannot be performed.  In
1760fact, you can set any (fictitious) @q{property} using any name you
1761like in any context that exists by using the @code{\set} command.  But
1762if the name is not known to LilyPond it will not cause any action to
1763be taken.  Some text editors with special support for LilyPond input
1764files document property names with bullets when you hover them with
1765the mouse, like JEdit with LilyPondTool, or highlight unknown property
1766names differently, like ConTEXT.  If you do not use an editor with
1767such features, it is recommended to check the property name in the
1768Internals Reference: see @rinternals{Tunable context properties}, or
1769@rinternals{Contexts}.
1770
1771The @code{instrumentName} property will take effect only
1772if it is set in the @code{Staff} context, but
1773some properties can be set in more than one context.
1774For example, the property @code{extraNatural} is by
1775default set to ##t (true) for all staves.
1776If it is set to ##f (false) in one particular @code{Staff}
1777context it applies just to the accidentals on that staff.
1778If it is set to false in the @code{Score} context
1779it applies to all staves.
1780
1781So this turns off extra naturals in one staff:
1782
1783@lilypond[quote,verbatim,ragged-right]
1784<<
1785  \new Staff \relative {
1786    aeses'2 aes
1787  }
1788  \new Staff \relative {
1789    \set Staff.extraNatural = ##f
1790    aeses'2 aes
1791  }
1792>>
1793@end lilypond
1794
1795@noindent
1796and this turns them off in all staves:
1797
1798@lilypond[quote,verbatim,ragged-right]
1799<<
1800  \new Staff \relative {
1801    aeses'2 aes
1802  }
1803  \new Staff \relative {
1804    \set Score.extraNatural = ##f
1805    aeses'2 aes
1806  }
1807>>
1808@end lilypond
1809
1810As another example, if @code{clefTransposition} is set in
1811the @code{Score} context this immediately changes the value
1812of the transposition in all current staves and sets a new default
1813value which will be applied to all staves.
1814
1815The opposite command, @code{\unset}, effectively removes the
1816property from the context, which causes most properties to
1817revert to their default value.  Usually @code{\unset} is not
1818required as a new @code{\set} command will achieve what is
1819wanted.
1820
1821The @code{\set} and @code{\unset} commands can appear anywhere
1822in the input file and will take effect from the time they are
1823encountered until the end of the score or until the property is
1824@code{\set} or @code{\unset} again.  Let's try changing the
1825font size, which affects the size of the note heads (among
1826other things) several times.  The change is from the default
1827value, not the most recently set value.
1828
1829@lilypond[quote,verbatim,ragged-right]
1830\relative {
1831  c'4 d
1832  % make note heads smaller
1833  \set fontSize = #-4
1834  e4 f |
1835  % make note heads larger
1836  \set fontSize = #2.5
1837  g4 a
1838  % return to default size
1839  \unset fontSize
1840  b4 c |
1841}
1842@end lilypond
1843
1844We have now seen how to set the values of several different types of
1845property.  Note that integers and numbers are always preceded by a
1846hash sign, @code{#}, while a true or false value is specified by
1847@code{##t} and @code{##f}, with two hash signs.  A text property
1848should be enclosed in double quotation signs, as above, although we
1849shall see later that text can actually be specified in a much more
1850general way by using the very powerful @code{\markup} command.
1851
1852@subsubheading Setting context properties with @code{\with}
1853
1854@funindex \with
1855@cindex context properties, setting with \with
1856
1857The default value of context properties may be set at the time the
1858context is created.  Sometimes this is a clearer way of setting a
1859property value if it is to remain fixed for the duration of
1860the context.  When a context is created with a @code{\new}
1861command it may be followed immediately by a @code{\with @{ .. @}}
1862block in which the default property values are set.  For example,
1863if we wish to suppress the printing of extra naturals for the
1864duration of a staff we would write:
1865
1866@example
1867\new Staff \with @{ extraNatural = ##f @}
1868@end example
1869
1870@noindent
1871like this:
1872
1873@lilypond[quote,verbatim,ragged-right]
1874<<
1875  \new Staff {
1876    \relative {
1877      gisis'4 gis aeses aes
1878    }
1879  }
1880  \new Staff \with { extraNatural = ##f } {
1881    \relative {
1882      gisis'4 gis aeses aes
1883    }
1884  }
1885>>
1886@end lilypond
1887
1888Properties set in this way may still be changed dynamically using
1889@code{\set} and returned to the default value set in the
1890@code{\with} block with @code{\unset}.
1891
1892@cindex fontSize, default and setting
1893
1894So if the @code{fontSize} property is set in a @code{\with} clause
1895it sets the default value of the font size.  If it is later changed
1896with @code{\set}, this new default value may be restored with the
1897@code{\unset fontSize} command.
1898
1899@subsubheading Setting context properties with @code{\context}
1900
1901@cindex context properties, setting with \context
1902@funindex \context
1903
1904The values of context properties may be set in @emph{all} contexts
1905of a particular type, such as all @code{Staff} contexts, with a single
1906command.  The context type is identified by using its
1907type name, like @code{Staff}, prefixed by a back-slash: @code{\Staff}.
1908The statement which sets the property value is the same as that in a
1909@code{\with} block, introduced above.  It is placed in a
1910@code{\context} block within a @code{\layout} block.  Each
1911@code{\context} block will affect all contexts of the type specified
1912throughout the @code{\score} or @code{\book} block in which the
1913@code{\layout} block appears.  Here is an example to show the format:
1914
1915@lilypond[verbatim,quote]
1916\score {
1917  \new Staff {
1918    \relative {
1919      cisis''4 e d cis
1920    }
1921  }
1922  \layout {
1923    \context {
1924      \Staff
1925      extraNatural = ##t
1926    }
1927  }
1928}
1929@end lilypond
1930
1931If the property override is to be applied to all staves
1932within the score:
1933
1934@lilypond[quote,verbatim]
1935\score {
1936  <<
1937    \new Staff {
1938      \relative {
1939        gisis'4 gis aeses aes
1940      }
1941    }
1942    \new Staff {
1943      \relative {
1944        gisis'4 gis aeses aes
1945      }
1946    }
1947  >>
1948  \layout {
1949    \context {
1950      \Score extraNatural = ##f
1951    }
1952  }
1953}
1954@end lilypond
1955
1956@noindent
1957Context properties set in this way may be overridden for particular
1958instances of contexts by statements in a @code{\with} block, and by
1959@code{\set} commands embedded in music statements.
1960
1961
1962@morerefs
1963Notation Reference:
1964@ruser{Changing context default settings}.
1965@ruser{The set command}.
1966
1967Internals Reference:
1968@rinternals{Contexts},
1969@rinternals{Tunable context properties}.
1970
1971
1972@node Adding and removing engravers
1973@subsection Adding and removing engravers
1974
1975@cindex engravers, adding
1976@cindex adding engravers
1977@cindex engravers, removing
1978@cindex removing engravers
1979
1980@funindex \consists
1981@funindex \remove
1982
1983We have seen that contexts each contain several engravers, each
1984of which is responsible for producing a particular part of the
1985output, like bar lines, staves, note heads, stems, etc.  If an
1986engraver is removed from a context, it can no longer produce its
1987output.  This is a crude way of modifying the output, but it
1988can sometimes be useful.
1989
1990@subsubheading Changing a single context
1991
1992To remove an engraver from a single context we use the
1993@code{\with} command placed immediately after the context creation
1994command, as in the previous section.
1995
1996As an illustration, let's repeat an example from the previous section
1997with the staff lines removed.  Remember that the staff lines are
1998produced by the @code{Staff_symbol_engraver}.
1999
2000@lilypond[quote,verbatim,ragged-right]
2001\new Staff \with {
2002  \remove "Staff_symbol_engraver"
2003}
2004\relative {
2005  c'4 d
2006  \set fontSize = #-4  % make note heads smaller
2007  e4 f |
2008  \set fontSize = #2.5  % make note heads larger
2009  g4 a
2010  \unset fontSize  % return to default size
2011  b4 c |
2012}
2013@end lilypond
2014
2015@cindex ambitus engraver
2016
2017Engravers can also be added to individual contexts.
2018The command to do this is
2019
2020@code{\consists @var{Engraver_name}},
2021
2022@noindent
2023placed inside a @code{\with} block.  Some vocal scores have an ambitus
2024placed at the beginning of a staff to indicate the range of notes in
2025that staff -- see @rglos{ambitus}.  The ambitus is produced by the
2026@code{Ambitus_engraver}, which is not normally included in any
2027context.  If we add it to the @code{Voice} context, it calculates the
2028range from that voice only:
2029
2030@lilypond[quote,verbatim,ragged-right]
2031\new Staff <<
2032  \new Voice \with {
2033    \consists "Ambitus_engraver"
2034  } {
2035    \relative {
2036      \voiceOne
2037      c''4 a b g
2038    }
2039  }
2040  \new Voice {
2041    \relative {
2042      \voiceTwo
2043      c'4 e d f
2044    }
2045  }
2046>>
2047@end lilypond
2048
2049@noindent
2050but if we add the ambitus engraver to the
2051@code{Staff} context, it calculates the range from all
2052the notes in all the voices on that staff:
2053
2054@lilypond[quote,verbatim,ragged-right]
2055\new Staff \with {
2056  \consists "Ambitus_engraver"
2057}
2058<<
2059  \new Voice {
2060    \relative {
2061      \voiceOne
2062      c''4 a b g
2063    }
2064  }
2065  \new Voice {
2066    \relative {
2067      \voiceTwo
2068      c'4 e d f
2069    }
2070  }
2071>>
2072@end lilypond
2073
2074@subsubheading Changing all contexts of the same type
2075
2076@funindex \layout
2077
2078The examples above show how to remove or add engravers to
2079individual contexts.  It is also possible to remove or add
2080engravers to every context of a specific type by placing the
2081commands in the appropriate context in a @code{\layout}
2082block.  For example, if we wanted to show an ambitus for every
2083staff in a four-staff score, we could write
2084
2085@lilypond[quote,verbatim,ragged-right]
2086\score {
2087  <<
2088    \new Staff {
2089      \relative {
2090        c''4 a b g
2091      }
2092    }
2093    \new Staff {
2094      \relative {
2095        c'4 a b g
2096      }
2097    }
2098    \new Staff {
2099      \clef "G_8"
2100      \relative {
2101        c'4 a b g
2102      }
2103    }
2104    \new Staff {
2105      \clef "bass"
2106      \relative {
2107        c4 a b g
2108      }
2109    }
2110  >>
2111  \layout {
2112    \context {
2113      \Staff
2114      \consists "Ambitus_engraver"
2115    }
2116  }
2117}
2118@end lilypond
2119
2120@noindent
2121The values of context properties may also be set
2122for all contexts of a particular type by including the
2123@code{\set} command in a @code{\context} block in the
2124same way.
2125
2126@morerefs
2127Notation Reference: @ruser{Modifying context plug-ins},
2128@ruser{Changing context default settings}.
2129
2130@knownissues
2131The @code{Stem_engraver} and @code{Beam_engraver} attach their
2132objects to note heads.  If the @code{Note_heads_engraver} is removed
2133no note heads are produced and therefore no stems or beams are created
2134either.
2135
2136
2137@node Extending the templates
2138@section Extending the templates
2139
2140You've read the tutorial, you know how to write music, you
2141understand the fundamental concepts.  But how can you
2142get the staves that you want?  Well, you can find lots of
2143templates (see @ref{Templates}) which may give you a start.
2144But what if you want something that isn't covered there?  Read on.
2145
2146@menu
2147* Soprano and cello::
2148* Four-part SATB vocal score::
2149* Building a score from scratch::
2150* Saving typing with variables and functions::
2151* Scores and parts::
2152@end menu
2153
2154@node Soprano and cello
2155@subsection Soprano and cello
2156
2157@cindex template, modifying
2158@cindex modifying templates
2159
2160Start off with the template that seems closest to what you want to
2161end up with.  Let's say that you want to write something for
2162soprano and cello.  In this case, we would start with the
2163@q{Notes and lyrics} template (for the soprano part).
2164
2165@example
2166\version @w{"@version{}"}
2167
2168melody = \relative @{
2169  \clef "treble"
2170  \key c \major
2171  \time 4/4
2172  a4 b c d
2173@}
2174
2175text = \lyricmode @{
2176  Aaa Bee Cee Dee
2177@}
2178
2179\score @{
2180  <<
2181    \new Voice = "one" @{
2182      \autoBeamOff
2183      \melody
2184    @}
2185    \new Lyrics \lyricsto "one" \text
2186  >>
2187  \layout @{ @}
2188  \midi @{ @}
2189@}
2190@end example
2191
2192Now we want to add a cello part.  Let's look at the @q{Notes only} example:
2193
2194@example
2195\version @w{"@version{}"}
2196
2197melody = \relative @{
2198  \clef "treble"
2199  \key c \major
2200  \time 4/4
2201  a4 b c d
2202@}
2203
2204\score @{
2205  \new Staff \melody
2206  \layout @{ @}
2207  \midi @{ @}
2208@}
2209@end example
2210
2211We don't need two @code{\version} commands.  We'll need the
2212@code{melody} section.  We don't want two @code{\score} sections
2213-- if we had two @code{\score}s, we'd get the two parts separately.
2214We want them together, as a duet.  Within the @code{\score}
2215section, we don't need two @code{\layout} or @code{\midi}.
2216
2217If we simply cut and paste the @code{melody} section, we would
2218end up with two @code{melody} definitions.  This would not generate
2219an error, but the second one would be used for both melodies.
2220So let's rename them to make them distinct.  We'll call the
2221section for the soprano @code{sopranoMusic} and the section for
2222the cello @code{celloMusic}.  While we're doing this, let's rename
2223@code{text} to be @code{sopranoLyrics}.  Remember to rename both
2224instances of all these names -- both the initial definition (the
2225@code{melody = \relative c' @{ } part) and the name's use (in the
2226@code{\score} section).
2227
2228While we're doing this, let's change the cello part's staff --
2229celli normally use bass clef.  We'll also give the cello some
2230different notes.
2231
2232@example
2233\version @w{"@version{}"}
2234
2235sopranoMusic = \relative @{
2236  \clef "treble"
2237  \key c \major
2238  \time 4/4
2239  a4 b c d
2240@}
2241
2242sopranoLyrics = \lyricmode @{
2243  Aaa Bee Cee Dee
2244@}
2245
2246celloMusic = \relative @{
2247  \clef "bass"
2248  \key c \major
2249  \time 4/4
2250  d4 g fis8 e d4
2251@}
2252
2253\score @{
2254  <<
2255    \new Voice = "one" @{
2256      \autoBeamOff
2257      \sopranoMusic
2258    @}
2259    \new Lyrics \lyricsto "one" \sopranoLyrics
2260  >>
2261  \layout @{ @}
2262  \midi @{ @}
2263@}
2264@end example
2265
2266This is looking promising, but the cello part won't appear in the
2267score -- we haven't used it in the @code{\score} section.  If we
2268want the cello part to appear under the soprano part, we need to add
2269
2270@example
2271\new Staff \celloMusic
2272@end example
2273
2274@noindent
2275underneath the soprano stuff.  We also need to add @code{<<} and
2276@code{>>} around the music -- that tells LilyPond that there's
2277more than one thing (in this case, two @code{Staves}) happening
2278at once.  The @code{\score} looks like this now:
2279
2280@c Indentation in this example is deliberately poor
2281@example
2282\score @{
2283  <<
2284  <<
2285    \new Voice = "one" @{
2286      \autoBeamOff
2287      \sopranoMusic
2288    @}
2289    \new Lyrics \lyricsto "one" \sopranoLyrics
2290  >>
2291  \new Staff \celloMusic
2292  >>
2293  \layout @{ @}
2294  \midi @{ @}
2295@}
2296@end example
2297
2298@noindent
2299This looks a bit messy; the indentation is messed up now.  That is
2300easily fixed.  Here's the complete soprano and cello template.
2301
2302@lilypond[quote,verbatim,ragged-right]
2303sopranoMusic = \relative {
2304  \clef "treble"
2305  \key c \major
2306  \time 4/4
2307  a4 b c d
2308}
2309
2310sopranoLyrics = \lyricmode {
2311  Aaa Bee Cee Dee
2312}
2313
2314celloMusic = \relative {
2315  \clef "bass"
2316  \key c \major
2317  \time 4/4
2318  d4 g fis8 e d4
2319}
2320
2321\score {
2322  <<
2323    <<
2324      \new Voice = "one" {
2325        \autoBeamOff
2326        \sopranoMusic
2327      }
2328      \new Lyrics \lyricsto "one" \sopranoLyrics
2329    >>
2330    \new Staff \celloMusic
2331  >>
2332  \layout { }
2333  \midi { }
2334}
2335@end lilypond
2336
2337
2338@morerefs
2339The starting templates can be found in the @q{Templates} appendix,
2340see @ref{Single staff templates}.
2341
2342
2343@node Four-part SATB vocal score
2344@subsection Four-part SATB vocal score
2345
2346@cindex template, SATB
2347@cindex SATB template
2348
2349Most vocal scores of music written for four-part mixed choir
2350with orchestral accompaniment such as Mendelssohn's Elijah or
2351Handel's Messiah have the choral music and words on four
2352staves, one for each of SATB, with a piano reduction of the
2353orchestral accompaniment underneath.  Here's an example
2354from Handel's Messiah:
2355
2356@c The following should appear as music without code
2357@lilypond[quote,ragged-right]
2358global = { \key d \major \time 4/4 }
2359
2360sopranoMusic = \relative {
2361  \clef "treble"
2362  r4 d''2 a4 | d4. d8 a2 | cis4 d cis2 |
2363}
2364sopranoWords = \lyricmode {
2365  Wor -- thy | is the lamb | that was slain |
2366}
2367
2368altoMusic = \relative {
2369  \clef "treble"
2370  r4 a'2 a4 | fis4. fis8 a2 | g4 fis e2 |
2371}
2372altoWords = \sopranoWords
2373
2374tenorMusic = \relative {
2375  \clef "G_8"
2376  r4 fis'2 e4 | d4. d8 d2 | e4 a, cis2 |
2377}
2378tenorWords = \sopranoWords
2379
2380bassMusic = \relative {
2381  \clef "bass"
2382  r4 d'2 cis4 | b4. b8 fis2 | e4 d a'2 |
2383}
2384bassWords = \sopranoWords
2385
2386upper = \relative {
2387  \clef "treble"
2388  \global
2389  r4 <a' d fis>2 <a e' a>4 |
2390  <d fis d'>4. <d fis d'>8 <a d a'>2 |
2391  <g cis g'>4 <a d fis> <a cis e>2 |
2392}
2393
2394lower = \relative {
2395  \clef "bass"
2396  \global
2397  <d, d'>4 <d d'>2 <cis cis'>4 |
2398  <b b'>4. <b' b'>8 <fis fis'>2 |
2399  <e e'>4 <d d'> <a' a'>2 |
2400}
2401
2402\score {
2403  <<  % combine ChoirStaff and PianoStaff in parallel
2404    \new ChoirStaff <<
2405      \new Staff = "sopranos" <<
2406        \set Staff.instrumentName = "Soprano"
2407        \new Voice = "sopranos" {
2408          \global
2409          \sopranoMusic
2410        }
2411      >>
2412      \new Lyrics \lyricsto "sopranos" {
2413        \sopranoWords
2414      }
2415      \new Staff = "altos" <<
2416        \set Staff.instrumentName = "Alto"
2417        \new Voice = "altos" {
2418          \global
2419          \altoMusic
2420        }
2421      >>
2422      \new Lyrics \lyricsto "altos" { \altoWords }
2423      \new Staff = "tenors" <<
2424        \set Staff.instrumentName = "Tenor"
2425        \new Voice = "tenors" {
2426          \global
2427          \tenorMusic
2428        }
2429      >>
2430      \new Lyrics \lyricsto "tenors" { \tenorWords }
2431      \new Staff = "basses" <<
2432        \set Staff.instrumentName = "Bass"
2433        \new Voice = "basses" {
2434          \global
2435          \bassMusic
2436        }
2437      >>
2438      \new Lyrics \lyricsto "basses" {
2439        \bassWords
2440      }
2441    >>  % end ChoirStaff
2442    \new PianoStaff <<
2443      \set PianoStaff.instrumentName = "Piano"
2444      \new Staff = "upper" \upper
2445      \new Staff = "lower" \lower
2446    >>
2447  >>
2448}
2449@end lilypond
2450
2451None of the templates provides this layout exactly.  The nearest is
2452@ref{SATB vocal score and automatic piano reduction} -- but we need
2453to change the layout and add a piano
2454accompaniment which is not derived automatically from the vocal parts.
2455The variables holding the music and words for the vocal parts are
2456fine, but we shall need to add variables for the piano reduction.
2457
2458The order in which the contexts appear in the ChoirStaff of the
2459template do not correspond with the order in the vocal score shown
2460above.  We need to rearrange them so there are four staves with the
2461words written directly underneath the notes for each part.  All the
2462voices should be @code{\voiceOne}, which is the default, so the
2463@code{\voiceXXX} commands should be removed.  We also need to specify
2464the tenor clef for the tenors.  The way in which lyrics are specified
2465in the template has not yet been encountered so we need to use the
2466method with which we are familiar.  We should also add the names of
2467each staff.
2468
2469Doing this gives for our ChoirStaff:
2470
2471@example
2472\new ChoirStaff <<
2473  \new Staff = "sopranos" <<
2474    \set Staff.instrumentName = "Soprano"
2475    \new Voice = "sopranos" @{
2476      \global
2477      \sopranoMusic
2478    @}
2479  >>
2480  \new Lyrics \lyricsto "sopranos" @{
2481    \sopranoWords
2482  @}
2483  \new Staff = "altos" <<
2484    \set Staff.instrumentName = "Alto"
2485    \new Voice = "altos" @{
2486      \global
2487      \altoMusic
2488    @}
2489  >>
2490  \new Lyrics \lyricsto "altos" @{
2491    \altoWords
2492  @}
2493  \new Staff = "tenors" <<
2494    \set Staff.instrumentName = "Tenor"
2495    \new Voice = "tenors" @{
2496      \global
2497      \tenorMusic
2498    @}
2499  >>
2500  \new Lyrics \lyricsto "tenors" @{
2501    \tenorWords
2502  @}
2503  \new Staff = "basses" <<
2504    \set Staff.instrumentName = "Bass"
2505    \new Voice = "basses" @{
2506      \global
2507      \bassMusic
2508    @}
2509  >>
2510  \new Lyrics \lyricsto "basses" @{
2511    \bassWords
2512  @}
2513>>  % end ChoirStaff
2514@end example
2515
2516Next we must work out the piano part.  This is
2517easy - we just pull out the piano part from the
2518@q{Solo piano} template:
2519
2520@example
2521\new PianoStaff <<
2522  \set PianoStaff.instrumentName = "Piano  "
2523  \new Staff = "upper" \upper
2524  \new Staff = "lower" \lower
2525>>
2526@end example
2527
2528and add the variable definitions for @code{upper}
2529and @code{lower}.
2530
2531The ChoirStaff and PianoStaff must be combined
2532using angle brackets as we want them to be
2533stacked one above the other:
2534
2535@example
2536<<  % combine ChoirStaff and PianoStaff one above the other
2537  \new ChoirStaff <<
2538    \new Staff = "sopranos" <<
2539      \new Voice = "sopranos" @{
2540        \global
2541        \sopranoMusic
2542      @}
2543    >>
2544    \new Lyrics \lyricsto "sopranos" @{
2545      \sopranoWords
2546     @}
2547    \new Staff = "altos" <<
2548      \new Voice = "altos" @{
2549        \global
2550        \altoMusic
2551      @}
2552    >>
2553    \new Lyrics \lyricsto "altos" @{
2554      \altoWords
2555    @}
2556    \new Staff = "tenors" <<
2557      \clef "G_8"  % tenor clef
2558      \new Voice = "tenors" @{
2559        \global
2560        \tenorMusic
2561      @}
2562    >>
2563    \new Lyrics \lyricsto "tenors" @{
2564      \tenorWords
2565    @}
2566    \new Staff = "basses" <<
2567      \clef "bass"
2568      \new Voice = "basses" @{
2569        \global
2570        \bassMusic
2571      @}
2572    >>
2573    \new Lyrics \lyricsto "basses" @{
2574      \bassWords
2575    @}
2576  >>  % end ChoirStaff
2577
2578  \new PianoStaff <<
2579    \set PianoStaff.instrumentName = "Piano"
2580    \new Staff = "upper" \upper
2581    \new Staff = "lower" \lower
2582  >>
2583>>
2584@end example
2585
2586Combining all these together and adding the music
2587for the three bars of the example above gives:
2588
2589@lilypond[quote,verbatim,ragged-right]
2590global = { \key d \major \time 4/4 }
2591sopranoMusic = \relative {
2592  \clef "treble"
2593  r4 d''2 a4 | d4. d8 a2 | cis4 d cis2 |
2594}
2595sopranoWords = \lyricmode {
2596  Wor -- thy | is the lamb | that was slain |
2597}
2598altoMusic = \relative {
2599  \clef "treble"
2600  r4 a'2 a4 | fis4. fis8 a2 | g4 fis fis2 |
2601}
2602altoWords = \sopranoWords
2603tenorMusic = \relative {
2604  \clef "G_8"
2605  r4 fis'2 e4 | d4. d8 d2 | e4 a, cis2 |
2606}
2607tenorWords = \sopranoWords
2608bassMusic = \relative {
2609  \clef "bass"
2610  r4 d'2 cis4 | b4. b8 fis2 | e4 d a'2 |
2611}
2612bassWords = \sopranoWords
2613upper = \relative {
2614  \clef "treble"
2615  \global
2616  r4 <a' d fis>2 <a e' a>4 |
2617  <d fis d'>4. <d fis d'>8 <a d a'>2 |
2618  <g cis g'>4 <a d fis> <a cis e>2 |
2619}
2620lower = \relative {
2621  \clef "bass"
2622  \global
2623  <d, d'>4 <d d'>2 <cis cis'>4 |
2624  <b b'>4. <b' b'>8 <fis fis'>2 |
2625  <e e'>4 <d d'> <a' a'>2 |
2626}
2627
2628\score {
2629  <<  % combine ChoirStaff and PianoStaff in parallel
2630    \new ChoirStaff <<
2631      \new Staff = "sopranos" <<
2632        \set Staff.instrumentName = "Soprano"
2633        \new Voice = "sopranos" {
2634          \global
2635          \sopranoMusic
2636        }
2637      >>
2638      \new Lyrics \lyricsto "sopranos" {
2639        \sopranoWords
2640      }
2641      \new Staff = "altos" <<
2642        \set Staff.instrumentName = "Alto"
2643        \new Voice = "altos" {
2644          \global
2645          \altoMusic
2646        }
2647      >>
2648      \new Lyrics \lyricsto "altos" {
2649        \altoWords
2650      }
2651      \new Staff = "tenors" <<
2652        \set Staff.instrumentName = "Tenor"
2653        \new Voice = "tenors" {
2654          \global
2655          \tenorMusic
2656        }
2657      >>
2658      \new Lyrics \lyricsto "tenors" {
2659        \tenorWords
2660      }
2661      \new Staff = "basses" <<
2662        \set Staff.instrumentName = "Bass"
2663        \new Voice = "basses" {
2664          \global
2665          \bassMusic
2666        }
2667      >>
2668      \new Lyrics \lyricsto "basses" {
2669        \bassWords
2670      }
2671    >>  % end ChoirStaff
2672
2673    \new PianoStaff <<
2674      \set PianoStaff.instrumentName = "Piano  "
2675      \new Staff = "upper" \upper
2676      \new Staff = "lower" \lower
2677    >>
2678  >>
2679}
2680@end lilypond
2681
2682
2683@node Building a score from scratch
2684@subsection Building a score from scratch
2685
2686@cindex template, writing your own
2687@cindex example of writing a score
2688@cindex writing a score, example
2689@cindex score, example of writing
2690
2691After gaining some facility with writing LilyPond code, you
2692may find that it is easier to build a score from scratch
2693rather than modifying one of the templates.  You can also
2694develop your own style this way to suit the sort of music you
2695like.  Let's see how to put together the score for an organ
2696prelude as an example.
2697
2698We begin with a header section.  Here go the title, name
2699of composer, etc, then come any variable definitions, and
2700finally the score block.  Let's start with these in outline
2701and fill in the details later.
2702
2703We'll use the first two bars of Bach's prelude
2704based on @emph{Jesu, meine Freude} which is written for two
2705manuals and pedal organ.  You can see these two bars of music
2706at the bottom of this section.  The top manual part has two voices,
2707the lower and pedal organ one each.  So we need four
2708music definitions and one to define the time signature
2709and key:
2710
2711@example
2712\version @w{"@version{}"}
2713\header @{
2714  title = "Jesu, meine Freude"
2715  composer = "J S Bach"
2716@}
2717keyTime = @{ \key c \minor \time 4/4 @}
2718ManualOneVoiceOneMusic = @{ s1 @}
2719ManualOneVoiceTwoMusic = @{ s1 @}
2720ManualTwoMusic = @{ s1 @}
2721PedalOrganMusic = @{ s1 @}
2722
2723\score @{
2724@}
2725@end example
2726
2727For now we've just used a spacer note, @code{s1},
2728instead of the real music.  We'll add that later.
2729
2730Next let's see what should go in the score block.
2731We simply mirror the staff structure we want.
2732Organ music is usually written on three staves,
2733one for each manual and one for the pedals.  The
2734manual staves should be bracketed together, so we
2735need to use a PianoStaff for them.  The first
2736manual part needs two voices and the second manual
2737part just one.
2738
2739@example
2740\new PianoStaff <<
2741  \new Staff = "ManualOne" <<
2742    \new Voice @{
2743      \ManualOneVoiceOneMusic
2744    @}
2745    \new Voice @{
2746      \ManualOneVoiceTwoMusic
2747    @}
2748  >>  % end ManualOne Staff context
2749  \new Staff = "ManualTwo" <<
2750    \new Voice @{
2751      \ManualTwoMusic
2752    @}
2753  >>  % end ManualTwo Staff context
2754>>  % end PianoStaff context
2755@end example
2756
2757Next we need to add a staff for the pedal organ.
2758This goes underneath the PianoStaff, but it must
2759be simultaneous with it, so we need angle brackets
2760around the two.  Missing these out would generate
2761an error in the log file.  It's a common mistake
2762which you'll make sooner or later!  Try copying
2763the final example at the end of this section,
2764remove these angle brackets, and compile it to
2765see what errors it generates.
2766
2767@example
2768<<  % PianoStaff and Pedal Staff must be simultaneous
2769  \new PianoStaff <<
2770    \new Staff = "ManualOne" <<
2771      \new Voice @{
2772        \ManualOneVoiceOneMusic
2773      @}
2774      \new Voice @{
2775        \ManualOneVoiceTwoMusic
2776      @}
2777    >>  % end ManualOne Staff context
2778    \new Staff = "ManualTwo" <<
2779      \new Voice @{
2780        \ManualTwoMusic
2781      @}
2782    >>  % end ManualTwo Staff context
2783  >>  % end PianoStaff context
2784  \new Staff = "PedalOrgan" <<
2785    \new Voice @{
2786      \PedalOrganMusic
2787    @}
2788  >>
2789>>
2790@end example
2791
2792It is not necessary to use the simultaneous construct
2793@code{<< .. >>} for the manual two staff and the pedal organ staff,
2794since they contain only one music expression, but it does no harm,
2795and always using angle brackets after @code{\new Staff} is a good
2796habit to cultivate in case there are multiple voices.  The opposite
2797is true for Voices: these should habitually be followed by braces
2798@code{@{ .. @}} in case your music is coded in several variables
2799which need to run consecutively.
2800
2801Let's add this structure to the score block, and adjust the indenting.
2802We also add the appropriate clefs, ensure stems, ties and slurs in
2803each voice on the upper staff point to the right direction with
2804@code{\voiceOne} and @code{\voiceTwo}, and enter the key and time
2805signature to each staff using our predefined variable, @code{\keyTime}.
2806
2807@example
2808\score @{
2809  <<  % PianoStaff and Pedal Staff must be simultaneous
2810    \new PianoStaff <<
2811      \new Staff = "ManualOne" <<
2812        \keyTime  % set key and time signature
2813        \clef "treble"
2814        \new Voice @{
2815          \voiceOne
2816          \ManualOneVoiceOneMusic
2817        @}
2818        \new Voice @{
2819          \voiceTwo
2820          \ManualOneVoiceTwoMusic
2821        @}
2822      >>  % end ManualOne Staff context
2823      \new Staff = "ManualTwo" <<
2824        \keyTime
2825        \clef "bass"
2826        \new Voice @{
2827          \ManualTwoMusic
2828        @}
2829      >>  % end ManualTwo Staff context
2830    >>  % end PianoStaff context
2831    \new Staff = "PedalOrgan" <<
2832      \keyTime
2833      \clef "bass"
2834      \new Voice @{
2835        \PedalOrganMusic
2836      @}
2837    >>  % end PedalOrgan Staff
2838  >>
2839@}  % end Score context
2840@end example
2841
2842@cindex stretchability of staves
2843@cindex staves, stretchability
2844
2845The above layout of the organ staves is almost perfect; however,
2846there is a slight defect which is not visible by looking at just a
2847single system: The distance of the pedal staff to the left hand staff
2848should behave approximately the same as the right hand staff to the
2849left hand staff.  In particular, the stretchability of staves in a
2850@code{PianoStaff} context is limited (so that the distance between
2851the staves for the left and right hand can't become too large), and
2852the pedal staff should behave similarly.
2853
2854@cindex sub-properties
2855@cindex properties, sub-properties
2856@cindex graphical objects
2857@cindex objects, graphical
2858@cindex grobs
2859
2860Stretchability of staves can be controlled with the
2861@code{staff-staff-spacing} property of the
2862@code{VerticalAxisGroup} @q{graphical object} (commonly called
2863@q{grob}s within the lilypond documentation) -- don't worry about
2864the details right now; this is fully explained later.  For the
2865curious, have a look at @ruser{Overview of modifying properties}.
2866In this case, we want to modify the @code{stretchability}
2867sub-property only. Again, for the curious, you can find the
2868default values for the staff-staff-spacing property
2869in file @file{scm/define-grobs.scm} by looking up the definition
2870of the @code{VerticalAxisGroup} grob.  The value for
2871@code{stretchability} is taken from the definition of the
2872@code{PianoStaff} context (in file @file{ly/engraver-init.ly})
2873so that the values are identical.
2874
2875@example
2876\score @{
2877  <<  % PianoStaff and Pedal Staff must be simultaneous
2878    \new PianoStaff <<
2879      \new Staff = "ManualOne" <<
2880        \keyTime  % set key and time signature
2881        \clef "treble"
2882        \new Voice @{
2883          \voiceOne
2884          \ManualOneVoiceOneMusic
2885        @}
2886        \new Voice @{
2887          \voiceTwo
2888          \ManualOneVoiceTwoMusic
2889        @}
2890      >>  % end ManualOne Staff context
2891      \new Staff = "ManualTwo" \with @{
2892        \override VerticalAxisGroup.staff-staff-spacing.stretchability = 5
2893      @} <<
2894        \keyTime
2895        \clef "bass"
2896        \new Voice @{
2897          \ManualTwoMusic
2898        @}
2899      >>  % end ManualTwo Staff context
2900    >>  % end PianoStaff context
2901    \new Staff = "PedalOrgan" <<
2902      \keyTime
2903      \clef "bass"
2904      \new Voice @{
2905        \PedalOrganMusic
2906      @}
2907    >>  % end PedalOrgan Staff
2908  >>
2909@}  % end Score context
2910@end example
2911That completes the structure.  Any three-staff organ music
2912will have a similar structure, although the number of voices
2913may vary.  All that remains now
2914is to add the music, and combine all the parts together.
2915
2916@lilypond[quote,verbatim,ragged-right]
2917\header {
2918  title = "Jesu, meine Freude"
2919  composer = "J S Bach"
2920}
2921keyTime = { \key c \minor \time 4/4 }
2922ManualOneVoiceOneMusic = \relative {
2923  g'4 g f ees |
2924  d2 c |
2925}
2926ManualOneVoiceTwoMusic = \relative {
2927  ees'16 d ees8~ 16 f ees d c8 d~ d c~ |
2928  8 c4 b8 c8. g16 c b c d |
2929}
2930ManualTwoMusic = \relative {
2931  c'16 b c8~ 16 b c g a8 g~ 16 g aes ees |
2932  f16 ees f d g aes g f ees d ees8~ 16 f ees d |
2933}
2934PedalOrganMusic = \relative {
2935  r8 c16 d ees d ees8~ 16 a, b g c b c8 |
2936  r16 g ees f g f g8 c,2 |
2937}
2938
2939\score {
2940  <<  % PianoStaff and Pedal Staff must be simultaneous
2941    \new PianoStaff <<
2942      \new Staff = "ManualOne" <<
2943        \keyTime  % set key and time signature
2944        \clef "treble"
2945        \new Voice {
2946          \voiceOne
2947          \ManualOneVoiceOneMusic
2948        }
2949        \new Voice {
2950          \voiceTwo
2951          \ManualOneVoiceTwoMusic
2952        }
2953      >>  % end ManualOne Staff context
2954      \new Staff = "ManualTwo" \with {
2955        \override VerticalAxisGroup.staff-staff-spacing.stretchability = 5
2956      } <<
2957        \keyTime
2958        \clef "bass"
2959        \new Voice {
2960          \ManualTwoMusic
2961        }
2962      >>  % end ManualTwo Staff context
2963    >>  % end PianoStaff context
2964    \new Staff = "PedalOrgan" <<
2965      \keyTime
2966      \clef "bass"
2967      \new Voice {
2968        \PedalOrganMusic
2969      }
2970    >>  % end PedalOrgan Staff context
2971  >>
2972}  % end Score context
2973@end lilypond
2974
2975@morerefs
2976Music Glossary:
2977@rglos{system}.
2978
2979@node Saving typing with variables and functions
2980@subsection Saving typing with variables and functions
2981
2982@cindex variables
2983@cindex variables
2984
2985By this point, you've seen this kind of thing:
2986
2987@lilypond[quote,verbatim,ragged-right]
2988hornNotes = \relative { c''4 b dis c }
2989
2990\score {
2991  {
2992    \hornNotes
2993  }
2994}
2995@end lilypond
2996
2997You may even realize that this could be useful in minimalist music:
2998
2999@lilypond[quote,verbatim,ragged-right]
3000fragmentA = \relative { a'4 a8. b16 }
3001fragmentB = \relative { a'8. gis16 ees4 }
3002
3003violin = \new Staff {
3004  \fragmentA \fragmentA |
3005  \fragmentB \fragmentA |
3006}
3007
3008\score {
3009  {
3010    \violin
3011  }
3012}
3013@end lilypond
3014
3015However, you can also use these variables (also known as
3016macros, or user-defined commands) for tweaks:
3017
3018@c TODO Avoid padtext - not needed with skylining
3019@lilypond[quote,verbatim,ragged-right]
3020dolce = \markup { \italic \bold dolce }
3021
3022padText = { \once \override TextScript.padding = #5.0 }
3023fthenp =_\markup {
3024  \dynamic f \italic \small { 2nd } \hspace #0.1 \dynamic p
3025}
3026
3027violin = \relative {
3028  \repeat volta 2 {
3029    c''4._\dolce b8 a8 g a b |
3030    \padText
3031    c4.^"hi there!" d8 e' f g d |
3032    c,4.\fthenp b8 c4 c-. |
3033  }
3034}
3035
3036\score {
3037  {
3038    \violin
3039  }
3040  \layout { ragged-right = ##t }
3041}
3042@end lilypond
3043
3044These variables are obviously useful for saving
3045typing.  But they're worth considering even if you
3046only use them once -- they reduce complexity.  Let's
3047look at the previous example without any
3048variables.  It's a lot harder to read, especially
3049the last line.
3050
3051@example
3052violin = \relative @{
3053  \repeat volta 2 @{
3054    c''4._\markup @{ \italic \bold dolce @} b8 a8 g a b |
3055    \once \override TextScript.padding = #5.0
3056    c4.^"hi there!" d8 e' f g d |
3057    c,4.\markup @{
3058      \dynamic f \italic \small @{ 2nd @} \hspace #0.1 \dynamic p
3059    @}
3060    b8 c4 c-. |
3061  @}
3062@}
3063@end example
3064
3065@c TODO Replace the following with a better example  -td
3066@c Skylining handles this correctly without padText
3067
3068So far we've seen static substitution -- when LilyPond
3069sees @code{\padText}, it replaces it with the stuff that
3070we've defined it to be (ie the stuff to the right of
3071@code{padtext=}).
3072
3073LilyPond can handle non-static substitution, too (you
3074can think of these as functions).
3075
3076@lilypond[quote,verbatim,ragged-right]
3077padText =
3078#(define-music-function
3079     (padding)
3080     (number?)
3081   #{
3082     \once \override TextScript.padding = #padding
3083   #})
3084
3085\relative {
3086  c'''4^"piu mosso" b a b |
3087  \padText #1.8
3088  c4^"piu mosso" d e f |
3089  \padText #2.6
3090  c4^"piu mosso" fis a g |
3091}
3092@end lilypond
3093
3094Using variables is also a good way to reduce work if the
3095LilyPond input syntax changes (see
3096@rprogram{Updating files with convert-ly}).  If
3097you have a single definition (such as @code{\dolce}) for all your
3098input files (see @ref{Style sheets}), then if the syntax changes, you
3099only need to update your single @code{\dolce} definition,
3100instead of making changes throughout every @file{.ly} file.
3101
3102
3103@node Scores and parts
3104@subsection Scores and parts
3105
3106In orchestral music, all notes are printed twice.  Once in a part for
3107the musicians, and once in a full score for the conductor.  Variables can
3108be used to avoid double work.  The music is entered once, and stored in
3109a variable.  The contents of that variable is then used to generate
3110both the part and the full score.
3111
3112It is convenient to define the notes in a special file.  For example,
3113suppose that the file @file{horn-music.ly} contains the following part
3114of a horn/@/bassoon duo
3115
3116@example
3117hornNotes = \relative @{
3118  \time 2/4
3119  r4 f8 a | cis4 f | e4 d |
3120@}
3121@end example
3122
3123@noindent
3124Then, an individual part is made by putting the following in a file
3125
3126@example
3127\include "horn-music.ly"
3128
3129\header @{
3130  instrument = "Horn in F"
3131@}
3132
3133@{
3134 \transpose f c' \hornNotes
3135@}
3136@end example
3137
3138The line
3139
3140@example
3141\include "horn-music.ly"
3142@end example
3143
3144@noindent
3145substitutes the contents of @file{horn-music.ly} at this position in
3146the file, so @code{hornNotes} is defined afterwards.  The command
3147@code{\transpose f@tie{}c'} indicates that the argument, being
3148@code{\hornNotes}, should be transposed by a fifth upwards.  Sounding
3149@code{f} is denoted by notated @code{c'}, which corresponds with the
3150tuning of a normal French Horn in@tie{}F.  The transposition can be seen
3151in the following output
3152
3153@lilypond[quote,ragged-right]
3154\transpose f c' \relative {
3155  \time 2/4
3156  r4 f8 a | cis4 f | e4 d |
3157}
3158@end lilypond
3159
3160In ensemble pieces, one of the voices often does not play for many
3161measures.  This is denoted by a special rest, the multi-measure
3162rest.  It is entered with a capital @code{R} followed by a duration
3163(@code{1}@tie{}for a whole note, @code{2}@tie{}for a half note,
3164etc.).  By multiplying the
3165duration, longer rests can be constructed.  For example, this rest
3166takes 3@tie{}measures in 2/4 time
3167
3168@example
3169R2*3
3170@end example
3171
3172When printing the part, multi-rests
3173must be condensed.  This is done by setting a run-time variable
3174
3175@example
3176\set Score.skipBars = ##t
3177@end example
3178
3179@noindent
3180This command sets the property @code{skipBars} in the
3181@code{Score} context to true (@code{##t}).  Prepending the rest and
3182this option to the music above, leads to the following result
3183
3184@lilypond[quote,ragged-right]
3185\transpose f c' \relative {
3186  \time 2/4
3187  \set Score.skipBars = ##t
3188  R2*3 |
3189  r4 f8 a | cis4 f | e4 d |
3190}
3191@end lilypond
3192
3193
3194The score is made by combining all of the music together.  Assuming
3195that the other voice is in @code{bassoonNotes} in the file
3196@file{bassoon-music.ly}, a score is made with
3197
3198@example
3199\include "bassoon-music.ly"
3200\include "horn-music.ly"
3201
3202<<
3203  \new Staff \hornNotes
3204  \new Staff \bassoonNotes
3205>>
3206@end example
3207
3208@noindent
3209leading to
3210
3211@lilypond[quote,ragged-right]
3212\relative <<
3213  \new Staff {
3214    \clef "treble"
3215    \time 2/4
3216    R2*3 |
3217    r4 f8 a | cis4 f | e4 d |
3218  }
3219  \new Staff {
3220    \clef "bass"
3221    \time 2/4
3222    r4 d,8 f | gis4 c | b4 bes |
3223    a8 e f4 | g4 d | gis4 f |
3224  }
3225>>
3226@end lilypond
3227
3228
3229
3230