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