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