

@c Note:
@c
@c A menu is needed before every deeper *section nesting of @node's; run
@c     M-x texinfo-all-menus-update
@c to automagically fill in these menus before saving changes

@c FIXME: singular vs. plural:  Beams/Beam


@macro refbugs
@strong{BUGS}

@end macro

@ifhtml
@macro internalsref{NAME}
@uref{../lilypond-internals/\NAME\.html,\NAME\}
@cindex \NAME\
@end macro
@macro seeinternals{NAME}
See @internalsref{\NAME\}
@end macro
@end ifhtml


@ifnothtml
@macro seeinternals{NAME}
@end macro
@macro internalsref{NAME}
\NAME\
@cindex \NAME\

@end macro
@end ifnothtml

@c .{Reference Manual}

@node Reference Manual
@chapter Reference Manual

@html
<!--- @@WEB-TITLE@@=Reference Manual --->
@end html

This document describes GNU LilyPond and its input format. The last
revision of this document was made for LilyPond 1.4.1.  It supposes a
passing familiarity with how LilyPond input works. New users are
encouraged to study the tutorial first.

The reference manual is ordered according to different tasks. 
More details on the property setting mechanisms and context handling is
provided in @ref{Tuning output} and @ref{Interpretation context}. The
syntactical details are described at the end of the manual.

@menu
* Overview::                    
* Note entry::                  
* Staff notation::              
* Polyphony::                   
* Beaming::                     
* Expressive marks::            
* Ornaments::                   
* Repeats::                     
* Rhythmic music::              
* Piano music::                 
* Lyrics::                      
* Chords::                      
* Writing parts::               
* Custodes::                    
* Figured bass::                
* Tuning output::               
* Page layout::                 
* Output formats::              
* Sound::                       
* Music entry::                 
* Skipping corrected music::    
* Interpretation context::      
* Syntactic details::           
* Lexical details::             
@end menu

@c . {Overview}
@node Overview
@section Overview


The purpose of LilyPond is explained informally by the term `music
typesetter'.  This is not a fully correct name: not only does the
program print musical symbols, it also makes aesthetic decisions.
Symbols and their placements are @emph{generated} from a high-level
musical description.  In other words, LilyPond would be best described
by `music compiler' or `music to notation compiler'.

LilyPond is linked to GUILE, GNU's Scheme library for extension
programming. The Scheme library provides the glue that holds together
the low-level routines and separate modules which are written in C++.

When lilypond is run to typeset sheet music, the following happens:
@itemize @bullet
@item GUILE Initialization: various scheme files are read
@item parsing: first standard @code{ly} initialization  files are read, and
then the user @file{ly} file is read.
@item interpretation: the music in the file is processed ``in playing
order'', i.e. the order that  you  use to read sheet music, or the
order in which notes are played. The result of this step is a typesetting
specification.

@item typesetting:
The typesetting specification is solved: positions and formatting is
calculated.

@item the visible results ("virtual ink") are written to the output file.
@end itemize

During these stages different types of data play the the main role:
during parsing, @strong{Music} objects are created.  During the
interpretation, @strong{contexts} are constructed, and with these contexts
a network of @strong{graphical objects} (``grobs'') is created. These
grobs contain unknown variables, and the network forms a set of
equations. After solving the equations and filling in these variables,
the printed output (in the form of @strong{molecules}) is written to an
output file.

These threemanship of tasks (parsing, translating, typesetting) and
data-structures (music, context, graphical objects) permeates the entire
design of the program.

@c FIXME: Note entry vs Music entry at top level menu is confusing.
@c . {Note entry}
@node Note entry
@section Note entry
@cindex Note entry

The most basic forms of music are notes. We discuss how you enter them
here.  Notes on their own don't form valid input, but for the sake of
brevity we omit obligatory lint such as @code{\score} blocks and
@code{\paper} declarations.


@menu
* Notes::                       
* Pitches::                     
* Rests::                       
* Skips::                       
* Durations::                   
* Ties::                        
* Tuplets::                     
* Defining pitch names::        
* Easy Notation note heads ::   
@end menu

@c . {Notes}
@node Notes
@subsection Notes

A note specification has the form

@example
  @var{pitch}[!][?][@var{duration}]
@end example

