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