]> git.donarmstrong.com Git - lilypond.git/blob - Documentation/user/fundamental.itely
Add 'See also's to LM 3 'Fundamental concepts'
[lilypond.git] / Documentation / user / fundamental.itely
1 @c -*- coding: utf-8; mode: texinfo; -*-
2 @c This file is part of lilypond-learning.tely
3 @ignore
4     Translation of GIT committish: FILL-IN-HEAD-COMMITTISH
5
6     When revising a translation, copy the HEAD committish of the
7     version that you are working on.  See TRANSLATION for details.
8 @end ignore
9
10 @c \version "2.11.51"
11
12 @node Fundamental concepts
13 @chapter Fundamental concepts
14
15 You've seen in the Tutorial how to produce beautifully printed
16 music from a simple text file.  This section introduces the
17 concepts and techniques required to produce equally beautiful
18 but more complex scores.
19
20 @menu
21 * How LilyPond input files work::
22 * Voices contain music::
23 * Contexts and engravers::
24 * Extending the templates::
25 @end menu
26
27
28 @node How LilyPond input files work
29 @section How LilyPond input files work
30
31 The LilyPond input format is quite free-form, giving experienced
32 users a lot of flexibility to structure their files however they
33 wish.  But this flexibility can make things confusing for new
34 users.  This section will explain some of this structure, but may
35 gloss over some details in favor of simplicity.  For a complete
36 description of the input format, see @ruser{File structure}.
37
38 @menu
39 * Introduction to the LilyPond file structure::
40 * Score is a (single) compound musical expression::
41 * Nesting music expressions::
42 * On the un-nestedness of brackets and ties::
43 @end menu
44
45 @node Introduction to the LilyPond file structure
46 @subsection Introduction to the LilyPond file structure
47
48 @cindex input format
49 @cindex file structure
50
51 A basic example of a LilyPond input file is
52
53 @example
54 \version @w{"@version{}"}
55 \header @{ @}
56 \score @{
57   @var{...compound music expression...}  % all the music goes here!
58   \layout @{ @}
59   \midi @{ @}
60 @}
61 @end example
62
63 @noindent
64 There are many variations of this basic pattern, but this
65 example serves as a useful starting place.
66
67 @funindex \book
68 @funindex \score
69 @cindex book
70 @cindex score
71
72 Up to this point none of the examples you have seen has used a
73 @code{\score@{@}} command.  This is because LilyPond automatically
74 adds the extra commands which are needed when you give it simple
75 input.  LilyPond treats input like this:
76
77 @example
78 \relative c'' @{
79   c4 a d c
80 @}
81 @end example
82
83 @noindent
84 as shorthand for this:
85
86 @example
87 \book @{
88   \score @{
89     \new Staff @{
90       \new Voice @{
91         \relative c'' @{
92           c4 a b c
93         @}
94       @}
95     @}
96     \layout @{ @}
97   @}
98 @}
99 @end example
100
101 In other words, if the input contains a single music expression,
102 LilyPond will interpret the file as though the music expression
103 was wrapped up inside the commands shown above.
104
105 @cindex implicit contexts
106
107 @strong{A word of warning!}  Many of the examples in the LilyPond
108 documentation will omit the @code{\new Staff} and @code{\new Voice}
109 commands, leaving them to be created implicitly.  For simple
110 examples this works well, but for more complex examples, especially
111 when additional commands are used, the implicit creation of contexts
112 can give surprising results, maybe creating extra unwanted staves.
113 The way to create contexts explicitly is explained in 
114 @ref{Contexts and engravers}.
115
116 @warning{When entering more than a few lines of music it is
117 advisable to always create staves and voices explicitly.}
118
119 For now, though, let us return to the first example and examine the
120 @code{\score} command, leaving the others to default.
121
122 A @code{\score} block must always contain just one music expression,
123 and this must appear immediately after the @code{\score} command.
124 Remember that a music expression could be anything from a single
125 note to a huge compound expression like
126
127 @example
128 @{
129   \new GrandStaff <<
130     @var{...insert the whole score of a Wagner opera in here...}
131   >>
132 @}
133 @end example
134
135 @noindent
136 Since everything is inside @code{@{ ... @}}, it counts
137 as one music expression.
138
139 As we saw previously, the @code{\score} block can contain other
140 things, such as
141
142 @example
143 \score @{
144   @{ c'4 a b c' @}
145   \header @{ @}
146   \layout @{ @}
147   \midi @{ @}
148 @}
149 @end example
150
151 @funindex \header
152 @funindex \layout
153 @funindex \midi
154 @cindex header
155 @cindex layout
156 @cindex midi
157
158 @noindent
159 Note that these three commands -- @code{\header}, @code{\layout} and
160 @code{\midi} -- are special: unlike many other commands which begin
161 with a backward slash (@code{\}) they are @emph{not} music expressions
162 and are not part of any music expression.  So they may be placed
163 inside a @code{\score} block or outside it.  In fact, these commands
164 are commonly placed outside the @code{\score} block -- for example,
165 @code{\header} is often placed above the @code{\score} command, as the
166 example at the beginning of this section shows.
167
168 Two more commands you have not previously seen are
169 @code{\layout @{ @}} and @code{\midi @{@}}.  If these appear as
170 shown they will cause LilyPond to produce a printed output and a
171 MIDI output respectively.  They are described fully in the
172 Notation Reference -- @ruser{Score layout}, and
173 @ruser{Creating MIDI files}.
174
175 @cindex scores, multiple
176
177 You may code multiple @code{\score} blocks.  Each will be
178 treated as a separate score, but they will be all combined into
179 a single output file.  A @code{\book} command is not necessary
180 -- one will be implicitly created.  However, if you would like
181 separate output files from one @code{.ly} file then the
182 @code{\book} command should be used to separate the different
183 sections: each @code{\book} block will produce a
184 separate output file.
185
186 In summary:
187
188 Every @code{\book} block creates a separate output file (e.g., a
189 PDF file).  If you haven't explicitly added one, LilyPond wraps
190 your entire input code in a @code{\book} block implicitly.
191
192 Every @code{\score} block is a separate chunk of music within a
193 @code{\book} block.
194
195 Every @code{\layout} block affects the @code{\score} or
196 @code{\book} block in which it appears -- i.e., a @code{\layout}
197 block inside a @code{\score} block affects only that @code{\score}
198 block, but a @code{\layout} block outside of a @code{\score} block
199 (and thus in a @code{\book} block, either explicitly or
200 implicitly) will affect every @code{\score} in that @code{\book}.
201
202 Every @code{\context} block will affect the named context (e.g.,
203 @code{\StaffGroup}) throughout the block (@code{\score} or
204 @code{\book}) in which it appears.
205
206 For details see @ruser{Multiple scores in a book}.
207
208 @cindex variables
209
210 Another great shorthand is the ability to define variables.  All
211 the templates use this
212
213 @example
214 melody = \relative c' @{
215   c4 a b c
216 @}
217
218 \score @{
219   \melody
220 @}
221 @end example
222
223 When LilyPond looks at this file, it takes the value of
224 @code{melody} (everything after the equals sign) and inserts it
225 whenever it sees @code{\melody}.  There's nothing special about
226 the names -- it could be @code{melody}, @code{global},
227 @code{TimeKey},
228 @code{pianorighthand}, or @code{foofoobarbaz}.  For more details,
229 see @ref{Saving typing with variables and functions}.
230 Remember that you can use almost any name you like as long
231 as it contains just alphabetic characters and is distinct from
232 LilyPond command names.  The exact
233 limitations on variable names are detailed in
234 @ruser{File structure}.
235
236
237
238 @seealso
239
240 For a complete definition of the input format, see
241 @ruser{File structure}.
242
243 @node Score is a (single) compound musical expression
244 @subsection Score is a (single) compound musical expression
245
246 @funindex \score
247 @cindex score
248 @cindex Compound music expression
249 @cindex Music expression, compound
250
251 We saw the general organization of LilyPond input files in the
252 previous section, @ref{Introduction to the LilyPond file structure}.
253 But we seemed to skip over the most important part: how do we figure
254 out what to write after @code{\score}?
255
256 We didn't skip over it at all.  The big mystery is simply that
257 there @emph{is} no mystery.  This line explains it all:
258
259 @quotation
260 @emph{A @code{\score} block must begin with a compound music expression.}
261 @end quotation
262
263 @noindent
264 To understand what is meant by a music expression and a compound
265 music expression, you may find it useful to review the tutorial,
266 @ref{Music expressions explained}.  In that section, we saw how to
267 build big music expressions from small pieces -- we started from
268 notes, then chords, etc.  Now we're going to start from a big
269 music expression and work our way down.
270
271 @example
272 \score @{
273   @{ % this brace begins the overall compound music expression
274     \new GrandStaff <<
275       @var{...insert the whole score of a Wagner opera in here...}
276     >>
277   @} % this brace ends the overall compound music expression
278   \layout @{ @}
279 @}
280 @end example
281
282 A whole Wagner opera would easily double the length of this
283 manual, so let's just add a singer and piano.  We don't need a
284 @code{GrandStaff} for this ensemble, which simply groups a number
285 of staves together with a brace at the left, so we shall remove
286 it.  We @emph{do} need a singer and a piano, though.
287
288 @example
289 \score @{
290   <<
291     \new Staff = "singer" <<
292     >>
293     \new PianoStaff = piano <<
294     >>
295   >>
296   \layout @{ @}
297 @}
298 @end example
299
300 Remember that we use @code{<< ... >>} instead of @code{@{ ... @}} to
301 show simultaneous music.  And we definitely want to show the vocal
302 part and piano part at the same time, not one after the other!  Note
303 that the @code{<< ... >>} construct is not really necessary for the
304 Singer staff, as it contains only one sequential music expression;
305 however, using @code{<< ... >>} instead of braces is still necessary
306 if the music in the Staff is made of two simultaneous expressions,
307 e.g. two simultaneous Voices, or a Voice with lyrics.  We'll add some
308 real music later; for now let's just put in some dummy notes and
309 lyrics.
310
311 @lilypond[verbatim,quote,ragged-right]
312 \score {
313   <<
314     \new Staff = "singer" <<
315       \new Voice = "vocal" { c'1 }
316       \addlyrics { And }
317     >>
318     \new PianoStaff = "piano" <<
319       \new Staff = "upper" { c'1 }
320       \new Staff = "lower" { c'1 }
321     >>
322   >>
323   \layout { }
324 }
325 @end lilypond
326
327 Now we have a lot more details.  We have the singer's staff: it
328 contains a @code{Voice} (in LilyPond, this term refers to a set of
329 notes, not necessarily vocal notes -- for example, a violin
330 generally plays one voice) and some lyrics.  We also have a piano
331 staff: it contains an upper staff (right hand) and a lower staff
332 (left hand).
333
334 At this stage, we could start filling in notes.  Inside the curly
335 braces next to @code{\new Voice = vocal}, we could start writing
336
337 @example
338 \relative c'' @{
339   r4 d8\noBeam g, c4 r
340 @}
341 @end example
342
343 But if we did that, the @code{\score} section would get pretty
344 long, and it would be harder to understand what was happening.  So
345 let's use variables instead.  These were introduced at the end
346 of the previous section, remember?  So, adding a few notes, we
347 now have a piece of real music:
348
349 @lilypond[verbatim,quote,ragged-right]
350 melody = \relative c'' { r4 d8\noBeam g, c4 r }
351 text   = \lyricmode { And God said, }
352 upper  = \relative c'' { <g d g,>2~ <g d g,> }
353 lower  = \relative c { b2 e2 }
354
355 \score {
356   <<
357     \new Staff = "singer" <<
358       \new Voice = "vocal" { \melody }
359       \addlyrics { \text }
360     >>
361     \new PianoStaff = "piano" <<
362       \new Staff = "upper" { \upper }
363       \new Staff = "lower" {
364         \clef "bass"
365         \lower
366       }
367     >>
368   >>
369   \layout { }
370 }
371 @end lilypond
372
373
374 Be careful about the difference between notes, which are introduced
375 with @code{\relative} or which are directly included in a music
376 expression, and lyrics, which are introduced with
377 @code{\lyricmode}.  These are essential to tell LilyPond
378 to interpret the following content as music and text
379 respectively.
380
381 When writing (or reading) a @code{\score} section, just take it
382 slowly and carefully.  Start with the outer level, then work on
383 each smaller level.  It also really helps to be strict with
384 indentation -- make sure that each item on the same level starts
385 on the same horizontal position in your text editor.
386
387 @seealso
388
389 Notation Reference: @ruser{Structure of a score}.
390
391 @node Nesting music expressions
392 @subsection Nesting music expressions
393
394 @cindex staves, temporary
395 @cindex ossias
396
397 It is not essential to declare all staves at the beginning; they may
398 be introduced temporarily at any point.  This is particularly useful
399 for creating ossia sections -- see @rglos{ossia}.  Here is a simple
400 example showing how to introduce a new staff temporarily for the
401 duration of three notes:
402
403 @lilypond[verbatim,quote,ragged-right]
404 \new Staff {
405   \relative g' {
406     r4 g8 g c4 c8 d |
407     e4 r8
408     <<
409       { f c c }
410       \new Staff {
411         f8 f c
412       }
413     >>
414     r4 |
415   }
416 }
417 @end lilypond
418
419 @noindent
420 Note that the size of the clef is the same as a clef printed
421 following a clef change -- slightly smaller than the clef
422 at the beginning of the line.  This is usual for clefs printed
423 in the middle of a line.
424
425 @cindex staff, positioning
426
427 The ossia section may be placed above the staff
428 as follows:
429
430 @lilypond[verbatim,quote,ragged-right]
431 \new Staff ="main" {
432   \relative g' {
433     r4 g8 g c4 c8 d |
434     e4 r8
435     <<
436       { f c c }
437       \new Staff \with {
438         alignAboveContext = "main" }
439       { f8 f c }
440     >>
441     r4 |
442   }
443 }
444 @end lilypond
445
446 This example uses @code{\with}, which will be explained more
447 fully later.  It is a means of modifying the default behavior
448 of a single Staff.  Here it says that the new staff should be
449 placed above the staff called @qq{main} instead of the default
450 position which is below.
451
452 @seealso
453
454 Ossia are often written without clef and without
455 time signature and are usually in a smaller font.
456 These require further commands which
457 have not yet been introduced.  See @ref{Size of objects},
458 and @ruser{Ossia staves}.
459
460
461 @node On the un-nestedness of brackets and ties
462 @subsection On the un-nestedness of brackets and ties
463
464 @cindex brackets, nesting
465
466 You have already met a number of different types of bracket in
467 writing the input file to LilyPond.  These obey different rules
468 which can be confusing at first.  Before we explain the rules
469 let's first review the different types of bracket.
470
471 @c attempt to force this onto a new page
472 @need 50
473 @multitable @columnfractions .3 .7
474 @headitem Bracket Type
475   @tab Function
476 @item @code{@{ .. @}}
477   @tab Encloses a sequential segment of music
478 @item @code{< .. >}
479   @tab Encloses the notes of a chord
480 @item @code{<< .. >>}
481   @tab Encloses simultaneous music expressions
482 @item @code{( .. )}
483   @tab Marks the start and end of a slur
484 @item @code{\( .. \)}
485   @tab Marks the start and end of a phrasing slur
486 @item @code{[ .. ]}
487   @tab Marks the start and end of a manual beam
488 @end multitable
489
490 To these we should add other constructs which generate lines
491 between or across notes: ties (marked by a tilde, @code{~}),
492 tuplets written as @code{\times x/y @{..@}}, and grace notes
493 written as @code{\grace@{..@}}.
494
495 Outside LilyPond, the conventional use of brackets requires
496 the different types to be properly nested, like this,
497 @code{<< [ @{ ( .. ) @} ] >>}, with the closing brackets being
498 encountered in exactly the opposite order to the opening
499 brackets.  This @strong{is} a requirement for the three types of
500 bracket described by the word @q{Encloses} in the table above --
501 they must nest properly.
502 However, the remaining brackets, described with the word
503 @q{Marks} in the table above together with ties and tuplets,
504 do @strong{not} have to nest
505 properly with any of the brackets.  In fact, these are not
506 brackets in the sense that
507 they enclose something -- they are simply markers to indicate
508 where something starts and ends.
509
510 So, for example, a phrasing slur can start before a manually
511 inserted beam and end before the end of the beam -- not very
512 musical, perhaps, but possible:
513
514 @lilypond[quote,verbatim,fragment,ragged-right,relative=2]
515  { g8\( a b[ c b\) a] }
516 @end lilypond
517
518 In general, different kinds of brackets, and those implied by
519 tuplets, ties and grace notes, may be mixed freely.
520 This example shows a beam extending into a tuplet (line 1),
521 a slur extending into a tuplet (line 2),
522 a beam and a slur extending into a tuplet, a tie crossing
523 two tuplets, and a phrasing slur extending out of a tuplet
524 (lines 3 and 4).
525
526 @lilypond[quote,verbatim,fragment,ragged-right]
527 {
528   r16[ g16 \times 2/3 {r16 e'8] }
529   g16( a \times 2/3 {b d) e' }
530   g8[( a \times 2/3 {b d') e'~]}
531   \times 4/5 {e'32\( a b d' e'} a'4.\)
532 }
533 @end lilypond
534
535
536 @node Voices contain music
537 @section Voices contain music
538
539 Singers need voices to sing, and so does LilyPond.
540 The actual music for all instruments in a score
541 is contained in Voices -- the most fundamental
542 of all LilyPond's concepts.
543
544 @menu
545 * I'm hearing Voices::
546 * Explicitly instantiating voices::
547 * Voices and vocals::
548 @end menu
549
550 @node I'm hearing Voices
551 @subsection I'm hearing Voices
552
553 @cindex polyphony
554 @cindex layers
555 @cindex multiple voices
556 @cindex Voice context
557 @cindex context, Voice
558 @cindex simultaneous music
559 @cindex concurrent music
560
561 The lowest, most fundamental or innermost layers in a LilyPond
562 score are called @q{Voice contexts} or just @q{Voices} for short.
563 Voices are sometimes called @q{layers} in other notation
564 packages.
565
566 In fact, a Voice layer or context is the only one which can
567 contain music.  If a Voice context is not explicitly declared
568 one is created automatically, as we saw at the beginning of
569 this chapter.  Some instruments such as an
570 Oboe can play only one note at a time.  Music written for
571 such instruments is monophonic and requires just a single
572 voice.  Instruments which can play more than one note at a
573 time like the piano will often require multiple voices to
574 encode the different concurrent notes and rhythms they are
575 capable of playing.
576
577 A single voice can contain many notes in a chord, of course,
578 so when exactly are multiple voices needed?  Look first at
579 this example of four chords:
580
581 @lilypond[quote,verbatim,fragment,ragged-right,relative=1]
582 \key g \major
583 <d g>4 <d fis> <d a'> <d g>
584 @end lilypond
585
586 This can be expressed using just the single angle bracket chord
587 symbols, @code{< ... >}, and for this just a single voice is
588 needed.  But suppose the F-sharp were actually an eighth-note
589 followed by an eighth-note G, a passing note on the way to the A?
590 Now we have two notes which start at the same time but have
591 different durations: the quarter-note D and the eighth-note
592 F-sharp.  How are these to be coded?  They cannot be written as
593 a chord because all the notes in a chord must have the same
594 duration.  And they cannot be written as two sequential notes
595 as they need to start at the same time.  This is when two
596 voices are required.
597
598 Let us see how this is done in LilyPond input syntax.
599
600 @funindex << \\ >>
601 @funindex \\
602
603 The easiest way to enter fragments with more than one voice on a
604 staff is to enter each voice as a sequence (with @code{@{...@}}),
605 and combine them simultaneously with angle brackets, @code{<<...>>}.
606 The fragments must also be separated with double backward slashes,
607 @code{\\}, to place them in separate voices.  Without these, the
608 notes would be entered into a single voice, which would usually
609 cause errors.  This technique is particularly suited to pieces of
610 music which are largely monophonic with occasional short sections
611 of polyphony.
612
613 Here's how we split the chords above into two voices and add both
614 the passing note and a slur:
615
616 @lilypond[quote,verbatim,fragment,ragged-right,relative=2]
617 \key g \major
618 %    Voice "1"                  Voice "2"
619 << { g4 fis8( g) a4 g }    \\ { d4 d d d }  >> |
620 @end lilypond
621
622 Notice how the stems of the second voice now point down.
623
624 Here's another simple example:
625
626 @lilypond[quote,verbatim,fragment,ragged-right,relative=2]
627 \key d \minor
628 %    Voice "1"             Voice "2"
629 << { r4 g g4. a8 }    \\ { d,2 d4 g }       >> |
630 << { bes4 bes c bes } \\ { g4 g g8( a) g4 } >> |
631 << { a2. r4 }         \\ { fis2. s4 }       >> |
632 @end lilypond
633
634 It is not necessary to use a separate @code{<< \\ >>} construct
635 for each bar. For music with few notes in each bar this layout
636 can help the legibility of the code, but if there are many
637 notes in each bar it may be better to split out each voice
638 separately, like this:
639
640 @lilypond[quote,verbatim,fragment,ragged-right,relative=2]
641 \key d \minor
642 << {
643   % Voice "1"
644   r4 g g4. a8 |
645   bes4 bes c bes |
646   a2. r4 |
647 } \\ {
648   % Voice "2"
649   d,2 d4 g |
650   g4 g g8( a) g4 |
651   fis2. s4 |
652 } >>
653 @end lilypond
654
655
656 This example has just two voices, but the same construct may be
657 used to encode three or more voices by adding more back-slash
658 separators.
659
660 The Voice contexts bear the names @code{"1"}, @code{"2"}, etc.
661 In each of these contexts, the vertical direction of slurs,
662 stems, ties, dynamics etc., is set appropriately.
663
664 @lilypond[quote,verbatim,fragment]
665 \new Staff \relative c' {
666   % Main voice
667   c16 d e f
668   %    Voice "1"     Voice "2"                 Voice "3"
669   << { g4 f e } \\ { r8 e4 d c8 ~ } >> |
670   << { d2 e2 }  \\ { c8 b16 a b8 g ~ g2 } \\ { s4 b4 c2 } >> |
671 }
672 @end lilypond
673
674 These voices are all separate from the main voice that contains
675 the notes just outside the @code{<< .. >>} construct.  Let's call
676 this the @emph{simultaneous construct}.  Slurs and ties may only
677 connect notes within the same voice, so slurs and ties cannot go
678 into or out of a simultaneous construct.  Conversely,
679 parallel voices from separate simultaneous constructs on the same
680 staff are the same voice.  Other voice-related properties also
681 carry across simultaneous constructs.  Here is the same example,
682 with different colors and note heads for each voice.  Note that
683 changes in one voice do not affect other voices, but they do
684 persist in the same voice later.  Note also that tied notes may be
685 split across the same voices in two constructs, shown here in the
686 blue triangle voice.
687
688 @lilypond[quote,verbatim]
689 \new Staff \relative c' {
690   % Main voice
691   c16 d e f
692   << % Bar 1
693     {
694       \voiceOneStyle
695       g4 f e
696     }
697   \\
698     {
699       \voiceTwoStyle
700       r8 e4 d c8 ~
701     }
702   >>
703   << % Bar 2
704      % Voice 1 continues
705     { d2 e2 }
706   \\
707      % Voice 2 continues
708     { c8 b16 a b8 g ~ g2 }
709   \\
710     {
711       \voiceThreeStyle
712       s4 b4 c2
713     }
714   >>
715 }
716 @end lilypond
717
718 @funindex \voiceOneStyle
719 @funindex \voiceTwoStyle
720 @funindex \voiceThreeStyle
721 @funindex \voiceFourStyle
722 @funindex \voiceNeutralStyle
723
724 The commands @code{\voiceXXXStyle} are mainly intended for use in
725 educational documents such as this one.  They modify the color
726 of the note head, the stem and the beams, and the style of the
727 note head, so that the voices may be easily distinguished.
728 Voice one is set to red diamonds, voice two to blue triangles,
729 voice three to green crossed circles, and voice four (not used
730 here) to magenta crosses;  @code{\voiceNeutralStyle} (also not
731 used here) reverts the style back to the default.  
732 We shall see later how commands like these may be created by the
733 user.
734 See @ref{Visibility and color of objects} and
735 @ref{Using variables for tweaks}.
736
737 Polyphony does not change the relationship of notes within a
738 @code{\relative @{ @}} block.  Each note is still calculated
739 relative to the note immediately preceding it, or to the first
740 note of the preceding chord.  So in
741
742 @example
743 \relative c' @{ noteA << < noteB noteC > \\ noteD >> noteE @}
744 @end example
745
746 @noindent
747 @code{noteB} is relative to @code{noteA}                      @*
748 @code{noteC} is relative to @code{noteB}, not @code{noteA};   @*
749 @code{noteD} is relative to @code{noteB}, not @code{noteA} or
750 @code{noteC};                                                 @*
751 @code{noteE} is relative to @code{noteD}, not @code{noteA}.
752
753 An alternative way, which may be clearer if the notes in the
754 voices are widely separated, is to place a @code{\relative}
755 command at the start of each voice:
756
757 @example
758 \relative c' @{ noteA ... @}
759 <<
760   \relative c'' @{ < noteB noteC > ... @}
761 \\
762   \relative g' @{ noteD ... @}
763 >>
764 \relative c' @{ noteE ... @}
765 @end example
766
767 Let us finally analyze the voices in a more complex piece of
768 music.  Here are
769 the notes from the first two bars of the second of Chopin's
770 Deux Nocturnes, Op 32.  This example will be used at later
771 stages in this and the next chapter to illustrate several
772 techniques for producing notation, so please ignore for now
773 anything in the underlying code which looks mysterious and
774 concentrate just on the music and the voices -- the
775 complications will all be explained in later sections.
776
777 @c The following should appear as music without code
778 @lilypond[quote,ragged-right]
779 \new Staff \relative c'' {
780   \key aes \major
781   << % Voice one
782     { c2 aes4. bes8 }
783   \\ % Voice two
784     { aes2 f4 fes }
785   \\ % No voice three
786   \\ % Voice four
787     {
788       % Ignore these for now - they are explained in Ch 4
789       \once \override NoteColumn #'force-hshift = #0
790       <ees c>2
791       \once \override NoteColumn #'force-hshift = #0.5
792       des2
793     }
794   >> |
795   <c ees aes c>1 |
796 }
797 @end lilypond
798
799 The direction of the stems is often used to indicate the
800 continuity of two simultaneous melodic lines.  Here the
801 stems of the highest notes are all pointing up and the
802 stems of the lower notes are all pointing down.
803 This is the first indication that more than one voice
804 is required.
805
806 But the real need for multiple voices arises when notes
807 which start at the same time have different durations.
808 Look at the notes which start at beat three in the first
809 bar.  The A-flat is a dotted quarter note, the F is a
810 quarter note and the D-flat is a half note.  These
811 cannot be written as a chord as all the notes in a chord
812 must have the same duration.  Neither can they be written
813 as sequential notes, as they must start at the same time.
814 This section of the bar requires three voices, and the
815 normal practice would be to write the whole bar as three
816 voices, as shown below, where we have used different note heads
817 and colors for the three voices.  Again, the code behind this
818 example will be explained later, so ignore anything you do
819 not understand.
820
821 @c The following should appear as music without code
822 @c The three voice styles should be defined in -init
823 @lilypond[quote,ragged-right]
824 \new Staff \relative c'' {
825   \key aes \major
826   <<
827     { % Voice one
828       \voiceOneStyle
829       c2 aes4. bes8
830     }
831   \\  % Voice two
832     { \voiceTwoStyle
833       aes2 f4 fes
834     }
835   \\  % No Voice three (we want stems down)
836   \\  % Voice four
837     { \voiceThreeStyle
838       % Ignore these for now - they are explained in Ch 4
839       \once \override NoteColumn #'force-hshift = #0
840       <ees c>2
841       \once \override NoteColumn #'force-hshift = #0.5
842       des2
843     }
844   >> |
845   <c ees aes c>1 |
846 }
847 @end lilypond
848
849
850 Let us try to encode this music from scratch.  As we
851 shall see, this encounters some difficulties.  We begin as
852 we have learnt, using the @code{<< \\  >>} construct to
853 enter the music of the first bar in three voices:
854
855 @lilypond[quote,verbatim,fragment,ragged-right]
856 \new Staff \relative c'' {
857   \key aes \major
858   <<
859     { c2 aes4. bes8 } \\ { aes2 f4 fes } \\ { <ees c>2 des2 }
860   >>
861   <c ees aes c>1
862 }
863 @end lilypond
864
865 @cindex stem down
866 @cindex stem up
867
868 The stem directions are automatically assigned with the
869 odd-numbered voices taking upward stems and the even-numbered
870 voices downward ones.  The stems for voices 1 and 2 are right,
871 but the stems in voice 3 should go down in this particular piece
872 of music.  We can correct this simply by missing out voice three
873 and placing the music in voice four:
874
875 @lilypond[quote,verbatim,fragment,ragged-right]
876 \new Staff \relative c'' {
877   \key aes \major
878   << % Voice one
879     { c2 aes4. bes8 }
880   \\ % Voice two
881     { aes2 f4 fes   }
882   \\ % Omit Voice three
883   \\ % Voice four
884     { <ees c>2 des2 }
885   >> |
886   <c ees aes c>1 |
887 }
888 @end lilypond
889
890 @noindent
891 We see that this fixes the stem direction, but exposes a problem
892 sometimes encountered with multiple voices -- the stems of the notes
893 in one voice can collide with the note heads in other voices.  In
894 laying out the notes, LilyPond allows the notes or chords from two
895 voices to occupy the same vertical note column provided the stems are
896 in opposite directions, but the notes from the third and fourth voices
897 are displaced, if necessary, to avoid the note heads colliding.  This
898 usually works well, but in this example the notes of the lowest voice
899 are clearly not well placed by default. LilyPond provides several ways
900 to adjust the horizontal placing of notes.  We are not quite ready yet
901 to see how to correct this, so we shall leave this problem until a
902 later section --- see the @code{force-hshift} property in @ref{Fixing
903 overlapping notation}.
904
905 @seealso
906
907 Notation Reference: @ruser{Multiple voices}.
908
909
910 @node Explicitly instantiating voices
911 @subsection Explicitly instantiating voices
912
913 @funindex \voiceOne
914 @funindex \voiceTwo
915 @funindex \voiceThree
916 @funindex \voiceFour
917 @funindex \oneVoice
918 @funindex \new Voice
919 @cindex Voice contexts, creating
920
921 Voice contexts can also be created manually
922 inside a @code{<< >>} block to create polyphonic music, using
923 @code{\voiceOne} ... @code{\voiceFour} to indicate the required
924 directions of stems, slurs, etc.  In longer scores this method
925 is clearer, as it permits the voices to be separated and to be
926 given more descriptive names.
927
928 Specifically, the construct @code{<< \\ >>} which we used in
929 the previous section:
930
931 @example
932 \new Staff @{
933   \relative c' @{
934     << @{ e4 f g a @} \\ @{ c,4 d e f @} >>
935   @}
936 @}
937 @end example
938
939 @noindent
940 is equivalent to
941
942 @example
943 \new Staff <<
944   \new Voice = "1" @{ \voiceOne \relative c' @{ e4 f g a @} @}
945   \new Voice = "2" @{ \voiceTwo \relative c' @{ c4 d e f @} @}
946 >>
947 @end example
948
949 Both of the above would produce
950
951 @c The following example should not display the code
952 @lilypond[ragged-right,quote]
953 \new Staff <<
954   \new Voice = "1" { \voiceOne \relative c' { e4 f g a } }
955   \new Voice = "2" { \voiceTwo \relative c' { c4 d e f } }
956 >>
957 @end lilypond
958
959 The @code{\voiceXXX} commands set the direction of stems, slurs,
960 ties, articulations, text annotations, augmentation dots of dotted
961 notes, and fingerings.  @code{\voiceOne} and @code{\voiceThree}
962 make these objects point upwards, while @code{\voiceTwo} and
963 @code{\voiceFour} make them point downwards.  These commands also
964 generate a horizontal shift for each voice when this is required
965 to avoid clashes of note heads.  The command @code{\oneVoice}
966 reverts the settings back to the normal values for a single voice.
967
968 Let us see in some simple examples exactly what effect
969 @code{\oneVoice}, @code{\voiceOne} and @code{voiceTwo} have on
970 markup, ties, slurs, and dynamics:
971
972 @lilypond[quote,ragged-right,verbatim]
973 \relative c'{
974   % Default behavior or behavior after \oneVoice
975   c d8 ~ d e4 ( f g a ) b-> c
976 }
977 @end lilypond
978
979 @lilypond[quote,ragged-right,verbatim]
980 \relative c'{
981   \voiceOne
982   c d8 ~ d e4 ( f g a ) b-> c
983   \oneVoice
984   c, d8 ~ d e4 ( f g a ) b-> c
985 }
986 @end lilypond
987
988 @lilypond[quote,ragged-right,verbatim]
989 \relative c'{
990   \voiceTwo
991   c d8 ~ d e4 ( f g a ) b-> c
992   \oneVoice
993   c, d8 ~ d e4 ( f g a ) b-> c
994 }
995 @end lilypond
996
997 Now let's look at three different ways to notate the same passage
998 of polyphonic music, each of which is advantageous in different
999 circumstances, using the example from the previous section.
1000
1001 An expression that appears directly inside a @code{<< >>} belongs
1002 to the main voice (but, note, @strong{not} in a @code{<< \\ >>}
1003 construct).  This is useful when extra voices appear while the
1004 main voice is playing.  Here is a more correct rendition of our
1005 example.  The red diamond-shaped notes
1006 demonstrate that the main melody is now in a single voice context,
1007 permitting a phrasing slur to be drawn over them.
1008
1009 @lilypond[quote,ragged-right,verbatim]
1010 \new Staff \relative c' {
1011   \voiceOneStyle
1012   % The following notes are monophonic
1013   c16^( d e f
1014   % Start simultaneous section of three voices
1015   <<
1016     % Continue the main voice in parallel
1017     { g4 f e | d2 e2) }
1018     % Initiate second voice
1019     \new Voice {
1020       % Set stems, etc, down
1021       \voiceTwo
1022       r8 e4 d c8 ~ | c8 b16 a b8 g ~ g2
1023     }
1024     % Initiate third voice
1025     \new Voice {
1026       % Set stems, etc, up
1027       \voiceThree
1028       s2. | s4 b4 c2
1029     }
1030   >>
1031 }
1032 @end lilypond
1033
1034 @cindex nesting music expressions
1035 @cindex nesting simultaneous constructs
1036
1037 @cindex voices, temporary
1038 @cindex voices, nesting
1039
1040 More deeply nested polyphony constructs are possible, and if a
1041 voice appears only briefly this might be a more natural way to
1042 typeset the music:
1043
1044 @lilypond[quote,ragged-right,verbatim]
1045 \new Staff \relative c' {
1046   c16^( d e f
1047   <<
1048     { g4 f e | d2 e2) }
1049     \new Voice {
1050       \voiceTwo
1051       r8 e4 d c8 ~ |
1052       <<
1053         {c8 b16 a b8 g ~ g2}
1054         \new Voice {
1055           \voiceThree
1056           s4 b4 c2
1057         }
1058       >>
1059     }
1060   >>
1061 }
1062 @end lilypond
1063
1064 @cindex spacing notes
1065
1066 This method of nesting new voices briefly is useful
1067 when only small sections of the music
1068 are polyphonic, but when the whole staff is largely polyphonic
1069 it can be clearer to use multiple voices throughout, using
1070 spacing notes to step over sections where the voice is silent,
1071 as here:
1072
1073 @lilypond[quote,ragged-right,verbatim]
1074 \new Staff \relative c' <<
1075   % Initiate first voice
1076   \new Voice {
1077     \voiceOne
1078     c16^( d e f g4 f e | d2 e2) |
1079   }
1080   % Initiate second voice
1081   \new Voice {
1082     % Set stems, etc, down
1083     \voiceTwo
1084     s4 r8 e4 d c8 ~ | c8 b16 a b8 g ~ g2 |
1085   }
1086   % Initiate third voice
1087   \new Voice {
1088     % Set stems, etc, up
1089     \voiceThree
1090     s1 | s4 b4 c2 |
1091   }
1092 >>
1093 @end lilypond
1094
1095 @subsubheading Note columns
1096
1097 @cindex note column
1098 @cindex shift commands
1099 @funindex \shiftOff
1100 @funindex \shiftOn
1101 @funindex \shiftOnn
1102 @funindex \shiftOnnn
1103
1104 Closely spaced notes in a chord, or notes occurring at the same
1105 time in different voices, are arranged in two, occasionally more,
1106 columns to prevent the note heads overlapping.  These are called
1107 note columns.  There are separate columns for each voice, and
1108 the currently specified voice-dependent shift is applied to the
1109 note column if there would otherwise be a collision.  This can
1110 be seen in the example above.  In bar 2 the C in voice two is
1111 shifted to the right relative to the D in voice one, and in the
1112 final chord the C in voice three is also shifted to the right
1113 relative to the other notes.
1114
1115 The @code{\shiftOn}, @code{\shiftOnn}, @code{\shiftOnnn}, and
1116 @code{\shiftOff} commands specify the degree to which notes and
1117 chords of the voice should be shifted if a collision
1118 would otherwise occur. By default, the outer voices (normally
1119 voices one and two) have @code{\shiftOff} specified, while the
1120 inner voices (three and four) have @code{\shiftOn} specified.
1121 When a shift is applied, Voices one and three are shifted to
1122 the right and voices two and four to the left.
1123
1124 @code{\shiftOnn} and @code{\shiftOnnn} define further shift
1125 levels which may be specified temporarily to resolve collisions
1126 in complex situations -- see @ref{Real music example}.
1127
1128 A note column can contain just one note (or chord) from a voice
1129 with stems up and one note (or chord) from a voice with stems
1130 down.  If notes from two voices which have their stems in the
1131 same direction are placed at the same position and both voices
1132 have no shift or the same shift specified, the error message
1133 @qq{Too many clashing note columns} will be produced.
1134
1135 @seealso
1136
1137 Notation Reference: @ruser{Multiple voices}.
1138
1139
1140 @node Voices and vocals
1141 @subsection Voices and vocals
1142
1143 Vocal music presents a special difficulty: we need to combine two
1144 expressions -- notes and lyrics.
1145
1146 @funindex \new Lyrics
1147 @funindex \lyricsto
1148 @cindex Lyrics context, creating
1149 @cindex lyrics, linking to voice
1150
1151 You have already seen the @code{\addlyrics@{@}} command, which
1152 handles simple scores well.  However, this technique is
1153 quite limited.  For more complex music, you must introduce the
1154 lyrics in a @code{Lyrics} context using @code{\new Lyrics} and
1155 explicitly link
1156 the lyrics to the notes with @code{\lyricsto@{@}}, using the
1157 name assigned to the Voice.
1158
1159 @lilypond[quote,verbatim,fragment]
1160 <<
1161   \new Voice = "one" \relative c'' {
1162     \autoBeamOff
1163     \time 2/4
1164     c4 b8. a16 g4. f8 e4 d c2
1165   }
1166   \new Lyrics \lyricsto "one" {
1167     No more let sins and sor -- rows grow.
1168   }
1169 >>
1170 @end lilypond
1171
1172 Note that the lyrics must be linked to a @code{Voice} context,
1173 @emph{not} a @code{Staff} context.  This is a case where it is
1174 necessary to create @code{Staff} and @code{Voice} contexts
1175 explicitly.
1176
1177 @cindex lyrics and beaming
1178 @cindex beaming and lyrics
1179 @funindex \autoBeamOff
1180
1181 The automatic beaming which LilyPond uses by default works well
1182 for instrumental music, but not so well for music with lyrics,
1183 where beaming is either not required at all or is used to indicate
1184 melismata in the lyrics.  In the example above we use the command
1185 @code{\autoBeamOff} to turn off the automatic beaming.
1186
1187 @funindex \new ChoirStaff
1188 @funindex \lyricmode
1189 @cindex vocal score structure
1190
1191 Let us reuse the earlier example from Judas Maccabæus to
1192 illustrate this more flexible technique.  We first recast
1193 it to use variables so the music and lyrics can be separated
1194 from the staff structure.  We also introduce a ChoirStaff
1195 bracket.  The lyrics themselves must be introduced with
1196 @code{\lyricmode} to ensure they are interpreted as lyrics
1197 rather than music.
1198
1199 @lilypond[quote,verbatim]
1200 global = { \time 6/8 \partial 8 \key f \major}
1201 SopOneMusic = \relative c'' {
1202   c8 | c([ bes)] a a([ g)] f | f'4. b, | c4.~ c4 }
1203 SopTwoMusic = \relative c' {
1204   r8 | r4. r4 c8 | a'([ g)] f f([ e)] d | e([ d)] c bes' }
1205 SopOneLyrics = \lyricmode {
1206   Let | flee -- cy flocks the | hills a -- dorn, __ }
1207 SopTwoLyrics = \lyricmode {
1208   Let | flee -- cy flocks the | hills a -- dorn, }
1209
1210 \score {
1211   \new ChoirStaff <<
1212     \new Staff <<
1213       \new Voice = "SopOne" {
1214         \global
1215         \SopOneMusic
1216       }
1217       \new Lyrics \lyricsto "SopOne" {
1218         \SopOneLyrics
1219       }
1220     >>
1221     \new Staff <<
1222       \new Voice = "SopTwo" {
1223         \global
1224         \SopTwoMusic
1225       }
1226       \new Lyrics \lyricsto "SopTwo" {
1227         \SopTwoLyrics
1228       }
1229     >>
1230   >>
1231 }
1232 @end lilypond
1233
1234 This is the basic structure of all vocal scores.  More staves may
1235 be added as required, more voices may be added to the staves,
1236 more verses may be added to the lyrics,
1237 and the variables containing the music can easily be placed
1238 in separate files should they become too long.
1239
1240 @cindex hymn structure
1241
1242 Here is a example of the first line of a hymn with four
1243 verses, set for SATB.  In this case the words for all four
1244 parts are the same.  Note how we use variables to separate the
1245 music notation and words from the staff structure.  See too
1246 how a variable, which we have chosen to call @q{TimeKey}, is used
1247 to hold several commands for use within the two staves.  In other
1248 examples this is often called @q{global}.
1249
1250 @lilypond[quote,verbatim]
1251 TimeKey = { \time 4/4 \partial 4 \key c \major}
1252 SopMusic   = \relative c' { c4 | e4. e8 g4  g  | a a g }
1253 AltoMusic  = \relative c' { c4 | c4. c8 e4  e  | f f e }
1254 TenorMusic = \relative c  { e4 | g4. g8 c4. b8 | a8 b c d e4 }
1255 BassMusic  = \relative c  { c4 | c4. c8 c4  c  | f8 g a b c4 }
1256 VerseOne   = \lyricmode {
1257   E -- | ter -- nal fa -- ther, | strong to save, }
1258 VerseTwo   = \lyricmode {
1259   O | Christ, whose voice the | wa -- ters heard, }
1260 VerseThree = \lyricmode {
1261   O | Ho -- ly Spi -- rit, | who didst brood }
1262 VerseFour  = \lyricmode {
1263   O | Tri -- ni -- ty of | love and pow'r }
1264
1265 \score {
1266   \new ChoirStaff <<
1267     \new Staff <<
1268       \clef "treble"
1269       \new Voice = "Sop"  { \voiceOne \TimeKey \SopMusic }
1270       \new Voice = "Alto" { \voiceTwo \AltoMusic }
1271       \new Lyrics \lyricsto "Sop" { \VerseOne   }
1272       \new Lyrics \lyricsto "Sop" { \VerseTwo   }
1273       \new Lyrics \lyricsto "Sop" { \VerseThree }
1274       \new Lyrics \lyricsto "Sop" { \VerseFour  }
1275     >>
1276     \new Staff <<
1277       \clef "bass"
1278       \new Voice = "Tenor" { \voiceOne \TimeKey \TenorMusic }
1279       \new Voice = "Bass"  { \voiceTwo \BassMusic  }
1280     >>
1281   >>
1282 }
1283 @end lilypond
1284
1285 @cindex verse and refrain
1286
1287 We end with an example to show how we might code a solo verse which
1288 continues into a two-part refrain in two staves.  The
1289 positioning of the sequential and simultaneous sections to achieve
1290 this within a single score is quite tricky, so follow the
1291 explanation carefully!
1292
1293 Let's start with a score block containing a @code{ChoirStaff}, as
1294 we would like the brace to appear at the start of the chorus.
1295 Normally you would need angle brackets after @code{\new ChoirStaff}
1296 to bring in all the staves in parallel, but here we want to
1297 defer the parallelism during the solo so we use braces, although
1298 angle brackets here wouldn't hurt.  Inside the @code{ChoirStaff} we
1299 want first the staff which will contain the verse.  This must
1300 contain notes and lyrics in parallel, so here we need angle
1301 brackets around the @code{\new Voice} and @code{\new Lyrics} to
1302 start them at the same time:
1303
1304 @lilypond[quote,verbatim,ragged-right]
1305 versenotes = \relative c'' {
1306   \clef "treble"
1307   \key g \major
1308   \time 3/4 g g g b b b
1309 }
1310 versewords = \lyricmode {
1311   One two three four five six
1312 }
1313 \score {
1314   \new Choirstaff {
1315     \new Staff <<
1316       \new Voice = "verse" {
1317         \versenotes \break
1318       }
1319       \new Lyrics \lyricsto verse {
1320         \versewords
1321       }
1322     >>
1323   }
1324 }
1325 @end lilypond
1326
1327 That gives the verse line.
1328
1329 Now we want to continue with refrainA on the same staff while a
1330 second staff is introduced in parallel with it for refrainB, so
1331 this is a parallel section which must be positioned immediately
1332 following the @code{\break} in the verse Voice.  Yes, @emph{within}
1333 the verse Voice!  Here's that parallel section.  More staves
1334 could be introduced here in the same way.
1335
1336 @example
1337 <<
1338   \refrainnotesA
1339   \new Lyrics \lyricsto verse @{
1340     \refrainwordsA
1341   @}
1342   \new Staff <<
1343     \new Voice = "refrainB" @{
1344       \refrainnotesB
1345     @}
1346     \new Lyrics \lyricsto "refrainB" @{
1347       \refrainwordsB
1348     @}
1349   >>
1350 >>
1351 @end example
1352
1353 Here's the final result with two staves in the chorus showing
1354 how the parallel section is positioned within the verse Voice:
1355
1356 @lilypond[quote,verbatim, ragged-right]
1357 versenotes = \relative c'' {
1358   \clef "treble"
1359   \key g \major
1360   \time 3/4 g g g b b b
1361 }
1362 refrainnotesA = \relative c'' {
1363   \time 2/4
1364   c c g g \bar "|."
1365 }
1366 refrainnotesB = \relative c {
1367   \clef "bass"
1368   \key g \major
1369   c e d d
1370 }
1371 versewords = \lyricmode {
1372   One two three four five six
1373 }
1374 refrainwordsA = \lyricmode {
1375   la la la la
1376 }
1377 refrainwordsB = \lyricmode {
1378   dum dum dum dum
1379 }
1380 \score {
1381   \new ChoirStaff {
1382     \new Staff <<
1383       \new Voice = "verse" {
1384         \versenotes \break
1385         <<
1386           \refrainnotesA
1387           \new Lyrics \lyricsto "verse" {
1388             \refrainwordsA
1389           }
1390           \new Staff <<
1391             \new Voice = "refrainB" {
1392               \refrainnotesB
1393             }
1394             \new Lyrics \lyricsto "refrainB" {
1395               \refrainwordsB
1396             }
1397           >>
1398         >>
1399       }
1400       \new Lyrics \lyricsto "verse" {
1401         \versewords
1402       }
1403     >>
1404   }
1405 }
1406 @end lilypond
1407
1408 @cindex book, example of using
1409 @funindex \book
1410
1411 However, although this is an interesting and useful exercise to
1412 help you to understand how sequential and simultaneous blocks work,
1413 in practice one would perhaps choose to code this as two
1414 @code{\score} blocks within an implicit @code{\book} block, as
1415 follows:
1416
1417 @lilypond[quote,verbatim,ragged-right]
1418 versenotes = \relative c'' {
1419   \clef "treble"
1420   \key g \major
1421   \time 3/4 g g g b b b
1422 }
1423 refrainnotesA = \relative c'' {
1424   \time 2/4
1425   c c g g \bar "|."
1426 }
1427 refrainnotesB = \relative c {
1428   \clef "bass"
1429   \key g \major
1430   c e d d
1431 }
1432 versewords = \lyricmode {
1433   One two three four five six
1434 }
1435 refrainwordsA = \lyricmode {
1436   la la la la
1437 }
1438 refrainwordsB = \lyricmode {
1439   dum dum dum dum
1440 }
1441 \score {
1442   \new Staff <<
1443     \new Voice = "verse" {
1444       \versenotes
1445     }
1446     \new Lyrics \lyricsto "verse" {
1447       \versewords
1448     }
1449   >>
1450 }
1451
1452 \score {
1453   \new ChoirStaff <<
1454     \new Staff <<
1455       \new Voice = "refrainA" {
1456         \refrainnotesA
1457       }
1458       \new Lyrics \lyricsto "refrainA" {
1459         \refrainwordsA
1460       }
1461     >>
1462     \new Staff <<
1463       \new Voice = "refrainB" {
1464         \refrainnotesB
1465       }
1466       \new Lyrics \lyricsto "refrainB" {
1467         \refrainwordsB
1468       }
1469     >>
1470   >>
1471 }
1472 @end lilypond
1473
1474 @seealso
1475
1476 Notation Reference: @ruser{Vocal music}.
1477
1478
1479 @node Contexts and engravers
1480 @section Contexts and engravers
1481
1482 Contexts and engravers have been mentioned informally
1483 in earlier sections; we now must look at
1484 these concepts in more detail, as they are important
1485 in the fine-tuning of LilyPond output.
1486
1487
1488 @menu
1489 * Contexts explained::
1490 * Creating contexts::
1491 * Engravers explained::
1492 * Modifying context properties::
1493 * Adding and removing engravers::
1494 @end menu
1495
1496 @node Contexts explained
1497 @subsection Contexts explained
1498
1499 @cindex contexts explained
1500
1501 When music is printed, many notational elements which do not
1502 appear explicitly in the input file must be added to the
1503 output.  For example, compare the input and output of the
1504 following example:
1505
1506 @lilypond[quote,verbatim,relative=2,fragment]
1507 cis4 cis2. g4
1508 @end lilypond
1509
1510 The input is rather sparse, but in the output, bar lines,
1511 accidentals, clef, and time signature have been added.  When
1512 LilyPond @emph{interprets} the input the musical information
1513 is inspected in time order, similar to reading a score from left
1514 to right.  While reading the input, the program remembers where
1515 measure boundaries are, and which pitches require explicit
1516 accidentals.  This information must be held on several levels.
1517 For example, the effect of an accidental is limited
1518 to a single staff, while a bar line must be synchronized across
1519 the entire score.
1520
1521 Within LilyPond, these rules and bits of information are grouped
1522 in @emph{Contexts}.  We have already met the
1523 @code{Voice} context.
1524 Others are the @code{Staff} and @code{Score} contexts.
1525 Contexts are hierarchical to reflect the hierarchical nature of
1526 a musical score.
1527 For example: a @code{Staff} context can contain many
1528 @code{Voice} contexts, and a @code{Score} context can
1529 contain many @code{Staff} contexts.
1530
1531 @quotation
1532 @sourceimage{context-example,5cm,,}
1533 @end quotation
1534
1535 Each context has the responsibility for enforcing some notation rules,
1536 creating some notation objects and maintaining the associated
1537 properties.  For example, the @code{Voice} context may introduce an
1538 accidental and then the @code{Staff} context maintains the rule to
1539 show or suppress the accidental for the remainder of the measure.
1540
1541 As another example, the synchronization of bar lines is, by default,
1542 handled in the @code{Score} context.
1543 However, in some music we may not want the bar lines to be
1544 synchronized -- consider a polymetric score in 4/4 and 3/4 time.
1545 In such cases, we must modify the default settings of the
1546 @code{Score} and @code{Staff} contexts.
1547
1548 For very simple scores, contexts are created implicitly, and you need
1549 not be aware of them.  For larger pieces, such as anything with more
1550 than one staff, they must be
1551 created explicitly to make sure that you get as many staves as you
1552 need, and that they are in the correct order.  For typesetting pieces
1553 with specialized notation, it is usual to modify existing, or
1554 even to define totally new, contexts.
1555
1556 In addition to the @code{Score,} @code{Staff} and
1557 @code{Voice} contexts there are contexts which fit between
1558 the score and staff levels to control staff groups, such as the
1559 @code{PianoStaff} and @code{ChoirStaff} contexts.  There
1560 are also alternative staff and voice contexts, and contexts for
1561 lyrics, percussion, fret boards, figured bass, etc.
1562
1563 The names of all context types are formed from one or more
1564 words, each word being capitalized and joined immediately to the
1565 preceding word with no hyphen or underscore, e.g.,
1566 @code{GregorianTranscriptionStaff}.
1567
1568 @seealso
1569
1570 Notation Reference: @ruser{Contexts explained}.
1571
1572
1573 @node Creating contexts
1574 @subsection Creating contexts
1575
1576 @funindex \new
1577 @cindex new contexts
1578 @cindex creating contexts
1579 @cindex contexts, creating
1580
1581 There can be only one top level context: the
1582 @code{Score}
1583 context.  This is created with the @code{\score} command,
1584 or, in simple scores, it is created automatically.
1585
1586 For scores with only one voice and one staff, the
1587 @code{Voice} and @code{Staff} contexts may be left to be
1588 created automatically, but for more complex scores it is
1589 necessary to create them by hand.
1590 The simplest command that does this is @code{\new}.
1591 It is prepended to a music expression, for example
1592
1593 @example
1594 \new @var{type} @var{music-expression}
1595 @end example
1596
1597 @noindent
1598 where @var{type} is a context name (like @code{Staff} or
1599 @code{Voice}).  This command creates a new context, and starts
1600 interpreting the @var{music-expression} within that context.
1601
1602 Note that there is no @code{\new Score} command;
1603 the single top-level @code{Score} context is introduced
1604 with @code{\score}.
1605
1606 You have seen many practical examples which created new
1607 @code{Staff} and @code{Voice} contexts in earlier sections, but
1608 to remind you how these commands are used in practice, here's an
1609 annotated real-music example:
1610
1611 @lilypond[quote,verbatim,ragged-right]
1612 \score {  % start of single compound music expression
1613   <<  % start of simultaneous staves section
1614     \time 2/4
1615     \new Staff {  % create RH staff
1616       \key g \minor
1617       \clef "treble"
1618       \new Voice {  % create voice for RH notes
1619         \relative c'' {  % start of RH notes
1620           d4 ees16 c8. |
1621           d4 ees16 c8. |
1622         }  % end of RH notes
1623       }  % end of RH voice
1624     }  % end of RH staff
1625     \new Staff <<  % create LH staff; needs two simultaneous voices
1626       \key g \minor
1627       \clef "bass"
1628       \new Voice {  % create LH voice one
1629         \voiceOne
1630         \relative g {  % start of LH voice one notes
1631           g8 <bes d> ees, <g c> |
1632           g8 <bes d> ees, <g c> |
1633         }  % end of LH voice one notes
1634       }  % end of LH voice one
1635       \new Voice {  % create LH voice two
1636         \voiceTwo
1637         \relative g {  % start of LH voice two notes
1638           g4 ees |
1639           g4 ees |
1640         }  % end of LH voice two notes
1641       }  % end of LH voice two
1642     >>  % end of LH staff
1643   >>  % end of simultaneous staves section
1644 }  % end of single compound music expression
1645 @end lilypond
1646
1647 (Note how all the statements which open a block with either a
1648 curly bracket, @code{@{}, or double angle brackets, @code{<<},
1649 are indented by two further spaces, and the corresponding
1650 closing bracket is indented by exactly the same amount.  While
1651 this is not required, following this practice will greatly
1652 reduce the number of @q{unmatched bracket} errors, and is
1653 strongly recommended.  It enables the structure of the music to
1654 be seen at a glance, and any unmatched brackets will be obvious.
1655 Note too how the LH staff is created using double angle brackets
1656 because it requires two voices for its music, whereas the RH staff
1657 is created with a single music expression surrounded by curly
1658 brackets because it requires only one voice.)
1659
1660 @cindex contexts, naming
1661 @cindex naming contexts
1662
1663 The @code{\new} command may also give a identifying name to the
1664 context to distinguish it from other contexts of the same type,
1665
1666 @example
1667 \new @var{type} = @var{id} @var{music-expression}
1668 @end example
1669
1670 Note the distinction between the name of the context type,
1671 @code{Staff}, @code{Voice}, etc, and the identifying name of a
1672 particular instance of that type, which can be any sequence of letters
1673 and digits invented by the user.  The identifying name is used to
1674 refer back to that particular instance of a context.  We saw this in
1675 use in the section on lyrics, see @ref{Voices and vocals}.
1676
1677 @seealso
1678
1679 Notation Reference: @ruser{Creating contexts}.
1680
1681
1682 @node Engravers explained
1683 @subsection Engravers explained
1684
1685 @cindex engravers
1686
1687 Every mark on the printed output of a score produced by LilyPond
1688 is produced by an @code{Engraver}.  Thus there is an engraver
1689 to print staves, one to print note heads, one for stems, one for
1690 beams, etc, etc.  In total there are over 120 such engravers!
1691 Fortunately, for most scores it is not necessary to know about
1692 more than a few, and for simple scores you do not need to know
1693 about any.
1694
1695 Engravers live and operate in Contexts.
1696 Engravers such as the @code{Metronome_mark_engraver}, whose
1697 action and output applies to the score as a whole, operate in
1698 the highest level context -- the @code{Score} context.
1699
1700 The @code{Clef_engraver} and @code{Key_engraver} are to be
1701 found in every Staff Context, as different staves may require
1702 different clefs and keys.
1703
1704 The @code{Note_heads_engraver} and @code{Stem_engraver} live
1705 in every @code{Voice} context, the lowest level context of all.
1706
1707 Each engraver processes the particular objects associated
1708 with its function, and maintains the properties that relate
1709 to that function.  These properties, like the properties
1710 associated with contexts, may be modified to change the
1711 operation of the engraver or the appearance of those elements
1712 in the printed score.
1713
1714 Engravers all have compound names formed from words which
1715 describe their function.  Just the first word is capitalized,
1716 and the remainder are joined to it with underscores.  Thus
1717 the @code{Staff_symbol_engraver} is responsible for creating the
1718 lines of the staff, the @code{Clef_engraver} determines and sets
1719 the pitch reference point on the staff by drawing a clef symbol.
1720
1721 Here are some of the most common engravers together with their
1722 function.  You will see it is usually easy to guess the function
1723 from the name, or vice versa.
1724
1725 @multitable @columnfractions .3 .7
1726 @headitem Engraver
1727   @tab Function
1728 @item Accidental_engraver
1729   @tab Makes accidentals, cautionary and suggested accidentals
1730 @item Beam_engraver
1731   @tab Engraves beams
1732 @item Clef_engraver
1733   @tab Engraves clefs
1734 @item Completion_heads_engraver
1735   @tab Splits notes which cross bar lines
1736 @c The old Dynamic_engraver is deprecated. -jm
1737 @item New_dynamic_engraver
1738   @tab Creates hairpins and dynamic texts
1739 @item Forbid_line_break_engraver
1740   @tab Prevents line breaks if a musical element is still active
1741 @item Key_engraver
1742   @tab Creates the key signature
1743 @item Metronome_mark_engraver
1744   @tab Engraves metronome marking
1745 @item Note_heads_engraver
1746   @tab Engraves note heads
1747 @item Rest_engraver
1748   @tab Engraves rests
1749 @item Staff_symbol_engraver
1750   @tab Engraves the five (by default) lines of the staff
1751 @item Stem_engraver
1752   @tab Creates stems and single-stem tremolos
1753 @item Time_signature_engraver
1754   @tab Creates time signatures
1755 @end multitable
1756
1757 @smallspace
1758
1759 We shall see later how the output of LilyPond can be changed
1760 by modifying the action of Engravers.
1761
1762 @seealso
1763
1764 Internals reference: @rinternals{Engravers and performers}.
1765
1766
1767 @node Modifying context properties
1768 @subsection Modifying context properties
1769
1770 @cindex context properties
1771 @cindex context properties, modifying
1772 @cindex modifying context properties
1773 @funindex \set
1774 @funindex \unset
1775
1776 Contexts are responsible for holding the values of a number of
1777 context @emph{properties}.  Many of them can be changed to
1778 influence the interpretation of the input and so change the
1779 appearance of the output.  They are changed by the
1780 @code{\set} command.  This takes the form
1781
1782 @example
1783 \set @emph{ContextName}.@emph{propertyName} = #@emph{value}
1784 @end example
1785
1786 Where the @emph{ContextName} is usually @code{Score},
1787 @code{Staff} or @code{Voice}.  It may be omitted,
1788 in which case @code{Voice} is assumed.
1789
1790 The names of context properties consist of words joined
1791 together with no hyphens or underscores, all except the
1792 first having a capital letter.  Here are a few examples
1793 of some commonly used ones.  There are many more.
1794
1795 @c attempt to force this onto a new page
1796 @need 50
1797 @multitable @columnfractions .25 .15 .45 .15
1798 @headitem propertyName
1799   @tab Type
1800   @tab Function
1801   @tab Example Value
1802 @item extraNatural
1803   @tab Boolean
1804   @tab If true, set extra natural signs before accidentals
1805   @tab @code{#t}, @code{#f}
1806 @item currentBarNumber
1807   @tab Integer
1808   @tab Set the current bar number
1809   @tab @code{50}
1810 @item doubleSlurs
1811   @tab Boolean
1812   @tab If true, print slurs both above and below notes
1813   @tab @code{#t}, @code{#f}
1814 @item instrumentName
1815   @tab Text
1816   @tab Set the name to be placed at the start of the staff
1817   @tab @code{"Cello I"}
1818 @item fontSize
1819   @tab Real
1820   @tab Increase or decrease the font size
1821   @tab @code{2.4}
1822 @item stanza
1823   @tab Text
1824   @tab Set the text to print before the start of a verse
1825   @tab @code{"2"}
1826 @end multitable
1827
1828 @noindent
1829 where a Boolean is either True (@code{#t}) or False (@code{#f}),
1830 an Integer is a positive whole number, a Real is a positive
1831 or negative decimal number, and text is enclosed in double
1832 apostrophes.  Note the occurrence of hash signs,
1833 (@code{#}), in two different places -- as part of the Boolean
1834 value before the @code{t} or @code{f}, and before @emph{value}
1835 in the @code{\set} statement.  So when a Boolean is being
1836 entered you need to code two hash signs, e.g., @code{##t}.
1837
1838 Before we can set any of these properties we need to know
1839 in which context they operate.  Sometimes this is obvious,
1840 but occasionally it can be tricky.  If the wrong context
1841 is specified, no error message is produced, but the expected
1842 action will not take place.  For example, the
1843 @code{instrumentName} clearly lives in the Staff context, since
1844 it is the staff that is to be named.
1845 In this example the first staff is labelled, but not the second,
1846 because we omitted the context name.
1847
1848 @lilypond[quote,verbatim,ragged-right]
1849 <<
1850   \new Staff \relative c'' {
1851     \set Staff.instrumentName = #"Soprano"
1852     c4 c
1853  }
1854   \new Staff \relative c' {
1855   \set instrumentName = #"Alto"  % Wrong!
1856   d4 d
1857  }
1858 >>
1859 @end lilypond
1860
1861 Remember the default context name is Voice, so the second
1862 @code{\set} command set the property @code{instrumentName} in the
1863 Voice context to @qq{Alto}, but as LilyPond does not look
1864 for any such property in the @code{Voice} context, no
1865 further action took place.  This is not an error, and no error
1866 message is logged in the log file.
1867
1868 Similarly, if the property name is mis-spelt no error message is
1869 produced, and clearly the expected action cannot be performed.  If
1870 fact, you can set any (fictitious) @q{property} using any name you
1871 like in any context that exists by using the @code{\set} command.  But
1872 if the name is not known to LilyPond it will not cause any action to
1873 be taken.  Some text editors with special support for LilyPond input
1874 files document property names with bullets when you hover them with
1875 the mouse, like JEdit with LilyPondTool, or highlight unknown property
1876 names differently, like ConTEXT.  If you do not use an editor with
1877 such features, it is recommended to check the property name in the
1878 Internals Reference: see @rinternals{Tunable context properties}, or
1879 @rinternals{Contexts}.
1880
1881 The @code{instrumentName} property will take effect only
1882 if it is set in the @code{Staff} context, but
1883 some properties can be set in more than one context.
1884 For example, the property @code{extraNatural} is by
1885 default set to ##t (true) for all staves.
1886 If it is set to ##f (false) in one particular @code{Staff}
1887 context it applies just to the accidentals on that staff.
1888 If it is set to false in the @code{Score} context
1889 it applies to all staves.
1890
1891 So this turns off extra naturals in one staff:
1892
1893 @lilypond[quote,verbatim,ragged-right]
1894 <<
1895   \new Staff \relative c'' {
1896     ais4 aes
1897  }
1898   \new Staff \relative c'' {
1899     \set Staff.extraNatural = ##f
1900     ais4 aes
1901  }
1902 >>
1903 @end lilypond
1904
1905 @noindent
1906 and this turns them off in all staves:
1907
1908 @lilypond[quote,verbatim,ragged-right]
1909 <<
1910   \new Staff \relative c'' {
1911     ais4 aes
1912  }
1913   \new Staff \relative c'' {
1914     \set Score.extraNatural = ##f
1915     ais4 aes
1916  }
1917 >>
1918 @end lilypond
1919
1920 As another example, if @code{clefOctavation} is set in
1921 the @code{Score} context this immediately changes the value
1922 of the octavation in all current staves and sets a new default
1923 value which will be applied to all staves.
1924
1925 The opposite command, @code{\unset}, effectively removes the
1926 property from the context, which causes most properties to
1927 revert to their default value.  Usually @code{\unset} is not
1928 required as a new @code{\set} command will achieve what is
1929 wanted.
1930
1931 The @code{\set} and @code{\unset} commands can appear anywhere
1932 in the input file and will take effect from the time they are
1933 encountered until the end of the score or until the property is
1934 @code{\set} or @code{\unset} again.  Let's try changing the
1935 font size, which affects the size of the note heads (among
1936 other things) several times.  The change is from the default
1937 value, not the most recently set value.
1938
1939 @lilypond[quote,verbatim,ragged-right,relative=1,fragment]
1940 c4
1941 % make note heads smaller
1942 \set fontSize = #-4
1943 d e
1944 % make note heads larger
1945 \set fontSize = #2.5
1946 f g
1947 % return to default size
1948 \unset fontSize
1949 a b
1950 @end lilypond
1951
1952 We have now seen how to set the values of several different types of
1953 property.  Note that integers and numbers are always preceded by a
1954 hash sign, @code{#}, while a true or false value is specified by
1955 @code{##t} and @code{##f}, with two hash signs.  A text property
1956 should be enclosed in double quotation signs, as above, although we
1957 shall see later that text can actually be specified in a much more
1958 general way by using the very powerful @code{markup} command.
1959
1960
1961 @funindex \with
1962 @cindex context properties, setting with \with
1963
1964 Context properties may also be set at the time the context is
1965 created.  Sometimes this is a clearer way of specifying a
1966 property value if it is to remain fixed for the duration of
1967 the context.  When a context is created with a @code{\new}
1968 command it may be followed immediately by a
1969 @code{\with @{ .. @}} block in which the property values are
1970 set.  For example, if we wish to suppress the printing of
1971 extra naturals for the duration of a staff we would write:
1972
1973 @example
1974 \new Staff \with @{ extraNatural = ##f @}
1975 @end example
1976
1977 @noindent
1978 like this:
1979
1980 @lilypond[quote,verbatim,ragged-right]
1981 <<
1982   \new Staff
1983   \relative c'' {
1984     gis ges aes ais
1985   }
1986   \new Staff \with { extraNatural = ##f }
1987   \relative c'' {
1988     gis ges aes ais
1989   }
1990 >>
1991 @end lilypond
1992
1993 Properties set in this way may still be changed dynamically using
1994 @code{\set} and returned to their default value with @code{\unset}.
1995
1996 The @code{fontSize} property is treated differently.  If this is
1997 set in a @code{\with} clause it effectively resets the default
1998 value of the font size.  If it is later changed with @code{\set},
1999 this new default value may be restored with the
2000 @code{\unset fontSize} command.
2001
2002 @seealso
2003
2004 Notation Reference: @ruser{Changing context default settings},
2005 @ruser{The set command}.
2006
2007 Internals Reference: @rinternals{Contexts},
2008 @rinternals{Tunable context properties}.
2009
2010
2011 @node Adding and removing engravers
2012 @subsection Adding and removing engravers
2013
2014 @cindex engravers, adding
2015 @cindex engravers, removing
2016
2017 @funindex \consists
2018 @funindex \remove
2019
2020 We have seen that contexts each contain several engravers, each
2021 of which is responsible for producing a particular part of the
2022 output, like bar lines, staves, note heads, stems, etc.  If an
2023 engraver is removed from a context, it can no longer produce its
2024 output.  This is a crude way of modifying the output, but it
2025 can sometimes be useful.
2026
2027 @subsubheading Changing a single context
2028
2029 To remove an engraver from a single context we use the
2030 @code{\with} command placed immediately after the context creation
2031 command, as in the previous section.
2032
2033 As an illustration, let's repeat an example from the previous section
2034 with the staff lines removed.  Remember that the staff lines are
2035 produced by the @code{Staff_symbol_engraver}.
2036
2037 @lilypond[quote,verbatim,ragged-right]
2038 \new Staff \with {
2039   \remove Staff_symbol_engraver
2040 }
2041 \relative c' {
2042   c4
2043   \set fontSize = #-4  % make note heads smaller
2044   d e
2045   \set fontSize = #2.5  % make note heads larger
2046   f g
2047   \unset fontSize  % return to default size
2048   a b
2049 }
2050 @end lilypond
2051
2052 @cindex ambitus engraver
2053
2054 Engravers can also be added to individual contexts.
2055 The command to do this is
2056
2057 @code{\consists @var{Engraver_name}},
2058
2059 @noindent
2060 placed inside a @code{\with} block.  Some vocal scores have an ambitus
2061 placed at the beginning of a staff to indicate the range of notes in
2062 that staff -- see @rglos{ambitus}.  The ambitus is produced by the
2063 @code{Ambitus_engraver}, which is not normally included in any
2064 context.  If we add it to the @code{Voice} context, it calculates the
2065 range from that voice only:
2066
2067 @lilypond[quote,verbatim,ragged-right]
2068 \new Staff <<
2069   \new Voice \with {
2070     \consists Ambitus_engraver
2071   }
2072   \relative c'' {
2073     \voiceOne
2074     c a b g
2075   }
2076   \new Voice
2077   \relative c' {
2078     \voiceTwo
2079     c e d f
2080   }
2081 >>
2082 @end lilypond
2083
2084 @noindent
2085 but if we add the ambitus engraver to the
2086 @code{Staff} context, it calculates the range from all
2087 the notes in all the voices on that staff:
2088
2089 @lilypond[quote,verbatim,ragged-right]
2090 \new Staff \with {
2091     \consists Ambitus_engraver
2092   }
2093   <<
2094   \new Voice
2095   \relative c'' {
2096     \voiceOne
2097     c a b g
2098   }
2099   \new Voice
2100   \relative c' {
2101     \voiceTwo
2102     c e d f
2103   }
2104 >>
2105 @end lilypond
2106
2107 @subsubheading Changing all contexts of the same type
2108
2109 @funindex \layout
2110
2111 The examples above show how to remove or add engravers to
2112 individual contexts.  It is also possible to remove or add
2113 engravers to every context of a specific type by placing the
2114 commands in the appropriate context in a @code{\layout}
2115 block.  For example, if we wanted to show an ambitus for every
2116 staff in a four-staff score, we could write
2117
2118 @lilypond[quote,verbatim,ragged-right]
2119 \score {
2120   <<
2121     \new Staff <<
2122       \relative c'' { c a b g }
2123     >>
2124     \new Staff <<
2125       \relative c' { c a b g }
2126     >>
2127     \new Staff <<
2128       \clef "G_8"
2129       \relative c' { c a b g }
2130     >>
2131     \new Staff <<
2132       \clef "bass"
2133       \relative c { c a b g }
2134     >>
2135   >>
2136   \layout {
2137     \context {
2138       \Staff
2139       \consists Ambitus_engraver
2140     }
2141   }
2142 }
2143 @end lilypond
2144
2145 @noindent
2146 The values of context properties may also be set
2147 for all contexts of a particular type by including the
2148 @code{\set} command in a @code{\context} block in the
2149 same way.
2150
2151 @seealso
2152
2153 Notation Reference: @ruser{Modifying context plug-ins}.
2154
2155
2156 @node Extending the templates
2157 @section Extending the templates
2158
2159 You've read the tutorial, you know how to write music, you
2160 understand the fundamental concepts.  But how can you
2161 get the staves that you want?  Well, you can find lots of
2162 templates (see @ref{Templates}) which may give you a start.
2163 But what if you want something that isn't covered there?  Read on.
2164
2165 @menu
2166 * Soprano and cello::
2167 * Four-part SATB vocal score::
2168 * Building a score from scratch::
2169 @end menu
2170
2171 @node Soprano and cello
2172 @subsection Soprano and cello
2173
2174 @cindex template, modifying
2175
2176 Start off with the template that seems closest to what you want to end
2177 up with.  Let's say that you want to write something for soprano and
2178 cello.  In this case, we would start with @q{Notes and lyrics} (for the
2179 soprano part).
2180
2181 @example
2182 \version @w{"@version{}"}
2183 melody = \relative c' @{
2184   \clef treble
2185   \key c \major
2186   \time 4/4
2187   a4 b c d
2188 @}
2189
2190 text = \lyricmode @{
2191   Aaa Bee Cee Dee
2192 @}
2193
2194 \score @{
2195   <<
2196     \new Voice = "one" @{
2197       \autoBeamOff
2198       \melody
2199     @}
2200     \new Lyrics \lyricsto "one" \text
2201   >>
2202   \layout @{ @}
2203   \midi @{ @}
2204 @}
2205 @end example
2206
2207 Now we want to add a cello part.  Let's look at the @q{Notes only} example:
2208
2209 @example
2210 \version @w{"@version{}"}
2211 melody = \relative c' @{
2212   \clef treble
2213   \key c \major
2214   \time 4/4
2215   a4 b c d
2216 @}
2217
2218 \score @{
2219   \new Staff \melody
2220   \layout @{ @}
2221   \midi @{ @}
2222 @}
2223 @end example
2224
2225 We don't need two @code{\version} commands.  We'll need the
2226 @code{melody} section.  We don't want two @code{\score} sections
2227 -- if we had two @code{\score}s, we'd get the two parts separately.
2228 We want them together, as a duet.  Within the @code{\score}
2229 section, we don't need two @code{\layout} or @code{\midi}.
2230
2231 If we simply cut and paste the @code{melody} section, we would
2232 end up with two @code{melody} definitions.  This would not generate
2233 an error, but the second one would be used for both melodies.
2234 So let's rename them to make them distinct.  We'll call the
2235 section for the soprano @code{sopranoMusic} and the section for
2236 the cello @code{celloMusic}.  While we're doing this, let's rename
2237 @code{text} to be @code{sopranoLyrics}.  Remember to rename both
2238 instances of all these names -- both the initial definition (the
2239 @code{melody = \relative c' @{ } part) and the name's use (in the
2240 @code{\score} section).
2241
2242 While we're doing this, let's change the cello part's staff --
2243 celli normally use bass clef.  We'll also give the cello some
2244 different notes.
2245
2246 @example
2247 \version @w{"@version{}"}
2248 sopranoMusic = \relative c' @{
2249   \clef treble
2250   \key c \major
2251   \time 4/4
2252   a4 b c d
2253 @}
2254
2255 sopranoLyrics = \lyricmode @{
2256   Aaa Bee Cee Dee
2257 @}
2258
2259 celloMusic = \relative c @{
2260   \clef bass
2261   \key c \major
2262   \time 4/4
2263   d4 g fis8 e d4
2264 @}
2265
2266 \score @{
2267   <<
2268     \new Voice = "one" @{
2269       \autoBeamOff
2270       \sopranoMusic
2271     @}
2272     \new Lyrics \lyricsto "one" \sopranoLyrics
2273   >>
2274   \layout @{ @}
2275   \midi @{ @}
2276 @}
2277 @end example
2278
2279 This is looking promising, but the cello part won't appear in the
2280 score -- we haven't used it in the @code{\score} section.  If we
2281 want the cello part to appear under the soprano part, we need to add
2282
2283 @example
2284 \new Staff \celloMusic
2285 @end example
2286
2287 @noindent
2288 underneath the soprano stuff.  We also need to add @code{<<} and
2289 @code{>>} around the music -- that tells LilyPond that there's
2290 more than one thing (in this case, two @code{Staves}) happening
2291 at once.  The @code{\score} looks like this now:
2292
2293 @c Indentation in this example is deliberately poor
2294 @example
2295 \score @{
2296   <<
2297   <<
2298     \new Voice = "one" @{
2299       \autoBeamOff
2300       \sopranoMusic
2301     @}
2302     \new Lyrics \lyricsto "one" \sopranoLyrics
2303   >>
2304   \new Staff \celloMusic
2305   >>
2306   \layout @{ @}
2307   \midi @{ @}
2308 @}
2309 @end example
2310
2311 @noindent
2312 This looks a bit messy; the indentation is messed up now.  That is
2313 easily fixed.  Here's the complete soprano and cello template.
2314
2315 @lilypond[quote,verbatim,ragged-right,addversion]
2316 sopranoMusic = \relative c' {
2317   \clef treble
2318   \key c \major
2319   \time 4/4
2320   a4 b c d
2321 }
2322
2323 sopranoLyrics = \lyricmode {
2324   Aaa Bee Cee Dee
2325 }
2326
2327 celloMusic = \relative c {
2328   \clef bass
2329   \key c \major
2330   \time 4/4
2331   d4 g fis8 e d4
2332 }
2333
2334 \score {
2335   <<
2336     <<
2337       \new Voice = "one" {
2338         \autoBeamOff
2339         \sopranoMusic
2340       }
2341       \new Lyrics \lyricsto "one" \sopranoLyrics
2342     >>
2343     \new Staff \celloMusic
2344   >>
2345   \layout { }
2346   \midi { }
2347 }
2348 @end lilypond
2349
2350 @seealso
2351
2352 The starting templates can be found in the @q{Templates} appendix,
2353 see @ref{Single staff}.
2354
2355
2356 @node Four-part SATB vocal score
2357 @subsection Four-part SATB vocal score
2358
2359 @cindex template, SATB
2360 @cindex SATB template
2361
2362 Most vocal scores of music written for four-part mixed choir
2363 with orchestral accompaniment such as Mendelssohn's Elijah or
2364 Handel's Messiah have the choral music and words on four
2365 staves, one for each of SATB, with a piano reduction of the
2366 orchestral accompaniment underneath.  Here's an example
2367 from Handel's Messiah:
2368
2369 @c The following should appear as music without code
2370 @lilypond[quote,ragged-right]
2371 global = { \key d \major \time 4/4 }
2372 sopranoMusic = \relative c'' {
2373   \clef "treble"
2374   r4 d2 a4 | d4. d8 a2 | cis4 d cis2 |
2375 }
2376 sopranoWords = \lyricmode {
2377   Wor -- thy is the lamb that was slain
2378 }
2379 altoMusic = \relative a' {
2380   \clef "treble"
2381   r4 a2 a4 | fis4. fis8 a2 | g4 fis e2 |
2382 }
2383 altoWords = \sopranoWords
2384 tenorMusic = \relative c' {
2385   \clef "G_8"
2386   r4 fis2 e4 | d4. d8 d2 | e4 a, cis2 |
2387 }
2388 tenorWords = \sopranoWords
2389 bassMusic = \relative c' {
2390   \clef "bass"
2391   r4 d2 cis4 | b4. b8 fis2 | e4 d a'2 |
2392 }
2393 bassWords = \sopranoWords
2394 upper = \relative a' {
2395   \clef "treble"
2396   \global
2397   r4 <a d fis>2 <a e' a>4 |
2398   <d fis d'>4. <d fis d'>8 <a d a'>2 |
2399   <g cis g'>4 <a d fis> <a cis e>2 |
2400 }
2401 lower = \relative c, {
2402   \clef "bass"
2403   \global
2404   <d d'>4 <d d'>2 <cis cis'>4 |
2405   <b b'>4. <b' b'>8 <fis fis'>2 |
2406   <e e'>4 <d d'> <a' a'>2 |
2407 }
2408
2409 \score {
2410   <<  % combine ChoirStaff and PianoStaff in parallel
2411     \new ChoirStaff <<
2412       \new Staff = "sopranos" <<
2413         \set Staff.instrumentName = "Soprano"
2414         \new Voice = "sopranos" { \global \sopranoMusic }
2415       >>
2416       \new Lyrics \lyricsto "sopranos" { \sopranoWords }
2417       \new Staff = "altos" <<
2418         \set Staff.instrumentName = "Alto"
2419         \new Voice = "altos" { \global \altoMusic }
2420       >>
2421       \new Lyrics \lyricsto "altos" { \altoWords }
2422       \new Staff = "tenors" <<
2423         \set Staff.instrumentName = "Tenor"
2424         \new Voice = "tenors" { \global \tenorMusic }
2425       >>
2426       \new Lyrics \lyricsto "tenors" { \tenorWords }
2427       \new Staff = "basses" <<
2428         \set Staff.instrumentName = "Bass"
2429         \new Voice = "basses" { \global \bassMusic }
2430       >>
2431       \new Lyrics \lyricsto "basses" { \bassWords }
2432     >>  % end ChoirStaff
2433
2434     \new PianoStaff <<
2435       \set PianoStaff.instrumentName = "Piano"
2436       \new Staff = "upper" \upper
2437       \new Staff = "lower" \lower
2438     >>
2439   >>
2440 }
2441 @end lilypond
2442
2443 None of the templates provides this layout exactly.  The nearest is
2444 @q{SATB vocal score and automatic piano reduction} -- see @ref{Vocal
2445 ensembles} -- but we need to change the layout and add a piano
2446 accompaniment which is not derived automatically from the vocal parts.
2447 The variables holding the music and words for the vocal parts are
2448 fine, but we shall need to add variables for the piano reduction.
2449
2450 The order in which the contexts appear in the ChoirStaff of
2451 the template do not correspond with the order in the vocal
2452 score shown above.  We need to rearrange them so there are
2453 four staves with the words written directly underneath the
2454 notes for each part.
2455 All the voices should be @code{\voiceOne}, which is
2456 the default, so the @code{\voiceXXX} commands should be removed.
2457 We also need to specify the tenor clef for the tenors.
2458 The way in which lyrics are specified in the template has not yet
2459 been encountered so we need to use the method with which we are
2460 familiar.  We should also add the names of each staff.
2461
2462 Doing this gives for our ChoirStaff:
2463
2464 @example
2465     \new ChoirStaff <<
2466       \new Staff = "sopranos" <<
2467         \set Staff.instrumentName = "Soprano"
2468         \new Voice = "sopranos" @{ \global \sopranoMusic @}
2469       >>
2470       \new Lyrics \lyricsto "sopranos" @{ \sopranoWords @}
2471       \new Staff = "altos" <<
2472         \set Staff.instrumentName = "Alto"
2473         \new Voice = "altos" @{ \global \altoMusic @}
2474       >>
2475       \new Lyrics \lyricsto "altos" @{ \altoWords @}
2476       \new Staff = "tenors" <<
2477         \set Staff.instrumentName = "Tenor"
2478         \new Voice = "tenors" @{ \global \tenorMusic @}
2479       >>
2480       \new Lyrics \lyricsto "tenors" @{ \tenorWords @}
2481       \new Staff = "basses" <<
2482         \set Staff.instrumentName = "Bass"
2483         \new Voice = "basses" @{ \global \bassMusic @}
2484       >>
2485       \new Lyrics \lyricsto "basses" @{ \bassWords @}
2486     >>  % end ChoirStaff
2487 @end example
2488
2489 Next we must work out the piano part.  This is
2490 easy - we just pull out the piano part from the
2491 @q{Solo piano} template:
2492
2493 @example
2494 \new PianoStaff <<
2495   \set PianoStaff.instrumentName = "Piano  "
2496   \new Staff = "upper" \upper
2497   \new Staff = "lower" \lower
2498 >>
2499 @end example
2500
2501 and add the variable definitions for @code{upper}
2502 and @code{lower}.
2503
2504 The ChoirStaff and PianoStaff must be combined
2505 using angle brackets as we want them to be
2506 stacked one above the other:
2507
2508 @example
2509 <<  % combine ChoirStaff and PianoStaff one above the other
2510   \new ChoirStaff <<
2511     \new Staff = "sopranos" <<
2512       \new Voice = "sopranos" @{ \global \sopranoMusic @}
2513     >>
2514     \new Lyrics \lyricsto "sopranos" @{ \sopranoWords @}
2515     \new Staff = "altos" <<
2516       \new Voice = "altos" @{ \global \altoMusic @}
2517     >>
2518     \new Lyrics \lyricsto "altos" @{ \altoWords @}
2519     \new Staff = "tenors" <<
2520       \clef "G_8"  % tenor clef
2521       \new Voice = "tenors" @{ \global \tenorMusic @}
2522     >>
2523     \new Lyrics \lyricsto "tenors" @{ \tenorWords @}
2524     \new Staff = "basses" <<
2525       \clef "bass"
2526       \new Voice = "basses" @{ \global \bassMusic @}
2527     >>
2528     \new Lyrics \lyricsto "basses" @{ \bassWords @}
2529   >>  % end ChoirStaff
2530
2531   \new PianoStaff <<
2532     \set PianoStaff.instrumentName = "Piano"
2533     \new Staff = "upper" \upper
2534     \new Staff = "lower" \lower
2535   >>
2536 >>
2537 @end example
2538
2539 Combining all these together and adding the music
2540 for the three bars of the example above gives:
2541
2542 @lilypond[quote,verbatim,ragged-right,addversion]
2543 global = { \key d \major \time 4/4 }
2544 sopranoMusic = \relative c'' {
2545   \clef "treble"
2546   r4 d2 a4 | d4. d8 a2 | cis4 d cis2 |
2547 }
2548 sopranoWords = \lyricmode {
2549   Wor -- thy is the lamb that was slain
2550 }
2551 altoMusic = \relative a' {
2552   \clef "treble"
2553   r4 a2 a4 | fis4. fis8 a2 | g4 fis fis2 |
2554 }
2555 altoWords = \sopranoWords
2556 tenorMusic = \relative c' {
2557   \clef "G_8"
2558   r4 fis2 e4 | d4. d8 d2 | e4 a, cis2 |
2559 }
2560 tenorWords = \sopranoWords
2561 bassMusic = \relative c' {
2562   \clef "bass"
2563   r4 d2 cis4 | b4. b8 fis2 | e4 d a'2 |
2564 }
2565 bassWords = \sopranoWords
2566 upper = \relative a' {
2567   \clef "treble"
2568   \global
2569   r4 <a d fis>2 <a e' a>4 |
2570   <d fis d'>4. <d fis d'>8 <a d a'>2 |
2571   <g cis g'>4 <a d fis> <a cis e>2 |
2572 }
2573 lower = \relative c, {
2574   \clef "bass"
2575   \global
2576   <d d'>4 <d d'>2 <cis cis'>4 |
2577   <b b'>4. <b' b'>8 <fis fis'>2 |
2578   <e e'>4 <d d'> <a' a'>2 |
2579 }
2580
2581 \score {
2582   <<  % combine ChoirStaff and PianoStaff in parallel
2583     \new ChoirStaff <<
2584       \new Staff = "sopranos" <<
2585         \set Staff.instrumentName = "Soprano"
2586         \new Voice = "sopranos" { \global \sopranoMusic }
2587       >>
2588       \new Lyrics \lyricsto "sopranos" { \sopranoWords }
2589       \new Staff = "altos" <<
2590         \set Staff.instrumentName = "Alto"
2591         \new Voice = "altos" { \global \altoMusic }
2592       >>
2593       \new Lyrics \lyricsto "altos" { \altoWords }
2594       \new Staff = "tenors" <<
2595         \set Staff.instrumentName = "Tenor"
2596         \new Voice = "tenors" { \global \tenorMusic }
2597       >>
2598       \new Lyrics \lyricsto "tenors" { \tenorWords }
2599       \new Staff = "basses" <<
2600         \set Staff.instrumentName = "Bass"
2601         \new Voice = "basses" { \global \bassMusic }
2602       >>
2603       \new Lyrics \lyricsto "basses" { \bassWords }
2604     >>  % end ChoirStaff
2605
2606     \new PianoStaff <<
2607       \set PianoStaff.instrumentName = "Piano  "
2608       \new Staff = "upper" \upper
2609       \new Staff = "lower" \lower
2610     >>
2611   >>
2612 }
2613 @end lilypond
2614
2615
2616 @node Building a score from scratch
2617 @subsection Building a score from scratch
2618
2619 @cindex template, writing your own
2620
2621 After gaining some facility with writing LilyPond code, you
2622 may find that it is easier to build a score from scratch
2623 rather than modifying one of the templates.  You can also
2624 develop your own style this way to suit the sort of music you
2625 like.  Let's see how to put together the score for an organ
2626 prelude as an example.
2627
2628 We begin with a header section.  Here go the title, name
2629 of composer, etc, then come any variable definitions, and
2630 finally the score block.  Let's start with these in outline
2631 and fill in the details later.
2632
2633 We'll use the first two bars of Bach's prelude
2634 based on @emph{Jesu, meine Freude} which is written for two
2635 manuals and pedal organ.  You can see these two bars of music
2636 at the bottom of this section.  The top manual part has two voices,
2637 the lower and pedal organ one each.  So we need four
2638 music definitions and one to define the time signature
2639 and key:
2640
2641 @example
2642 \version @w{"@version{}"}
2643 \header @{
2644   title = "Jesu, meine Freude"
2645   composer = "J S Bach"
2646 @}
2647 TimeKey = @{ \time 4/4 \key c \minor @}
2648 ManualOneVoiceOneMusic = @{s1@}
2649 ManualOneVoiceTwoMusic = @{s1@}
2650 ManualTwoMusic = @{s1@}
2651 PedalOrganMusic = @{s1@}
2652
2653 \score @{
2654 @}
2655 @end example
2656
2657 For now we've just used a spacer note, @code{s1},
2658 instead of the real music.  We'll add that later.
2659
2660 Next let's see what should go in the score block.
2661 We simply mirror the staff structure we want.
2662 Organ music is usually written on three staves,
2663 one for each manual and one for the pedals.  The
2664 manual staves should be bracketed together, so we
2665 need to use a PianoStaff for them.  The first
2666 manual part needs two voices and the second manual
2667 part just one.
2668
2669 @example
2670   \new PianoStaff <<
2671     \new Staff = "ManualOne" <<
2672       \new Voice @{ \ManualOneVoiceOneMusic @}
2673       \new Voice @{ \ManualOneVoiceTwoMusic @}
2674     >>  % end ManualOne Staff context
2675     \new Staff = "ManualTwo" <<
2676       \new Voice @{ \ManualTwoMusic @}
2677     >>  % end ManualTwo Staff context
2678   >>  % end PianoStaff context
2679 @end example
2680
2681 Next we need to add a staff for the pedal organ.
2682 This goes underneath the PianoStaff, but it must
2683 be simultaneous with it, so we need angle brackets
2684 around the two.  Missing these out would generate
2685 an error in the log file.  It's a common mistake
2686 which you'll make sooner or later!  Try copying
2687 the final example at the end of this section,
2688 remove these angle brackets, and compile it to
2689 see what errors it generates.
2690
2691 @example
2692 <<  % PianoStaff and Pedal Staff must be simultaneous
2693   \new PianoStaff <<
2694     \new Staff = "ManualOne" <<
2695       \new Voice @{ \ManualOneVoiceOneMusic @}
2696       \new Voice @{ \ManualOneVoiceTwoMusic @}
2697     >>  % end ManualOne Staff context
2698     \new Staff = "ManualTwo" <<
2699       \new Voice @{ \ManualTwoMusic @}
2700     >>  % end ManualTwo Staff context
2701   >>  % end PianoStaff context
2702   \new Staff = "PedalOrgan" <<
2703     \new Voice @{ \PedalOrganMusic @}
2704   >>
2705 >>
2706 @end example
2707
2708 It is not necessary to use the simultaneous construct
2709 @code{<< .. >>} for the manual two staff and the pedal organ staff,
2710 since they contain only one music expression, but it does no harm,
2711 and always using angle brackets after @code{\new Staff} is a good
2712 habit to cultivate in case there are multiple voices.  The opposite
2713 is true for Voices: these should habitually be followed by braces
2714 @code{@{ .. @}} in case your music is coded in several variables
2715 which need to run consecutively.
2716
2717 Let's add this structure to the score block, and adjust the indenting.
2718 We also add the appropriate clefs, ensure stems, ties and slurs in
2719 each voice on the upper staff point to the right direction with
2720 @code{\voiceOne} and @code{\voiceTwo}, and enter the time signature
2721 and key to each staff using our predefined variable, @code{\TimeKey}.
2722
2723 @example
2724 \score @{
2725   <<  % PianoStaff and Pedal Staff must be simultaneous
2726     \new PianoStaff <<
2727       \new Staff = "ManualOne" <<
2728         \TimeKey  % set time signature and key
2729         \clef "treble"
2730         \new Voice @{ \voiceOne \ManualOneVoiceOneMusic @}
2731         \new Voice @{ \voiceTwo \ManualOneVoiceTwoMusic @}
2732       >>  % end ManualOne Staff context
2733       \new Staff = "ManualTwo" <<
2734         \TimeKey
2735         \clef "bass"
2736         \new Voice @{ \ManualTwoMusic @}
2737       >>  % end ManualTwo Staff context
2738     >>  % end PianoStaff context
2739     \new Staff = "PedalOrgan" <<
2740       \TimeKey
2741       \clef "bass"
2742       \new Voice @{ \PedalOrganMusic @}
2743     >>  % end PedalOrgan Staff
2744   >>
2745 @}  % end Score context
2746 @end example
2747
2748 That completes the structure.  Any three-staff organ music
2749 will have a similar structure, although the number of voices
2750 may vary.  All that remains now
2751 is to add the music, and combine all the parts together.
2752
2753 @lilypond[quote,verbatim,ragged-right,addversion]
2754 \header {
2755   title = "Jesu, meine Freude"
2756   composer = "J S Bach"
2757 }
2758 TimeKey = { \time 4/4 \key c \minor }
2759 ManualOneVoiceOneMusic = \relative g' {
2760   g4 g f ees | d2 c2 |
2761 }
2762 ManualOneVoiceTwoMusic = \relative c' {
2763   ees16 d ees8~ ees16 f ees d c8 d~ d c~ |
2764   c c4 b8 c8. g16 c b c d |
2765 }
2766 ManualTwoMusic = \relative c' {
2767   c16 b c8~ c16 b c g a8 g~ g16 g aes ees |
2768   f ees f d g aes g f ees d e8~ ees16 f ees d |
2769 }
2770 PedalOrganMusic = \relative c {
2771   r8 c16 d ees d ees8~ ees16 a, b g c b c8 |
2772   r16 g ees f g f g8 c,2 |
2773   }
2774
2775 \score {
2776   <<  % PianoStaff and Pedal Staff must be simultaneous
2777     \new PianoStaff <<
2778       \new Staff = "ManualOne" <<
2779         \TimeKey  % set time signature and key
2780         \clef "treble"
2781         \new Voice { \voiceOne \ManualOneVoiceOneMusic }
2782         \new Voice { \voiceTwo \ManualOneVoiceTwoMusic }
2783       >>  % end ManualOne Staff context
2784       \new Staff = "ManualTwo" <<
2785         \TimeKey
2786         \clef "bass"
2787         \new Voice { \ManualTwoMusic }
2788       >>  % end ManualTwo Staff context
2789     >>  % end PianoStaff context
2790     \new Staff = "PedalOrgan" <<
2791       \TimeKey
2792       \clef "bass"
2793       \new Voice { \PedalOrganMusic }
2794     >>  % end PedalOrgan Staff context
2795   >>
2796 }  % end Score context
2797 @end lilypond
2798
2799