[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

5.1 Interpretation contexts

This section describes what contexts are, and how to modify them.

See also

Learning Manual: (learning)Contexts and engravers section ‘Contexts and engravers’ in Learning Manual.

Installed Files: ‘ly/engraver-init.ly’, ‘ly/performer-init.ly’.

Snippets: (snippets)Contexts and engravers section ‘Contexts and engravers’ in Snippets.

Internals Reference: (internals)Contexts section ‘Contexts’ in Internals Reference, (internals)Engravers and Performers section ‘Engravers and Performers’ in Internals Reference.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

5.1.1 Contexts explained

Contexts are arranged hierarchically:


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

Output definitions - blueprints for contexts

This section explains the relevance of output definitions when working with contexts. Examples for actual output definitions are given later (see Changing all contexts of the same type).

While music written in a file may refer to context types and names, contexts are created only when the music is actually being interpreted. LilyPond interprets music under control of an ‘output definition’ and may do so for several different output definitions, resulting in different output. The output definition relevant for printing music is specified using \layout.

A much simpler output definition used for producing Midi output is specified using \midi. Several other output definitions are used by LilyPond internally, like when using the part combiner (Automatic part combining) or creating music quotes (Quoting other voices).

Output definitions define the relation between contexts as well as their respective default settings. While most changes will usually be made inside of a \layout block, Midi-related settings will only have an effect when made within a \midi block.

Some settings affect several outputs: for example, if autoBeaming is turned off in some context, beams count as melismata for the purpose of matching music to lyrics as described in Automatic syllable durations. This matching is done both for printed output as well as for Midi. If changes made to autoBeaming within a context definition of a \layout block are not repeated in the corresponding \midi block, lyrics and music will get out of sync in Midi.

See also

Installed Files: ‘ly/engraver-init.ly’. ‘ly/performer-init.ly’.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

Score - the master of all contexts

This is the top level notation context. No other context can contain a Score context. By default the Score context handles the administration of time signatures and makes sure that items such as clefs, time signatures, and key-signatures are aligned across staves.

A Score context is instantiated implicitly when a \score {…} block is processed.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

Top-level contexts - staff containers

StaffGroup

Groups staves while adding a bracket on the left side, grouping the staves together. The bar lines of the contained staves are connected vertically. StaffGroup only consists of a collection of staves, with a bracket in front and spanning bar lines.

ChoirStaff

Identical to StaffGroup except that the bar lines of the contained staves are not connected vertically.

GrandStaff

A group of staves, with a brace on the left side, grouping the staves together. The bar lines of the contained staves are connected vertically.

PianoStaff

Just like GrandStaff, but with support for instrument names to the left of each system.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

Intermediate-level contexts - staves

Staff

Handles clefs, bar lines, keys, accidentals. It can contain Voice contexts.

RhythmicStaff

Like Staff but for printing rhythms. Pitches are ignored when engraving; the notes are printed on one line. The MIDI rendition retains pitches unchanged.

TabStaff

Context for generating tablature. By default lays the music expression out as a guitar tablature, printed on six lines.

DrumStaff

Handles typesetting for percussion. Can contain DrumVoice.

VaticanaStaff

Same as Staff, except that it is designed for typesetting a piece in gregorian style.

MensuralStaff

Same as Staff, except that it is designed for typesetting a piece in mensural style.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

Bottom-level contexts - voices

Voice-level contexts initialise certain properties and start appropriate engravers. A bottom-level context is one without defaultchild. While it is possible to let it accept/contain subcontexts, they can only be created and entered explicitly.

Voice

Corresponds to a voice on a staff. This context handles the conversion of dynamic signs, stems, beams, super- and sub-scripts, slurs, ties, and rests. You have to instantiate this explicitly if you require multiple voices on the same staff.

VaticanaVoice

Same as Voice, except that it is designed for typesetting a piece in gregorian style.

MensuralVoice

Same as Voice, with modifications for typesetting a piece in mensural style.

Lyrics

Corresponds to a voice with lyrics. Handles the printing of a single line of lyrics.

DrumVoice

The voice context used in a percussion staff.

FiguredBass

The context in which BassFigure objects are created from input entered in \figuremode mode.

TabVoice

The voice context used within a TabStaff context. Usually left to be created implicitly.

CueVoice

A voice context used to render notes of a reduced size, intended primarily for adding cue notes to a staff, see Formatting cue notes. Usually left to be created implicitly.

ChordNames

Typesets chord names.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

5.1.2 Creating and referencing contexts

LilyPond will create lower-level contexts automatically if a music expression is encountered before a suitable context exists, but this is usually successful only for simple scores or music fragments like the ones in the documentation. For more complex scores it is advisable to specify all contexts explicitly with either the \new or \context command. The syntax of these two commands is very similar:

 
[\new | \context] Context [ = name] [music-expression]

where either \new or \context may be specified. Context is the type of context which is to be created, name is an optional name to be given to the particular context being created and music-expression is a single music expression that is to be interpreted by the engravers and performers in this context.

The \new prefix without a name is commonly used to create scores with many staves:

 
<<
  \new Staff \relative {
    % leave the Voice context to be created implicitly
    c''4 c
  }
  \new Staff \relative {
    d''4 d
  }
>>

[image of music]

and to place several voices into one staff:

 
\new Staff <<
  \new Voice \relative {
    \voiceOne
    c''8 c c4 c c
  }
  \new Voice \relative {
    \voiceTwo
    g'4 g g g
  }
>>

[image of music]

\new should always be used to specify unnamed contexts.

The difference between \new and \context is in the action taken:

A context must be named if it is to be referenced later, for example when lyrics are associated with music:

 
\new Voice = "tenor" music
…
\new Lyrics \lyricsto "tenor" lyrics

For details of associating lyrics with music see Automatic syllable durations.

The properties of all contexts of a particular type can be modified in a \layout block (with a different syntax), see Changing all contexts of the same type. This construct also provides a means of keeping layout instructions separate from the musical content. If a single context is to be modified, a \with block must be used, see Changing just one specific context.

See also

Learning Manual: (learning)Organizing pieces with variables section ‘Organizing pieces with variables’ in Learning Manual.

Notation Reference: Changing just one specific context, Automatic syllable durations.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

5.1.3 Keeping contexts alive

Contexts are usually terminated at the first musical moment in which they have nothing to do. So Voice contexts die as soon as they contain no events, Staff contexts die as soon as all the Voice contexts within them contain no events, etc. This can cause difficulties if earlier contexts which have died have to be referenced, for example, when changing staves with \change commands, associating lyrics with a voice with \lyricsto commands, or when adding further musical events to an earlier context.

There is an exception to this general rule: inside of an {…} construct (sequential music), the construct’s notion of the “current context” will descend whenever an element of the sequence ends in a subcontext of the previous current context. This avoids spurious creation of implicit contexts in a number of situations but means that the first context descended into will be kept alive until the end of the expression.

In contrast, the contexts of a <<…>> construct’s (simultaneous music) expression are not carried forth, so enclosing a context creating command in an extra pair of <<…>> will keep the context from persisting through all of the enclosing {…} sequence.

Any context can be kept alive by ensuring it has something to do at every musical moment. Staff contexts are kept alive by ensuring one of their voices is kept alive. One way of doing this is to add spacer rests to a voice in parallel with the real music. These need to be added to every Voice context which needs to be kept alive. If several voices are to be used sporadically it is safest to keep them all alive rather than attempting to rely on the exceptions mentioned above.

In the following example, both voice A and voice B are kept alive in this way for the duration of the piece:

 
musicA = \relative { d''4 d d d }
musicB = \relative { g'4 g g g }
keepVoicesAlive = {
  <<
    \new Voice = "A" { s1*5 }  % Keep Voice "A" alive for 5 bars
    \new Voice = "B" { s1*5 }  % Keep Voice "B" alive for 5 bars
  >>
}

music = {
  \context Voice = "A" {
    \voiceOneStyle
    \musicA
  }
  \context Voice = "B" {
    \voiceTwoStyle
    \musicB
  }
  \context Voice = "A" { \musicA }
  \context Voice = "B" { \musicB }
  \context Voice = "A" { \musicA }
}

\score {
  \new Staff <<
    \keepVoicesAlive
    \music
  >>
}

[image of music]

The following example shows how a sporadic melody line with lyrics might be written using this approach. In a real situation the melody and accompaniment would consist of several different sections, of course.

 
melody = \relative { a'4 a a a }
accompaniment = \relative { d'4 d d d }
words = \lyricmode { These words fol -- low the mel -- o -- dy }
\score {
  <<
    \new Staff = "music" {
      <<
        \new Voice = "melody" {
          \voiceOne
          s1*4  % Keep Voice "melody" alive for 4 bars
        }
        {
          \new Voice = "accompaniment" {
            \voiceTwo
            \accompaniment
          }
          <<
            \context Voice = "melody" { \melody }
            \context Voice = "accompaniment" { \accompaniment }
          >>
          \context Voice = "accompaniment" { \accompaniment }
          <<
            \context Voice = "melody" { \melody }
            \context Voice = "accompaniment" { \accompaniment }
          >>
        }
      >>
    }
    \new Lyrics \with { alignAboveContext = "music" }
    \lyricsto "melody" { \words }
  >>
}

[image of music]

An alternative way, which may be better in many circumstances, is to keep the melody line alive by simply including spacer notes to line it up correctly with the accompaniment:

 
melody = \relative {
  s1  % skip a bar
  a'4 a a a
  s1  % skip a bar
  a4 a a a
}
accompaniment = \relative {
  d'4 d d d
  d4 d d d
  d4 d d d
  d4 d d d
}
words = \lyricmode { These words fol -- low the mel -- o -- dy }

\score {
  <<
    \new Staff = "music" {
      <<
        \new Voice = "melody" {
          \voiceOne
          \melody
        }
        \new Voice = "accompaniment" {
          \voiceTwo
          \accompaniment
        }
      >>
    }
    \new Lyrics \with { alignAboveContext = "music" }
    \lyricsto "melody" { \words }
  >>
}

[image of music]


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

5.1.4 Modifying context plug-ins

Notation contexts (like Score and Staff) not only store properties, they also contain plug-ins called ‘engravers’ that create notation elements. For example, the Voice context contains a Note_heads_engraver and the Staff context contains a Key_engraver.

For a full a description of each plug-in, see (internals)Engravers and Performers section ‘Engravers and Performers’ in Internals Reference. Every context described in (internals)Contexts section ‘Contexts’ in Internals Reference lists the engravers used for that context.

It can be useful to shuffle around these plug-ins. This is done by starting a new context with \new or \context, and modifying it,

 
\new context \with {
  \consists …
  \consists …
  \remove …
  \remove …
  etc.
}
{
  …music…
}

where each … should be the name of an engraver. Here is a simple example which removes Time_signature_engraver and Clef_engraver from a Staff context,

 
<<
  \new Staff \relative {
    f'2 g
  }
  \new Staff \with {
     \remove "Time_signature_engraver"
     \remove "Clef_engraver"
  } \relative {
    f'2 g2
  }
>>

[image of music]

In the second staff there are no time signature or clef symbols. This is a rather crude method of making objects disappear since it will affect the entire staff. This method also influences the spacing, which may or may not be desirable. More sophisticated methods of blanking objects are shown in (learning)Visibility and color of objects section ‘Visibility and color of objects’ in Learning Manual.

The next example shows a practical application. Bar lines and time signatures are normally synchronized across the score. This is done by the Timing_translator and Default_bar_line_engraver. This plug-in keeps an administration of time signature, location within the measure, etc. By moving these engraver from Score to Staff context, we can have a score where each staff has its own time signature.

 
\score {
  <<
    \new Staff \with {
      \consists "Timing_translator"
      \consists "Default_bar_line_engraver"
    }
    \relative {
        \time 3/4
        c''4 c c c c c
    }
  \new Staff \with {
    \consists "Timing_translator"
    \consists "Default_bar_line_engraver"
  }
  \relative {
      \time 2/4
      c''4 c c c c c
  }
>>
\layout {
  \context {
    \Score
    \remove "Timing_translator"
    \remove "Default_bar_line_engraver"
    }
  }
}

[image of music]

Known issues and warnings

The order in which the engravers are specified is the order in which they are called to carry out their processing. Usually the order in which the engravers are specified does not matter, but in a few special cases the order is important, for example where one engraver writes a property and another reads it, or where one engraver creates a grob and another must process it.

The following orderings are important:

See also

Installed Files: ‘ly/engraver-init.ly’.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

5.1.5 Changing context default settings

Context and grob properties can be changed with \set and \override commands, as described in Modifying properties. These commands create music events, making the changes take effect at the point in time the music is being processed.

In contrast, this section explains how to change the default values of context and grob properties at the time the context is created. There are two ways of doing this. One modifies the default values in all contexts of a particular type, the other modifies the default values in just one particular instance of a context.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

Changing all contexts of the same type

The default context settings which are to be used for typesetting in Score, Staff, Voice and other contexts may be specified in a \context block within any \layout block.

Settings for Midi output as opposed to typesetting will have to be separately specified in \midi blocks (see Output definitions - blueprints for contexts).

The \layout block should be placed within the \score block to which it is to apply, after the music.

 
\layout {
  \context {
    \Voice
    [context settings for all Voice contexts]
  }
  \context {
    \Staff
    [context settings for all Staff contexts]
  }
}

The following types of settings may be specified:

Property-setting commands can be placed in a \layout block without being enclosed in a \context block. Such settings are equivalent to including the same property-setting commands at the start of every context of the type specified. If no context is specified every bottom-level context is affected, see Bottom-level contexts - voices. The syntax of a property-setting command in a \layout block is the same as the same command written in the music stream.

 
\score {
  \new Staff {
    \relative {
      a'4^"Smaller font" a a a
      a4 a a a
    }
  }
  \layout {
    \accidentalStyle dodecaphonic
    \set fontSize = #-4
    \override Voice.Stem.thickness = #4.0
  }
}

[image of music]


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

Changing just one specific context

The context properties of just one specific context instance can be changed in a \with block. All other context instances of the same type retain the default settings built into LilyPond and modified by any \layout block within scope. The \with block must be placed immediately after the \new context-type command:

 
\new Staff \with { [context settings for this context instance only] }
{
  …
}

Alternatively, if the music is being entered using the short form of the input mode-specifying commands, e.g. \chords rather than \chordmode, the \with command must be placed immediately after the mode-specifying command:

 
\chords \with { [context settings for this (implicit) context instance only] }
{
  …
}

as it is the implicit context created by these short forms which should be modified. The same consideration applies to the other input mode-specifying short forms (\drums, \figures), see Input modes.

Since context modifications specified in \with blocks are inside music, they will affect all outputs (typesetting and Midi) as opposed to changes within an output definition.

The following types of settings may be specified:

See also

Notation Reference: Input modes


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

Order of precedence

The value of a property which applies at a particular time is determined as follows:

See also

Learning Manual: (learning)Modifying context properties section ‘Modifying context properties’ in Learning Manual.

Notation Reference: Contexts explained, Bottom-level contexts - voices, The \set command, The \override command, The \layout block.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

5.1.6 Defining new contexts

Specific contexts, like Staff and Voice, are made from simple building blocks. It is possible to create new types of contexts with different combinations of engraver plug-ins.

The next example shows how to build a different type of Voice context from scratch. It will be similar to Voice, but only prints centered slash note heads. It can be used to indicate improvisation in jazz pieces,

[image of music]

These settings are defined within a \context block inside a \layout block,

 
\layout {
  \context {
    …
  }
}

In the following discussion, the example input shown should go in place of the … in the previous fragment.

First it is necessary to define a name for the new context:

 
\name ImproVoice

Since it is similar to the Voice context, we want commands that work in (existing) Voice contexts to continue working. This is achieved by giving the new context an alias of Voice,

 
\alias Voice

The context will print notes and instructive texts, so we need to add the engravers which provide this functionality, plus the engraver which groups notes, stems and rests which occur at the same musical moment into columns,

 
\consists "Note_heads_engraver"
\consists "Text_engraver"
\consists "Rhythmic_column_engraver"

The note heads should all be placed on the center line,

 
\consists "Pitch_squash_engraver"
squashedPosition = #0

The Pitch_squash_engraver modifies note heads (created by the Note_heads_engraver) and sets their vertical position to the value of squashedPosition, in this case 0, the center line.

The notes look like a slash, and have no stem,

 
\override NoteHead.style = #'slash
\hide Stem

All these plug-ins have to communicate under the control of the context. The mechanisms with which contexts communicate are established by declaring the context \type. Within a \layout block, most contexts will be of type Engraver_group. Some special contexts and contexts in \midi blocks use other context types. Copying and modifying an existing context definition will also fill in the type. Since this example creates a definition from scratch, it needs to be specified explicitly.

 
\type "Engraver_group"

Put together, we get

 
\context {
  \name ImproVoice
  \type "Engraver_group"
  \consists "Note_heads_engraver"
  \consists "Text_engraver"
  \consists "Rhythmic_column_engraver"
  \consists "Pitch_squash_engraver"
  squashedPosition = #0
  \override NoteHead.style = #'slash
  \hide Stem
  \alias Voice
}

Contexts form hierarchies. We want to place the ImproVoice context within the Staff context, just like normal Voice contexts. Therefore, we modify the Staff definition with the \accepts command,

 
\context {
  \Staff
  \accepts ImproVoice
}

Often when reusing an existing context definition, the resulting context can be used anywhere where the original context would have been useful.

 
\layout {
  …
  \inherit-acceptability to from
}

will arrange to have contexts of type to accepted by all contexts also accepting from. For example, using

 
\layout {
  …
  \inherit-acceptability "ImproVoice" "Voice"
}

will add an \accepts for ImproVoice to both Staff and RhythmicStaff definitions.

The opposite of \accepts is \denies, which is sometimes needed when reusing existing context definitions.

Arranging the required pieces into a \layout block leaves us with

 
\layout {
  \context {
    \name ImproVoice
    …
  }
  \inherit-acceptability "ImproVoice" "Voice"
}

Then the output at the start of this subsection can be entered as

 
\relative {
  a'4 d8 bes8
  \new ImproVoice {
    c4^"ad lib" c
    c4 c^"undress"
    c c_"while playing :)"
  }
  a1
}

To complete this example, changes affecting the context hierarchy should be repeated in a \midi block so that Midi output depends on the same context relations.

See also

Internals Reference: (internals)Note_heads_engraver section ‘Note_heads_engraver’ in Internals Reference, (internals)Text_engraver section ‘Text_engraver’ in Internals Reference, (internals)Rhythmic_column_engraver section ‘Rhythmic_column_engraver’ in Internals Reference, (internals)Pitch_squash_engraver section ‘Pitch_squash_engraver’ in Internals Reference.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

5.1.7 Context layout order

Contexts are normally positioned in a system from top to bottom in the order in which they are encountered in the input file. When contexts are nested, the outer context will include inner nested contexts as specified in the input file, provided the inner contexts are included in the outer context’s “accepts” list. Nested contexts which are not included in the outer context’s “accepts” list will be repositioned below the outer context rather than nested within it.

The “accepts” list of a context can be changed with the \accepts or \denies commands. \accepts adds a context to the “accepts” list and \denies removes a context from the list.

For example, a square-braced staff group is not usually found within a curved-braced staff with connecting staff bars, and a GrandStaff does not accept a StaffGroup inside it by default.

 
\score {
  \new GrandStaff <<
    \new StaffGroup <<
      \new Staff { c'1 }
      \new Staff { d'1 }
    >>
    \new Staff { \set Staff.instrumentName = bottom f'1 }
  >>
}

[image of music]

However, by using the \accepts command, StaffGroup can be added to the GrandStaff context:

 
\score {
  \new GrandStaff <<
    \new StaffGroup <<
      \new Staff { c'1 }
      \new Staff { d'1 }
    >>
    \new Staff { \set Staff.instrumentName = bottom f'1 }
  >>
  \layout {
    \context {
      \GrandStaff
      \accepts "StaffGroup"
    }
  }
}

[image of music]

\denies is mainly used when a new context is being based on another, but the required nesting differs. For example, the VaticanaStaff context is based on the Staff context, but with the VaticanaVoice context substituted for the Voice context in the “accepts” list.

Note that a context will be silently created implicitly if a command is encountered when there is no suitable context available to contain it.

Within a context definition, the type of subcontext to be implicitly created is specified using \defaultchild. A number of music events require a ‘Bottom’ context: when such an event is encountered, subcontexts are created recursively until reaching a context with no ‘defaultchild’ setting.

Implicit context creation can at times give rise to unexpected new staves or scores. Using \new to create contexts explicitly avoids those problems.

Sometimes a context is required to exist for just a brief period, a good example being the staff context for an ossia. This is usually achieved by introducing the context definition at the appropriate place in parallel with corresponding section of the main music. By default, the temporary context will be placed below all the existing contexts. To reposition it above the context called “main”, it should be defined like this:

 
\new Staff \with { alignAboveContext = "main" }

A similar situation arises when positioning a temporary lyrics context within a multi-staff layout such as a ChoirStaff, for example, when adding a second verse to a repeated section. By default the temporary lyrics context will be placed beneath the lower staves. By defining the temporary lyrics context with alignBelowContext it can be positioned correctly beneath the (named) lyrics context containing the first verse.

Examples showing this repositioning of temporary contexts can be found elsewhere — see (learning)Nesting music expressions section ‘Nesting music expressions’ in Learning Manual, Modifying single staves and Techniques specific to lyrics.

See also

Learning Manual: (learning)Nesting music expressions section ‘Nesting music expressions’ in Learning Manual.

Notation Reference: Modifying single staves, Techniques specific to lyrics.

Application Usage: (usage)An extra staff appears section ‘An extra staff appears’ in Application Usage.

Installed Files: ‘ly/engraver-init.ly’.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]

This document was generated by gub on July 13, 2020 using texi2html 1.82.

Más nyelvek: català, deutsch, español, français, italiano, 日本語.
Az automatikus nyelvválasztásról.