]> git.donarmstrong.com Git - lilypond.git/blob - Documentation/user/fundamental.itely
Merge branch 'master' of ssh://jeancharlesm@git.sv.gnu.org/srv/git/lilypond
[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 a 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 and digits invented by the user.  The identifying name is used to
1670 refer back to that particular instance of a context.  We saw this in
1671 use in the section on lyrics, see @ref{Voices and vocals}.
1672
1673 @seealso
1674
1675 Notation Reference: @ruser{Creating contexts}.
1676
1677
1678 @node Engravers explained
1679 @subsection Engravers explained
1680
1681 @cindex engravers
1682
1683 Every mark on the printed output of a score produced by LilyPond
1684 is produced by an @code{Engraver}.  Thus there is an engraver
1685 to print staves, one to print note heads, one for stems, one for
1686 beams, etc, etc.  In total there are over 120 such engravers!
1687 Fortunately, for most scores it is not necessary to know about
1688 more than a few, and for simple scores you do not need to know
1689 about any.
1690
1691 Engravers live and operate in Contexts.
1692 Engravers such as the @code{Metronome_mark_engraver}, whose
1693 action and output applies to the score as a whole, operate in
1694 the highest level context -- the @code{Score} context.
1695
1696 The @code{Clef_engraver} and @code{Key_engraver} are to be
1697 found in every Staff Context, as different staves may require
1698 different clefs and keys.
1699
1700 The @code{Note_heads_engraver} and @code{Stem_engraver} live
1701 in every @code{Voice} context, the lowest level context of all.
1702
1703 Each engraver processes the particular objects associated
1704 with its function, and maintains the properties that relate
1705 to that function.  These properties, like the properties
1706 associated with contexts, may be modified to change the
1707 operation of the engraver or the appearance of those elements
1708 in the printed score.
1709
1710 Engravers all have compound names formed from words which
1711 describe their function.  Just the first word is capitalized,
1712 and the remainder are joined to it with underscores.  Thus
1713 the @code{Staff_symbol_engraver} is responsible for creating the
1714 lines of the staff, the @code{Clef_engraver} determines and sets
1715 the pitch reference point on the staff by drawing a clef symbol.
1716
1717 Here are some of the most common engravers together with their
1718 function.  You will see it is usually easy to guess the function
1719 from the name, or vice versa.
1720
1721 @multitable @columnfractions .3 .7
1722 @headitem Engraver
1723   @tab Function
1724 @item Accidental_engraver
1725   @tab Makes accidentals, cautionary and suggested accidentals
1726 @item Beam_engraver
1727   @tab Engraves beams
1728 @item Clef_engraver
1729   @tab Engraves clefs
1730 @item Completion_heads_engraver
1731   @tab Splits notes which cross bar lines
1732 @c The old Dynamic_engraver is deprecated. -jm
1733 @item New_dynamic_engraver
1734   @tab Creates hairpins and dynamic texts
1735 @item Forbid_line_break_engraver
1736   @tab Prevents line breaks if a musical element is still active
1737 @item Key_engraver
1738   @tab Creates the key signature
1739 @item Metronome_mark_engraver
1740   @tab Engraves metronome marking
1741 @item Note_heads_engraver
1742   @tab Engraves note heads
1743 @item Rest_engraver
1744   @tab Engraves rests
1745 @item Staff_symbol_engraver
1746   @tab Engraves the five (by default) lines of the staff
1747 @item Stem_engraver
1748   @tab Creates stems and single-stem tremolos
1749 @item Time_signature_engraver
1750   @tab Creates time signatures
1751 @end multitable
1752
1753 @smallspace
1754
1755 We shall see later how the output of LilyPond can be changed
1756 by modifying the action of Engravers.
1757
1758 @seealso
1759
1760 Internals reference: @rinternals{Engravers and performers}.
1761
1762
1763 @node Modifying context properties
1764 @subsection Modifying context properties
1765
1766 @cindex context properties
1767 @cindex context properties, modifying
1768 @cindex modifying context properties
1769 @funindex \set
1770 @funindex \unset
1771
1772 Contexts are responsible for holding the values of a number of
1773 context @emph{properties}.  Many of them can be changed to
1774 influence the interpretation of the input and so change the
1775 appearance of the output.  They are changed by the
1776 @code{\set} command.  This takes the form
1777
1778 @example
1779 \set @emph{ContextName}.@emph{propertyName} = #@emph{value}
1780 @end example
1781
1782 Where the @emph{ContextName} is usually @code{Score},
1783 @code{Staff} or @code{Voice}.  It may be omitted,
1784 in which case @code{Voice} is assumed.
1785
1786 The names of context properties consist of words joined
1787 together with no hyphens or underscores, all except the
1788 first having a capital letter.  Here are a few examples
1789 of some commonly used ones.  There are many more.
1790
1791 @c attempt to force this onto a new page
1792 @need 50
1793 @multitable @columnfractions .25 .15 .45 .15
1794 @headitem propertyName
1795   @tab Type
1796   @tab Function
1797   @tab Example Value
1798 @item extraNatural
1799   @tab Boolean
1800   @tab If true, set extra natural signs before accidentals
1801   @tab @code{#t}, @code{#f}
1802 @item currentBarNumber
1803   @tab Integer
1804   @tab Set the current bar number
1805   @tab @code{50}
1806 @item doubleSlurs
1807   @tab Boolean
1808   @tab If true, print slurs both above and below notes
1809   @tab @code{#t}, @code{#f}
1810 @item instrumentName
1811   @tab Text
1812   @tab Set the name to be placed at the start of the staff
1813   @tab @code{"Cello I"}
1814 @item fontSize
1815   @tab Real
1816   @tab Increase or decrease the font size
1817   @tab @code{2.4}
1818 @item stanza
1819   @tab Text
1820   @tab Set the text to print before the start of a verse
1821   @tab @code{"2"}
1822 @end multitable
1823
1824 @noindent
1825 where a Boolean is either True (@code{#t}) or False (@code{#f}),
1826 an Integer is a positive whole number, a Real is a positive
1827 or negative decimal number, and text is enclosed in double
1828 apostrophes.  Note the occurrence of hash signs,
1829 (@code{#}), in two different places -- as part of the Boolean
1830 value before the @code{t} or @code{f}, and before @emph{value}
1831 in the @code{\set} statement.  So when a Boolean is being
1832 entered you need to code two hash signs, e.g., @code{##t}.
1833
1834 Before we can set any of these properties we need to know
1835 in which context they operate.  Sometimes this is obvious,
1836 but occasionally it can be tricky.  If the wrong context
1837 is specified, no error message is produced, but the expected
1838 action will not take place.  For example, the
1839 @code{instrumentName} clearly lives in the Staff context, since
1840 it is the staff that is to be named.
1841 In this example the first staff is labelled, but not the second,
1842 because we omitted the context name.
1843
1844 @lilypond[quote,verbatim,ragged-right]
1845 <<
1846   \new Staff \relative c'' {
1847     \set Staff.instrumentName = #"Soprano"
1848     c4 c
1849  }
1850   \new Staff \relative c' {
1851   \set instrumentName = #"Alto"  % Wrong!
1852   d4 d
1853  }
1854 >>
1855 @end lilypond
1856
1857 Remember the default context name is Voice, so the second
1858 @code{\set} command set the property @code{instrumentName} in the
1859 Voice context to @qq{Alto}, but as LilyPond does not look
1860 for any such property in the @code{Voice} context, no
1861 further action took place.  This is not an error, and no error
1862 message is logged in the log file.
1863
1864 Similarly, if the property name is mis-spelt no error message is
1865 produced, and clearly the expected action cannot be performed.  If
1866 fact, you can set any (fictitious) @q{property} using any name you
1867 like in any context that exists by using the @code{\set} command.  But
1868 if the name is not known to LilyPond it will not cause any action to
1869 be taken.  Some text editors with special support for LilyPond input
1870 files document property names with bullets when you hover them with
1871 the mouse, like JEdit with LilyPondTool, or highlight unknown property
1872 names differently, like ConTEXT.  If you do not use an editor with
1873 such features, it is recommended to check the property name in the
1874 Internals Reference: see @rinternals{Tunable context properties}, or
1875 @rinternals{Contexts}.
1876
1877 The @code{instrumentName} property will take effect only
1878 if it is set in the @code{Staff} context, but
1879 some properties can be set in more than one context.
1880 For example, the property @code{extraNatural} is by
1881 default set to ##t (true) for all staves.
1882 If it is set to ##f (false) in one particular @code{Staff}
1883 context it applies just to the accidentals on that staff.
1884 If it is set to false in the @code{Score} context
1885 it applies to all staves.
1886
1887 So this turns off extra naturals in one staff:
1888
1889 @lilypond[quote,verbatim,ragged-right]
1890 <<
1891   \new Staff \relative c'' {
1892     ais4 aes
1893  }
1894   \new Staff \relative c'' {
1895     \set Staff.extraNatural = ##f
1896     ais4 aes
1897  }
1898 >>
1899 @end lilypond
1900
1901 @noindent
1902 and this turns them off in all staves:
1903
1904 @lilypond[quote,verbatim,ragged-right]
1905 <<
1906   \new Staff \relative c'' {
1907     ais4 aes
1908  }
1909   \new Staff \relative c'' {
1910     \set Score.extraNatural = ##f
1911     ais4 aes
1912  }
1913 >>
1914 @end lilypond
1915
1916 As another example, if @code{clefOctavation} is set in
1917 the @code{Score} context this immediately changes the value
1918 of the octavation in all current staves and sets a new default
1919 value which will be applied to all staves.
1920
1921 The opposite command, @code{\unset}, effectively removes the
1922 property from the context, which causes most properties to
1923 revert to their default value.  Usually @code{\unset} is not
1924 required as a new @code{\set} command will achieve what is
1925 wanted.
1926
1927 The @code{\set} and @code{\unset} commands can appear anywhere
1928 in the input file and will take effect from the time they are
1929 encountered until the end of the score or until the property is
1930 @code{\set} or @code{\unset} again.  Let's try changing the
1931 font size, which affects the size of the note heads (among
1932 other things) several times.  The change is from the default
1933 value, not the most recently set value.
1934
1935 @lilypond[quote,verbatim,ragged-right,relative=1,fragment]
1936 c4
1937 % make note heads smaller
1938 \set fontSize = #-4
1939 d e
1940 % make note heads larger
1941 \set fontSize = #2.5
1942 f g
1943 % return to default size
1944 \unset fontSize
1945 a b
1946 @end lilypond
1947
1948 We have now seen how to set the values of several different types of
1949 property.  Note that integers and numbers are always preceded by a
1950 hash sign, @code{#}, while a true or false value is specified by
1951 @code{##t} and @code{##f}, with two hash signs.  A text property
1952 should be enclosed in double quotation signs, as above, although we
1953 shall see later that text can actually be specified in a much more
1954 general way by using the very powerful @code{markup} command.
1955
1956 @unnumberedsubsubsec Setting context properties with @code{\with}
1957
1958 @funindex \with
1959 @cindex context properties, setting with \with
1960
1961 Context properties may also be set at the time the context is
1962 created.  Sometimes this is a clearer way of specifying a
1963 property value if it is to remain fixed for the duration of
1964 the context.  When a context is created with a @code{\new}
1965 command it may be followed immediately by a
1966 @code{\with @{ .. @}} block in which the property values are
1967 set.  For example, if we wish to suppress the printing of
1968 extra naturals for the duration of a staff we would write:
1969
1970 @example
1971 \new Staff \with @{ extraNatural = ##f @}
1972 @end example
1973
1974 @noindent
1975 like this:
1976
1977 @lilypond[quote,verbatim,ragged-right]
1978 <<
1979   \new Staff
1980   \relative c'' {
1981     gis ges aes ais
1982   }
1983   \new Staff \with { extraNatural = ##f }
1984   \relative c'' {
1985     gis ges aes ais
1986   }
1987 >>
1988 @end lilypond
1989
1990 Properties set in this way may still be changed dynamically using
1991 @code{\set} and returned to their default value with @code{\unset}.
1992
1993 The @code{fontSize} property is treated differently.  If this is
1994 set in a @code{\with} clause it effectively resets the default
1995 value of the font size.  If it is later changed with @code{\set},
1996 this new default value may be restored with the
1997 @code{\unset fontSize} command.
1998
1999 @unnumberedsubsubsec Setting context properties with @code{\context}
2000
2001 The values of context properties may be set in @emph{all} contexts
2002 of a particular type, such as all @code{Staff} contexts, with a single
2003 command.  The context type is identified by using its
2004 type name, like @code{Staff}, prefixed by a back-slash: @code{\Staff}.
2005 The statement which sets the property value is the same as that in a 
2006 @code{\with} block, introduced above.  It is placed in a
2007 @code{\context} block within a @code{\layout} block.  Each
2008 @code{\context} block will affect all contexts of the type specified
2009 throughout the @code{\score} or @code{\book} block in which the
2010 @code{\layout} block appears.  Here is a example to show the format:
2011
2012 @lilypond[verbatim,quote]
2013 \score {
2014   \new Staff {
2015     \relative c'' {
2016       cis4 e d ces
2017     }
2018   }
2019   \layout {
2020     \context {
2021       \Staff
2022       extraNatural = ##t
2023     }
2024   }
2025 }
2026 @end lilypond
2027
2028 @noindent
2029 Context properties set in this way may be overridden for particular
2030 instances of contexts by statements in a @code{\with} block, and by
2031 @code{\set} commands embedded in music statements.
2032
2033 @seealso
2034
2035 Notation Reference: @ruser{Changing context default settings},
2036 @ruser{The set command}.
2037
2038 Internals Reference: @rinternals{Contexts},
2039 @rinternals{Tunable context properties}.
2040
2041
2042 @node Adding and removing engravers
2043 @subsection Adding and removing engravers
2044
2045 @cindex engravers, adding
2046 @cindex engravers, removing
2047
2048 @funindex \consists
2049 @funindex \remove
2050
2051 We have seen that contexts each contain several engravers, each
2052 of which is responsible for producing a particular part of the
2053 output, like bar lines, staves, note heads, stems, etc.  If an
2054 engraver is removed from a context, it can no longer produce its
2055 output.  This is a crude way of modifying the output, but it
2056 can sometimes be useful.
2057
2058 @subsubheading Changing a single context
2059
2060 To remove an engraver from a single context we use the
2061 @code{\with} command placed immediately after the context creation
2062 command, as in the previous section.
2063
2064 As an illustration, let's repeat an example from the previous section
2065 with the staff lines removed.  Remember that the staff lines are
2066 produced by the @code{Staff_symbol_engraver}.
2067
2068 @lilypond[quote,verbatim,ragged-right]
2069 \new Staff \with {
2070   \remove Staff_symbol_engraver
2071 }
2072 \relative c' {
2073   c4
2074   \set fontSize = #-4  % make note heads smaller
2075   d e
2076   \set fontSize = #2.5  % make note heads larger
2077   f g
2078   \unset fontSize  % return to default size
2079   a b
2080 }
2081 @end lilypond
2082
2083 @cindex ambitus engraver
2084
2085 Engravers can also be added to individual contexts.
2086 The command to do this is
2087
2088 @code{\consists @var{Engraver_name}},
2089
2090 @noindent
2091 placed inside a @code{\with} block.  Some vocal scores have an ambitus
2092 placed at the beginning of a staff to indicate the range of notes in
2093 that staff -- see @rglos{ambitus}.  The ambitus is produced by the
2094 @code{Ambitus_engraver}, which is not normally included in any
2095 context.  If we add it to the @code{Voice} context, it calculates the
2096 range from that voice only:
2097
2098 @lilypond[quote,verbatim,ragged-right]
2099 \new Staff <<
2100   \new Voice \with {
2101     \consists Ambitus_engraver
2102   }
2103   \relative c'' {
2104     \voiceOne
2105     c a b g
2106   }
2107   \new Voice
2108   \relative c' {
2109     \voiceTwo
2110     c e d f
2111   }
2112 >>
2113 @end lilypond
2114
2115 @noindent
2116 but if we add the ambitus engraver to the
2117 @code{Staff} context, it calculates the range from all
2118 the notes in all the voices on that staff:
2119
2120 @lilypond[quote,verbatim,ragged-right]
2121 \new Staff \with {
2122     \consists Ambitus_engraver
2123   }
2124   <<
2125   \new Voice
2126   \relative c'' {
2127     \voiceOne
2128     c a b g
2129   }
2130   \new Voice
2131   \relative c' {
2132     \voiceTwo
2133     c e d f
2134   }
2135 >>
2136 @end lilypond
2137
2138 @subsubheading Changing all contexts of the same type
2139
2140 @funindex \layout
2141
2142 The examples above show how to remove or add engravers to
2143 individual contexts.  It is also possible to remove or add
2144 engravers to every context of a specific type by placing the
2145 commands in the appropriate context in a @code{\layout}
2146 block.  For example, if we wanted to show an ambitus for every
2147 staff in a four-staff score, we could write
2148
2149 @lilypond[quote,verbatim,ragged-right]
2150 \score {
2151   <<
2152     \new Staff <<
2153       \relative c'' { c a b g }
2154     >>
2155     \new Staff <<
2156       \relative c' { c a b g }
2157     >>
2158     \new Staff <<
2159       \clef "G_8"
2160       \relative c' { c a b g }
2161     >>
2162     \new Staff <<
2163       \clef "bass"
2164       \relative c { c a b g }
2165     >>
2166   >>
2167   \layout {
2168     \context {
2169       \Staff
2170       \consists Ambitus_engraver
2171     }
2172   }
2173 }
2174 @end lilypond
2175
2176 @noindent
2177 The values of context properties may also be set
2178 for all contexts of a particular type by including the
2179 @code{\set} command in a @code{\context} block in the
2180 same way.
2181
2182 @seealso
2183
2184 Notation Reference: @ruser{Modifying context plug-ins},
2185 @ruser{Changing context default settings}.
2186
2187
2188 @node Extending the templates
2189 @section Extending the templates
2190
2191 You've read the tutorial, you know how to write music, you
2192 understand the fundamental concepts.  But how can you
2193 get the staves that you want?  Well, you can find lots of
2194 templates (see @ref{Templates}) which may give you a start.
2195 But what if you want something that isn't covered there?  Read on.
2196
2197 @menu
2198 * Soprano and cello::
2199 * Four-part SATB vocal score::
2200 * Building a score from scratch::
2201 @end menu
2202
2203 @node Soprano and cello
2204 @subsection Soprano and cello
2205
2206 @cindex template, modifying
2207
2208 Start off with the template that seems closest to what you want to end
2209 up with.  Let's say that you want to write something for soprano and
2210 cello.  In this case, we would start with @q{Notes and lyrics} (for the
2211 soprano part).
2212
2213 @example
2214 \version @w{"@version{}"}
2215 melody = \relative c' @{
2216   \clef treble
2217   \key c \major
2218   \time 4/4
2219   a4 b c d
2220 @}
2221
2222 text = \lyricmode @{
2223   Aaa Bee Cee Dee
2224 @}
2225
2226 \score @{
2227   <<
2228     \new Voice = "one" @{
2229       \autoBeamOff
2230       \melody
2231     @}
2232     \new Lyrics \lyricsto "one" \text
2233   >>
2234   \layout @{ @}
2235   \midi @{ @}
2236 @}
2237 @end example
2238
2239 Now we want to add a cello part.  Let's look at the @q{Notes only} example:
2240
2241 @example
2242 \version @w{"@version{}"}
2243 melody = \relative c' @{
2244   \clef treble
2245   \key c \major
2246   \time 4/4
2247   a4 b c d
2248 @}
2249
2250 \score @{
2251   \new Staff \melody
2252   \layout @{ @}
2253   \midi @{ @}
2254 @}
2255 @end example
2256
2257 We don't need two @code{\version} commands.  We'll need the
2258 @code{melody} section.  We don't want two @code{\score} sections
2259 -- if we had two @code{\score}s, we'd get the two parts separately.
2260 We want them together, as a duet.  Within the @code{\score}
2261 section, we don't need two @code{\layout} or @code{\midi}.
2262
2263 If we simply cut and paste the @code{melody} section, we would
2264 end up with two @code{melody} definitions.  This would not generate
2265 an error, but the second one would be used for both melodies.
2266 So let's rename them to make them distinct.  We'll call the
2267 section for the soprano @code{sopranoMusic} and the section for
2268 the cello @code{celloMusic}.  While we're doing this, let's rename
2269 @code{text} to be @code{sopranoLyrics}.  Remember to rename both
2270 instances of all these names -- both the initial definition (the
2271 @code{melody = \relative c' @{ } part) and the name's use (in the
2272 @code{\score} section).
2273
2274 While we're doing this, let's change the cello part's staff --
2275 celli normally use bass clef.  We'll also give the cello some
2276 different notes.
2277
2278 @example
2279 \version @w{"@version{}"}
2280 sopranoMusic = \relative c' @{
2281   \clef treble
2282   \key c \major
2283   \time 4/4
2284   a4 b c d
2285 @}
2286
2287 sopranoLyrics = \lyricmode @{
2288   Aaa Bee Cee Dee
2289 @}
2290
2291 celloMusic = \relative c @{
2292   \clef bass
2293   \key c \major
2294   \time 4/4
2295   d4 g fis8 e d4
2296 @}
2297
2298 \score @{
2299   <<
2300     \new Voice = "one" @{
2301       \autoBeamOff
2302       \sopranoMusic
2303     @}
2304     \new Lyrics \lyricsto "one" \sopranoLyrics
2305   >>
2306   \layout @{ @}
2307   \midi @{ @}
2308 @}
2309 @end example
2310
2311 This is looking promising, but the cello part won't appear in the
2312 score -- we haven't used it in the @code{\score} section.  If we
2313 want the cello part to appear under the soprano part, we need to add
2314
2315 @example
2316 \new Staff \celloMusic
2317 @end example
2318
2319 @noindent
2320 underneath the soprano stuff.  We also need to add @code{<<} and
2321 @code{>>} around the music -- that tells LilyPond that there's
2322 more than one thing (in this case, two @code{Staves}) happening
2323 at once.  The @code{\score} looks like this now:
2324
2325 @c Indentation in this example is deliberately poor
2326 @example
2327 \score @{
2328   <<
2329   <<
2330     \new Voice = "one" @{
2331       \autoBeamOff
2332       \sopranoMusic
2333     @}
2334     \new Lyrics \lyricsto "one" \sopranoLyrics
2335   >>
2336   \new Staff \celloMusic
2337   >>
2338   \layout @{ @}
2339   \midi @{ @}
2340 @}
2341 @end example
2342
2343 @noindent
2344 This looks a bit messy; the indentation is messed up now.  That is
2345 easily fixed.  Here's the complete soprano and cello template.
2346
2347 @lilypond[quote,verbatim,ragged-right,addversion]
2348 sopranoMusic = \relative c' {
2349   \clef treble
2350   \key c \major
2351   \time 4/4
2352   a4 b c d
2353 }
2354
2355 sopranoLyrics = \lyricmode {
2356   Aaa Bee Cee Dee
2357 }
2358
2359 celloMusic = \relative c {
2360   \clef bass
2361   \key c \major
2362   \time 4/4
2363   d4 g fis8 e d4
2364 }
2365
2366 \score {
2367   <<
2368     <<
2369       \new Voice = "one" {
2370         \autoBeamOff
2371         \sopranoMusic
2372       }
2373       \new Lyrics \lyricsto "one" \sopranoLyrics
2374     >>
2375     \new Staff \celloMusic
2376   >>
2377   \layout { }
2378   \midi { }
2379 }
2380 @end lilypond
2381
2382 @seealso
2383
2384 The starting templates can be found in the @q{Templates} appendix,
2385 see @ref{Single staff}.
2386
2387
2388 @node Four-part SATB vocal score
2389 @subsection Four-part SATB vocal score
2390
2391 @cindex template, SATB
2392 @cindex SATB template
2393
2394 Most vocal scores of music written for four-part mixed choir
2395 with orchestral accompaniment such as Mendelssohn's Elijah or
2396 Handel's Messiah have the choral music and words on four
2397 staves, one for each of SATB, with a piano reduction of the
2398 orchestral accompaniment underneath.  Here's an example
2399 from Handel's Messiah:
2400
2401 @c The following should appear as music without code
2402 @lilypond[quote,ragged-right]
2403 global = { \key d \major \time 4/4 }
2404 sopranoMusic = \relative c'' {
2405   \clef "treble"
2406   r4 d2 a4 | d4. d8 a2 | cis4 d cis2 |
2407 }
2408 sopranoWords = \lyricmode {
2409   Wor -- thy is the lamb that was slain
2410 }
2411 altoMusic = \relative a' {
2412   \clef "treble"
2413   r4 a2 a4 | fis4. fis8 a2 | g4 fis e2 |
2414 }
2415 altoWords = \sopranoWords
2416 tenorMusic = \relative c' {
2417   \clef "G_8"
2418   r4 fis2 e4 | d4. d8 d2 | e4 a, cis2 |
2419 }
2420 tenorWords = \sopranoWords
2421 bassMusic = \relative c' {
2422   \clef "bass"
2423   r4 d2 cis4 | b4. b8 fis2 | e4 d a'2 |
2424 }
2425 bassWords = \sopranoWords
2426 upper = \relative a' {
2427   \clef "treble"
2428   \global
2429   r4 <a d fis>2 <a e' a>4 |
2430   <d fis d'>4. <d fis d'>8 <a d a'>2 |
2431   <g cis g'>4 <a d fis> <a cis e>2 |
2432 }
2433 lower = \relative c, {
2434   \clef "bass"
2435   \global
2436   <d d'>4 <d d'>2 <cis cis'>4 |
2437   <b b'>4. <b' b'>8 <fis fis'>2 |
2438   <e e'>4 <d d'> <a' a'>2 |
2439 }
2440
2441 \score {
2442   <<  % combine ChoirStaff and PianoStaff in parallel
2443     \new ChoirStaff <<
2444       \new Staff = "sopranos" <<
2445         \set Staff.instrumentName = "Soprano"
2446         \new Voice = "sopranos" { \global \sopranoMusic }
2447       >>
2448       \new Lyrics \lyricsto "sopranos" { \sopranoWords }
2449       \new Staff = "altos" <<
2450         \set Staff.instrumentName = "Alto"
2451         \new Voice = "altos" { \global \altoMusic }
2452       >>
2453       \new Lyrics \lyricsto "altos" { \altoWords }
2454       \new Staff = "tenors" <<
2455         \set Staff.instrumentName = "Tenor"
2456         \new Voice = "tenors" { \global \tenorMusic }
2457       >>
2458       \new Lyrics \lyricsto "tenors" { \tenorWords }
2459       \new Staff = "basses" <<
2460         \set Staff.instrumentName = "Bass"
2461         \new Voice = "basses" { \global \bassMusic }
2462       >>
2463       \new Lyrics \lyricsto "basses" { \bassWords }
2464     >>  % end ChoirStaff
2465
2466     \new PianoStaff <<
2467       \set PianoStaff.instrumentName = "Piano"
2468       \new Staff = "upper" \upper
2469       \new Staff = "lower" \lower
2470     >>
2471   >>
2472 }
2473 @end lilypond
2474
2475 None of the templates provides this layout exactly.  The nearest is
2476 @q{SATB vocal score and automatic piano reduction} -- see @ref{Vocal
2477 ensembles} -- but we need to change the layout and add a piano
2478 accompaniment which is not derived automatically from the vocal parts.
2479 The variables holding the music and words for the vocal parts are
2480 fine, but we shall need to add variables for the piano reduction.
2481
2482 The order in which the contexts appear in the ChoirStaff of
2483 the template do not correspond with the order in the vocal
2484 score shown above.  We need to rearrange them so there are
2485 four staves with the words written directly underneath the
2486 notes for each part.
2487 All the voices should be @code{\voiceOne}, which is
2488 the default, so the @code{\voiceXXX} commands should be removed.
2489 We also need to specify the tenor clef for the tenors.
2490 The way in which lyrics are specified in the template has not yet
2491 been encountered so we need to use the method with which we are
2492 familiar.  We should also add the names of each staff.
2493
2494 Doing this gives for our ChoirStaff:
2495
2496 @example
2497     \new ChoirStaff <<
2498       \new Staff = "sopranos" <<
2499         \set Staff.instrumentName = "Soprano"
2500         \new Voice = "sopranos" @{ \global \sopranoMusic @}
2501       >>
2502       \new Lyrics \lyricsto "sopranos" @{ \sopranoWords @}
2503       \new Staff = "altos" <<
2504         \set Staff.instrumentName = "Alto"
2505         \new Voice = "altos" @{ \global \altoMusic @}
2506       >>
2507       \new Lyrics \lyricsto "altos" @{ \altoWords @}
2508       \new Staff = "tenors" <<
2509         \set Staff.instrumentName = "Tenor"
2510         \new Voice = "tenors" @{ \global \tenorMusic @}
2511       >>
2512       \new Lyrics \lyricsto "tenors" @{ \tenorWords @}
2513       \new Staff = "basses" <<
2514         \set Staff.instrumentName = "Bass"
2515         \new Voice = "basses" @{ \global \bassMusic @}
2516       >>
2517       \new Lyrics \lyricsto "basses" @{ \bassWords @}
2518     >>  % end ChoirStaff
2519 @end example
2520
2521 Next we must work out the piano part.  This is
2522 easy - we just pull out the piano part from the
2523 @q{Solo piano} template:
2524
2525 @example
2526 \new PianoStaff <<
2527   \set PianoStaff.instrumentName = "Piano  "
2528   \new Staff = "upper" \upper
2529   \new Staff = "lower" \lower
2530 >>
2531 @end example
2532
2533 and add the variable definitions for @code{upper}
2534 and @code{lower}.
2535
2536 The ChoirStaff and PianoStaff must be combined
2537 using angle brackets as we want them to be
2538 stacked one above the other:
2539
2540 @example
2541 <<  % combine ChoirStaff and PianoStaff one above the other
2542   \new ChoirStaff <<
2543     \new Staff = "sopranos" <<
2544       \new Voice = "sopranos" @{ \global \sopranoMusic @}
2545     >>
2546     \new Lyrics \lyricsto "sopranos" @{ \sopranoWords @}
2547     \new Staff = "altos" <<
2548       \new Voice = "altos" @{ \global \altoMusic @}
2549     >>
2550     \new Lyrics \lyricsto "altos" @{ \altoWords @}
2551     \new Staff = "tenors" <<
2552       \clef "G_8"  % tenor clef
2553       \new Voice = "tenors" @{ \global \tenorMusic @}
2554     >>
2555     \new Lyrics \lyricsto "tenors" @{ \tenorWords @}
2556     \new Staff = "basses" <<
2557       \clef "bass"
2558       \new Voice = "basses" @{ \global \bassMusic @}
2559     >>
2560     \new Lyrics \lyricsto "basses" @{ \bassWords @}
2561   >>  % end ChoirStaff
2562
2563   \new PianoStaff <<
2564     \set PianoStaff.instrumentName = "Piano"
2565     \new Staff = "upper" \upper
2566     \new Staff = "lower" \lower
2567   >>
2568 >>
2569 @end example
2570
2571 Combining all these together and adding the music
2572 for the three bars of the example above gives:
2573
2574 @lilypond[quote,verbatim,ragged-right,addversion]
2575 global = { \key d \major \time 4/4 }
2576 sopranoMusic = \relative c'' {
2577   \clef "treble"
2578   r4 d2 a4 | d4. d8 a2 | cis4 d cis2 |
2579 }
2580 sopranoWords = \lyricmode {
2581   Wor -- thy is the lamb that was slain
2582 }
2583 altoMusic = \relative a' {
2584   \clef "treble"
2585   r4 a2 a4 | fis4. fis8 a2 | g4 fis fis2 |
2586 }
2587 altoWords = \sopranoWords
2588 tenorMusic = \relative c' {
2589   \clef "G_8"
2590   r4 fis2 e4 | d4. d8 d2 | e4 a, cis2 |
2591 }
2592 tenorWords = \sopranoWords
2593 bassMusic = \relative c' {
2594   \clef "bass"
2595   r4 d2 cis4 | b4. b8 fis2 | e4 d a'2 |
2596 }
2597 bassWords = \sopranoWords
2598 upper = \relative a' {
2599   \clef "treble"
2600   \global
2601   r4 <a d fis>2 <a e' a>4 |
2602   <d fis d'>4. <d fis d'>8 <a d a'>2 |
2603   <g cis g'>4 <a d fis> <a cis e>2 |
2604 }
2605 lower = \relative c, {
2606   \clef "bass"
2607   \global
2608   <d d'>4 <d d'>2 <cis cis'>4 |
2609   <b b'>4. <b' b'>8 <fis fis'>2 |
2610   <e e'>4 <d d'> <a' a'>2 |
2611 }
2612
2613 \score {
2614   <<  % combine ChoirStaff and PianoStaff in parallel
2615     \new ChoirStaff <<
2616       \new Staff = "sopranos" <<
2617         \set Staff.instrumentName = "Soprano"
2618         \new Voice = "sopranos" { \global \sopranoMusic }
2619       >>
2620       \new Lyrics \lyricsto "sopranos" { \sopranoWords }
2621       \new Staff = "altos" <<
2622         \set Staff.instrumentName = "Alto"
2623         \new Voice = "altos" { \global \altoMusic }
2624       >>
2625       \new Lyrics \lyricsto "altos" { \altoWords }
2626       \new Staff = "tenors" <<
2627         \set Staff.instrumentName = "Tenor"
2628         \new Voice = "tenors" { \global \tenorMusic }
2629       >>
2630       \new Lyrics \lyricsto "tenors" { \tenorWords }
2631       \new Staff = "basses" <<
2632         \set Staff.instrumentName = "Bass"
2633         \new Voice = "basses" { \global \bassMusic }
2634       >>
2635       \new Lyrics \lyricsto "basses" { \bassWords }
2636     >>  % end ChoirStaff
2637
2638     \new PianoStaff <<
2639       \set PianoStaff.instrumentName = "Piano  "
2640       \new Staff = "upper" \upper
2641       \new Staff = "lower" \lower
2642     >>
2643   >>
2644 }
2645 @end lilypond
2646
2647
2648 @node Building a score from scratch
2649 @subsection Building a score from scratch
2650
2651 @cindex template, writing your own
2652
2653 After gaining some facility with writing LilyPond code, you
2654 may find that it is easier to build a score from scratch
2655 rather than modifying one of the templates.  You can also
2656 develop your own style this way to suit the sort of music you
2657 like.  Let's see how to put together the score for an organ
2658 prelude as an example.
2659
2660 We begin with a header section.  Here go the title, name
2661 of composer, etc, then come any variable definitions, and
2662 finally the score block.  Let's start with these in outline
2663 and fill in the details later.
2664
2665 We'll use the first two bars of Bach's prelude
2666 based on @emph{Jesu, meine Freude} which is written for two
2667 manuals and pedal organ.  You can see these two bars of music
2668 at the bottom of this section.  The top manual part has two voices,
2669 the lower and pedal organ one each.  So we need four
2670 music definitions and one to define the time signature
2671 and key:
2672
2673 @example
2674 \version @w{"@version{}"}
2675 \header @{
2676   title = "Jesu, meine Freude"
2677   composer = "J S Bach"
2678 @}
2679 TimeKey = @{ \time 4/4 \key c \minor @}
2680 ManualOneVoiceOneMusic = @{s1@}
2681 ManualOneVoiceTwoMusic = @{s1@}
2682 ManualTwoMusic = @{s1@}
2683 PedalOrganMusic = @{s1@}
2684
2685 \score @{
2686 @}
2687 @end example
2688
2689 For now we've just used a spacer note, @code{s1},
2690 instead of the real music.  We'll add that later.
2691
2692 Next let's see what should go in the score block.
2693 We simply mirror the staff structure we want.
2694 Organ music is usually written on three staves,
2695 one for each manual and one for the pedals.  The
2696 manual staves should be bracketed together, so we
2697 need to use a PianoStaff for them.  The first
2698 manual part needs two voices and the second manual
2699 part just one.
2700
2701 @example
2702   \new PianoStaff <<
2703     \new Staff = "ManualOne" <<
2704       \new Voice @{ \ManualOneVoiceOneMusic @}
2705       \new Voice @{ \ManualOneVoiceTwoMusic @}
2706     >>  % end ManualOne Staff context
2707     \new Staff = "ManualTwo" <<
2708       \new Voice @{ \ManualTwoMusic @}
2709     >>  % end ManualTwo Staff context
2710   >>  % end PianoStaff context
2711 @end example
2712
2713 Next we need to add a staff for the pedal organ.
2714 This goes underneath the PianoStaff, but it must
2715 be simultaneous with it, so we need angle brackets
2716 around the two.  Missing these out would generate
2717 an error in the log file.  It's a common mistake
2718 which you'll make sooner or later!  Try copying
2719 the final example at the end of this section,
2720 remove these angle brackets, and compile it to
2721 see what errors it generates.
2722
2723 @example
2724 <<  % PianoStaff and Pedal Staff must be simultaneous
2725   \new PianoStaff <<
2726     \new Staff = "ManualOne" <<
2727       \new Voice @{ \ManualOneVoiceOneMusic @}
2728       \new Voice @{ \ManualOneVoiceTwoMusic @}
2729     >>  % end ManualOne Staff context
2730     \new Staff = "ManualTwo" <<
2731       \new Voice @{ \ManualTwoMusic @}
2732     >>  % end ManualTwo Staff context
2733   >>  % end PianoStaff context
2734   \new Staff = "PedalOrgan" <<
2735     \new Voice @{ \PedalOrganMusic @}
2736   >>
2737 >>
2738 @end example
2739
2740 It is not necessary to use the simultaneous construct
2741 @code{<< .. >>} for the manual two staff and the pedal organ staff,
2742 since they contain only one music expression, but it does no harm,
2743 and always using angle brackets after @code{\new Staff} is a good
2744 habit to cultivate in case there are multiple voices.  The opposite
2745 is true for Voices: these should habitually be followed by braces
2746 @code{@{ .. @}} in case your music is coded in several variables
2747 which need to run consecutively.
2748
2749 Let's add this structure to the score block, and adjust the indenting.
2750 We also add the appropriate clefs, ensure stems, ties and slurs in
2751 each voice on the upper staff point to the right direction with
2752 @code{\voiceOne} and @code{\voiceTwo}, and enter the time signature
2753 and key to each staff using our predefined variable, @code{\TimeKey}.
2754
2755 @example
2756 \score @{
2757   <<  % PianoStaff and Pedal Staff must be simultaneous
2758     \new PianoStaff <<
2759       \new Staff = "ManualOne" <<
2760         \TimeKey  % set time signature and key
2761         \clef "treble"
2762         \new Voice @{ \voiceOne \ManualOneVoiceOneMusic @}
2763         \new Voice @{ \voiceTwo \ManualOneVoiceTwoMusic @}
2764       >>  % end ManualOne Staff context
2765       \new Staff = "ManualTwo" <<
2766         \TimeKey
2767         \clef "bass"
2768         \new Voice @{ \ManualTwoMusic @}
2769       >>  % end ManualTwo Staff context
2770     >>  % end PianoStaff context
2771     \new Staff = "PedalOrgan" <<
2772       \TimeKey
2773       \clef "bass"
2774       \new Voice @{ \PedalOrganMusic @}
2775     >>  % end PedalOrgan Staff
2776   >>
2777 @}  % end Score context
2778 @end example
2779
2780 That completes the structure.  Any three-staff organ music
2781 will have a similar structure, although the number of voices
2782 may vary.  All that remains now
2783 is to add the music, and combine all the parts together.
2784
2785 @lilypond[quote,verbatim,ragged-right,addversion]
2786 \header {
2787   title = "Jesu, meine Freude"
2788   composer = "J S Bach"
2789 }
2790 TimeKey = { \time 4/4 \key c \minor }
2791 ManualOneVoiceOneMusic = \relative g' {
2792   g4 g f ees | d2 c2 |
2793 }
2794 ManualOneVoiceTwoMusic = \relative c' {
2795   ees16 d ees8~ ees16 f ees d c8 d~ d c~ |
2796   c c4 b8 c8. g16 c b c d |
2797 }
2798 ManualTwoMusic = \relative c' {
2799   c16 b c8~ c16 b c g a8 g~ g16 g aes ees |
2800   f ees f d g aes g f ees d e8~ ees16 f ees d |
2801 }
2802 PedalOrganMusic = \relative c {
2803   r8 c16 d ees d ees8~ ees16 a, b g c b c8 |
2804   r16 g ees f g f g8 c,2 |
2805   }
2806
2807 \score {
2808   <<  % PianoStaff and Pedal Staff must be simultaneous
2809     \new PianoStaff <<
2810       \new Staff = "ManualOne" <<
2811         \TimeKey  % set time signature and key
2812         \clef "treble"
2813         \new Voice { \voiceOne \ManualOneVoiceOneMusic }
2814         \new Voice { \voiceTwo \ManualOneVoiceTwoMusic }
2815       >>  % end ManualOne Staff context
2816       \new Staff = "ManualTwo" <<
2817         \TimeKey
2818         \clef "bass"
2819         \new Voice { \ManualTwoMusic }
2820       >>  % end ManualTwo Staff context
2821     >>  % end PianoStaff context
2822     \new Staff = "PedalOrgan" <<
2823       \TimeKey
2824       \clef "bass"
2825       \new Voice { \PedalOrganMusic }
2826     >>  % end PedalOrgan Staff context
2827   >>
2828 }  % end Score context
2829 @end lilypond
2830
2831