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