The alteration refers to what note is heard, not to whether an
accidental is printed. This is done depending on the key and context.
A reminder accidental
@cindex reminder accidental
@cindex @code{?}
can be forced by adding an exclamation mark @code{!} after the pitch.  A
cautionary accidental,
@cindex cautionary accidental
@cindex parenthesized accidental
i.e., an accidental within parentheses can be obtained by adding the
question mark `@code{?}' after the pitch.

@lilypond[fragment,verbatim,center]
  cis' d' e' cis'  c'? d' e' c'!
@end lilypond

The grob for a note head is called @internalsref{NoteHead}.


@c .  {Pitches}
@node Pitches
@subsection Pitches

@cindex Pitch names
@cindex Note specification
@cindex pitches
@cindex entering notes

The verbose syntax for pitch specification is

@cindex @code{\pitch}
@example
  \pitch @var{scmpitch}
@end example

@var{scmpitch} is a pitch scheme object, see @ref{Pitch data type}.

In Note and Chord mode, pitches may be designated by names.  The default
names are the Dutch note names.  The notes are specified by the letters
@code{a} through @code{g} (where the octave is formed by notes ranging
from @code{c} to @code{b}).  The pitch @code{c} is an octave below
middle C and the letters span the octave above that C.

@cindex note names, Dutch

In Dutch, a sharp is formed by adding @code{-is} to the end of a pitch
name and a flat is formed by adding @code{-es}. Double sharps and double
flats are obtained by adding @code{-isis} or @code{-eses}.  @code{aes}
and @code{ees} are contracted to @code{as} and @code{es} in Dutch, but
both forms are accepted.

LilyPond has predefined sets of note names for various other languages.
To use them, simply include the language specific init file.  For
example: @code{\include "english.ly"}.  The available language files and
the names they define are:

@example 
                        Note Names               sharp       flat
nederlands.ly  c   d   e   f   g   a   bes b   -is         -es
english.ly     c   d   e   f   g   a   bf  b   -s/-sharp   -f/-flat
deutsch.ly     c   d   e   f   g   a   b   h   -is         -es
norsk.ly       c   d   e   f   g   a   b   h   -iss/-is    -ess/-es
svenska.ly     c   d   e   f   g   a   b   h   -iss        -ess
italiano.ly    do  re  mi  fa  sol la  sib si  -d          -b
catalan.ly     do  re  mi  fa  sol la  sib si  -d/-s       -b 
@end example 

@cindex @code{'}
@cindex @code{,}



The optional octave specification takes the form of a series of
single quote (`@code{'}') characters or a series of comma
(`@code{,}') characters.  Each @code{'} raises the pitch by one
octave; each @code{,} lowers the pitch by an octave.

@lilypond[fragment,verbatim,center]
  c' c'' es' g' as' gisis' ais'  
@end lilypond

@c .  {Rests}
@node  Rests
@subsection Rests
@cindex Rests

A rest is entered like a note, with note name `@code{r}':

@lilypond[singleline,verbatim]
r1 r2 r4 r8
@end lilypond

The grob is @internalsref{Rest}. Whole bar rests centered in the bar are
specified using @code{R}, see @ref{Multi measure rests}.

For polyphonic music, it can be convenient to specify the rest position
directly. You can do that by entering a note, with the keyword
@code{\rest} appended, e.g. Rest collisions will leave these rests alone.

@lilypond[singleline,verbatim]
a'4\rest d'4\rest
@end lilypond


@c .  {Skips}
@c FIXME: naming.
@node Skips
@subsection Skips
@cindex Skip
@cindex Invisible rest
@cindex Space note

An invisible rest, or skip, can be entered like a note with note name
`@code{s}':

@lilypond[singleline,verbatim]
a2 s4 a4 s1 a4
@end lilypond

Actually, this is a shorthand for the @code{\skip} command, and it is
only available in Note mode and Chord mode.

@c FIXME: in lyrics mode, we have " " and _

In Lyrics mode, you can use `@code{" "}' and `@code{_}':
@lilypond[singleline,verbatim]
<
  \context Lyrics \lyrics { lah2 di4 " " dah2 _4 di }
  \notes\relative c'' { a2 a4 a a2 a4 a }
>
@end lilypond

The unabbreviated `@code{\skip} @var{duration}' also works outside of
note mode:

@lilypond[singleline,verbatim]
\score {
  \context Staff <
    { \time 4/8 \skip 2 \time 4/4 } 
    \notes\relative c'' { a2 a1 }
  >
}
@end lilypond

Note that the skip does not produce any output, not even transparent output.


@c .  {Durations}
@node Durations
@subsection Durations


@cindex duration
@cindex @code{\duration}

The syntax for a verbose duration specification is
@example
 \duration @var{scmduration}
@end example
Here, @var{scmduration} is a Scheme object of type @code{Duration}. See
@ref{Duration} for more information.


In Note, Chord, and Lyrics mode, durations may be designated by numbers
and dots: durations are entered as their reciprocal values.  For notes
longer than a whole you must use identifiers.

@example 
 c'\breve  
c'1 c'2 c'4 c'8 c'16 c'32 c'64 c'64 
r\longa r\breve  
r1 r2 r4 r8 r16 r32 r64 r64 
@end example 


@lilypond[]
\score {
  \notes \relative c'' {
    a\breve  \autoBeamOff
    a1 a2 a4 a8 a16 a32 a64 a64 
    r\longa r\breve  
    r1 r2 r4 r8 r16 r32 r64 r64 
  }
  \paper {
    \translator {
      \StaffContext
        \remove "Clef_engraver"
        \remove "Staff_symbol_engraver"
        \remove "Time_signature_engraver"
        \consists "Pitch_squash_engraver"
    }
  }
}
@end lilypond

 To get a longa note head, you have to use mensural note heads. This
is accomplished by setting the @code{style} property of the
NoteHead grob to @code{mensural}. There is also a note head style
@code{baroque} which gives mensural note heads for @code{\longa} and
@code{\breve} but standard note heads for shorter notes.

@lilypond[fragment,singleline,verbatim]
 \property Voice.NoteHead \set #'style = #'mensural
 a'\longa
@end lilypond

If the duration is omitted then it is set to the previous duration
entered.  At the start of parsing a quarter note is assumed.  The
duration can be followed by dots (`@code{.}')  to obtain dotted note
lengths.
@cindex @code{.}

@lilypond[fragment,verbatim,center]
  a'4. b'4.. c'8.
@end lilypond
@cindex @code{r}
@cindex @code{s}

You can alter the length of duration by a fraction @var{N/M} by
appending `@code{*}@var{N/M}' (or `@code{*}@var{N}' if @var{M=1}). This
will not affect the appearance of the notes or rests produced.




@node Ties
@subsection Ties

@cindex Tie
@cindex ties
@cindex @code{~}

A tie connects two adjacent note heads of the same pitch.  When used
with chords, it connects all the note heads whose pitches match.
Ties are indicated using the tilde symbol `@code{~}'.  If you try to tie
together chords which have no common pitches then no ties will be
created.

@lilypond[fragment,verbatim,center]
  e' ~ e' <c' e' g'> ~ <c' e' g'>
@end lilypond

If you dislike the amount of ties created for a chord, you set
@code{Voice.sparseTies} to true, resulting in  a smaller number of
ties:
@lilypond[fragment,verbatim,center]
  \property Voice.sparseTies = ##t
  <c' e' g'> ~ <c' e' g'>
@end lilypond

In its meaning a tie is just a way of extending a note duration, similar
to the augmentation dot: the following example are two ways of notating
exactly the same concept.
@c
@lilypond[fragment, singleline]
\time 3/4 c'2. c'2 ~ c'4
@end lilypond

The name of the tie grob is @internalsref{Tie}, and it is created in the
@internalsref{Voice} context.

@refbugs

At present, the tie is implemented as a separate thing, temporally
located in between the notes. There is also no way to convert
between tied notes, dotted notes and plain notes.

Tieing only a subset of the note heads of a chord is not supported in a
simple way.  It can be achieved by moving the tie-engraver into the Thread
context and turning on and off ties per Thread.


@node Tuplets
@subsection Tuplets

@cindex tuplets
@cindex triplets
@cindex @code{\times}

Tuplets are made out of a music expression by multiplying all duration
with a fraction.

@cindex @code{\times}
@example
  \times @var{fraction} @var{musicexpr}
@end example

The duration of @var{musicexpr} will be multiplied by the fraction. 
In print, the fraction's denominator will be printed over the notes,
optionally with a bracket.  The most common tuplet is the triplet in
which 3 notes have the length of 2, so the notes are 2/3 of
their written length:

@lilypond[fragment,verbatim,center]
  g'4 \times 2/3 {c'4 c' c'} d'4 d'4
@end lilypond

The property @code{tupletSpannerDuration} specifies how long each bracket
should last.  With this, you can make lots of tuplets while typing
@code{\times} only once, thus  saving typing work.

@lilypond[fragment,  relative, singleline, verbatim]
\property Voice.tupletSpannerDuration = #(make-moment 1 4)
\times 2/3 { c'8 c c c c c }
@end lilypond

The format of the number is determined by the property
@code{tupletNumberFormatFunction}. The default prints only the
denominator, but if you set it to the Scheme function
@code{fraction-tuplet-formatter}, Lilypond will print @var{num}:@var{den}
instead.

The typesetting of brackets and numbers is controlled by the properties
@code{tuplet-bracket-visibility} and @code{tuplet-number-visibility}. 

@lilypond[fragment,  relative, singleline, verbatim]
\property Voice.TupletBracket \set #'tuplet-bracket-visibility = ##t
\times 2/3{c'8 d e} \times 2/3{d4 e8} 
\property Voice.TupletBracket \set #'tuplet-bracket-visibility = #'if-no-beam
\times 2/3{c d e} \times 2/3{d4 e8} 
\property Voice.TupletBracket \set #'tuplet-bracket-visibility = ##f
\times 2/3{c d e} \times 2/3{d4 e8}
\property Voice.TupletBracket \set #'tuplet-number-visibility = ##f
\times 2/3{c d e} \times 2/3{d4 e8}
\property Voice.TupletBracket \set #'tuplet-number-visibility = #'if-no-beam
\times 2/3{c d e} \times 2/3{d4 e8}
@end lilypond

@cindex @code{tupletNumberFormatFunction}
@cindex tuplet formatting 

Tuplet brackets are printed as @internalsref{TupletBracket} grobs, most
often in the @internalsref{Voice} context.

@c .  {Defining pitch names}
@node Defining pitch names
@subsection Defining pitch names

@cindex defining pitch names
@cindex pitch names, defining 

Note names and chord modifiers can be customized for nationalities.  The
syntax is as follows.

@cindex @code{\pitchnames}
@cindex @code{\chordmodifiers}
@example
   \pitchnames @var{scheme-alist}
   \chordmodifiers @var{scheme-alist}
@end example

See @file{ly/nederlands.ly} and @file{ly/chord-modifiers.ly} for
specific examples on how to do this.


@node Easy Notation note heads 
@subsection Easy Notation note heads

@cindex easy notation
@cindex Hal Leonard

A entirely different type of note head is the "easyplay" note head: a
note head that includes a note name.  It is used in some publications by
Hal-Leonard Inc.  music publishers.

@lilypond[singleline,verbatim]
\include "paper23.ly"
\score {
  \notes { c'2 e'4 f' | g'1 }
  \paper { \translator { \EasyNotation } } 
}
@end lilypond

Note that @internalsref{EasyNotation} overrides a @internalsref{Score} context.  You
probably will want to print it with magnification to make it more
readable, see @ref{Output scaling}.


@cindex Xdvi
@cindex ghostscript

If you view the result with Xdvi, then staff lines will show through the
letters.  Printing the postscript file obtained either by using dvips or
the @code{-f ps} option of lilypond produces the correct result.



@node Staff notation
@section Staff notation

@cindex Staff notation

@menu
* Key signature::               
* Clef::                        
* Time signature::              
* Unmetered music::             
* Bar lines::                   
@end menu

@c .  {Key}
@node Key signature
@subsection Key signature
@cindex Key

@cindex @code{\key}

Setting or changing the key signature is done with the @code{\key}
command.
@example
  @code{\key} @var{pitch} @var{type}
@end example

@cindex @code{\minor}
@cindex @code{\major}
@cindex @code{\minor}
@cindex @code{\ionian}
@cindex @code{\locrian}
@cindex @code{\aeolian}
@cindex @code{\mixolydian}
@cindex @code{\lydian}
@cindex @code{\phrygian}
@cindex @code{\dorian}

Here, @var{type} should be @code{\major} or @code{\minor} to get
@var{pitch}-major or @var{pitch}-minor, respectively.
The standard mode names @code{\ionian},
@code{\locrian}, @code{\aeolian}, @code{\mixolydian}, @code{\lydian},
@code{\phrygian}, and @code{\dorian} are also defined.

This command sets the context property @code{Staff.keySignature}. 
Non-standard key signatures can be specified by setting this property
directly.

The printed signature is a @internalsref{KeySignature} grob, typically
created in @internalsref{Staff} context.

@cindex @code{keySignature}

@c .  {Clef}
@node Clef
@subsection Clef
@cindex @code{\clef}

The clef can be set or changed with the @code{\clef} command.
@example
  \clef @var{clefname}
@end example

Shortcut for

@example
  \property Staff.clefGlyph = @var{glyph associated with clefname} 
  \property Staff.clefPosition = @var{clef Y-position for clefname}
  \property Staff.centralCPosition = @var{position for central C} 
  \property Staff.clefOctavation = @var{extra transposition of clefname}
@end example


Any change in these properties creates a clef (A @internalsref{Clef} grob).

Supported clef-names include 

@c Moved standard clefs to the top /MB
@table @code
@item treble, violin, G, G2
G clef on 2nd line
@item alto, C
 C clef on 3rd line
@item tenor
 C clef on 4th line
@item bass, F
 F clef on 4th line
@item french
 G clef on 1st line, so-called French violin clef
@item soprano
 C clef on 1st line
@item mezzosoprano
 C clef on 2nd line
@item baritone
 C clef on 5th line
@item varbaritone
 F clef on 3rd line
@item subbass
 F clef on 5th line
@item percussion
 percussion clef
@end table

By adding @code{_8} or @code{^8} to the clef name, the clef is
transposed one octave down or up, respectively.  Note that you have to
enclose @var{clefname} in quotes if you use underscores or digits in the
name. For example,
@example
	\clef "G_8"
@end example 

Supported associated glyphs (for @code{Staff.clefGlyph}) are:

@table @code
@item clefs-C
 modern style C clef
@item clefs-F
 modern style F clef
@item clefs-G
 modern style G clef
@item clefs-vaticana_do
 Editio Vaticana style do clef
@item clefs-vaticana_fa
 Editio Vaticana style fa clef
@item clefs-medicaea_do
 Editio Medicaea style do clef
@item clefs-medicaea_fa
 Editio Medicaea style fa clef
@item clefs-mensural1_c
 modern style mensural C clef
@item clefs-mensural2_c
 historic style small mensural C clef
@item clefs-mensural3_c
 historic style big mensural C clef
@item clefs-mensural1_f
 historic style traditional mensural F clef
@item clefs-mensural2_f
 historic style new mensural F clef
@item clefs-mensural_g
 historic style mensural G clef
@item clefs-hufnagel_do
 historic style hufnagel do clef
@item clefs-hufnagel_fa
 historic style hufnagel fa clef
@item clefs-hufnagel_do_fa
 historic style hufnagel combined do/fa clef
@item clefs-percussion
 modern style percussion clef
@end table

@emph{Modern style} means ``as is typeset in current editions.''
@emph{Historic style} means ``as was typeset or written in contemporary
historic editions''.  @emph{Editio XXX style} means ``as is/was printed in
Editio XXX.''

@cindex Vaticana, Editio
@cindex Medicaea, Editio
@cindex hufnagel clefs


@c .  {Time signature}
@node Time signature
@subsection Time signature
@cindex Time signature
@cindex meter
@cindex @code{\time}

The time signature is set or changed by the @code{\time}
command. Syntax:
@example
  \time @var{n}@code{/}@var{d} 
@end example
Internally, this is a shortcut for doing
@example
\property Score.timeSignatureFraction = #'(@var{n} . @var{d})
\property Score.beatLength = #(make-moment 1 @var{d})
\property Score.measureLength = #(make-moment @var{n} @var{d})
@end example

These properties @code{timeSignatureFraction} determine where bar lines
should be inserted, and how automatic beams should be
generated.

Changing the value of @code{timeSignatureFraction} also causes a
fraction to be printed. This grob is @internalsref{TimeSignature}.

The actual symbol that's printed can be customized with the style
property.
@lilypond[fragment, verbatim, singleline]
\time 3/4 s2
\property Staff.TimeSignature \override #'style = #'C
\time 4/4 s2
\property Staff.TimeSignature \override #'style = #'()
\time 4/4 s2
\property Staff.TimeSignature \override #'style = #'C
\time 2/2 s2
@end lilypond

There are many more options for the layout of this grob. They are
selected through the @code{style} grob property.

@c FIXME: this isn't documented except in example?
See
@file{input/test/time.ly} for examples.

@c .   {Partial}
@subsection Partial
@cindex Partial
@cindex anacrusis
@cindex upbeat
@cindex partial measure
@cindex measure, partial
@cindex shorten measures
@cindex @code{\partial}

Partial measures, for example in upbeats, are entered using the
@code{\partial} command: 
@example
  \partial @var{duration} 
@end example

Internally,  this is a shortcut for 

@example
  \property Score.measurePosition = -@var{length of duration}
@end example
@cindex @code{|}

The property @code{measurePosition} contains a rational number
indicating how much of the measure has passed at this point. 


@node Unmetered music
@subsection Unmetered music

Bar lines and bar numbers are calculated automatically. For unmetered
music (e.g. cadenzas), this is not desirable. The property
@code{Score.timing} can be used to switch off this automatic timing

@lilypond[fragment,relative,singleline,verbatim]
c'2.
\property Score.timing = ##f
c2
\property Score.timing = ##t
c4 c4 c4 
@end lilypond

The identifiers @code{\cadenzaOn} and @code{\cadenzaOff} can be used as
shortcuts.



@c .   {Bar lines}
@node Bar lines
@subsection Bar lines
@cindex Bar lines

@cindex @code{\bar}
@cindex measure lines
@cindex repeat bars

@example
  \bar @var{bartype}
@end example

This is a shortcut for doing
@example
  \property Score.whichBar = @var{bartype} 
@end example
The following bar types are available

@lilypond[fragment,  relative, singleline, verbatim]
c4
\bar "|" c
\bar "" c
\bar "|:" c
\bar "||" c
\bar ":|" c
\bar ".|" c
\bar ".|." c
\bar "|." 
@end lilypond


You are encouraged to use @code{\repeat} for repetitions.  See
@ref{Repeats}.


@cindex Bar_line_engraver
@cindex whichBar
@cindex repeatCommands
@cindex defaultBarType

Whenever @code{whichBar} is set to a string, a bar line of that type is
created.  @code{whichBar} is usually set automatically: at the start of
a measure it is set to @code{defaultBarType}. The contents of
@code{repeatCommands} is used to override default measure bars.

@code{whichBar} can also be set directly, using @code{\property} or
@code{\bar  }.  These settings take precedence over the automatic
@code{whichBar} settings. 

@internalsref{BarLine} grobs are created by the @code{Bar_engraver}.

@c .   {Polyphony}
@node Polyphony
@section Polyphony
@cindex polyphony

Polyphonic parts, i.e. parts with more than one voice on a staff can be
typeset with LilyPond.

The easiest way to enter such fragments, is the Scheme function
@code{voicify-music}. It will split chords using the separator
@code{\\}, to make multiple voices.  You can use it for small,
short-lived voices (make a chord of voices) or for single chords:

@lilypond[verbatim,fragment]
\context Voice = VA \apply #voicify-music \relative c'' {
 c4 < { f d e  } \\ { b c2 } > c4 < g' \\ c, \\  f \\ d >
}
@end lilypond

The function @code{voicify-music} instantiates @internalsref{Voice}
contexts, bearing the names @code{"1"}, @code{"2"}, etc.

To explicity typeset polyphonic music, instantiate a separate Voice
context for each part, and assign a stem direction to each part.
@c
@lilypond[fragment,verbatim]
\context Staff
< \context Voice = VA { \stemUp b'4 a' g' f' e' }
  \context Voice = VB { \stemDown g'4 g' g' g' g' } >
@end lilypond

When there are more than two voices on a staff, you must also indicate
which voice should moved horizontally in case of a collision. This can
be done with the identifiers @code{\shiftOff}, @code{\shiftOn},
@code{\shiftOnn}, etc. (which sets the grob property @code{horizontal-shift}
in @internalsref{NoteColumn}).

@lilypond[fragment, verbatim]
  \context Staff \notes\relative c''<
       \context Voice=one {
       \shiftOff \stemUp e4
       }
       \context Voice=two {
          \shiftOn \stemUp cis
       }
       \context Voice=three {
         \shiftOnn \stemUp ais
       }
       \context Voice=four {
          \shiftOnnn \stemUp fis
       }
  >
@end lilypond

The most convenient way is to use the identifiers @code{\voiceOne}
through @code{\voiceFour}, which also set slur and tie directions in the
correct manner.

@lilypond[singleline, verbatim]
\relative c''
\context Staff < \context Voice = VA { \voiceOne cis2 b  }
  \context Voice = VB { \voiceThree b4 ais ~ ais4 gis4 } 
  \context Voice = VC { \voiceTwo fis4~  fis4 f ~ f  } >
@end lilypond

Normally, note heads with a different number of dots are not merged, but
if you set the grob property @code{merge-differently-dotted}, they are:

@lilypond[verbatim,fragment,singleline]
  \context Staff <
  \context Voice = VA { \voiceOne
     g'8 g'8 
     \property Staff.NoteCollision \override #'merge-differently-dotted = ##t
     g'8 g'8
  }
  \context Voice = VB { \voiceTwo [g'8. f16] [g'8. f'16] } 
  >
@end lilypond

LilyPond also vertically shifts rests that are opposite of a stem. 

@lilypond[singleline,verbatim]
\context Staff <
\context Voice {  \stemUp c''4  }
\context Voice =VB { r4 }
>
@end lilypond

Note head collisions (horizontal shifting of note heads) are handled by
the @internalsref{NoteCollision} grob. @internalsref{RestCollision}
handles vertical shifting of rests.





@refbugs

Resolving collisions is a very intricate subject, and LilyPond only
handles a few situations. When it can not cope, you are advised to use
@code{force-hshift} of the NoteColumn grob and @code{staff-position} of
the Rest grob to override typesetting decisions.

@node Beaming
@section Beaming

Beams are used to group short notes into chunks that are aligned with
the metrum.  LilyPond guesses where beams should be inserted. If you're
not satisfied with the automatic beaming, you can specify which patterns
to beam automatically. In specific cases, you can also enter the beams
explicitly.


@c .    {Automatic beams}
@subsection Automatic beams

@cindex @code{Voice.autoBeamSettings}
@cindex @code{(end * * * *)}
@cindex @code{(begin * * * *)}


In normal time signatures, automatic beams can start on any note but can
only end in a few positions within the measure: beams can end on a beat,
or at durations specified by the properties in
@code{Voice.autoBeamSettings}. The defaults for @code{autoBeamSettings}
are defined in @file{scm/auto-beam.scm}.

The value of @code{autoBeamSettings} is changed using
@code{\override} and unset using @code{\revert}:
@example
\property Voice.autoBeamSettings \override #'(@var{BE} @var{P} @var{Q} @var{N} @var{M}) = @var{dur}
\property Voice.autoBeamSettings \revert #'(@var{BE} @var{P} @var{Q} @var{N} @var{M})
@end example
Here, @var{BE} is the symbol @code{begin} or @code{end}. It determines
whether the rule applies to begin or end-points.  The quantity
@var{P}/@var{Q} refers to the length of the beamed notes (and `@code{*
*}' designates notes of any length), @var{N}/@var{M} refers to a time
signature (wildcards, `@code{* *}' may be entered to designate all time
signatures).

For example, if you want automatic beams to end on every quarter note,
you can use the following:
@example
\property Voice.autoBeamSettings \override
    #'(end * * * *) = #(make-moment 1 4)
@end example
Since the duration of a quarter note is 1/4 of a whole note, it is
entered as @code{(make-moment 1 4)}.

The same syntax can be used to specify beam starting points. In this
example, automatic beams can only end on a dotted quarter note. 
@example
\property Voice.autoBeamSettings \override
    #'(end * * * *) = #(make-moment 3 8)
@end example
In 4/4 time signature, this means that automatic beams could end only on
3/8 and on the fourth beat of the measure (after 3/4, that is 2 times
3/8 has passed within the measure).

You can also restrict rules to specific time signatures. A rule that
should only be applied in @var{N}/@var{M} time signature is formed by
replacing the second asterisks by @var{N} and @var{M}. For example, a
rule for 6/8 time exclusively looks like
@example
\property Voice.autoBeamSettings \override
    #'(begin * * 6 8) =  ... 
@end example

If you want a rule to apply to certain types of beams, you can use the
first pair of asterisks. Beams are classified according to the shortest
note they contain. For a beam ending rule that only applies to beams
with 32nd notes (and no shorter notes), you would use @code{(end 1
32 * *)}.

@c not true
@c Automatic beams can not be put on the last note in a score.

If a score ends while an automatic beam has not been ended and is still
accepting notes, this last beam will not be typeset at all.

@cindex automatic beam generation
@cindex autobeam
@cindex @code{Voice.noAutoBeaming}

Automatic beaming is on by default, but can be switched off by setting
@code{Voice.noAutoBeaming} to true.  You you may find this necessary for
a melody that goes with lyrics.

@refbugs

It is not possible to specify beaming parameters for beams with mixed
durations, that differ from the beaming parameters of all separate
durations, i.e., you'll have to specify manual beams to get:
@lilypond[fragment,singleline,relative]
  \property Voice.autoBeamSettings
  \override #'(end * * * *) = #(make-moment 3 8)
  \time 12/8 c'8 c c c16 c c c c c [c c c c] c8 c c4
@end lilypond

It is not possible to specify beaming parameters that act differently in
different parts of a measure. This means that it is not possible to use
automatic beaming in irregular meters such as @code{5/8}.

@c .    {Manual beams}
@cindex Automatic beams
@subsection Manual beams
@cindex beams, manual
@cindex @code{]}
@cindex @code{[}

In some cases it may be necessary to override LilyPond's automatic
beaming algorithm.  For example, the auto beamer will not beam over
rests or bar lines, If you want that, specify the begin and end point
manually using a @code{[} before the first beamed note and a @code{]}
after the last note:

@lilypond[fragment,relative,verbatim]
  \context Staff {
    r4 [r8 g' a r8] r8 [g | a] r8
  }
@end lilypond
Whenever an manual beam is busy, the automatic beamer will not produce
anything.

@cindex @code{stemLeftBeamCount}

Normally, beaming patterns within a beam are determined automatically.
When this mechanism fouls up, the properties
@code{Voice.stemLeftBeamCount} and @code{Voice.stemRightBeamCount}.  can
be used to control the beam subdivision on a stem.  If you set either
property, it's value will be used only once, and then it is erased.

@lilypond[fragment,relative,verbatim]
  \context Staff {
    [f8 r16 f g a]
    [f8 r16 \property Voice.stemLeftBeamCount = #1 f g a]
  }
@end lilypond
@cindex @code{stemRightBeamCount}

The beam symbol (grob @internalsref{Beam} in @internalsref{Voice}
context), both for automatic and manual beams) can be tweaked through
grob-properties @code{height} and @code{staff-position}. These specify
vertical location and vertical span. Both are measured in half
staff-spaces, @code{staff-position=0} corresponds to the middle staff
line.

Set @code{height} to zero, to get horizontal beams:

@lilypond[fragment,relative,verbatim]
  \property Voice.Beam \set #'direction = #1
  \property Voice.Beam \set #'height = #0
  [a'8 e' d c]
@end lilypond

Here's how you'd specify a weird looking beam that instead of being
horizontal, falls two staff spaces:


[FIXME]


@lilypond[fragment,relative,verbatim]
  \property Voice.Beam \set #'staff-position = #4
  \property Voice.Beam \set #'height = #-4
  [c8 c] 
@end lilypond

[TODO: doc autokneeing ? ]

@c TODO -> why this ref? Document? 
@cindex @code{neutral-direction}

@node Expressive marks
@section Expressive marks

@c .   {Slurs}
@menu
* Slurs ::                      
* Phrasing slurs::              
* Breath marks::                
* Tempo::                       
* Text spanners::               
@end menu

@node Slurs 
@subsection Slurs
@cindex slurs

A slur indicates that notes are to be played bound or @emph{legato}.
They are entered using parentheses:

@lilypond[fragment,verbatim,center]
  f'()g'()a' [a'8 b'(] a'4 g'2 )f'4
@end lilypond


Slurs avoid crossing stems, and are generally attached to note heads.
However, in some situations with beams, slurs may be attached to stem
ends.  If you want to override this layout you can do this through the
grob-property @code{attachment} of @internalsref{Slur} in
@internalsref{Voice} context It's value is a pair of symbols, specifying
the attachment type of the left and right end points.

@lilypond[fragment,relative,verbatim]
  \property Voice.Slur \set #'direction = #1
  \property Voice.Stem \set #'length = #5.5
  g'8(g)g4
  \property Voice.Slur \set #'attachment = #'(stem . stem)
  g8(g)g4
@end lilypond

If a slur would strike through a stem or beam, the slur will be moved
away upward or downward. If this happens, attaching the slur to the
stems might look better:

@lilypond[fragment,relative,verbatim]
  \property Voice.Stem \set #'direction = #1
  \property Voice.Slur \set #'direction = #1
  d32( d'4 )d8..
  \property Voice.Slur \set #'attachment = #'(stem . stem)
  d,32( d'4 )d8..
@end lilypond


Similarly, the curvature of a slur is adjusted to stay clear of note
heads and stems.  When that would increase the curvature too much, the
slur is reverted to its default shape.  The threshold for this decision
is in @internalsref{Slur}'s grob-property @code{beautiful}.  It is loosely
related to the enclosed area between the slur and the notes.  Usually,
the default setting works well, but in some cases you may prefer a
curved slur when LilyPond decides for a vertically moved one.  You can
indicate this preference by increasing the @code{beautiful} value:

@lilypond[verbatim,singleline,relative]
  \property Voice.Beam \override #'direction = #-1
  \property Voice.Slur \override #'direction = #1
  c16( a' f' a a f a, )c,
  c( a' f' a a f d, )c
  \property Voice.Slur \override #'beautiful = #5.0
  c( a' f' a a f d, )c
@end lilypond

@refbugs

@code{beautiful} is an arbitrary parameter in the slur formatter.
Useful values can only be determined by trial and error.

@cindex Adjusting slurs

@node Phrasing slurs
@subsection Phrasing slurs

@cindex phrasing slurs
@cindex phrasing marks

A phrasing slur (or phrasing mark) connects chords and is used to
indicate a musical sentence. It is started using @code{\(} and @code{\)}
respectively.

@lilypond[fragment,verbatim,center,relative]
  \time 6/4 c' \( ( d ) e f ( e ) \) d
@end lilypond

Typographically, the phrasing slur behaves almost exactly like a normal
slur. The grob associated with it is @internalsref{PhrasingSlur}, in
@internalsref{Voice} context.

@node Breath marks
@subsection Breath marks

Breath marks are entered using @code{\breathe}.  The result is a
@internalsref{BreathingSign} grob in @internalsref{Voice} context.

@lilypond[fragment,relative]
c'4 \breathe d4
@end lilypond




@refbugs

The current layout of the default comma style breath marks
could be improved and more optional symbols should be added to the
font.



@c .  {Tempo}
@node Tempo
@subsection Tempo
@cindex Tempo
@cindex beats per minute
@cindex metronome marking

Metronome settings can be entered as follows:

@cindex @code{\tempo}
@example
  \tempo @var{duration} = @var{perminute} 
@end example

For example, @code{\tempo 4 = 76} requests output with 76 quarter notes
per minute.
  
@refbugs
  
The tempo setting is not printed, but is only used in the MIDI
output. You can trick lily into producing a metronome mark,
though. Details are in @ref{Text markup}.
  


@node Text spanners
@subsection Text spanners
@cindex Text spanners

Some textual indications, e.g. rallentando or accelerando, often extend
over many measures. This is indicated by following the text with a
dotted line.  You can create such texts using text spanners. The syntax
is as follows:
@example
\spanrequest \start "text"
\spanrequest \stop "text"
@end example
LilyPond will respond by creating a @internalsref{TextSpanner} grob (typically
in @internalsref{Voice} context).  The string to be printed, as well as the
style is set through grob properties.

An application---or rather, a hack---is to fake octavation indications.
@lilypond[fragment,relative,verbatim]
 \relative c' {  a''' b c a
  \property Voice.TextSpanner \set #'type = #'dotted-line
  \property Voice.TextSpanner \set #'edge-height = #'(0 . 1.5)
  \property Voice.TextSpanner \set #'edge-text = #'("8va " . "")
  \property Staff.centralCPosition = #-13
  a\spanrequest \start "text" b c a \spanrequest \stop "text" }
@end lilypond


@c .  {Ornaments}
@node Ornaments
@section Ornaments
@cindex Ornaments
@menu
* Articulations::               
* Text scripts::                
* Grace notes::                 
* Glissando ::                  
* Dynamics::                    
@end menu

@c .   {Articulation}
@node Articulations
@subsection Articulations
@cindex Articulations

@cindex articulations
@cindex scripts
@cindex ornaments

A variety of symbols can appear above and below notes to indicate
different characteristics of the performance.  These symbols can be
added to a note with `@var{note}@code{-\}@var{name}'.  Numerous symbols
are defined in @file{script.ly}.  Symbols can be forced to appear above
or below the note by writing `@var{note}@code{^\}@var{name}' and
`@var{note}@code{_\}@var{name}' respectively.  Here is a chart showing
symbols on notes, with the name of the corresponding symbol appearing
underneath.

@lilypond[]
  \score {
    <
      \property Score.LyricSyllable \override #'font-family =#'typewriter
      \property Score.LyricSyllable \override #'font-shape = #'upright
      \context Staff \notes {
        c''-\accent      c''-\marcato      c''-\staccatissimo c''^\fermata 
        c''-\stopped     c''-\staccato     c''-\tenuto        c''-\upbow
        c''-\downbow     c''^\lheel        c''-\rheel         c''^\ltoe
        c''-\rtoe        c''-\turn         c''-\open          c''-\flageolet
        c''-\reverseturn c''-\trill        c''-\prall         c''-\mordent
        c''-\prallprall  c''-\prallmordent c''-\upprall       c''-\downprall
        c''-\upmordent   c''-\downmordent  c''-\pralldown     c''-\prallup
        c''-\lineprall   c''-\thumb        c''-\segno         c''-\coda
      }
      \context Lyrics \lyrics {
        accent__      marcato__      staccatissimo__ fermata
        stopped__     staccato__     tenuto__        upbow
        downbow__     lheel__        rheel__         ltoe
        rtoe__        turn__         open__          flageolet
        reverseturn__ trill__        prall__         mordent
        prallprall__  prallmordent__ uprall__        downprall
        upmordent__   downmordent__  pralldown__  prallup__
        lineprall__   thumb__       segno__        coda
      }
    >
    \paper {
      linewidth = 5.875\in
      indent    = 0.0
    }
  }
@end lilypond

To save typing work, some shorthands are available:
@lilypond[singleline]
  \score {
    \notes \context Voice {
      \property Voice.TextScript \set #'font-family = #'typewriter
      \property Voice.TextScript \set #'font-shape = #'upright
      c''4-._"c-."      s4
      c''4--_"c-{}-"    s4
      c''4-+_"c-+"      s4
      c''4-|_"c-|"      s4
      c''4->_"c->"      s4
      c''4-^_"c-\\^{ }" s4
    }
  }
@end lilypond

@cindex fingering

Fingering instructions can also be entered in  this shorthand. For
changes, some markup texts would be needed:
@lilypond[verbatim, singleline, fragment]
      c'4-1 c'4-2 c'4-3 c'4-4
      c^#'(finger "2-3")
@end lilypond


@cindex @code{\script}
@cindex scripts
@cindex superscript
@cindex subscript

You can add scripts by editing @file{scm/script.scm}. This file contains
a table, listing script definitions and aliases. The following syntax
accesses a script definition from the table:

@example
  \script @var{alias}
@end example

Usually the @code{\script} keyword is not used directly.  Various
helpful identifier definitions appear in @file{script.ly}.

Grobs for these objects are @internalsref{Script} and @internalsref{Fingering}.

@refbugs

All of these note ornaments appear in the printed output but have no
effect on the MIDI rendering of the music.

Unfortunately, there is no support for adding fingering instructions or 
ornaments to individual note heads. Some hacks exist, though. See
@file{input/test/script-horizontal.ly}.


@c .  {Text scripts}
@node Text scripts
@subsection Text scripts
@cindex Text scripts

In addition, it is possible to place arbitrary strings of text or markup
text (see @ref{Text markup}) above or below notes by using a string:
@code{c^"text"}. 

By default, these indications do not influence the note spacing, but
if @code{Voice.textNonEmpty} is set to true the widths will be taken
into account.  The identifier @code{\fatText} is defined in the standard
includes.
@lilypond[fragment,singleline,verbatim]
\relative c' { c4^"longtext" \fatText c4_"longlongtext" c4 }
@end lilypond

Text scripts are created in form of @internalsref{TextScript} grobs, in
@internalsref{Voice} context.

@ref{Text markup} describes how to change the font or access
special symbols in text scripts.

@c .   {Grace notes}
@node Grace notes
@subsection Grace notes







@cindex Grace music
@cindex @code{\grace}
@cindex ornaments
@cindex grace notes
@cindex @code{graceAlignPosition}

Grace notes are ornaments that are written out, but do not take up  any
logical time in a measure. LilyPond has limited support for grace notes.
The syntax is as follows. 
@example
  \grace @var{musicexpr}
@end example

Unbeamed eighth notes and shorter by default have a slash through the
stem.

@lilypond[fragment,verbatim]
\relative c'' {
  \grace c8 c4 \grace { [c16 c16] } c4
  \grace { 
    \property Voice.Stem \override #'flag-style = #'() 
    c16 
    \property Voice.Stem \revert #'flag-style
  } c4
}
@end lilypond

A grace note expression has duration 0; the next real note is assumed to
be the main note. If you want the note to appear after the main note,
set @code{Voice.graceAlignPosition} to @code{1}.

@refbugs

Nesting @code{\grace} notes is not supported. The following may cause
run-time errors: @example
  @code{\grace @{ \grace c32 c16 @} c4}
@end example
Since the meaning of such a construct is unclear, we don't consider this
a loss.  Similarly, juxtaposing two @code{\grace} sections is
syntactically valid, but makes no sense and may cause runtime errors.
Ending a staff or score with grace notes may also generate a run-time
error, since there will be no main note to attach the grace notes to.

@menu
* Glissando ::                  
* Dynamics::                    
@end menu



@c .   {Glissando}
@node Glissando 
@subsection Glissando
@cindex Glissando 

@cindex @code{\glissando}

A glissando line (grob @internalsref{Glissando}) can be requested by
attaching a @code{\glissando} to a notte:

@lilypond[fragment,relative,verbatim]
  c'-\glissando c'
@end lilypond

@refbugs

Printing of an additional text (such as @emph{gliss.}) must be done
manually.



@c .   {Dynamics}
@node Dynamics
@subsection Dynamics
@cindex Dynamics



@cindex @code{\ppp}
@cindex @code{\pp}
@cindex @code{\p}
@cindex @code{\mp}
@cindex @code{\mf}
@cindex @code{\f}
@cindex @code{\ff}
@cindex @code{\fff}
@cindex @code{\ffff}
@cindex @code{\fp}
@cindex @code{\sf}
@cindex @code{\sff}
@cindex @code{\sp}
@cindex @code{\spp}
@cindex @code{\sfz}
@cindex @code{\rfz}


Absolute dynamic marks are specified using an identifier after a
note: @code{c4-\ff}.  The available dynamic marks are: @code{\ppp},
@code{\pp}, @code{\p}, @code{\mp}, @code{\mf}, @code{\f}, @code{\ff},
@code{\fff}, @code{\fff}, @code{\fp}, @code{\sf}, @code{\sff},
@code{\sp}, @code{\spp}, @code{\sfz}, and @code{\rfz}.

@lilypond[verbatim,singleline,fragment,relative]
  c'\ppp c\pp c \p c\mp c\mf c\f c\ff c\fff
  c2\sf c\rfz
@end lilypond

@cindex @code{\cr}
@cindex @code{\rc}
@cindex @code{\decr}
@cindex @code{\rced}
@cindex @code{\<}
@cindex @code{\>}
@cindex @code{\"!}


A crescendo mark is started with @code{\cr} and terminated with
@code{\rc} (the textual reverse of @code{cr}).  A decrescendo mark is
started with @code{\decr} and terminated with @code{\rced}.  There are
also shorthands for these marks.  A crescendo can be started with
@code{\<} and a decrescendo can be started with @code{\>}.  Either one
can be terminated with @code{\!}.  Note that @code{\!}  must go before
the last note of the dynamic mark whereas @code{\rc} and @code{\rced} go
after the last note.  Because these marks are bound to notes, if you
want several marks during one note, you have to use spacer notes.

@lilypond[fragment,verbatim,center]
  c'' \< \! c''   d'' \decr e'' \rced 
  < f''1 { s4 s4 \< \! s4 \> \! s4 } >
@end lilypond

You can also use a text saying @emph{cresc.} instead of hairpins. Here
is an example how to do it:

@cindex crescendo
@cindex decrescendo

@lilypond[fragment,relative,verbatim]
  \context Voice {
    \property Voice.crescendoText = "cresc."
    \property Voice.crescendoSpanner = #'dashed-line
    a'2\mf\< a a \!a 
  }
@end lilypond

For everyday use, we recommend the identifiers @code{\cresc},
@code{endcresc}, @code{\dim} and @code{\enddim}.

@cindex diminuendo

Dynamics are grobs of @internalsref{DynamicText} and
@internalsref{Hairpin}. Vertical positioning of these symbols is handled
by the @internalsref{DynamicLineSpanner} grob.  If you want to adjust
padding or vertical direction of the dynamics, you must set properties
for the @internalsref{DynamicLineSpanner} grob. Predefined identifiers
to set the vertical direction are \dynamicUp and \dynamicDown.

@cindex direction, of dynamics
@cindex @code{\dynamicDown}
@cindex @code{\dynamicUp}

@c .  {Repeats}
@node Repeats
@section Repeats


@cindex repeats
@cindex @code{\repeat}

To specify repeats, use the @code{\repeat} keyword.  Since repeats
should work differently when played or printed, there are a few
different variants of repeats.

@table @asis
@item unfold
Repeated music is fully written (played) out.  Useful for MIDI
output, and entering repetitive music.

@item volta  
This is the normal notation: Repeats are not written out, but
alternative endings (voltas) are printed, left to right.

@item fold
Alternative endings are written stacked. This has limited use but may be
used to typeset two lines of lyrics in songs with repeats, see
@file{input/star-spangled-banner.ly}.

@item tremolo
Make tremolo beams.

@item percent
Make beat or measure repeats. These look like percent signs.

@end table  

@menu
* Repeat syntax::               
* Manual repeat commands::      
* Tremolo repeats::             
* Tremolo subdivisions::        
* Measure repeats::             
@end menu

@node Repeat syntax
@subsection Repeat syntax

The syntax for repeats is

@example
  \repeat @var{variant} @var{repeatcount} @var{repeatbody}
@end example

If you have alternative endings, you may add
@cindex @code{\alternative}
@example
 \alternative @code{@{} @var{alternative1}
            @var{alternative2}
            @var{alternative3} @dots{} @code{@}}
@end example
where each @var{alternative} is a music expression.

Normal notation repeats are used like this:
@lilypond[fragment,verbatim]
  c'1
  \repeat volta 2 { c'4 d' e' f' }
  \repeat volta 2 { f' e' d' c' }
@end lilypond

With alternative endings:
@lilypond[fragment,verbatim]
  c'1
  \repeat volta 2 {c'4 d' e' f'} 
  \alternative { {d'2 d'} {f' f} }
@end lilypond

Folded repeats look like this:


@lilypond[fragment,verbatim]
  c'1
  \repeat fold 2 {c'4 d' e' f'} 
  \alternative { {d'2 d'} {f' f} }

@end lilypond

If you don't give enough alternatives for all of the repeats, then
the first alternative is assumed to be repeated often enough to equal
the specified number of repeats.

@lilypond[fragment,verbatim]
\context Staff {
  \relative c' {
    \partial 4
    \repeat volta 4 { e | c2 d2 | e2 f2 | }
    \alternative { { g4 g g } { a | a a a a | b2. } }
  }
}
@end lilypond

@subsection Unfolding repeats for MIDI output.

@cindex expanding repeats

See @file{input/test/unfold-all-repeats.ly}. 


@refbugs

Notice that timing information is not remembered at the start of an
alternative, so you have to reset timing information after a repeat,
e.g. using a bar-check (See @ref{Bar check}), setting
@code{Score.measurePosition} or entering @code{\partial}.  Slurs or ties
are also not repeated.

It is possible to nest @code{\repeat}s, although this probably is only
meaningful for unfolded repeats.

Folded repeats offer little more over simultaneous music.  However, it
is to be expected that more functionality -- especially for the MIDI
backend -- will be implemented at some point in the future.

Volta repeats are printed over all staves in a score. You must turn them
off explicitly, for example by doing
@example
  \property Staff.VoltaBracket = \turnOff
@end example
in all but the top staff.

@node Manual repeat commands
@subsection Manual repeat commands

@cindex @code{repeatCommands}

The property @code{repeatCommands} can be used to control the layout of
repeats. Its value is a Scheme list of repeat commands, where each repeat
command can be

@table @code
@item 'start-repeat
 Print a |: bar line
@item 'stop-repeat
 Print a :| bar line
@item (volta . @var{text})
  Print a volta bracket saying @var{text}.
@item (volta . #f)
  Stop a running volta bracket
@end table

@lilypond[verbatim, fragment]
 c''4
    \property Score.repeatCommands = #'((volta "93") end-repeat)
 c''4 c''4
    \property Score.repeatCommands = #'((volta #f))
 c''4 c''4
@end lilypond


Repeats brackets are @internalsref{VoltaBracket} grobs.

@node Tremolo repeats
@subsection Tremolo repeats
@cindex tremolo beams

To place tremolo marks between notes, use @code{\repeat} with tremolo
style.  
@lilypond[verbatim,center,singleline]
\score { 
  \context Voice \notes\relative c' {
    \repeat "tremolo" 8 { c16 d16 }
    \repeat "tremolo" 4 { c16 d16 }    
    \repeat "tremolo" 2 { c16 d16 }
    \repeat "tremolo" 4 c16
  }
}
@end lilypond

Tremolo beams are @internalsref{Beam} grobs. Single stem tremolos are
@internalsref{StemTremolo}.

@refbugs


At present, the spacing between tremolo beams is not regular, since the
spacing engine does not notice that not all notes are printed.

@node Tremolo subdivisions
@subsection Tremolo subdivisions
@cindex tremolo marks
@cindex @code{tremoloFlags}

Tremolo marks can be printed on a single note by adding
`@code{:}[@var{length}]' after the note.  The length must be at least 8.
A @var{length} value of 8 gives one line across the note stem.  If the
length is omitted, then then the last value (stored in
@code{Voice.tremoloFlags}) is used.

@lilypond[verbatim,fragment,center]
  c'2:8 c':32 | c': c': |
@end lilypond

@refbugs


Tremolos in this style do not carry over into the MIDI output.


@node Measure repeats
@subsection Measure repeats

@cindex percent repeats
@cindex measure repeats

In the @code{percent} style, a note pattern can be repeated. It is
printed once, and then the pattern is replaced with a special sign.
Patterns of a one and two measures are replaced by percent-like signs,
patterns that divide the measure length are replaced by slashes.

@lilypond[verbatim,singleline]
 \context Voice { \repeat  "percent" 4  { c'4 }
    \repeat "percent" 2 { c'2 es'2 f'4 fis'4 g'4 c''4 }
}
@end lilypond   

The signs are represented by these grobs: @internalsref{RepeatSlash} and
@internalsref{PercentRepeat} and @internalsref{DoublePercentRepeat}.

@refbugs

You can not nest percent repeats, e.g. by filling in the first measure
with slashes, and repeating that measure with percents.

@node Rhythmic music
@section Rhythmic music


@menu
* Rhythmic staves::             
@end menu

@node Rhythmic staves
@subsection Rhythmic staves

Sometimes you might want to show only the rhythm of a melody.  This can
be done with the rhythmic staff. All pitches of notes on such a staff
are squashed, and the  staff itself  looks has  a single staff line:

@lilypond[fragment,relative,verbatim]
  \context RhythmicStaff {
      \time 4/4
      c4 e8 f  g2 | r4 g r2 | g1:32 | r1 |
  }
@end lilypond


@c . {Piano music}
@node Piano music
@section Piano music

Piano music is an odd type of notation. Piano staves are two normal
staves coupled with a brace.  The staves are largely independent, but
sometimes voices can cross between the two staves.  The
@internalsref{PianoStaff} is especially built to handle this cross-staffing
behavior.  In this section we discuss the @internalsref{PianoStaff} and some
other pianistic peculiarities.

@menu
* Automatic staff changes::     
* Manual staff switches::       
* Pedals::                      
* Arpeggio::                    
* Voice follower lines::        
@end menu 


@c .   {Automatic staff changes}
@node Automatic staff changes
@subsection Automatic staff changes
@cindex Automatic staff changes

Voices can switch automatically between the top and the bottom
staff. The syntax for this is
@example
        \autochange @var{contexttype} @var{musicexp}
@end example
This will switch the interpretation context of @var{musicexp} between a
@var{contexttype} named @code{up} and @code{down}. Typically, you use
@internalsref{Staff} for @var{contexttype}.  The autochanger switches on basis
of pitch (central C is the turning point), and it looks ahead skipping
over rests to switch rests in advance.
        
@lilypond[verbatim,singleline]
\score { \notes \context PianoStaff <
  \context Staff = "up" {
    \autochange Staff \context Voice = VA < \relative c' {
       g4 a  b c d r4 a g } > }
  \context Staff = "down" {
       \clef bass
       s1*2
} > }
@end lilypond

Note how spacer rests are used to prevent the bottom staff from
terminating too soon.


@node Manual staff switches
@subsection Manual staff switches

@cindex manual staff switches
@cindex staff switch, manual

Voices can be switched between staves manually, using the following command:
@example
  \translator Staff = @var{staffname} @var{music}
@end example
The string @var{staffname} is the name of the staff. It switches the
current voice from its current staff to the Staff called
@var{staffname}. Typically @var{staffname} is @code{"up"} or
@code{"down"}.

The formal definition of this construct is obtuse, but for the sake of
completeness we give it here.
@cindex @code{\translator}
@example
  \translator @var{contexttype} = @var{name}
@end example
Formally, this construct is a music expression indicating
that the context which is a direct child of the context of type
@var{contexttype} should be shifted to a context of type
@var{contexttype} and the specified name.


@c .   {Pedals}
@node Pedals
@subsection Pedals
@cindex Pedals

Piano pedal instruction can be expressed using 
@code{\sustainDown}, @code{\sustainUp}, @code{\unaCorda},
@code{\treCorde}, @code{\sostenutoDown} and @code{\sostenutoUp}.

These identifiers are shorthands for spanner commands of the types
@internalsref{Sustain}, @internalsref{UnaCorda} and @internalsref{Sostenuto}:

@lilypond[fragment,verbatim]
c''4 \spanrequest \start "Sustain" c''4
c''4 \spanrequest \stop "Sustain"
@end lilypond

The symbols that are printed can be modified by setting
@code{pedal@var{X}Strings}, where @var{X} is one of the pedal types:
Sustain, Sostenuto or UnaCorda.  Refer to the generated documentation of
@rgrob{SustainPedal}, for example, for more information.

Pedals can also be indicated by a sequence of brackets, by setting the 
@code{pedal-type} property of SustainPedal grobs: 

@lilypond[fragment,verbatim]
\property Staff.SustainPedal \override #'pedal-type = #'bracket
c''4 \sustainDown d''4 e''4 a'4 \sustainUp \sustainDown f'4 g'4 a'4 \sustainUp
@end lilypond

A third style of pedal notation is a mixture of text and brackets,
obtained by setting @code{pedal-type} to @code{mixed}:

@lilypond[fragment,verbatim]
\property Staff.SustainPedal \override #'pedal-type = #'mixed
c''4 \sustainDown d''4 e''4 c'4 \sustainUp \sustainDown f'4 g'4 a'4 \sustainUp
@end lilypond

The default '*Ped' style for sustain and damper pedals corresponds to
@code{\pedal-type = #'text}. However, @code{mixed} is the default style
for a sostenuto pedal:

@lilypond[fragment,verbatim]
c''4 \sostenutoDown d''4 e''4 c'4 f'4 g'4 a'4 \sostenutoUp
@end lilypond

For fine-tuning of the appearance of a pedal bracket, the properties
@code{edge-width}, @code{edge-height}, and @code{shorten-pair} of
@code{PianoPedalBracket} grobs (see the detailed documentation of
@rgrob{PianoPedalBracket}) can be modified.  For example, the bracket
may be extended to the end of the note head.

@lilypond[fragment,verbatim]
\property Staff.PianoPedalBracket \override #'shorten-pair = #'(0 . -1.0)
c''4 \sostenutoDown d''4 e''4 c'4 f'4 g'4 a'4 \sostenutoUp
@end lilypond



@c .   {Arpeggio}
@node Arpeggio
@subsection Arpeggio
@cindex Arpeggio

@cindex broken arpeggio
@cindex @code{\arpeggio}

You can specify an arpeggio sign on a chord by attaching an
@code{\arpeggio} to a note of the chord.


@lilypond[fragment,relative,verbatim]
  \context Voice <c\arpeggio e g c>
@end lilypond

When an arpeggio crosses staves in piano music, you attach an arpeggio
to the chords in both staves, and set
@code{PianoStaff.connectArpeggios}.

@lilypond[fragment,relative,verbatim]
  \context PianoStaff <
    \property PianoStaff.connectArpeggios = ##t
    \context Voice = one  { <c'\arpeggio e g c> }
    \context Voice = other { \clef bass  <c,,\arpeggio e g>}
  >  
@end lilypond

This command creates @internalsref{Arpeggio} grobs.  Cross staff arpeggios
are @code{PianoStaff.Arpeggio}.

To add an arrow head to explicitly specify the direction of the
arpeggio, you should set the arpeggio grob property
@code{arpeggio-type}.

@lilypond[fragment,relative,verbatim]
  \context Voice {
     \property Voice.Arpeggio \override #'arpeggio-direction = #1
     <c\arpeggio e g c>
     \property Voice.Arpeggio \override #'arpeggio-direction = #-1
     <c\arpeggio e g c>
  }
@end lilypond

A square bracket on the left indicates that the player should not
arpeggiate the chord. To draw these brackets, set the
@code{molecule-callback} property of @code{Arpeggio} or
@code{PianoStaff.Arpeggio} grobs to @code{\arpeggioBracket}, and use
@code{\arpeggio} statements within the chords as before.

@lilypond[fragment,relative,verbatim]
  \context PianoStaff <
    \property PianoStaff.connectArpeggios = ##t
    \property PianoStaff.Arpeggio \override #'molecule-callback = \arpeggioBracket
    \context Voice = one  { <c'\arpeggio e g c> }
    \context Voice = other { \clef bass  <c,,\arpeggio e g>}
  >  
@end lilypond


@refbugs

It is not possible to mix connected arpeggios and unconnected arpeggios
at the same time.



@node  Voice follower lines
@subsection Voice follower lines

@cindex follow voice
@cindex staff switching
@cindex cross staff

@cindex @code{followVoice}

Whenever a voice switches to another staff a line connecting the notes
can be printed automatically. This is enabled if the property
@code{PianoStaff.followVoice} is set to true:

@lilypond[fragment,relative,verbatim]
  \context PianoStaff <
    \property PianoStaff.followVoice = ##t
    \context Staff \context Voice {
      c1
      \translator Staff=two
      b2 a
    }
    \context Staff=two {\clef bass \skip 1*2 }
  >  
@end lilypond

The associated grob is @internalsref{VoiceFollower}.


@node Lyrics
@section Lyrics


@menu
* Lyrics mode::                 
* Printing lyrics::             
* Automatic syllable durations::  
* More stanzas::                
@end menu

@c .  {Lyrics mode}
@node Lyrics mode
@subsection Lyrics mode
@cindex Lyrics mode

To print lyrics, you must first make a music expression from the lyric
text.  That music expression can be printed by selecting an appropriate
context.

@cindex lyric mode
@cindex @code{\lyrics}

You can enter lyrics in a special input mode of LilyPond. This mode is
called Lyrics mode, and it is introduced by the keyword @code{\lyrics}.
The purpose of this mode is that you can enter lyrics as plain text,
punctuation and accents without any hassle.

Syllables are entered like notes, with pitches replaced by text.  For
example, @code{Twin- kle twin- kle} enters four syllables.  Note that
the hyphen has no special meaning for lyrics, and does not introduce
special symbols.

Spaces can be introduced into a lyric either by using quotes:
@code{"He could"4 not4} or by using an underscore without quotes:
@code{He_could4 not4}.  All unquoted underscores are converted to
spaces.

The precise definition of this mode can be found in @ref{Lyrics mode
definition}. 

@c .  {Printing lyrics}
@node Printing lyrics
@subsection Printing lyrics
@cindex lyrics

Lyrics are printed by interpreting them in the @internalsref{Lyrics}  context.

@c Maybe more pedagogical to avoid \addlyrics in this first example? /MB
@c Add tied and beamed melismata too.
@lilypond[verbatim,singleline]
\addlyrics
  \notes \relative c' {
    \time 7/4
    \property Staff.automaticMelismata = ##t
    d'2 c4 b16 ( a g a b a b ) c a2
    b2 c4 b8 ( a16 g ) a4 g2 }
  \context Lyrics \lyrics { 
    Join us now __ and
    share the soft -- ware; }
@end lilypond


Notes and syllable durations are matched automatically. This is
accomplished using @code{\addlyrics}, which is documented in
@ref{Automatic syllable durations}. Setting @code{automaticMelismata} in
the melody staff will cause tied, slurred or beamed notes to be
interpreted as melismata.

The Lyric syllables are @code{LyricsVoice.LyricSyllable} grobs.

@cindex extender
@cindex lyric extender
@cindex melisma

As you can see, extender lines are entered as @code{__}.  This will
create an extender, a line that extends over the entire duration of the
lyric.  This line will run all the way to the start of the next lyric,
so you may want to shorten it by using a blank lyric (using @code{_}).
The grob for this symbol is @code{LyricsVoice.LyricExtender}.


@cindex hyphen

If you want to have hyphens centered between syllables (rather than
attached to the end of the first syllable) you can use the special
`@code{-}@code{-}' lyric as a separate word between syllables.  This
will result in a hyphen whose length varies depending on the space
between syllables. It will be centered between the syllables.  The grob
for this symbol is @code{LyricsVoice.LyricHyphen}.

@cindex Lyric hyphen

@node Automatic syllable durations
@subsection Automatic syllable durations
@cindex Automatic syllable durations

@cindex automatic lyric durations
@cindex @code{\addlyrics}

If you have lyrics that are set to a melody, you can copy the rhythm
of that melody into the lyrics using @code{\addlyrics}.  The syntax for
this is
@example
  \addlyrics @var{musicexpr1 musicexpr2}
@end example

Both @var{musicexpr1} and @var{musicexpr2} are interpreted, but every
music event (``every syllable'') in @var{musicexpr2} is interpreted only
when there are events in @var{musicexpr1}.

@cindex @code{automaticMelismata}

If the property @code{automaticMelismata} is set in the
context of @var{musicexpr1}, no lyrics will be put on slurred or tied
notes.

@lilypond[verbatim,fragment]
\addlyrics
\transpose c'' {
  \property Voice.automaticMelismata = ##t
  c8 () cis d8. e16 f2
}
\context Lyrics \lyrics {
 do4 re mi fa }
@end lilypond

If you want the lyric lines to be above the melody staff, or in some
other, more complex configuration, then build that configuration first
using simultaneous music, and use @code{\addlyrics} after that.

@lilypond[verbatim, singleline]
\notes <
  \context Lyrics = LA { s1 }
  \context Staff = SA { s1 }
  \addlyrics
        \context Staff = SA \relative c' { c4 e g g }
        \context Lyrics  = LA \lyrics { geen ge -- don -- der } >
@end lilypond

For @code{\addlyrics} you should use a single rhythm melody, and single
rhythm lyrics (a constant duration is the obvious choice).  If you do
not, you can get undesired effects when using multiple stanzas:

@lilypond[verbatim,fragment]
\addlyrics
\transpose c'' {
  c8 () cis d8. e16 f2
}
\context Lyrics \lyrics
< { do4 re fa sol }
  { do8 re fa sol } >
@end lilypond

It is valid (but probably not very useful) to use notes instead of
lyrics for @var{musicexpr2}.

@node More stanzas
@subsection More stanzas

@cindex phrasing

If you have multiple stanzas printed underneath each other, the vertical
groups of syllables should be aligned around punctuation. LilyPond can
do this if you tell it which lyric lines belong to which melody.

To this end, give the Voice context an identity, and set the LyricsVoice
to a name starting with that identity followed by a dash.
In the following example, the Voice
identity is @code{duet}, and the identities of the LyricsVoices are
@code{duet-1} and @code{duet-2}.


@lilypond[singleline,verbatim]
\score {
\addlyrics
  \notes \relative c'' \context Voice = duet { \time 3/4
     g2 e4 a2 f4 g2.  }
  \lyrics \context Lyrics <
  \context LyricsVoice = "duet-1" {
    \property LyricsVoice . stanza = "Bert"
    Hi, my name is bert.    }
  \context LyricsVoice = "duet-2" {
    \property LyricsVoice . stanza = "Ernie" 
    Ooooo, ch\'e -- ri, je t'aime. }
  >
}
@end lilypond

You can add stanza numbers by setting @code{LyricsVoice.Stanza} (for the
first system) and @code{LyricsVoice.stz} for the following
systems. Notice how you must surround dots with spaces in @code{\lyrics}
mode.




@cindex stanza numbering


@c . {Chords}
@node Chords
@section Chords
@cindex Chords

LilyPond has support for both entering and printing chords.  Chords are
characterized by a set of pitches. They are
internally stored as simultaneous music expressions. This means you can
enter chords by name and print them as note head, enter them as notes
and print them as chord names, or (the most common case) enter them by
name, and print them as name.


@lilypond[verbatim,singleline]
twoWays = \notes \transpose c'' {
  \chords {
    c1 f:sus4 bes/f
  }
  <c e g>
  <f bes c'>
  <f bes d'>
  }

\score {
   < \context ChordNames \twoWays
     \context Voice \twoWays > }
@end lilypond

Note that this example also shows that the chord printing routines do
not attempt to be intelligent. If you enter @code{f bes d}, it does not
interpret this as an inversion.

@menu
* Chords mode::                 
* Printing named chords::       
@end menu

@c .  {Chords mode}
@node Chords mode
@subsection Chords mode
@cindex Chords mode

Chord mode is a mode where you can input sets of pitches using common
names.  It is introduced by the keyword @code{\chords}.  It is similar
to note mode, but words are also looked up in a chord modifier table
(containing @code{maj}, @code{dim}, etc).

Dashes and carets are used to indicate chord additions and subtractions,
so articulation scripts can not be entered in Chord mode.

The syntax for named chords is as follows:
@example
  @var{tonic}[@var{duration}][@code{-}@var{modifiers}][@code{^}@var{subtractions}][@code{/}@var{inversion}][@code{/+}@var{bass}].
@end example

@var{tonic} should be the tonic note of the chord, and @var{duration} is
the chord duration in the usual notation.  There are two kinds of
modifiers.  One type is formed by @emph{chord additions}. Additions are
obtained by listing intervals separated by dots.  An interval is written
by its number with an optional @code{+} or @code{-} to indicate raising
or lowering by half a step.  Chord additions have two effects: they adds
the specified interval and all lower odd numbered intervals to the
chord, and they may lower or raise the specified interval.

Throughout these examples, chords have been shifted around the staff
using @code{\transpose}.

@lilypond[fragment,verbatim]
\transpose c'' {
  \chords {
    c1  c:3-       c:7     c:8
    c:9 c:9-.5+.7+ c:3-.5- 
  }
}
@end lilypond

@cindex @code{aug}
@cindex @code{dim}
@cindex @code{maj}
@cindex @code{sus}

The second type of modifier that may appear after the @code{:} is a
named modifier.  Named modifiers are listed in the file
@file{chord-modifiers.ly}.  The available modifiers are @code{m} and
@code{min} which lower the 3rd half a step, `@code{aug}' which
raises the 5th, `@code{dim}' which lowers the 5th,
`@code{maj}' which adds a raised 7th, and `@code{sus}'
which replaces the 5th with a 4th.

@lilypond[fragment,verbatim]
\transpose c'' {
  \chords {
    c1:m c:min7 c:maj c:aug c:dim c:sus
  }
}
@end lilypond
 

Chord subtractions are used to eliminate notes from a chord.  The
notes to be subtracted are listed after a @code{^} character,
separated by dots.

@lilypond[fragment,verbatim,center]
  \transpose c'' {
    \chords {
      c1^3 c:7^5.3 c:8^7
    }
  }
@end lilypond 
@cindex @code{/}

Chord inversions can be specified by appending `@code{/}' and the name
of a single note to a chord.  In a chord inversion, the inverted note is
transposed down until it is the lowest note in the chord.  If the note
is not in the chord, a warning will be printed.

@lilypond[fragment,verbatim,center]
  \transpose c''' {
    \chords {
      c1 c/e c/g c:7/e
    }
  }

@end lilypond 
@cindex @code{/+}

Bass notes can be added by `@code{/+}' and
the name of a single note to a chord.  This has the effect of
adding the specified note to the chord, lowered by an octave,
so it becomes the lowest note in the chord.

@lilypond[fragment,verbatim,center]
  \transpose c''' {
    \chords {
      c1 c/+c c/+g c:7/+b
    }
  }

@end lilypond 

@refbugs

Implementation details are quite gory. For example @code{c:4} not only
adds a fourth, but also removes the third.


@c .  {Printing named chords}
@node Printing named chords
@subsection Printing named chords

@cindex printing chord names
@cindex chord names
@cindex chords

For displaying printed chord names, use the @internalsref{ChordNames} context.
The chords may be entered either using the notation described above, or
directly using simultaneous music.

@lilypond[verbatim,singleline]
scheme = \notes {
  \chords {a1 b c} <d f g>  <e g b>
}
\score {
  \notes<
    \context ChordNames \scheme
    \context Staff \transpose c'' \scheme
  >
}
@end lilypond

You can make the chord changes stand out by setting
@code{ChordNames.chordChanges} to true.  This will only display chord
names when there's a change in the chords scheme and at the start of a
new line.

@lilypond[verbatim]
scheme = \chords {
  c1:m c:m \break c:m c:m d
}
\score {
  \notes <
    \context ChordNames {
        \property ChordNames.chordChanges = ##t
        \scheme }
    \context Staff \transpose c'' \scheme
  > }
@end lilypond

LilyPond examines chords specified as lists of notes to determine a name
to give the chord. LilyPond will not try to identify chord inversions or
an added bass note, which may result in strange chord names when chords
are entered as a list of pitches:

@lilypond[verbatim,center,singleline]
scheme = \notes {
  <c'1 e' g'>
  <e' g' c''>
  <e e' g' c''>
}

\score {
  <
    \context ChordNames \scheme
    \context Staff \scheme
  >
}
@end lilypond


By default, a chord name system proposed by Harald Banter (See
@ref{Literature}) is used. The system is very regular and predictable.
Typical American style chord names may be selected by setting the
@code{style} property of the @code{ChordNames.ChordName} grob to
@code{'american}. Similarly @code{'jazz} selects Jazz chordnames.

Routines that determine the names to be printed are written in Scheme,
and may be customized by the user.  The code can be found in
@file{scm/chord-name.scm}.  Here's an example showing the differences in
chord name styles:

@c too long?
@c maybe just junk verbatim option?
@lilypond[verbatim,singleline]
scheme = \chords {
  c1 c:5^3 c:4^3 c:5+
  c:m7+ c:m5-.7
  c:5-.7 c:5+.7
  c:9^7
}

\score {
  \notes <
    \context ChordNames = banter \scheme
    \context ChordNames = american {
      \property ChordNames.ChordName \override
        #'style = #'american \scheme }
    \context ChordNames = jazz {
      \property ChordNames.ChordName \override
        #'style = #'jazz \scheme }
    \context Staff \transpose c'' \scheme
  >
}
@end lilypond


@node Writing parts
@section Writing parts

Orchestral music involves some special notation, both in the full score,
as in the individual parts. This section explains how to tackle common
problems in orchestral music.


@c .  {Transpose}
@menu
* Rehearsal marks::             
* Bar numbers::                 
* Instrument names::            
* Transpose::                   
* Sound output for transposing instruments::  
* Multi measure rests::         
* Automatic part combining::    
* Hara kiri staves::            
@end menu

@c .   {Rehearsal marks}
@node Rehearsal marks
@subsection Rehearsal marks
@cindex Rehearsal marks
@cindex mark
@cindex @code{\mark}


@example
  \mark @var{unsigned}
  \mark @var{string}
  \mark \default
@end example

This command prints a rehearsal mark above the system. You can provide
a number, a string or a markup text as argument. If you use
@code{\default}, the value of property @code{rehearsalMark} is used and
automatically incremented.

@lilypond[fragment,verbatim]
\relative c'' {
  c1 \mark "A2"
  c1 \mark \default
  c1 \mark \default 
  c1 \mark "12"
  c1 \mark #'(music "scripts-segno") 
  c1
}
@end lilypond

The grob is @internalsref{RehearsalMark} in @internalsref{Score} context. See
@code{input/test/boxed-molecule.ly} if you need boxes around the marks.

@node Bar numbers
@subsection Bar numbers


@cindex bar numbers
@cindex measure numbers
@cindex currentBarNumber

Bar numbers are @internalsref{BarNumber} grobs.  They are printed at the
start of the line.  The number itself is a property that can be set by
modifying the @code{currentBarNumber} property, i.e.
@example
  \property Score.currentBarNumber = #217
@end example

If you want boxed bar numbers, see the example file
@code{input/test/boxed-molecule.ly}.

@refbugs

It is not possible to have bar numbers printed at regular intervals
only.

@node Instrument names
@subsection Instrument names

You can specify an instrument name for a staff by setting
@code{Staff.instrument} and @code{Staff.instr}. This will print a string
before the start of the staff. For the first start, @code{instrument} is
used, for the next ones @code{instr} is used.

@lilypond[verbatim,singleline]
  \property Staff.instrument = "ploink " { c''4 }  
@end lilypond

You can also use markup texts to construct more complicated instrument
names:


@lilypond[verbatim,singleline]
#(define text-flat
  '((font-relative-size . -2 ) (music "accidentals--1")))

\score { \notes {
  \property Staff.instrument = #`((kern . 0.5) (lines
    "2 Clarinetti" (columns "     (B" ,text-flat ")")))
    c'' 4 }
}
@end lilypond


@refbugs

When you put a name on a grand staff or piano staff the width of the
brace is not taken into account. You must add extra spaces to the end of
the name to avoid a collision.

@node Transpose
@subsection Transpose
@cindex Transpose
@cindex transposition of pitches
@cindex @code{\transpose}

A music expression can be transposed with @code{\transpose}.  The syntax
is
@example
  \transpose @var{pitch} @var{musicexpr}
@end example

This means that middle C in @var{musicexpr} is transposed to
@var{pitch}.

@code{\transpose} distinguishes between enharmonic pitches: both
@code{\transpose cis'} or @code{\transpose des'} will transpose up half
a tone.  The first version will print sharps and the second version
will print flats.

@lilypond[fragment,verbatim]
\context Staff {
  \clef "F"
  { \key e \major c d e f }
  \clef "G"
  \transpose des'' { \key e \major c d e f }
  \transpose cis'' { \key e \major c d e f }
}
@end lilypond

If you want to use both @code{\transpose} and @code{\relative}, then
you must use @code{\transpose} first.  @code{\relative} will have no
effect music that appears inside a @code{\transpose}.

@node Sound output for transposing instruments
@subsection Sound output transposing instruments

When you want to make a MIDI file from a score containing transposed and
untransposed 
instruments, you have to instruct LilyPond the pitch offset (in
semitones) for the transposed instruments. This is done using the
@code{transposing} property. It does not affect printed output.

@cindex @code{transposing}

@example
        \property Staff.instrument = #"Cl. in B-flat"
        \property Staff.transposing = #-2
@end example

@c .  {Multi measure rests}
@node  Multi measure rests
@subsection Multi measure rests
@cindex Multi measure rests

@cindex @code{R}

Multi measure rests are entered using `@code{R}'. It is specifically
meant for full bar rests and for entering parts: the rest can expand to
fill a score with 
rests, or it can be printed as a single multimeasure rest This expansion
is controlled by the property @code{Score.skipBars}. If this is set to true,
Lily will not expand empty measures, and the appropriate number is added
automatically.

@lilypond[fragment,verbatim]
 \time 3/4 r2. | R2. | R2.*2 \property Score.skipBars = ##t R2.*17  R2.*4
@end lilypond

Notice that the @code{R2.} is printed as a whole rest, centered in the
measure. 

@cindex whole rests for a full measure 

The grob for this object is @internalsref{MultiMeasureRest}.

@refbugs

Currently, there is no way to automatically condense multiple rests into
a single multimeasure rest.

@cindex condensing rests

@node Automatic part combining
@subsection Automatic part combining
@cindex automatic part combining
@cindex part combiner


Automatic part combining is used to merge two parts of music onto a
staff in an intelligent way.  It is aimed primarily at typesetting
orchestral scores.  When the two parts are identical for a period of
time, only one is shown.  In places where the two parts differ, they are
typeset as separate voices, and stem directions are set automatically.
Also, solo and @emph{a due} parts can be identified and marked.

The syntax for part combining is

@example
  \partcombine @var{context} @var{musicexpr1} @var{musicexpr2}
@end example
where the pieces of music @var{musicexpr1} and @var{musicexpr2} will be
combined into one context of type @var{context}.  The music expressions
must be interpreted by contexts whose names should start with @code{one}
and @code{two}.

The most useful function of the part combiner is to combine parts into
one voice, as common for wind parts in orchestral scores:

@lilypond[verbatim,singleline,fragment]
  \context Staff <
    \context Voice=one \partcombine Voice
      \context Thread=one \relative c'' {
        g a () b r
      }
      \context Thread=two \relative c'' {
        g r4 r f
      }
  >
@end lilypond

Notice that the first @code{g} appears only once, although it was
specified twice (once in each part).  Stem, slur and tie directions are
set automatically, depending whether there is a solo or unisono. The
first part (with context called @code{one}) always gets up stems, and
`solo', while the second (called @code{two}) always gets down stems and
`Solo II'.

If you just want the merging parts, and not the textual markings, you
may set the property @var{soloADue} to false.

@lilypond[verbatim,singleline,fragment]
  \context Staff <
    \property Staff.soloADue = ##f
    \context Voice=one \partcombine Voice
      \context Thread=one \relative c'' {
        b4 a c g
      }
      \context Thread=two \relative c'' {
        d,2 a4 g'
      }
  >
@end lilypond

There are a number of other properties that you can use to tweak the
behavior of part combining, refer to the automatically generated
documentation of @reng{Thread_devnull_engraver} and
@reng{Voice_devnull_engraver}. Look at the documentation of the
responsible engravers, @code{Thread_devnull_engraver},
@code{Voice_devnull_engraver} and @code{A2_engraver}.

@refbugs

In @code{soloADue} mode, when the two voices play the same notes on and
off, the part combiner may typeset @code{a2} more than once in a
measure.

@lilypond[fragment,singleline]
  \context Staff <
    \context Voice=one \partcombine Voice
      \context Thread=one \relative c'' {
        c b c b c a c a
      }
      \context Thread=two \relative c'' {
        b b b b f a f a
      }
  >
@end lilypond

@cindex @code{Thread_devnull_engraver}
@cindex @code{Voice_engraver}
@cindex @code{A2_engraver}

@node Hara kiri staves
@subsection Hara kiri staves

In orchestral scores, staff lines that only have rests are usually removed.
This saves some space.  LilyPond also supports this through the hara
kiri@footnote{Hara kiri, also called Seppuku, is the ritual suicide of
the Japanese Samourai warriors.} staff. This staff commits suicide when
it finds itself to be empty after the line-breaking process.  It will
not disappear when it contains normal rests, you must use multi measure
rests.

The hara kiri staff is specialized version of the @internalsref{Staff}
context. It is available as the context identifier
@code{\HaraKiriStaffContext}.  Observe how the second staff in this
example disappears in the second line.

@lilypond[verbatim]
\score  {
  \notes \relative c' <
    \context Staff = SA { e4 f g a \break c1 }
    \context Staff = SB { c4 d e f \break R1 }
  >
  \paper {
    linewidth = 6.\cm 
    \translator { \HaraKiriStaffContext }
  }
}
@end lilypond



@c . {Custodes}
@node Custodes
@section Custodes
@cindex Custos
@cindex Custodes

A @emph{custos} (plural: @emph{custodes}; latin word for `guard') is a
staff context symbol that appears at the end of a staff line.  It
anticipates the pitch of the first note(s) of the following line and
thus helps the player or singer to manage line breaks during
performance, thus enhancing readability of a score.

@lilypond[verbatim]
\score {
  \notes { c'1 \break
        \property Staff.Custos \set #'style = #'mensural
        d' }
  \paper {
    \translator {
      \StaffContext
      \consists Custos_engraver
    }
  }
}
@end lilypond

Custodes were frequently used in music notation until the 17th century.
There were different appearances for different notation styles.
Nowadays, they have survived only in special forms of musical notation
such as via the @emph{editio vaticana} dating back to the beginning of
the 20th century.

For typesetting custodes, just put a @code{Custos_engraver} into the
@internalsref{Staff} context when declaring the @code{\paper} block.  In this
block, you can also globally control the appearance of the custos symbol
by setting the custos @code{style} property.  Currently supported styles
are @code{vaticana}, @code{medicaea}, @code{hufnagel} and
@code{mensural}.

@example
\paper @{
  \translator @{
      \StaffContext
      \consists Custos_engraver
      Custos \override #'style = #'mensural
  @}
@}
@end example

The property can also be set locally, for example in a @code{\notes}
block:

@example
\notes @{
  \property Staff.Custos \override #'style = #'vaticana
  c'1 d' e' d' \break c' d' e' d'
@}
@end example


@c . {Figured bass}
@node Figured bass
@section Figured bass

@cindex Basso continuo

TODO. see figured-bass.ly

@c . {Tuning output}
@node Tuning output
@section Tuning output

LilyPond tries to take as much formatting as possible out of your
hands. Nevertheless, there are situations where it needs some help, or
where you want to override its decisions. In this section we discuss
ways to do just that.

Formatting is internally done by manipulating so called grobs (graphic
objects). Each grob carries with it a set of properties (grob
properties) specific to that object.  For example, a stem grob has
properties that specify its direction, length and thickness.

The most direct way of tuning the output is by altering the values of
these properties. There are two ways of doing that: first, you can
temporarily change the definition of a certain type of grob, thus
affecting a whole set of objects.  Second, you can select one specific
object, and set a grob property in that object.

@menu
* Tuning groups of grobs ::     
* Tuning per grob ::            
* What to tune?::               
* Font selection::              
* Text markup::                 
* Invisible grobs::             
* Dirty tricks::                
@end menu

@node Tuning groups of grobs 
@subsection Tuning groups of grobs 

@cindex grob description



A grob definition is a Scheme association list, that is stored in a
context property.  By assigning to that property (using plain
@code{\property}), you can change the resulting grobs.

@lilypond[verbatim, fragment]
c'4 \property Voice.Stem  = #'((meta . ((interfaces . ())))) c'4
@end lilypond

The @code{\property} assignment effectively empties the definition of
the Stem object. One of the effects is that the recipe of how it should be
printed is erased, with the effect of rendering it invisible.  The above
assignment is available as a standard identifier, for the case that you
find this useful:

@example
  \property Voice.Stem = \turnOff
@end example

@cindex \override
@cindex \revert
@cindex \set

This mechanism is fairly crude, since you can only set, but not modify,
the definition of a grob. For this reason, there is a more advanced
mechanism.

The definition of a grob is actually a list of default grob
properties. For example, the definition of the Stem grob (available in
@file{scm/grob-description.scm}), defines the following values for
@internalsref{Stem}

@example
        (thickness . 0.8)
        (beamed-lengths . (0.0 2.5 2.0 1.5))
        (Y-extent-callback . ,Stem::height)
        @var{...}
@end example

You can add a property on top of the existing definition, or remove a
property, thus overriding the system defaults:
@lilypond[verbatim]
c'4 \property Voice.Stem \override #'thickness = #4.0
c'4 \property Voice.Stem \revert #'thickness
c'4
@end lilypond
You should balance @code{\override} and @code{\revert}. If that's too
much work, you can use the @code{\set} shorthand. It performs a revert
followed by an override. The following example gives exactly the same
result as the previous one. 
@lilypond[verbatim]
c'4 \property Voice.Stem \set #'thickness = #4.0
c'4 \property Voice.Stem \set #'thickness = #0.8
c'4
@end lilypond
If you use @code{\set}, you must explicitly restore the default.


Formally the syntax for these constructions is
@example
\property @var{context}.@var{grobname} \override @var{symbol} = @var{value}
\property @var{context}.@var{grobname} \set @var{symbol} = @var{value}
\property @var{context}.@var{grobname} \revert @var{symbol}
@end example
Here @var{symbol} is a Scheme expression of symbol type, @var{context}
and @var{grobname} are strings and @var{value} is a Scheme expression.


If you revert a setting which was not set in the first place, then it
has no effect. However, if the setting was set as a system default, it
may remove the default value, and this may give surprising results,
including crashes.  In other words, @code{\override} and @code{\revert},
must be carefully balanced.

These are examples of correct nesting of @code{\override}, @code{\set},
@code{\revert}. 

A clumsy but correct form:
@example
  \override \revert \override \revert \override \revert
@end example

Shorter version of the same:
@example 
  \override \set \set  \revert
@end example

A short form, using only @code{\set}. This requires you to know the
default value:
@example
  \set \set \set \set @var{to default value}
@end example

If there is no default (i.e. by default, the grob property is unset),
then you can use
@example
  \set \set \set \revert
@end example

For the digirati, the grob description is an Scheme association
list. Since a Scheme list is a singly linked list, we can treat it as a
stack, and @code{\override} and @code{\revert} are just push and pop
operations. This pushing and popping is also used for overriding
automatic beaming settings.

@refbugs

LilyPond will hang or crash if @var{value} contains cyclic references.
The backend is not very strict in type-checking grob properties. If you
@code{\revert} properties that are expected to be set by default,
LilyPond may crash.

Some grobs are created at the moment that their context is created. An
example of such a grob is the staff itself (i.e. the horizontal lines).
You can not change the appearance of the staff symbol by manipulating
@code{\property Staff.StaffSymbol}.  At the moment that @code{\property
Staff} is interpreted, a Staff context is made, and the StaffSymbol is
created before any @code{\override} is effective. You can deal with this
either overriding properties in a @code{\translator} definition, or by
using @code{\outputproperty}.




@node Tuning per grob 
@subsection Tuning per grob 

@cindex \outputproperty

A second way of tuning grobs is the more arcane @code{\outputproperty}
feature.  The syntax is as follows:
@example
\outputproperty @var{predicate} @var{symbol} = @var{value}
@end example
Here @code{predicate} is a Scheme function taking a grob argument, and
returning a boolean.  This statement is processed by the
@code{Output_property_engraver}.  It instructs the engraver to feed all
grobs that it sees to @var{predicate}. Whenever the predicate returns
true, the grob property @var{symbol} will be set to @var{value}.

You will need to combine this statement with @code{\context} to select
the appropriate context to apply this to.

Here are some random examples. 


In the following example, all note heads occurring at current staff
level, are shifted up and right by setting their @code{extra-offset}
property.

@lilypond[fragment,verbatim,singleline]
\relative c'' { c4
  \context Staff \outputproperty
  #(make-type-checker 'note-head-interface)
  #'extra-offset = #'(0.5 . 0.75)
  <c8 e g> }
@end lilypond

@cindex @code{extra-offset}

In this example, the predicate checks the @code{text} grob property, to
shift only the `m.d.' text,  but not the fingering instruction "2".
@lilypond[verbatim,singleline]
#(define (make-text-checker text)
   (lambda (grob) (equal? text (ly-get-grob-property grob 'text))))

\score {    
  \notes\relative c''' {
    \property Voice.Stem \set #'direction = #1
    \outputproperty #(make-text-checker "m.d.")
      #'extra-offset = #'(-3.5 . -4.5)
    a^2^"m.d."    
  }
}
@end lilypond

@refbugs

If possible, avoid this feature: the semantics are not very clean, and
the syntax and semantics are up for rewrite.




@node What to tune?
@subsection What to tune?

This all tells you how to tune grobs, but you don't know what variables
to set? The question is not answered in this part of the manual
(although you may encounter some examples.).

Grob properties are tied directly to the implementation of LilyPond, and
they are thus a moving target. Documentation of such variables is in the
automatically generated documentation.  Description of properties are
generated from the source code for each version. This documentation is
therefore more up to date.  It should be available from the same place
where you got this manual.

To decide how to tune a grob, you need to find the following information
@itemize @bullet
@item
which grob to modify
@item
which property to modify
@item
which context the grob comes from.
@end itemize

Included with the automatically generated documentation is a master list
of grobs. Selecting a grob will take you to an overview of the
properties available for that grob.

There is also a master list of contexts. Selecting one takes you to an
overview of that context which lists which grob types are created there.


@node Font selection
@subsection Font selection

Most graphics in LilyPond are composed of characters of fonts.  You can
alter the characteristics of the font by setting certain grob
properties. The mechanism that is used for this resembles La@TeX{}'s New
Font Selection Scheme. Within this scheme, a font is entirely
characterized by its font name.

For each grob that uses fonts (in other words, each grob that supports
@code{font-interface}) a font-name must be selected before it can be
printed.  The font name is selected by looking at a number of grob
properties:

@table @code
@item font-family
 A symbol indicating the general class of the typeface.  Supported are
@code{roman} (Computer Modern), @code{braces} (for piano staff braces),
@code{music} (the standard music font), @code{dynamic} (font for dynamic
signs) and @code{typewriter}

@item font-shape
  A symbol indicating the shape of the font, there are typically several
  font shapes available for each font family. Choices are @code{italic},
  @code{caps} and @code{upright} 

@item font-series
A  symbol indicating the series of the font. There are typically several
font series for each font family and shape. Choices are @code{medium}
and @code{bold}. 

@item font-relative-size
  A number indicating the size relative the standard size.  For example,
  with 20pt staff height, relative size -1  corresponds to 16pt staff
  height, and relative size +1 corresponds to 23 pt staff height.

@item font-design-size
A number indicating  the design size of the font. 

This is a feature of the Computer Modern Font: each point size has a
slightly different design. Smaller design sizes are relatively wider,
which enhances readability. Scalable type faces such TrueType and Adobe
Type1 usually come as ``one design fits all sizes''.

@item font-name
  The name of the font, without the design size, e.g. @code{cmr},
@code{cmti}, etc. Setting this overrides font-family, font-shape and
font-series.


@end table


The font is selected by taking the first font that satisfies all
qualifiers specified. You can override any of these fields through
@code{\override} and @code{\revert}. The special value @code{*} matches
any value for that qualifier.

@example
  \property Lyrics.LyricText \override #'font-series = #'bold
  \property Lyrics.LyricText \override #'font-shape = #'*
@end example

@cindex @code{font-style}

There are also pre-cooked font selection qualifiers. These are selected
through the grob property @code{font-style}.  For example, the style
@code{finger} selects family @code{number} and relative size @code{-3}.
Styles available include @code{volta}, @code{finger}, @code{tuplet},
@code{timesig}, @code{mmrest}, @code{script}, @code{large}, @code{Large}
and @code{dynamic}.

The style sheets and tables for selecting fonts are located in
@file{scm/font.scm}. Refer to this file for more information.


Setting @code{font-name} overrides all other qualifiers. The value for
this property should be a string, the file name of the font. You may use
this to use special fonts, which are not a part of the style sheet, or
which have special encodings.

The size of the font may be set with the grob property
@code{font-magnification}.  It is the size of font, relative to its
standard size. For example, @code{1.0} is normal size.

@refbugs

Relative size is not linked to any real size.

There is no style sheet provided for other fonts besides the @TeX{}
family.

@cindex font selection
@cindex font magnification
@cindex @code{font-interface}


@node Text markup
@subsection Text markup
@cindex text markup
@cindex markup text

LilyPond has an internal mechanism to typeset texts. You can
form text markup expressions by composing scheme expressions
in the following way.

@lilypond[verbatim, singleline]
 \relative c' {
    \fatText
    a^#"upright"
    b_#'(bold "bold")
    c^#'(italic "italic")
    d_#'((bold italic) "ff")
    e^#'(dynamic "ff")
    f_#'(lines "one" (bold "two"))
    g^#'(music "noteheads-2" ((raise . 2.4) "flags-u3"))
  }
@end lilypond

Normally, the Scheme markup text is stored in the @code{text} property
of a grob.  Formally, it is defined as follows:

@example
text: string | (head? text+)
head: markup | (markup+)
markup-item: property | abbrev
property: (@var{key} . @var{value})
abbrev: @code{columns lines roman music bold italic named super sub}
        @code{overstrike text finger volta timesig mmrest mark script}
        @code{large Large dynamic}
@end example

The markup is broken down and converted into a list of grob properties,
which are prepended to the property list.  The @var{key}-@var{value}
pair is a grob property. A list of properties available is included in
the generated documentation for @rint{Text_interface}.

The following abbreviations are currently defined:
@table @code
@item columns
 horizontal mode: set all text on one line (default)
@item lines
 vertical mode: set every text on a new line
@item roman
 select roman font
@item music
 selects the Feta font (the standard font for music notation glyphs),
and uses named lookup

@item bold
 select bold series
@item italic
 select italic shape
@item named
 lookup by character name
@item text
 plain text lookup (by character value)
@item super
 superscript
@item sub
 subscript
@item overstrike
 the next text or character overstrikes this one
@item finger
 select fingering number fontstyle
@item volta
 select volta number fontstyle
@item timesig
 select time signature number fontstyle
@item mmrest
 select multi measure rest number fontstyle
@item mark
 select mark number fontstyle
@item script
 select scriptsize roman fontstyle
@item large
 select large roman fontstyle
@item Large
 select Large roman fontstyle
@item dynamic
 select dynamics fontstyle
@end table


@cindex metronome mark

One practical application of complicated markup is to fake a metronome
marking:

@lilypond[verbatim]
#(define note '(columns
  (music "noteheads-2" ((kern . -0.1) "flags-stem"))))
#(define eight-note `(columns ,note ((kern . -0.1)
  (music ((raise . 3.5) "flags-u3")))))
#(define dotted-eight-note
  `(columns ,eight-note (music "dots-dot")))

\score {
  \notes\relative c'' {
    a1^#`((columns (font-relative-size . -1)) ,dotted-eight-note " = 64")
  }
  \paper {
    linewidth = -1.
    \translator{
      \ScoreContext
      TextScript \override #'font-shape = #'upright
    }
  }
}
@end lilypond

@node Invisible grobs
@subsection Invisible grobs
@cindex invisible grobs

@ignore

ben nog steeds niet kapot van de informatiedichtheid hier.

--hwn

@end ignore

You can imagine a number of situations where you would want to make
certain grobs not show up in the output.  There may be aesthetic
reasons, to make the output resemble an (old) manuscript as close as
possible, or to make lessons or exercises for students.

Grobs can be made invisible in a number of ways:

Here's an example with blanked-out notes and stems:
@lilypond[singleline,verbatim]
blanknotes = {
  \property Voice.NoteHead \override
    #'transparent = ##t
  \property Voice.Stem \override
    #'transparent = ##t }
  
unblanknotes = {
  \property Voice.NoteHead \revert #'transparent
  \property Voice.Stem \revert #'transparent }

\score {
  \notes\relative c'' {
    \time 6/4
    a b c b \blanknotes c \unblanknotes d
  }
}
@end lilypond
This method makes the grobs invisible but they still take the normal space. 
To remove all traces of the grob, you can redefine the function
typesetting them:
@lilypond[verbatim]
\score {
  \notes\relative c'' {
    \key c \minor
    \time 6/4
    as bes c bes c d \break
    \property Staff.KeySignature \override #'molecule-callback = #'()
    as bes c bes c d 
  }
  \paper{linewidth=5.0\cm indent=0}
}
@end lilypond

A very rigorous way of removing grobs from the whole score is to remove
the engraver that creates them. For example,

@lilypond[singleline,verbatim]
\score {\notes { c'4 d'8 e'8 g2 }
  \paper { \translator {
     \VoiceContext
     \remove Stem_engraver
  } }
}
@end lilypond

@node Dirty tricks
@subsection Dirty tricks
@cindex embedded tex

It is possible to use @TeX{} commands in the strings, but this should be
avoided because it makes it impossible for LilyPond to compute the
exact length of the string, which may lead to collisions.  Also, @TeX{}
commands won't work with direct PostScript output (see @ref{PostScript
output}).

@lilypond[fragment,relative,verbatim]
  a'^"3 $\\times$ \\`a deux"
@end lilypond

You can also use raw PostScript commands embedded in text scripts.  This
offers ultimate flexibility, but requires you to learn PostScript.
Currently, embedded PostScript will @strong{not} work with direct
PostScript output.  Note that all dimensions that you use are in staff
space.

@lilypond[verbatim]
\score {
  \notes \relative c'' {
    a-#"\\embeddedps{3 4 moveto 5 3 rlineto stroke}"
    -#"\\embeddedps{ [ 0 1 ] 0 setdash 3 5 moveto 5 -3 rlineto stroke}"
    b-#"\\embeddedps{3 4 moveto 0 0 1 2 8 4 20 3.5 rcurveto stroke}"
    s2
    a'1
  }
  \paper { linewidth = 70*\staffspace }
}
@end lilypond


@c . {Page layout}
@node Page layout
@section Page layout
@cindex Page layout

The page layout is the combined product of LilyPond formatting notation,
and (La)@TeX{} putting the notation on a page, including page breaks.
The part of LilyPond is documented here.

@menu
* Paper block::                 
* Paper variables::             
* Font Size::                   
* Paper size::                  
* Line break::                  
* Page break::                  
* Output scaling::              
@end menu

@c .  {Paper block}
@node Paper block
@subsection Paper block
@cindex Paper block

The most important output definition is the @code{\paper} block, for
music notation.  The syntax is

@example
  @code{\paper @{} [@var{paperidentifier}] @var{items} @code{@}}
@end example

where each of the items is one of

@itemize @bullet
  @item  An assignment.

  @item  A context definition.  See @ref{Interpretation context} for
       more information on context definitions.

  @item  \stylesheet  declaration.  Its syntax is
       @example
        	\stylesheet @var{alist}
       @end example

        See @file{scm/font.scm} for details of @var{alist}.
  @item an @code{\elementdescriptions} declaration.
        @example
                \elementdescriptions @var{alist}
        @end example
        See @file{scm/grob-description.scm} for details of
@var{alist}. This command is not user-serviceable.

@end itemize

@c .  {Paper variables}
@node Paper variables
@subsection Paper variables 
@cindex Paper variables

The paper block has some variables you may want to use or change:

@table @code
@cindex @code{indent}
  @item @code{indent}  
    The indentation of the first line of music.
@cindex @code{staffspace}

  @item @code{staffspace}
    The distance between two staff lines, calculated from the center
    of the lines.

@cindex @code{linewidth}
  @item @code{linewidth}  
    Sets the width of the lines.

If set to a negative value, a single unjustified line is produced.
@c rename to singleLinePaper ?
The shorthand @code{\singleLine} defines a default paper block that
produces a single line.

@cindex @code{textheight}

  @item @code{textheight}  
    Sets the total height of the music on each page. Only used by
@code{ly2dvi}.

@cindex @code{interscoreline}

  @item @code{interscoreline}  
    Sets the spacing between systems. The default is 16pt.
    
@cindex @code{interscorelinefill}

  @item @code{interscorelinefill}  
    If set to a positive number, the distance between the score 
    lines will stretch in order to fill the full page. In that
    case @code{interscoreline} specifies the minimum spacing.

        Not set by default.


@cindex @code{stafflinethickness}

  @item @code{stafflinethickness}  
    Determines the thickness of staff lines, and also acts as a scaling
    parameter for other line thicknesses.
@end table

You may enter these dimension using units (@code{cm}, @code{in},
@code{mm}, @code{pt}), or relative to another dimension
@example
        linewidth = 20.0 * \staffspace
        indent  = 0.5 \cm
@end example


@c .  {Font size}
@node Font Size
@subsection Font size
@cindex font size, setting
@cindex staff size, setting
@cindex @code{paper} file

The Feta font provides musical symbols at six different sizes.  These
fonts are 11 point, 13 point, 16 point, 20 point, 23 point, and 26
point.  The point size of a font is the height of the five lines in a
staff when displayed in the font.

Definitions for these sizes are the files @file{paperSZ.ly}, where
@code{SZ} is one of 11, 13, 16, 20, 23 and 26.  If you include any of
these files, the identifiers @code{paperEleven}, @code{paperThirteen},
@code{paperSixteen}, @code{paperTwenty}, @code{paperTwentythree}, and
@code{paperTwentysix} are defined respectively.  The default
@code{\paper} block is also set. These files should be imported at toplevel, i.e.
@example
	\include "paper26.ly"
	\score @{  ... @}
@end example

The font definitions are generated using a Scheme function. For more
details, see the file @file{scm/font.scm}.



@c .  {Paper size}
@node Paper size
@subsection Paper size
@cindex Paper size

@cindex paper size
@cindex page size
@cindex @code{papersize}

To change the paper size, you must first set the
@code{papersize} paper variable variable.  Set it to
the strings @code{a4}, @code{letter}, or @code{legal}.  After this
specification, you must set the font as described above.  If you want
the default font, then use the 20 point font.

@example
        \paper@{ papersize = "a4" @}
        \include "paper16.ly"
@end example

The file @code{paper16.ly}  will now include a file named @file{a4.ly}, which
will set the paper variables @code{hsize} and @code{vsize} (used by
Lilypond and @code{ly2dvi})

@c .  {Line break}
@node Line break
@subsection Line break

@cindex line breaks
@cindex breaking lines

Line breaks are normally computed automatically. They are chosen such
that it looks neither cramped nor loose, and that consecutive lines have
similar density.

Occasionally you might want to override the automatic breaks; you can do
this by specifying @code{\break}. This will force a line break at this
point. Do remember that line breaks can only occur at places where there
are bar lines.  If you want to have a line break where there is no
bar line, you can force an invisible bar line by entering @code{\bar
""}. Similarly, @code{\noBreak} forbids a line break at a certain point.

If you want linebreaks at regular intervals, you can use the following:
@example

<  \repeat 7 unfold @{ s1 * 4 \break  @}
   @emph{real music}
> 
@end  example
This makes the following 28 measures (assuming 4/4 time) be broken every
4 measures.


@cindex @code{\penalty}

The @code{\break} and @code{\noBreak} commands are defined in terms of
the penalty command:
@example
  \penalty @var{int} 
@end example

This encourages or discourages LilyPond to make a line break at this
point.

@refbugs

The scaling of the @code{\penalty} argument is not well-defined.  The
command is rather kludgey, and slated for rewriting.

@c .  {Page break}
@node Page break
@subsection Page break

@cindex page breaks
@cindex breaking pages

Page breaks are normally computed by @TeX{}, so they are not under
direct control of LilyPond.  However, you can insert a commands into the
@file{.tex} output to instruct @TeX{} where to break pages, by inserting
the command @code{\newpage}
@cindex @code{\newpage}

@example
  \newpage
@end example

@c why do so difficult?
@c maybe should explain contents of between-system.ly,
@c but not now, we're talking about page breaks here.
@c For more
@c details, see the example file @file{input/test/between-systems.ly}


@c .  {Output scaling}
@node Output scaling
@subsection Output scaling

[TODO]

@example
dvips ...
@end example

@example
pstops ...
@end example


@refbugs

There is no mechanism to select magnification of particular fonts,
meaning that you don't have access to continuously scaled fonts.



@c . {Output formats}
@node Output formats
@section Output formats

LilyPond can output processed music in different output formats.  

@menu
* TeX output::                  
* PostScript output::           
* Scheme output::               
* ASCIIScript output::          
@end menu

@node TeX output
@subsection TeX output
@cindex TeX output

LilyPond will use @TeX{} by default.  Even if you want to produce
PostScript output for viewing or printing, you should normally have
LilyPond produce @TeX{} first.  The .tex output must be processed by
@TeX{} (@strong{not} La@TeX{}) to generate a .dvi.  Then, @file{Dvips}
is used to generate PostScript.  Alternatively, @file{ly2dvi} can be
used to generate the .dvi for you.

@refbugs

Titling is not generated unless you use @file{ly2dvi}. 


@node PostScript output
@subsection PostScript output
@cindex PostScript output
@cindex direct PostScript output

LilyPond can produce PostScript directly, without going through @TeX{}.
Currently, this is mainly useful if you cannot use TeX, because direct
PostScript output has some problems; see Bugs below.

@example
$ lilypond -fps foo.ly
GNU LilyPond 1.3.144
Now processing: `foo.ly'
Parsing...
Interpreting music...[3]
Preprocessing elements... 
Calculating column positions... 
paper output to foo.ps...

$ cat /usr/share/lilypond/pfa/feta20.pfa foo.ps | lpr
@end example


@refbugs

Text font selection is broken.

The .ps file does not contain the .pfa font files.  To print a .ps
created through direct postscript output, you should prepend the
necessary .pfa files to LilyPond's .ps output, or upload them to the
printer before printing.

The line height calculation is broken, you must set @var{lineheight} in
the paperblock if you have more than one staff in your score, e.g.

@example
  ...
  \paper @{
    % Set line height to 40 staff spaces
    lineheight = 40    
  @}
@end example

@node Scheme output
@subsection Scheme output
@cindex Scheme output

In the typesetting stage, LilyPond builds a page description, which is
then written to disk in postscript, @TeX{} or ASCII art. Before it is
written, the page description is represented as Scheme expressions.  You
can also dump these  Scheme expressions to a file, which may be
convenient for debugging output routines.  This is done with the Scheme
output format

@example
$ lilypond -fscm foo.ly
GNU LilyPond 1.3.144
Now processing: `foo.ly'
Parsing...
Interpreting music...[3]
Preprocessing elements... 
Calculating column positions... 
paper output to foo.scm...

$ head -4 foo.scm 
;;; Usage: guile -s x.scm > x.tex
 (primitive-load-path 'standalone.scm)
; (scm-tex-output)
 (scm-ps-output)

$ guile -s foo.scm > foo.tex
@end example


@node ASCIIScript output
@subsection ASCIIScript output
@cindex ASCIIScript output
@cindex ascii script
@cindex ascii art

LilyPond can output ASCII Art.  This is a two step process, LilyPond
produces an ASCII description file, dubbed ASCIIScript (extension
@file{.as}).  ASCIIScript has a small and simple command set that
includes font selection, character and string printing and line drawing
commands.  The program @file{as2text} is used to translate an .as file
to text.

To produce ASCII Art, you must include an ASCII Art paper definition
file in your .ly, one of:
@example
\include "paper-as5.ly"
\include "paper-as9.ly"
@end example

Here's an example use for ASCII Art output (the example file
@file{as-email.ly} is included in the LilyPond distribution), the staff
symbol has been made invisible:

@example
$ lilypond -fas as-email.ly
GNU LilyPond 1.3.144
Now processing: `as-email.ly'
Parsing...
Interpreting music...[3]
Preprocessing elements... 
Calculating column positions... [2]
paper output to as-email.as...

$ as2text as-email.as 2>/dev/null
          |\
          |/     |##|##|      |  |  |  |  |
         /|      |  |  | |    |\ |\ |\ |\ |\ |
        / |_  3  |  |  | | 5  | )| )| )| )| )|
       | /| \ 8 *  *  *  | 8 *  *  *  *  *   |
        \_|_/            |                   |
        *_|

                                               lily
@end example


@refbugs

The ASCII Art fonts are far from complete and not very well designed.
It's easy to change the glyphs, though; if you think you can do better,
have a look at @file{mf/*.af}.

Lots of resizable symbols such as slurs, ties and tuplets are missing.

The poor looks of most ASCII Art output and its limited general
usefulness gives ASCII Art output a low priority; it may be
dropped in future versions.

@c . {Sound}
@node Sound
@section Sound
@cindex Sound

LilyPond can produce MIDI output.  The performance lacks lots of
interesting effects, such as swing, articulation, slurring, etc., but it
is good enough for proof-hearing the music you have entered.  Ties,
dynamics and tempo changes are interpreted.

Dynamic marks, crescendi and decrescendi translate into MIDI volume
levels.  Dynamic marks translate to a fixed fraction of the available
MIDI volume range, crescendi and decrescendi make the the volume vary
linearly between their two extremities.  The fractions be adjusted by
overriding the @code{absolute-volume-alist} defined in
@file{scm/midi.scm}.

For each type of musical instrument (that MIDI supports), a volume range
can be defined.  This gives you basic equalizer control, which can
enhance the quality of the MIDI output remarkably.  You can add
instruments and ranges or change the default settings by overriding the
@code{instrument-equalizer-alist} defined in @file{scm/midi.scm}.

Both loudness controls are combined to produce the final  MIDI volume. 


@refbugs

It is currently not possible to use the percussion channel (generally
channel 10 of a MIDI file).

@menu
* MIDI block::                  
* MIDI instrument names::       
@end menu

@c .  {MIDI block}
@node MIDI block
@subsection MIDI block
@cindex MIDI block


The MIDI block is analogous to the paper block, but it is somewhat
simpler.  The @code{\midi} block can contain:
@cindex MIDI block

@itemize @bullet
  @item  a @code{\tempo} definition
  @item  context definitions
@end itemize

Assignments in the @code{\midi} block are not allowed.



@cindex context definition

Context definitions follow precisely the same syntax as within the
\paper block.  Translation modules for sound are called performers.
The contexts for MIDI output are defined in @file{ly/performer.ly}.


@node MIDI instrument names
@subsection MIDI instrument names

@cindex instrument names
@cindex @code{Staff.midiInstrument}
@cindex @code{Staff.instrument}

The MIDI instrument name is set by the @code{Staff.midiInstrument}
property or, if that property is not set, the @code{Staff.instrument}
property.  The instrument name should be chosen from the list in
@ref{MIDI instruments}.

@refbugs

If the selected string does not exactly match, then LilyPond uses the
default (Grand Piano). It is not possible to select an instrument by
number.








@c FIXME: Note entry vs Music entry at top level menu is confusing.
@c . {Music entry}
@node Music entry
@section Music entry
@cindex Music entry
@menu
* Relative::                    
* Bar check::                   
* Point and click::             
@end menu

When entering music with LilyPond, it is easy to introduce errors. This
section deals with tricks and features that help you enter music, and
find and correct mistakes.

@c .  {Relative}
@node Relative
@subsection Relative
@cindex Relative
@cindex relative octave specification

Octaves are specified by adding @code{'} and @code{,} to pitch names.
When you copy existing music, it is easy to accidentally put a pitch in
the wrong octave and hard to find such an error.  To prevent these
errors, LilyPond features octave entry.

@cindex @code{\relative}
@example
  \relative @var{startpitch} @var{musicexpr}
@end example

The octave of notes that appear in @var{musicexpr} are calculated as
follows: If no octave changing marks are used, the basic interval
between this and the last note is always taken to be a fourth or less
(This distance is determined without regarding alterations; a
@code{fisis} following a @code{ceses} will be put above the
@code{ceses})

The octave changing marks @code{'} and @code{,} can be added to raise or
lower the pitch by an extra octave.  Upon entering relative mode, an
absolute starting pitch must be specified that will act as the
predecessor of the first note of @var{musicexpr}.

Entering music that changes octave frequently  is easy in relative mode.
@lilypond[fragment,singleline,verbatim,center]
  \relative c'' {
    b c d c b c bes a 
  }
@end lilypond

And octave changing marks are used for intervals greater than a fourth.
@lilypond[fragment,verbatim,center]
  \relative c'' {
    c g c f, c' a, e'' }
@end lilypond

If the preceding item is a chord, the first note of the chord is used
to determine the first note of the next chord. However, other notes
within the second chord are determined by looking at the immediately
preceding note.

@lilypond[fragment,verbatim,center]
  \relative c' {
    c <c e g> 
    <c' e g>
    <c, e' g>
  }
@end lilypond 
@cindex @code{\notes}

The pitch after the @code{\relative} contains a note name.  To parse
the pitch as a note name, you have to be in note mode, so there must
be a surrounding @code{\notes} keyword (which is not
shown here).

The relative conversion will not affect @code{\transpose},
@code{\chords} or @code{\relative} sections in its argument.  If you
want to use relative within transposed music, you must place an
additional @code{\relative} inside the @code{\transpose}.


@c .  {Bar check}
@node Bar check
@subsection Bar check
@cindex Bar check

@cindex bar check
@cindex @code{barCheckNoSynchronize}
@cindex @code{|}


Whenever a bar check is encountered during interpretation, a warning
message is issued if it doesn't fall at a measure boundary.  This can
help you find errors in the input.  Depending on the value of
@code{barCheckNoSynchronize}, the beginning of the measure will be
relocated, so this can also be used to shorten measures.

A bar check is entered using the bar symbol, @code{|}:
@example
  \time 3/4 c2 e4 | g2.
@end example



@cindex skipTypesetting

Failed bar checks are most often caused by entering incorrect
durations. Incorrect durations often completely garble up the score,
especially if it is polyphonic, so you should start correcting the score
by scanning for failed bar checks and incorrect durations.  To speed up
this process, you can use @code{skipTypesetting} (See @ref{Skipping
corrected music})). Bar


@c .  {Point and click}
@node Point and click
@subsection Point and click

Point and click lets you find notes in the input by clicking on them in
the Xdvi window. This makes it very easy to find input that causes some
error in the sheet music.

To use it, you need the following software

@unnumberedsubsec Installation

@itemize @bullet
@item 
@uref{ftp://ftp.math.berkeley.edu/pub/Software/TeX/xdvi.tar.gz,plain
Xdvi} version 22.36 or newer.

  Note that most @TeX{} distributions ship with xdvik, which is a
  different and less well maintained program. To find out which xdvi you
  are running, try @code{xdvi --version} or @code{xdvi.bin --version}.
@item emacs
@end itemize

Xdvi must be configured to find the TeX fonts and music
fonts. Refer to the Xdvi documentation for more information.


@unnumberedsubsec Using it

Add one of these lines to the top of your .ly file. The first one is for
line location only. The second one is more convenient, but requires
patching @code{emacsclient} and @code{server.el}.

@example
#(set! point-and-click line-location)
@end example

In the emacs startup file (usually @file{~/.emacs}), add the following
@example
(server-start)
@end example

Make sure that  the environment  variable @code{XEDITOR} is set
to
@example
emacsclient --no-wait +%l %f
@end example
The second one, that also specifies the column, only works if you have
patched your emacsclient and server, and have compiled your @code{.ly}
file using the @code{line-column-location} setting.

When viewing, control-mousebutton 1 will take you to the originating
spot in the @file{.ly} file. Control-mousebutton 2 will show all
clickable boxes.


@unnumberedsubsec Column location

If you want emacs to jump to the exact spot (and not just the line) on a
click, you must enable column positioning. To do so, you need to patch
emacsclient. Apply @file{emacsclient.patch} (included with the source
package) to @file{emacsclient.c} and @file{server.el} from the emacs
source code. Recompile and stick the recompiled emacsclient into a bin
directory, and put @file{server.el} into a elisp directory
(e.g. @file{~/usr/share/emacs/}). Add the following to your @file{.emacs}
init file, before invoking server-start.

@example
 (setq load-path (cons "~/usr/share/emacs" load-path))
@end example

Set @code{XEDITOR} to @code{emacsclient --no-wait +%l:%c %f}

At the top of the @code{ly} file, replace the @code{set!} line with the
following line
@example
#(set! point-and-click line-column-location)
@end example

One final hint: if you correct large files with point-and-click, then
start correcting at the end of the file. When you start at the top, and
insert one line, all subsequent locations will be off by a line.


@refbugs

When you convert the @TeX{} file to PostScript using @code{dvips}, it
will complain about not finding @code{src:X:Y} files. Those complaints
are harmless, and can be ignored.

@node Skipping corrected music
@section Skipping corrected music

The property @code{Score.skipTypesetting} can be used to switch on and
off typesetting completely during the interpretation phase. When
typesetting is switched off, the music is processed much more quickly.
You can use this to skip over the parts of a score that you have already
checked for errors. 

@lilypond[fragment,singleline,verbatim]
\relative c'' { c8 d
\property Score.skipTypesetting = ##t
  e f g a g c, f e d
\property Score.skipTypesetting = ##f
c d b bes a g c2 } 
@end lilypond


@node Interpretation context
@section Interpretation context

@menu
* Creating contexts::           
* Default contexts::            
* Context properties::          
* Engravers and performers::    
* Changing context definitions::  
* Defining new contexts::       
@end menu


Interpretation contexts are objects that only exist during a run of
LilyPond.  During the interpretation phase of LilyPond (when it prints
"interpreting music"), the music expression in a @code{\score} block is
interpreted in time order. This is the same order that humans hear and
play the music.

During this interpretation, the interpretation context holds the
state for the current point within the music. It contains information
like

@itemize @bullet
  @item What notes are playing at this point?
  @item What symbols will be printed at this point?
  @item What is the current key signature, time signature, point within
       the measure, etc.?
@end itemize

Contexts are grouped hierarchically: A @internalsref{Voice} context is
contained in a @internalsref{Staff} context (because a staff can contain
multiple voices at any point), a @internalsref{Staff} context is contained in
@internalsref{Score}, @internalsref{StaffGroup}, or @internalsref{ChoirStaff} context.

Contexts associated with sheet music output are called @emph{notation
contexts}, those for sound output are called @emph{performance
contexts}. The default definitions of the standard notation and
performance contexts can be found in @file{ly/engraver.ly} and
@file{ly/performer.ly}, respectively.


@node Creating contexts
@subsection Creating contexts

@cindex @code{\context}
@cindex context selection

Contexts for a music expression can be selected manually, using the
following music expression.

@example
  \context @var{contexttype} [= @var{contextname}] @var{musicexpr}
@end example

This instructs lilypond to interpret @var{musicexpr} within the context
 of type @var{contexttype} and with name @var{contextname}.  If this
context does not exist, it will be created.  

@lilypond[verbatim,singleline]
\score {
  \notes \relative c'' {
    c4 <d4 \context Staff = "another" e4> f
  }
}

@end lilypond

In this example, the @code{c} and @code{d} are printed on the
default staff.  For the @code{e}, a context Staff called
@code{another} is specified; since that does not exist, a new
context is created.  Within @code{another}, a (default) Voice context
is created for the @code{e4}.  When all music referring to a
context is finished, the context is ended as well.  So after the
third quarter, @code{another} is removed.



@node Default contexts
@subsection Default contexts

Most music expressions don't need an explicit @code{\context}
declaration: they inherit the 
notation context from their parent. Each note is a music expression, and
as you can see in the following example, only the sequential music
enclosing the three notes has an explicit context. 

@lilypond[verbatim,singleline]
\score { \notes \context Voice = goUp { c'4 d' e' } } 
@end lilypond

There are some quirks that you must keep in mind when dealing with
defaults:

First, every top level music is interpreted by the Score context, in other
words, you may think of @code{\score} working like
@example
        \score @{
                \context Score @var{music}
        @}
@end example

Second, contexts are created automatically to be able to interpret the
music expressions. Consider the following example.

@lilypond[verbatim, singleline]
\score { \context Score \notes { c'4 (  d' )e' } }
@end lilypond

The sequential music is interpreted by the Score context initially
(notice that the @code{\context} specification is redundant), but when a
note is encountered, contexts are setup to accept that note. In this
case, a Thread, Voice and Staff are created. The rest of the sequential
music is also interpreted with the same Thread, Voice and Staff context,
putting the notes on the same staff, in the same voice.

This is a convenient mechanism, but do not expect opening chords to work
without @code{\context}. For every note, a separate staff is
instantiated.

@cindex explicit context
@cindex starting with chords
@cindex chords, starting with

@lilypond[verbatim, singleline]
\score { \notes <c'4 es'> } 
@end lilypond

Of course, if the chord is preceded by a normal note in sequential
music, the chord will be interpreted by the Thread of the preceding
note:
@lilypond[verbatim,singleline]
\score { \notes { c'4 <c'4 es'> }  }
@end lilypond



@node Context properties
@subsection Context properties

Notation contexts have properties. These properties are from
the @file{.ly} file using the following  expression:
@cindex @code{\property}
@example
  \property @var{contextname}.@var{propname} =  @var{value}
@end example

Sets the @var{propname} property of the context @var{contextname} to the
specified Scheme expression @var{value}.  All @var{propname} and
@var{contextname} are strings, which are typically unquoted.

Properties that are set in one context are inherited by all of the
contained contexts.  This means that a property valid for the
@internalsref{Voice} context can be set in the @internalsref{Score} context (for
example) and thus take effect in all @internalsref{Voice} contexts.

Properties can be unset using the following expression:
@example
  \property @var{contextname}.@var{propname} \unset
@end example

@cindex properties, unsetting
@cindex @code{\unset} 

This removes the definition of @var{propname} in @var{contextname}. If
@var{propname} was not defined in @var{contextname} (but was inherited
from a higher context), then this has no effect.


@refbugs

The syntax of @code{\unset} is asymmetric: @code{\property \unset} is not
the inverse of @code{\property \set}.

@node Engravers and performers
@subsection Engravers and performers

[TODO]

Basic building blocks of translation are called engravers; they are
special C++ classes.



@c .  {Context definitions}
@node Changing context definitions
@subsection Changing context definitions

@cindex context definition
@cindex translator definition

The most common way to define a context is by extending an existing
context.  You can change an existing context from the paper block, by
first initializing a translator with an existing context identifier:
@example
\paper @{
  \translator @{
    @var{context-identifier}
  @} @}
@end example
Then you can add and remove engravers using the following syntax:
@example
 \remove @var{engravername}
 \consists @var{engravername}
@end example


Here @var{engravername} is a string, the name of an engraver in the
system.


@lilypond[verbatim,singleline]
\score {  \notes {
        c'4 c'4 }
  \paper {
    \translator  { \StaffContext
        \remove Clef_engraver
       } } }
@end lilypond

@cindex engraver

You can also set properties in a translator definition. The syntax is as
follows:
@example
 @var{propname} = @var{value}
 @var{propname} \set  @var{grob-propname} = @var{pvalue}
 @var{propname} \override @var{grob-propname} =  @var{pvalue}
 @var{propname} \revert @var{grob-propname} 
@end example
@var{propname} is a string, @var{grob-propname} a symbol, @var{value}
and @code{pvalue} are Scheme expressions. These type of property
assignments happen before interpretation starts, so a @code{\property}
command will override any predefined settings.


 To simplify editing translators, all standard contexts have standard
identifiers called @var{name}@code{Context}, e.g. @code{StaffContext},
@code{VoiceContext}, see @file{ly/engraver.ly}.

@node Defining new contexts
@subsection Defining new contexts

If you want to build a context from scratch, you must also supply the
following extra information:
@itemize @bullet
  @item  A name, specified by @code{\name @var{contextname}}.

  @item A cooperation module. This is specified by   @code{\type
@var{typename}}.
@end itemize

This is an example:
@example
\translator @code{
  \type "Engraver_group_engraver"
  \name "SimpleStaff"
  \alias "Staff"
  \consists "Staff_symbol_engraver"
  \consists "Note_head_engraver"
  \consistsend "Axis_group_engraver"
}@
@end example

The argument of @code{\type} is the name for a special engraver that
handles cooperation between simple engravers such as
@code{Note_head_engraver} and @code{Staff_symbol_engraver}. Alternatives
for this engraver are the following:
@table @code
@cindex @code{Engraver_group_engraver}
  @item @code{Engraver_group_engraver}  
    The standard cooperation engraver.

@cindex @code{Score_engraver}

  @item @code{Score_engraver}  
    This is cooperation module that should be in the top level context,
and only the top level context.

@cindex @code{Grace_engraver_group}

  @item @code{Grace_engraver_group}  
    This is a special cooperation module (resembling
    @code{Score_engraver}) that is used to create an embedded
    `miniscore'.
@end table 

Other modifiers   are

@itemize @bullet
  @item @code{\alias} @var{alternate-name}
    This specifies a different name. In the above example,
@code{\property Staff.X = Y} will also work on @code{SimpleStaff}s

  @item  @code{\consistsend} @var{engravername} 
    Analogous to @code{\consists}, but makes sure that
    @var{engravername} is always added to the end of the list of
    engravers.

    Some engraver types need to be at the end of the list; this
    insures they stay there even if a user adds or removes engravers.
End-users generally don't need this command.
    
  @item  @code{\accepts} @var{contextname}
    Add @var{contextname} to the list of contexts this context can
    contain in the context hierarchy. The first listed context is the
    context to create by default.

  @item @code{\denies}. The opposite of @code{\accepts}. Added for
completeness, but is never used in practice.
 
  
  @item  @code{\name} @var{contextname} 
    This sets the type name of the context, e.g. @internalsref{Staff},
    @internalsref{Voice}.  If the name is not specified, the translator won't do
    anything. 
@end itemize

In the @code{\paper} block, it is also possible to define translator
identifiers.  Like other block identifiers, the identifier can only
be used as the very first item of a translator.  In order to define
such an identifier outside of @code{\score}, you must do

@quotation
@example 
\paper @{
  foo = \translator @{ @dots{} @}
@}
\score @{
  \notes @{
    @dots{}
  @}
  \paper @{
    \translator @{ \foo @dots{} @}
  @}
@} 
@end example 

@end quotation


@cindex paper types, engravers, and pre-defined translators

      




@c . {Syntactic details}
@node Syntactic details
@section Syntactic details
@cindex Syntactic details

This section describes details that were too boring to be put elsewhere.

@menu
* Top level::                   
* Identifiers::                 
* Music expressions::           
* Manipulating music expressions::  
* Assignments::                 
* Lexical modes::               
* Ambiguities::                 
@end menu

@c .  {Top level}
@node Top level
@subsection Top level
@cindex Top level

This section describes what you may enter at top level.


@c .   {Score}
@subsubsection Score
@cindex Score

@cindex score definition

The output is generated combining a music expression with an output
definition.  A score block has the following syntax:

@example
  \score @{ @var{musicexpr} @var{outputdefs} @}
@end example

@var{outputdefs} are zero or more output definitions.  If none is
supplied, the default @code{\paper} block will be added.



@c .   {Default output}
@subsubsection Default output

Default values for the @code{\paper} and @code{\midi} block are set by
entering such a block at the top level.

@c .   {Header}
@subsubsection Header
@cindex Header
@cindex @code{\header}


A header describes bibliographic information of the file's contents.  It
can also appear in a @code{\score} block.  Tools like @code{ly2dvi} can
use this information for generating titles.  Key values that are used by
@code{ly2dvi} are: title, subtitle, composer, opus, poet, instrument,
meter, arranger, piece and tagline.

@cindex @code{ly2dvi}

The syntax is
@example
  \header @{ @var{key1} = @var{val1}
             @var{key2} = @var{val2} @dots{} @}
@end example

It is customary to put the @code{\header} at the top of the file.

@subsubsection Default output

A @code{\midi} or @code{\paper} block at top level sets the default
paper block for all scores that lack an explicit paper block.

@c .  {Identifiers}
@node Identifiers
@subsection Identifiers
@cindex  Identifiers

@ignore
 What has this section got to do with identifiers?
 It seems more appropriate in the introduction to Chapter 4,
 "Internals".

   /MB
@end ignore

All of the information in a LilyPond input file, is internally
represented as a Scheme value. In addition to normal Scheme data types
(such as pair, number, boolean, etc.), LilyPond has a number of
specialized data types,

@itemize @bullet
@item Input
@item c++-function
@item Music
@item Identifier
@item Translator_def
@item Duration
@item Pitch
@item Score
@item Music_output_def
@item Moment (rational number)
@end itemize

LilyPond also includes some transient object types. Objects of these
types are built during a LilyPond run, and do not `exist' per se within
your input file. These objects are created as a result of your input
file, so you can include commands in the input to manipulate them,
during a lilypond run.

@itemize @bullet
@item Grob: short for Graphical object. See @ref{Grobs}. 
@item Molecule: device-independent page output object,
including dimensions.  Produced by some Grob functions
See @ref{Molecules}
@item Translator: object that produces audio objects or Grobs. This is
not yet user accessible.
@item Font_metric: object representing a font. (See @ref{Font metrics})

@end itemize


@node Music expressions
@subsection Music expressions

@cindex music expressions

Music in LilyPond is entered as a music expression.  Notes, rests, lyric
syllables are music expressions, and you can combine music expressions
to form new ones, for example by enclosing a list of expressions in
@code{\sequential @{ @}} or @code{< >}.  In the following example, a
compound expression is formed out of the quarter note @code{c} and a
quarter note @code{d}:

@example 
\sequential @{ c4 d4 @} 
@end example 

@cindex Sequential music
@cindex @code{\sequential}
@cindex sequential music
@cindex @code{<}
@cindex @code{>}
@cindex Simultaneous music
@cindex @code{\simultaneous}

The two basic compound  music expressions are simultaneous  and
sequential music.

@example
  \sequential @code{@{} @var{musicexprlist} @code{@}}
  \simultaneous @code{@{} @var{musicexprlist} @code{@}}
@end example
For both, there is a shorthand:
@example
  @code{@{} @var{musicexprlist} @code{@}}
@end example
for sequential and
@example
  @code{<} @var{musicexprlist} @code{>}
@end example
for simultaneous music.
In principle, the way in which you nest sequential and simultaneous to
produce music is not relevant.  In the following example, three chords
are expressed in two different ways:

@lilypond[fragment,verbatim,center]
  \notes \context Voice {
    <a c'> <b  d' > <c' e'>
    < { a b  c' } { c' d' e' } >
  }
@end lilypond


Other compound music expressions include
@example
 \repeat @var{expr}
 \transpose @var{pitch} @var{expr}
 \apply @var{func} @var{expr}
 \context @var{type} = @var{id} @var{expr}
 \times @var{fraction} @var{expr}
@end example


@c . {Manipulating music expressions}
@node Manipulating music expressions
@subsection  Manipulating music expressions

The @code{\apply} mechanism gives you access to the internal
representation of music. You can write Scheme-functions that operate
directly on it. The syntax is 
@example
        \apply #@var{func} @var{music}
@end example
This means that @var{func} is applied to @var{music}.  The function
@var{func} should return a music expression.

This example replaces the text string of a script. It also shows a dump
of the music it processes, which is useful if you want to know more
about how music is stored.

@lilypond[verbatim,singleline]
#(define (testfunc x)
        (if (equal? (ly-get-mus-property x 'text) "foo")
                (ly-set-mus-property x 'text "bar"))
        ;; recurse
        (ly-set-mus-property x 'elements
          (map testfunc (ly-get-mus-property x 'elements)))
        (display x)
        x        
)
\score { \notes
  \apply #testfunc { c'4_"foo" }
} 
@end lilypond

For more information on what is possible, see the automatically
generated documentation.


Directly accessing internal representations is dangerous: the
implementation is subject to changes, so you should avoid this feature
if possible.

A final example is a function that reverses a piece of music in time:

@lilypond[verbatim,singleline]
#(define (reverse-music music)
  (let* ((elements (ly-get-mus-property music 'elements))
         (reversed (reverse elements))
         (span-dir (ly-get-mus-property music 'span-direction)))
    (ly-set-mus-property music 'elements reversed)
    (if (dir? span-dir)
        (ly-set-mus-property music 'span-direction (- span-dir)))
    (map reverse-music reversed)
    music))

music = \notes { c'4 d'4( e'4 f'4 }

\score { \context Voice {
    \music
    \apply #reverse-music \music
  }
}
@end lilypond

More examples are given in the distributed example files in
@code{input/test/}.

@c .   {Span requests}
@menu
* Span requests::               
@end menu

@node Span requests
@subsubsection Span requests
@cindex Span requests

Notational constructs that start and end on different notes can be
entered using span requests. The syntax is as follows:


@example
  \spanrequest @var{startstop} @var{type}
@end example


@cindex @code{\start}
@cindex @code{\stop}

This defines a spanning request. The @var{startstop} parameter is either
-1 (@code{\start}) or 1 (@code{\stop}) and @var{type} is a string that
describes what should be started.  Much of the syntactic sugar is a
shorthand for @code{\spanrequest}, for example,

@lilypond[fragment,verbatim,center]
  c'4-\spanrequest \start "slur"
  c'4-\spanrequest \stop "slur"
@end lilypond

Among the supported types are @code{crescendo}, @code{decrescendo},
@code{beam}, @code{slur}. This is an internal command.  Users are
encouraged to use the shorthands which are defined in the initialization
file @file{spanners.ly}.


@c .   {Assignments}
@node Assignments
@subsection Assignments
@cindex Assignments

Identifiers allow objects to be assigned to names during the parse
stage.  To assign an identifier, you use @var{name}@code{=}@var{value}
and to refer to an identifier, you precede its name with a backslash:
`@code{\}@var{name}'.  @var{value} is any valid Scheme value or any of
the input-types listed above.  Identifier assignments can appear at top
level in the LilyPond file, but also in @code{\paper} blocks.

An identifier can be created with any string for its name, but you will
only be able to refer to identifiers whose names begin with a letter,
being entirely alphabetical.  It is impossible to refer to an identifier
whose name is the same as the name of a keyword.

The right hand side of an identifier assignment is parsed completely
before the assignment is done, so it is allowed to redefine an
identifier in terms of its old value, e.g.

@example
foo = \foo * 2.0
@end example

When an identifier is referenced, the information it points to is
copied.  For this reason, an identifier reference must always be the
first item in a block.
@example
\paper  @{
  foo = 1.0
  \paperIdent % wrong and invalid
@}

\paper @{
  \paperIdent % correct
  foo = 1.0 @}
@end example


@c .  {Lexical modes}
@node Lexical modes
@subsection Lexical modes
@cindex Lexical modes
@cindex input mode
@cindex mode, input 
@cindex @code{\notes}
@cindex @code{\chords}
@cindex @code{\lyrics}

To simplify entering notes, lyrics, and chords, LilyPond has three
special input modes in addition to the default mode: note, lyrics and
chords mode.  These input modes change the way that normal, unquoted
words are interpreted: for example, the word @code{cis} may be
interpreted as a C-sharp, as a lyric syllable `cis' or as a C-sharp
major triad respectively.

A mode switch is entered as a compound music expression
@example
@code{\notes} @var{musicexpr}
@code{\chords} @var{musicexpr}
@code{\lyrics} @var{musicexpr}.
@end example

In each of these cases, these expressions do not add anything to the
meaning of their arguments.  They just instruct the parser in what mode
to parse their arguments.  The modes are treated in more detail in
@ref{Lyrics} and @ref{Chords}.

Different input modes may be nested.

@c .  {Ambiguities}
@node Ambiguities
@subsection Ambiguities
@cindex ambiguities
@cindex grammar


The grammar contains a number of ambiguities. We hope to resolve them at
some time.

@itemize @bullet
  @item  The assignment

@example 
foo = bar 
@end example 
         is interpreted as the string identifier assignment. However,
it can also  be interpreted as making a string identifier @code{\foo}
       containing @code{"bar"}, or a music identifier @code{\foo}
       containing the syllable `bar'.  

  @item  If you do a nested repeat like

       @quotation

@example 
\repeat @dots{}
\repeat @dots{}
\alternative 
@end example 

       @end quotation

       then it is ambiguous to which @code{\repeat} the
       @code{\alternative} belongs.  This is the classic if-then-else
       dilemma.  It may be solved by using braces.

  @item The parser is not sophisticated enough to distinguish at the
right time between
        @code{c4*2 / 3 } and @code{c4*2 / g} (in chord mode).

[checkme]

@end itemize


@c .  {Lexical details}
@node Lexical details
@section Lexical details

Even more boring details, now on lexical side of the input parser.

@menu
* Comments::                    
* Direct Scheme::               
* Keywords::                    
* Integers::                    
* Reals::                       
* Strings::                     
* Main input::                  
* File inclusion::              
* Version information::         
@end menu


@node Comments
@subsection Comments

@cindex comments
@cindex block comment
@cindex line comment

@cindex @code{%}

A one line comment is introduced by a @code{%} character. 
Block comments are started by @code{%@{} and ended by @code{%@}}. 
They cannot be nested.

@node Direct Scheme
@subsection Direct Scheme

@cindex Scheme
@cindex GUILE
@cindex Scheme, in-line code


LilyPond contains a Scheme interpreter (the GUILE library) for
internal use. In some places, Scheme expressions also form valid syntax:
wherever it is allowed,
@example
  #@var{scheme}
@end example
evaluates the specified Scheme code.  Example:
@example
  \property Staff.TestObject \override #'foobar =  #(+ 1 2)
@end example
@code{\override} expects two Scheme expressions, so there are two Scheme
expressions. The first one is a symbol (@code{foobar}), the second one
an integer (namely, 3).

In-line scheme may be used at the top level. In this case the result is
discarded.

Scheme is a full-blown programming language, and a full discussion is
outside the scope of this document. Interested readers are referred to
the website @uref{http://www.schemers.org/} for more information on
Scheme.


@node Keywords
@subsection Keywords
@cindex Keywords


Keywords start with a backslash, followed by a number of lower case
alphabetic characters.  These are all the keywords.

@example
apply arpeggio autochange spanrequest commandspanrequest
simultaneous sequential accepts alternative bar breathe
char chordmodifiers chords clef cm consists consistsend
context denies duration dynamicscript elementdescriptions
font grace header in lyrics key mark pitch
time times midi mm name pitchnames notes outputproperty
override set revert partial paper penalty property pt
relative remove repeat addlyrics partcombine score
script stylesheet skip textscript tempo translator
transpose type
@end example

@node Integers
@subsection Integers

@cindex integers
@cindex @code{+}
@cindex @code{-}
@cindex @code{*}
@cindex @code{/}

Formed from an optional minus sign followed by digits.  Arithmetic
operations cannot be done with integers, and integers cannot be mixed
with reals.

@node Reals
@subsection Reals
@cindex real numbers





Formed from an optional minus sign and a sequence of digits followed
by a @emph{required} decimal point and an optional exponent such as
@code{-1.2e3}.  Reals can be built up using the usual operations:
`@code{+}', `@code{-}', `@code{*}', and
`@code{/}', with parentheses for grouping.

@cindex @code{\mm},
@cindex @code{\in}
@cindex @code{\cm}
@cindex @code{\pt}
@cindex dimensions

A real constant can be followed by one of the dimension keywords:
@code{\mm} @code{\pt}, @code{\in}, or @code{\cm}, for millimeters,
points, inches and centimeters, respectively.  This converts the number
a number that is the internal representation of that dimension.


@node Strings
@subsection Strings
@cindex string
@cindex concatenate

Begins and ends with the @code{"} character.  To include a @code{"}
character in a string write @code{\"}.  Various other backslash
sequences have special interpretations as in the C language.  A string
that contains no spaces can be written without the quotes.  Strings can
be concatenated with the @code{+} operator.


@node Main input
@subsection Main input
@cindex Main input

@cindex @code{\maininput}

The @code{\maininput} command is used in init files to signal that the
user file must be read. This command cannot be used in a user file.

@node File inclusion
@subsection File inclusion
@cindex @code{\include}
@example
  \include @var{filename}
@end example

Include @var{filename}.  The argument @var{filename} may be a quoted string (an
unquoted string will not work here!) or a string identifier.  The full
filename including the @file{.ly} extension must be given,


@node Version information
@subsection Version information 
@cindex @code{\version}
@example
  \version @var{string} 
@end example

Specify the version of LilyPond that a file was written for.  The
argument is a version string in quotes, for example @code{"1.2.0"}. 
This is used to detect invalid input, and to aid
@code{convert-ly}  a tool that automatically upgrades input files. See
See @ref{convert-ly} for more information on @code{convert-ly}.

@cindex convert-ly





@c broken with  emacs-21
@c {Local emac s  vars}
@c Local varia bles:
@c mode: texi nfo
@c minor-mod e: font-lock
@c minor-mo de: outline
@c outline -layout: (-1 : 0)
@c outlin e-use-mode-specific-leader: "@c \."
@c outli ne-primary-bullet: "{"
@c outli ne-stylish-prefixes: nil
@c outli ne-override-protect: t
@c End:

