Frammenti LilyPond: Contexts and engravers

# Contexts and engravers

Changing defaults

Contexts and engravers

## Adding a figured bass above or below the notes

When writing a figured bass, you can place the figures above or below the bass notes, by defining the `BassFigureAlignmentPositioning.direction` property (exclusively in a `Staff` context). Choices are `#UP` (or `#1`), `#CENTER` (or `#0`) and `#DOWN` (or `#-1`).

This property can be changed as many times as you wish. Use `\once \override` if you don’t want the override to apply to the whole score.

    bass = {
      \clef bass
      g4 b, c d
      e d8 c d2
    }

    continuo = \figuremode {
      <_>4 <6>4 <5/>4
      \override Staff.BassFigureAlignmentPositioning.direction = #UP
      %\bassFigureStaffAlignmentUp
      < _+ >4 <6>
      \set Staff.useBassFigureExtenders = ##t
      \override Staff.BassFigureAlignmentPositioning.direction = #DOWN
      %\bassFigureStaffAlignmentDown
      <4>4. <4>8 <_+>4
    }

    \score {
      <<
        \new Staff = bassStaff \bass
        \context Staff = bassStaff \continuo
      >>
    }

## Adding an extra staff

An extra staff can be added (possibly temporarily) after the start of a piece.

    \score {
      <<
        \new Staff \relative c'' {
          c1 | c | c | c | c
        }
        \new StaffGroup \relative c'' {
          \new Staff {
            c1 | c
            <<
              {
                c1 | d
              }
              \new Staff {
                \once \omit Staff.TimeSignature
                c1 | b
              }
            >>
            c1
          }
        }
      >>
    }

## Adding an extra staff at a line break

When adding a new staff at a line break, some extra space is unfortunately added at the end of the line before the break (to fit in a key signature change, which will never be printed anyway). The workaround is to add a setting of `Staff.explicitKeySignatureVisibility` as is shown in the example.

    \score {
      \new StaffGroup \relative c'' {
        \new Staff
        \key f \major
        c1 c^"Unwanted extra space" \break
        << { c1 | c }
           \new Staff {
             \key f \major
             \once \omit Staff.TimeSignature
             c1 | c
           }
        >>
        c1 | c^"Fixed here" \break
        << { c1 | c }
           \new Staff {
             \once \set Staff.explicitKeySignatureVisibility = #end-of-line-invisible
             \key f \major
             \once \omit Staff.TimeSignature
             c1 | c
           }
        >>
      }
    }

## Cambiare automaticamente la direzione del gambo della nota centrale in base alla melodia

LilyPond può modificare la direzione del gambo della nota centrale di un rigo in modo che segua la melodia: occorre aggiungere l’incisore `Melody_engraver` al contesto `Voice`.

La proprietà di contesto `suspendMelodyDecisions` può essere usata per disattivare questo comportamento localmente.

    \relative c'' {
      \time 3/4
      a8 b g f b g |
      \set suspendMelodyDecisions = ##t
      a  b g f b g |
      \unset suspendMelodyDecisions
      c  b d c b c |
    }

    \layout {
      \context {
        \Voice
        \consists "Melody_engraver"
        \autoBeamOff
      }
    }

## Centered measure numbers

Scores of large ensemble works often have bar numbers placed beneath the system, centered horizontally on the measure’s extent. This snippet shows how the `Measure_counter_engraver` may be used to simulate this notational practice. Here, the engraver has been added to a `Dynamics` context.

This snippet presents a legacy method: starting from LilyPond 2.23.3, `\set Score.centerBarNumbers = ##t` is enough.

    \layout {
      \context {
        \Dynamics
        \consists #Measure_counter_engraver
        \override MeasureCounter.direction = #DOWN
        \override MeasureCounter.font-encoding = #'latin1
        \override MeasureCounter.font-shape = #'italic
        % to control the distance of the Dynamics context from the staff:
        \override VerticalAxisGroup.nonstaff-relatedstaff-spacing.padding = #2
      }
      \context {
        \Score
        \remove "Bar_number_engraver"
      }
    }

    pattern = \repeat unfold 7 { c'4 d' e' f' }

    \new StaffGroup <<
      \new Staff {
        \pattern
      }
      \new Staff {
        \pattern
      }
      \new Dynamics {
        \startMeasureCount
        s1*7
        \stopMeasureCount
      }
    >>

## Impostare l’output MIDI su un canale per voce

Nella creazione del file di output MIDI, il comportamento predefinito prevede che ogni rigo sia assegnato a un canale MIDI, con tutte le voci del rigo amalgamate in un canale. Ciò diminuisce il rischio di esaurire i canali MIDI disponibili, dato che ce ne sono solo 16 per traccia.

Tuttavia, spostando `Staff_performer` nel contesto `Voice`, ogni voce in un rigo può avere il proprio canale MIDI, come è illustrato nell’esempio seguente: sebbene le voci siano sullo stesso rigo, vengono creati due canali MIDI, ciascuno con un diverso strumento MIDI (`midiInstrument`).

    \score {
      \new Staff <<
        \new Voice \relative c''' {
          \set midiInstrument = #"flute"
          \voiceOne
          \key g \major
          \time 2/2
          r2 g-"Flute" ~
          g fis ~
          fis4 g8 fis e2 ~
          e4 d8 cis d2
        }
        \new Voice \relative c'' {
          \set midiInstrument = #"clarinet"
          \voiceTwo
          b1-"Clarinet"
          a2. b8 a
          g2. fis8 e
          fis2 r
        }
      >>
      \layout { }
      \midi {
        \context {
          \Staff
          \remove "Staff_performer"
        }
        \context {
          \Voice
          \consists "Staff_performer"
        }
        \tempo 2 = 72
      }
    }

## Changing time signatures inside a polymetric section using \scaleDurations

The `measureLength` property, together with `measurePosition`, determines when a bar line is needed. However, when using `\scaleDurations`, the scaling of durations makes it difficult to change time signatures. In this case, `measureLength` should be set manually, using the `ly:make-moment` callback. The second argument must be the same as the second argument of `\scaleDurations`.

    \layout {
      \context {
        \Score
        \remove "Timing_translator"
      }
      \context {
        \Staff
        \consists "Timing_translator"
      }
    }

    <<
      \new Staff {
        \scaleDurations 8/5 {
          \time 6/8
          \set Timing.measureLength = #(ly:make-moment 6/5)
          b8 b b b b b
          \time 2/4
          \set Timing.measureLength = #(ly:make-moment 4/5)
          b4 b
        }
      }
      \new Staff {
        \clef bass
        \time 2/4
        c2 d e f
      }
    >>

## Notazione per canti e salmi

Questa forma di notazione è utilizzata per i salmi, dove i versi non sono sempre della stessa lunghezza.

    stemOff = \hide Staff.Stem
    stemOn  = \undo \stemOff

    \score {
      \new Staff \with { \remove "Time_signature_engraver" }
      {
        \key g \minor
        \cadenzaOn
        \stemOff a'\breve bes'4 g'4
        \stemOn a'2 \section
        \stemOff a'\breve g'4 a'4
        \stemOn f'2 \section
        \stemOff a'\breve^\markup { \italic flexe }
        \stemOn g'2 \fine
      }
    }

## Creating blank staves

To create blank staves, generate empty measures then remove the `Bar_number_engraver` from the `Score` context, and the `Time_signature_engraver`, `Clef_engraver` and `Bar_engraver` from the `Staff` context.

    #(set-global-staff-size 20)

    \score {
      {
        \repeat unfold 12 { s1 \break }
      }
      \layout {
        indent = 0\in
        \context {
          \Staff
          \remove "Time_signature_engraver"
          \remove "Clef_engraver"
          \remove "Bar_engraver"
        }
        \context {
          \Score
          \remove "Bar_number_engraver"
        }
      }
    }

    % uncomment these lines for "letter" size
    %{
    \paper {
      #(set-paper-size "letter")
      ragged-last-bottom = ##f
      line-width = 7.5\in
      left-margin = 0.5\in
      bottom-margin = 0.25\in
      top-margin = 0.25\in
    }
    %}

    % uncomment these lines for "A4" size
    %{
    \paper {
      #(set-paper-size "a4")
      ragged-last-bottom = ##f
      line-width = 180
      left-margin = 15
      bottom-margin = 10
      top-margin = 10
    }
    %}

## Creating custom key signatures

LilyPond supports custom key signatures. In this example, print for D minor with an extended range of printed flats.

    \new Staff \with {
      \override StaffSymbol.line-count = #8
      \override KeySignature.flat-positions = #'((-7 . 6))
      \override KeyCancellation.flat-positions = #'((-7 . 6))
      % presumably sharps are also printed in both octaves
      \override KeySignature.sharp-positions = #'((-6 . 7))
      \override KeyCancellation.sharp-positions = #'((-6 . 7))

      \override Clef.stencil = #
      (lambda (grob)(grob-interpret-markup grob
      #{ \markup\combine
        \musicglyph "clefs.C"
        \translate #'(-3 . -2)
        \musicglyph "clefs.F"
       #}))
        clefPosition = #3
        middleCPosition = #3
        middleCClefPosition = #3
    }

    {
      \key d\minor
      f bes, f bes,
    }

## Cross staff stems

This snippet shows the use of the `Span_stem_engraver` and `\crossStaff` to connect stems across staves automatically.

The stem length need not be specified, as the variable distance between noteheads and staves is calculated automatically.

    \layout {
      \context {
        \PianoStaff
        \consists "Span_stem_engraver"
      }
    }

    {
      \new PianoStaff <<
        \new Staff {
          <b d'>4 r d'16\> e'8. g8 r\!
          e'8 f' g'4 e'2
        }
        \new Staff {
          \clef bass
          \voiceOne
          \autoBeamOff
          \crossStaff { <e g>4 e, g16 a8. c8} d
          \autoBeamOn
          g8 f g4 c2
        }
      >>
    }

## Defining an engraver in Scheme: ambitus engraver

This example demonstrates how the ambitus engraver may be defined on the user side, with a Scheme engraver. This is basically a rewrite in Scheme of the code from `lily/ambitus-engraver.cc`.

    #(use-modules (oop goops))

    %%%
    %%% Grob utilities
    %%%
    %%% These are literal rewrites of some C++ methods used by the ambitus engraver.

    #(define (ly:separation-item::add-conditional-item grob grob-item)
       "Add @var{grob-item} to the array of conditional elements of @var{grob}.
    Rewrite of @code{Separation_item::add_conditional_item} from @file{lily/separation-item.cc}."
       (ly:pointer-group-interface::add-grob grob 'conditional-elements grob-item))

    #(define (ly:accidental-placement::accidental-pitch accidental-grob)
       "Get the pitch from the grob cause of @var{accidental-grob}.
    Rewrite of @code{accidental_pitch} from @file{lily/accidental-placement.cc}."
       (ly:event-property (ly:grob-property (ly:grob-parent accidental-grob Y) 'cause)
                          'pitch))

    #(define (ly:accidental-placement::add-accidental grob accidental-grob)
       "Add @var{accidental-grob}, an @code{Accidental} grob, to the
    list of the accidental grobs of @var{grob}, an @code{AccidentalPlacement}
    grob.
    Rewrite of @code{Accidental_placement::add_accidental} from @file{lily/accidental-placement.cc}."
       (let ((pitch (ly:accidental-placement::accidental-pitch accidental-grob)))
         (set! (ly:grob-parent accidental-grob X) grob)
         (let* ((accidentals (ly:grob-object grob 'accidental-grobs))
                (handle (assq (ly:pitch-notename pitch) accidentals))
                (entry (if handle (cdr handle) '())))
           (set! (ly:grob-object grob 'accidental-grobs)
                 (assq-set! accidentals
                            (ly:pitch-notename pitch)
                            (cons accidental-grob entry))))))

    %%%
    %%% Ambitus data structure
    %%%

    %%% The <ambitus> class holds the various grobs that are created
    %%% to print an ambitus:
    %%% - ambitus-group: the grob that groups all the components of an ambitus
    %%% (Ambitus grob);
    %%% - ambitus-line: the vertical line between the upper and lower ambitus
    %%% notes (AmbitusLine grob);
    %%% - ambitus-up-note and ambitus-down-note: the note head and accidental
    %%% for the lower and upper note of the ambitus (see <ambitus-note> class
    %%% below).
    %%% The other slots define the key and clef context of the engraver:
    %%% - start-c0: position of middle c at the beginning of the piece.  It
    %%% is used to place the ambitus notes according to their pitch;
    %%% - start-key-sig: the key signature at the beginning of the piece.  It
    %%% is used to determine if accidentals shall be printed next to ambitus
    %%% notes.

    #(define-class <ambitus> ()
       (ambitus-group #:accessor ambitus-group)
       (ambitus-line #:accessor ambitus-line)
       (ambitus-up-note #:getter ambitus-up-note
                        #:init-form (make <ambitus-note>))
       (ambitus-down-note #:getter ambitus-down-note
                          #:init-form (make <ambitus-note>))
       (start-c0 #:accessor ambitus-start-c0
                 #:init-value #f)
       (start-key-sig #:accessor ambitus-start-key-sig
                      #:init-value '()))

    %%% Accessor for the lower and upper note data of an ambitus
    #(define-method (ambitus-note (ambitus <ambitus>) direction)
       "If @var{direction} is @code{UP}, then return the upper ambitus note
    of @var{ambitus}, otherwise return the lower ambitus note."
       (if (= direction UP)
           (ambitus-up-note ambitus)
           (ambitus-down-note ambitus)))

    %%% The <ambitus-note> class holds the grobs that are specific to ambitus
    %%% (lower and upper) notes:
    %%% - head: an AmbitusNoteHead grob;
    %%% - accidental: an AmbitusAccidental grob, to be possibly printed next
    %%% to the ambitus note head.
    %%% Moreover:
    %%% - pitch is the absolute pitch of the note
    %%% - cause is the note event that causes this ambitus note, i.e. the lower
    %%% or upper note of the considered music sequence.

    #(define-class <ambitus-note> ()
       (head #:accessor ambitus-note-head
             #:init-value #f)
       (accidental #:accessor ambitus-note-accidental
                   #:init-value #f)
       (cause #:accessor ambitus-note-cause
              #:init-value #f)
       (pitch #:accessor ambitus-note-pitch
              #:init-value #f))

    %%%
    %%% Ambitus engraving logics
    %%%
    %%% Rewrite of the code from @file{lily/ambitus-engraver.cc}.

    #(define (make-ambitus translator)
       "Build an ambitus object: initialize all the grobs and their relations.

    The Ambitus grob contain all other grobs:
     Ambitus
      |- AmbitusLine
      |- AmbitusNoteHead   for upper note
      |- AmbitusAccidental for upper note
      |- AmbitusNoteHead   for lower note
      |- AmbitusAccidental for lower note

    The parent of an accidental is the corresponding note head,
    and the accidental is set as the 'accidental-grob of the note head
    so that is printed by the function that prints notes."
       ;; make the ambitus object
       (let ((ambitus (make <ambitus>)))
         ;; build the Ambitus grob, which will contain all other grobs
         (set! (ambitus-group ambitus) (ly:engraver-make-grob translator 'Ambitus '()))
         ;; build the AmbitusLine grob (line between lower and upper note)
         (set! (ambitus-line ambitus) (ly:engraver-make-grob translator 'AmbitusLine '()))
         ;; build the upper and lower AmbitusNoteHead and AmbitusAccidental
         (for-each (lambda (direction)
                     (let ((head (ly:engraver-make-grob translator 'AmbitusNoteHead '()))
                           (accidental (ly:engraver-make-grob translator 'AmbitusAccidental '()))
                           (group (ambitus-group ambitus)))
                       ;; The parent of the AmbitusAccidental grob is the
                       ;; AmbitusNoteHead grob
                       (set! (ly:grob-parent accidental Y) head)
                       ;; The AmbitusAccidental grob is set as the accidental-grob
                       ;; object of the AmbitusNoteHead.  This is later used by the
                       ;; function that prints notes.
                       (set! (ly:grob-object head 'accidental-grob) accidental)
                       ;; both the note head and the accidental grobs are added
                       ;; to the main ambitus grob.
                       (ly:axis-group-interface::add-element group head)
                       (ly:axis-group-interface::add-element group accidental)
                       ;; the note head and the accidental grobs are added to the
                       ;; ambitus object
                       (set! (ambitus-note-head (ambitus-note ambitus direction))
                             head)
                       (set! (ambitus-note-accidental (ambitus-note ambitus direction))
                             accidental)))
                   (list DOWN UP))
         ;; The parent of the ambitus line is the lower ambitus note head
         (set! (ly:grob-parent (ambitus-line ambitus) X)
               (ambitus-note-head (ambitus-note ambitus DOWN)))
         ;; the ambitus line is added to the ambitus main grob
         (ly:axis-group-interface::add-element (ambitus-group ambitus) (ambitus-line ambitus))
         ambitus))

    #(define-method (initialize-ambitus-state (ambitus <ambitus>) translator)
       "Initialize the state of @var{ambitus}, by getting the starting
    position of middle C and key signature from @var{translator}'s context."
       (if (not (ambitus-start-c0 ambitus))
           (begin
             (set! (ambitus-start-c0 ambitus)
                   (ly:context-property (ly:translator-context translator)
                                        'middleCPosition
                                        0))
             (set! (ambitus-start-key-sig ambitus)
                   (ly:context-property (ly:translator-context translator)
                                        'keyAlterations)))))

    #(define-method (update-ambitus-notes (ambitus <ambitus>) note-grob)
       "Update the upper and lower ambitus pithes of @var{ambitus}, using
    @var{note-grob}."
       ;; Get the event that caused the note-grob creation
       ;; and check that it is a note-event.
       (let ((note-event (ly:grob-property note-grob 'cause)))
         (if (ly:in-event-class? note-event 'note-event)
             ;; get the pitch from the note event
             (let ((pitch (ly:event-property note-event 'pitch)))
               ;; if this pitch is lower than the current ambitus lower
               ;; note pitch (or it has not been initialized yet),
               ;; then this pitch is the new ambitus lower pitch,
               ;; and conversely for upper pitch.
               (for-each (lambda (direction pitch-compare)
                           (if (or (not (ambitus-note-pitch (ambitus-note ambitus direction)))
                                   (pitch-compare pitch
                                                  (ambitus-note-pitch (ambitus-note ambitus direction))))
                               (begin
                                 (set! (ambitus-note-pitch (ambitus-note ambitus direction))
                                       pitch)
                                 (set! (ambitus-note-cause (ambitus-note ambitus direction))
                                       note-event))))
                         (list DOWN UP)
                         (list ly:pitch<? (lambda (p1 p2)
                                            (ly:pitch<? p2 p1))))))))

    #(define-method (typeset-ambitus (ambitus <ambitus>) translator)
       "Typeset the ambitus:
    - place the lower and upper ambitus notes according to their pitch and
      the position of the middle C;
    - typeset or delete the note accidentals, according to the key signature.
      An accidental, if it is to be printed, is added to an AccidentalPlacement
      grob (a grob dedicated to the placement of accidentals near a chord);
    - both note heads are added to the ambitus line grob, so that a line should
      be printed between them."
       ;; check if there are lower and upper pitches
       (if (and (ambitus-note-pitch (ambitus-note ambitus UP))
                (ambitus-note-pitch (ambitus-note ambitus DOWN)))
           ;; make an AccidentalPlacement grob, for placement of note accidentals
           (let ((accidental-placement (ly:engraver-make-grob
                                        translator
                                        'AccidentalPlacement
                                        (ambitus-note-accidental (ambitus-note ambitus DOWN)))))
             ;; For lower and upper ambitus notes:
             (for-each (lambda (direction)
                         (let ((pitch (ambitus-note-pitch (ambitus-note ambitus direction))))
                           ;; set the cause and the staff position of the ambitus note
                           ;; according to the associated pitch
                           (set! (ly:grob-property (ambitus-note-head (ambitus-note ambitus direction))
                                                   'cause)
                                 (ambitus-note-cause (ambitus-note ambitus direction)))
                           (set! (ly:grob-property (ambitus-note-head (ambitus-note ambitus direction))
                                                   'staff-position)
                                 (+ (ambitus-start-c0 ambitus)
                                    (ly:pitch-steps pitch)))
                           ;; determine if an accidental shall be printed for this note,
                           ;; according to the key signature
                           (let* ((handle (or (assoc (cons (ly:pitch-octave pitch)
                                                           (ly:pitch-notename pitch))
                                                     (ambitus-start-key-sig ambitus))
                                              (assoc (ly:pitch-notename pitch)
                                                     (ambitus-start-key-sig ambitus))))
                                  (sig-alter (if handle (cdr handle) 0)))
                             (cond ((= (ly:pitch-alteration pitch) sig-alter)
                                    ;; the note alteration is in the key signature
                                    ;; => it does not have to be printed
                                    (ly:grob-suicide!
                                     (ambitus-note-accidental (ambitus-note ambitus direction)))
                                    (set! (ly:grob-object (ambitus-note-head (ambitus-note ambitus direction))
                                                          'accidental-grob)
                                          '()))
                                   (else
                                    ;; otherwise, the accidental shall be printed
                                    (set! (ly:grob-property (ambitus-note-accidental
                                                             (ambitus-note ambitus direction))
                                                            'alteration)
                                          (ly:pitch-alteration pitch)))))
                           ;; add the AccidentalPlacement grob to the
                           ;; conditional items of the AmbitusNoteHead
                           (ly:separation-item::add-conditional-item
                            (ambitus-note-head (ambitus-note ambitus direction))
                            accidental-placement)
                           ;; add the AmbitusAccidental to the list of the
                           ;; AccidentalPlacement grob accidentals
                           (ly:accidental-placement::add-accidental
                            accidental-placement
                            (ambitus-note-accidental (ambitus-note ambitus direction)))
                           ;; add the AmbitusNoteHead grob to the AmbitusLine grob
                           (ly:pointer-group-interface::add-grob
                            (ambitus-line ambitus)
                            'note-heads
                            (ambitus-note-head (ambitus-note ambitus direction)))))
                       (list DOWN UP))
             ;; add the AccidentalPlacement grob to the main Ambitus grob
             (ly:axis-group-interface::add-element (ambitus-group ambitus) accidental-placement))
           ;; no notes ==> suicide the grobs
           (begin
             (for-each (lambda (direction)
                         (ly:grob-suicide! (ambitus-note-accidental (ambitus-note ambitus direction)))
                         (ly:grob-suicide! (ambitus-note-head (ambitus-note ambitus direction))))
                       (list DOWN UP))
             (ly:grob-suicide! ambitus-line))))

    %%%
    %%% Ambitus engraver definition
    %%%
    #(define ambitus-engraver
       (lambda (context)
         (let ((ambitus #f))
           ;; when music is processed: make the ambitus object, if not already built
           (make-engraver
        ((process-music translator)
         (if (not ambitus)
             (set! ambitus (make-ambitus translator))))
        ;; set the ambitus clef and key signature state
        ((stop-translation-timestep translator)
         (if ambitus
             (initialize-ambitus-state ambitus translator)))
        ;; when a note-head grob is built, update the ambitus notes
        (acknowledgers
              ((note-head-interface engraver grob source-engraver)
           (if ambitus
               (update-ambitus-notes ambitus grob))))
        ;; finally, typeset the ambitus according to its upper and lower notes
        ;; (if any).
        ((finalize translator)
         (if ambitus
             (typeset-ambitus ambitus translator)))))))

    %%%
    %%% Example
    %%%

    \score {
      \new StaffGroup <<
        \new Staff { c'4 des' e' fis' gis' }
        \new Staff { \clef "bass" c4 des ~ des ees b, }
      >>
      \layout { \context { \Staff \consists #ambitus-engraver } }
    }

## Displaying a whole GrandStaff system if only one of its staves is alive

In orchestral scores sometimes single or groups of instruments are silent for a while and their staves can be removed for that time (with `\removeEmptyStaves`).

When they play again it is often preferred to show the staves of all instruments of such a group. This can be done adding the `Keep_alive_together_engraver` in the grouper (e.g., a GrandStaff or a StaffGroup).

In the example the violins are silent in the 2nd system and in the 3rd system. Only the first violin plays the last measure but the staff of the second violin is also displayed.

    \score {
      <<
        \new StaffGroup = "StaffGroup_woodwinds"
        <<
          \new Staff = "Staff_flute" \with {
            instrumentName = "Flute"
            shortInstrumentName = "Fl"
          }
          \relative c' {
            \repeat unfold 3 { c'4 c c c | c c c c | c c c c | \break }
          }
        >>
        \new StaffGroup = "StaffGroup_Strings"
        <<
          \new GrandStaff = "GrandStaff_violins"
          <<
            \new Staff = "StaffViolinI" \with {
              instrumentName = "Violin I"
              shortInstrumentName = "Vi I"
            }
            \relative c'' {
              a1 \repeat unfold 7 { s1 } \repeat unfold 12 a16  a4
            }
            \new Staff = "StaffViolinII" \with {
              instrumentName = "Violin II"
              shortInstrumentName = "Vi II"
            }
            \relative c' { e1 \repeat unfold 8 { s1 } }
          >>
          \new Staff = "Staff_cello" \with {
            instrumentName = "Cello"
            shortInstrumentName = "Ce"
          }
          \relative c { \clef bass \repeat unfold 9 { c1 }}
        >>
      >>
    }
    \layout {
      indent = 3.0\cm
      short-indent = 1.5\cm
      \context {
        \GrandStaff
        \consists Keep_alive_together_engraver
      }
      \context {
        \Staff
        \RemoveEmptyStaves
      }
    }

## Engravers one-by-one

The notation problem, creating a certain symbol, is handled by plugins. Each plugin is called an Engraver. In this example, engravers are switched on one by one, in the following order:

- note heads,

- staff symbol,

- clef,

- stem,

- beams, slurs, accents,

- accidentals, bar lines, time signature and key signature.

Engravers are grouped. For example, note heads, slurs, beams etc. form a `Voice` context. Engravers for key signature, accidentals, bar line, etc. form a `Staff` context.

    %% sample music
    topVoice = \relative c' {
      \key d \major
      es8([ g] a[ fis])
      b4
      b16[-. b-. b-. cis-.]
      d4->
    }

    botVoice = \relative c' {
      \key d \major
      c8[( f] b[ a)]
      es4
      es16[-. es-. es-. fis-.]
      b4->
    }

    hoom = \relative c {
      \key d \major
      \clef bass
      g8-. r
      r4
      fis8-.
      r8
      r4
      b'4->
    }

    pah = \relative c' {
      r8 b-.
      r4
      r8 g8-.
      r16 g-. r8
      \clef treble
      fis'4->
    }

    %
    % setup for Request->Element conversion. Guru-only
    %

    MyStaff = \context {
      \type "Engraver_group"
      \name Staff

      \description "Handles clefs, bar lines, keys, accidentals.  It can contain
    @code{Voice} contexts."

      \consists "Output_property_engraver"

      \consists "Font_size_engraver"

      \consists "Volta_engraver"
      \consists "Separating_line_group_engraver"
      \consists "Dot_column_engraver"

      \consists "Ottava_spanner_engraver"
      \consists "Rest_collision_engraver"
      \consists "Piano_pedal_engraver"
      \consists "Piano_pedal_align_engraver"
      \consists "Instrument_name_engraver"
      \consists "Grob_pq_engraver"
      \consists "Forbid_line_break_engraver"
      \consists "Axis_group_engraver"

      \consists "Pitch_squash_engraver"

      localAlterations = #'()

      % explicitly set instrumentName, so we don't get
      % weird effects when doing instrument names for
      % piano staves

      instrumentName = #'()
      shortInstrumentName = #'()

      \accepts "Voice"
      \defaultchild "Voice"
    }

    MyVoice = \context {
      \type "Engraver_group"
      \name Voice

      \description "
        Corresponds to a voice on a staff.  This context handles the
        conversion of dynamic signs, stems, beams, super- and subscripts,
        slurs, ties, and rests.

        You have to instantiate this explicitly if you want to have
        multiple voices on the same staff."

      localAlterations = #'()
      \consists "Font_size_engraver"

      % must come before all
      \consists "Output_property_engraver"
      \consists "Arpeggio_engraver"
      \consists "Multi_measure_rest_engraver"
      \consists "Text_spanner_engraver"
      \consists "Grob_pq_engraver"
      \consists "Note_head_line_engraver"
      \consists "Glissando_engraver"
      \consists "Ligature_bracket_engraver"
      \consists "Breathing_sign_engraver"
      % \consists "Rest_engraver"
      \consists "Grace_beam_engraver"
      \consists "New_fingering_engraver"
      \consists "Chord_tremolo_engraver"
      \consists "Percent_repeat_engraver"
      \consists "Slash_repeat_engraver"

      %{
        Must come before text_engraver, but after note_column engraver.
      %}
      \consists "Text_engraver"
      \consists "Dynamic_engraver"
      \consists "Dynamic_align_engraver"
      \consists "Fingering_engraver"

      \consists "Script_column_engraver"
      \consists "Rhythmic_column_engraver"
      \consists "Cluster_spanner_engraver"
      \consists "Tie_engraver"
      \consists "Tie_engraver"
      \consists "Tuplet_engraver"
      \consists "Note_heads_engraver"
      \consists "Rest_engraver"
    }

    \score {
      \topVoice
      \layout {
        \context { \MyStaff }
        \context { \MyVoice }
      }
    }

    MyStaff = \context {
      \MyStaff
      \consists "Staff_symbol_engraver"
    }

    \score {
      \topVoice
      \layout {
        \context { \MyStaff }
        \context { \MyVoice }
      }
    }

    MyStaff = \context {
      \MyStaff
      \consists "Clef_engraver"
      \remove "Pitch_squash_engraver"
    }

    \score {
      \topVoice
      \layout {
        \context { \MyStaff }
        \context { \MyVoice }
      }
    }

    MyVoice = \context {
      \MyVoice
      \consists "Stem_engraver"
    }

    \score {
      \topVoice
      \layout {
        \context { \MyStaff }
        \context { \MyVoice }
      }
    }

    MyVoice = \context {
      \MyVoice
      \consists "Beam_engraver"
    }

    \score {
      \topVoice
      \layout {
        \context { \MyStaff }
        \context { \MyVoice }
      }
    }

    MyVoice = \context {
      \MyVoice
      \consists "Phrasing_slur_engraver"
      \consists "Slur_engraver"
      \consists "Script_engraver"
    }

    \score {
      \topVoice
      \layout {
        \context { \MyStaff }
        \context { \MyVoice }
      }
    }

    MyStaff = \context {
      \MyStaff
      \consists "Bar_engraver"
      \consists "Time_signature_engraver"
    }

    \score {
      \topVoice
      \layout {
        \context { \MyStaff }
        \context { \MyVoice }
      }
    }

    MyStaff = \context {
      \MyStaff
      \consists "Accidental_engraver"
      \consists "Key_engraver"
    }
    \score {
      \topVoice
      \layout {
        \context { \MyStaff }
        \context { \MyVoice }
      }
    }

## Formattazione mensurale (stanghette tra i righi)

La formattazione mensurale, in cui le stanghette non appaiono sui righi ma nello spazio tra i righi, si può ottenere usando `StaffGroup` al posto di `ChoirStaff`. La stanghetta sui righi viene nascosta con `\hide`.

    \layout {
      \context {
        \Staff
        measureBarType = "-span|"
      }
    }

    music = \fixed c'' {
      c1
      d2 \section e2
      f1 \fine
    }

    \new StaffGroup <<
      \new Staff \music
      \new Staff \music
    >>

## Annidare i righi

Si può usare la proprietà `systemStartDelimiterHierarchy` per creare gruppi di righi annidati più complessi. Il comando `\set StaffGroup.systemStartDelimiterHierarchy` prende come argomento una lista alfabetica dell’insieme di righi prodotti. Prima di ogni rigo si può assegnare un delimitatore di inizio del sistema. Deve essere racchiuso tra parentesi e collega tutti i righi compresi tra le parentesi. Gli elementi nella lista possono essere omessi, ma la prima parentesi quadra collega sempre tutti i righi. Le possibilità sono `SystemStartBar`, `SystemStartBracket`, `SystemStartBrace` e `SystemStartSquare`.

    \new StaffGroup
    \relative c'' <<
      \override StaffGroup.SystemStartSquare.collapse-height = #4
      \set StaffGroup.systemStartDelimiterHierarchy
        = #'(SystemStartSquare (SystemStartBrace (SystemStartBracket a
                                 (SystemStartSquare b)  ) c ) d)
      \new Staff { c1 }
      \new Staff { c1 }
      \new Staff { c1 }
      \new Staff { c1 }
      \new Staff { c1 }
    >>

## Numbering groups of measures

This snippet demonstrates the use of the `Measure_counter_engraver` to number groups of successive measures. Any stretch of measures may be numbered, whether consisting of repetitions or not.

The engraver must be added to the appropriate context. Here, a `Staff` context is used; another possibility is a `Dynamics` context.

The counter is begun with `\startMeasureCount` and ended with `\stopMeasureCount`. Numbering will start by default with `1`, but this behavior may be modified by overriding the `count-from` property.

When a measure extends across a line break, the number will appear twice, the second time in parentheses.

    \layout {
      \context {
        \Staff
        \consists #Measure_counter_engraver
      }
    }

    \new Staff {
      \startMeasureCount
      \repeat unfold 7 {
        c'4 d' e' f'
      }
      \stopMeasureCount
      \bar "||"
      g'4 f' e' d'
      \override Staff.MeasureCounter.count-from = #2
      \startMeasureCount
      \repeat unfold 5 {
        g'4 f' e' d'
      }
      g'4 f'
      \bar ""
      \break
      e'4 d'
      \repeat unfold 7 {
        g'4 f' e' d'
      }
      \stopMeasureCount
    }

## Print ChordNames with same root and different bass as slash and bass-note

To print subsequent `ChordNames` only differing in its bass note as slash and bass note use the here defined engraver. The behaviour may be controlled in detail by the `chordChanges` context property.

    #(define Bass_changes_equal_root_engraver
      (lambda (ctx)
      "For sequential @code{ChordNames} with same root, but different bass, the root
    markup is dropped: D D/C D/B  -> D /C /B
    The behaviour may be controlled by setting the @code{chordChanges}
    context-property."
        (let ((chord-pitches '())
              (last-chord-pitches '())
              (bass-pitch #f))
          (make-engraver
            ((initialize this-engraver)
              (let ((chord-note-namer (ly:context-property ctx 'chordNoteNamer)))
                ;; Set 'chordNoteNamer, respect user setting if already done
                (ly:context-set-property! ctx 'chordNoteNamer
                  (if (procedure? chord-note-namer)
                      chord-note-namer
                      note-name->markup))))
            (listeners
              ((note-event this-engraver event)
                (let* ((pitch (ly:event-property event 'pitch))
                       (pitch-name (ly:pitch-notename pitch))
                       (pitch-alt (ly:pitch-alteration pitch))
                       (bass (ly:event-property event 'bass #f))
                       (inversion (ly:event-property event 'inversion #f)))
                ;; Collect notes of the chord
                ;;  - to compare inversed chords we need to collect the bass note
                ;;    as usual member of the chord, whereas an added bass must be
                ;;    treated separate from the usual chord-notes
                ;;  - notes are stored as pairs containing their
                ;;    pitch-name (an integer), i.e. disregarding their octave and
                ;;    their alteration
                (cond (bass (set! bass-pitch pitch))
                      (inversion
                        (set! bass-pitch pitch)
                        (set! chord-pitches
                              (cons (cons pitch-name pitch-alt) chord-pitches)))
                      (else
                        (set! chord-pitches
                              (cons (cons pitch-name pitch-alt) chord-pitches)))))))
            (acknowledgers
              ((chord-name-interface this-engraver grob source-engraver)
                (let ((chord-changes (ly:context-property ctx 'chordChanges #f)))
                  ;; If subsequent chords are equal apart from their bass,
                  ;; reset the 'text-property.
                  ;; Equality is done by comparing the sorted lists of this chord's
                  ;; elements and the previous chord. Sorting is needed because
                  ;; inverted chords may have a different order of pitches.
                  ;; `chord-changes' needs to be true
                  (if (and bass-pitch
                           chord-changes
                           (equal?
                             (sort chord-pitches car<)
                             (sort last-chord-pitches car<)))
                      (ly:grob-set-property! grob 'text
                        (make-line-markup
                          (list
                            (ly:context-property ctx 'slashChordSeparator)
                            ((ly:context-property ctx 'chordNoteNamer)
                             bass-pitch
                             (ly:context-property ctx 'chordNameLowercaseMinor))))))
                  (set! last-chord-pitches chord-pitches)
                  (set! chord-pitches '())
                  (set! bass-pitch #f))))
            ((finalize this-engraver)
              (set! last-chord-pitches '()))))))

    myChords = \chordmode {
      %\germanChords

      \set chordChanges = ##t
      d2:m d:m/cis

      d:m/c
      \set chordChanges = ##f
      d:m/b

      e1:7
      \set chordChanges = ##t
      e
      \break
      \once \set chordChanges = ##f
      e1/f
      e2/gis e/+gis e e:m/f d:m d:m/cis d:m/c
      \set chordChanges = ##f
      d:m/b
    }

    <<
      \new ChordNames
        \with { \consists #Bass_changes_equal_root_engraver }
        \myChords
      \new Staff \myChords
    >>

## Togliere i numeri di battuta da uno spartito

I numeri di battuta possono essere tolti rimuovendo l’incisore `Bar_number_engraver` dal contesto `Score`.

    \layout {
      \context {
        \Score
        \omit BarNumber
        % or:
        %\remove "Bar_number_engraver"
      }
    }

    \relative c'' {
      c4 c c c \break
      c4 c c c
    }

## Usare una parentesi quadra all’inizio di un gruppo di righi

Si può usare il segno `SystemStartSquare` (uno dei segni che delimitano l’inizio del sistema) impostandolo esplicitamente in un contesto `StaffGroup` o `ChoirStaff`.

    \score {
      \new StaffGroup { <<
      \set StaffGroup.systemStartDelimiter = #'SystemStartSquare
        \new Staff { c'4 d' e' f' }
        \new Staff { c'4 d' e' f' }
      >> }
    }

## Using marklines in a Frenched score

Using `MarkLine` contexts (such as in LSR1010) in a Frenched score can be problematic if all the staves between two `MarkLine`s are removed in one system. The `Keep_alive_together_engraver` can be used within each `StaffGroup` to keep the `MarkLine` alive only as long as the other staves in the group stay alive.

    bars = {
      \tempo "Allegro" 4=120
      s1*2
      \repeat unfold 5 { \mark \default s1*2 }
      \bar "||"
      \tempo "Adagio" 4=40
      s1*2
      \repeat unfold 8 { \mark \default s1*2 }
      \bar "|."
    }
    winds = \repeat unfold 120 { c''4 }
    trumpet = { \repeat unfold 8 g'2 R1*16 \repeat unfold 4 g'2 R1*8 }
    trombone = { \repeat unfold 4 c'1 R1*8 d'1 R1*17 }
    strings = \repeat unfold 240 { c''8 }

    #(set-global-staff-size 16)
    \paper {
      systems-per-page = 5
      ragged-last-bottom = ##f
    }

    \layout {
      indent = 15\mm
      short-indent = 5\mm
      \context {
        \name MarkLine
        \type Engraver_group
        \consists Output_property_engraver
        \consists Axis_group_engraver
        \consists Mark_engraver
        \consists Metronome_mark_engraver
        \consists Staff_collecting_engraver
        \override VerticalAxisGroup.remove-empty = ##t
        \override VerticalAxisGroup.remove-layer = #'any
        \override VerticalAxisGroup.staff-affinity = #DOWN
        \override VerticalAxisGroup.nonstaff-relatedstaff-spacing.padding = 1
        keepAliveInterfaces = #'()
      }
      \context {
        \Staff
        \override VerticalAxisGroup.remove-empty = ##t
        \override VerticalAxisGroup.remove-layer = ##f
      }
      \context {
        \StaffGroup
        \accepts MarkLine
        \consists Keep_alive_together_engraver
      }
      \context {
        \Score
        \remove Mark_engraver
        \remove Metronome_mark_engraver
        \remove Staff_collecting_engraver
      }
    }

    \score {
      <<
        \new StaffGroup = "winds" \with {
          instrumentName = "Winds"
          shortInstrumentName = "Winds"
        } <<
          \new MarkLine \bars
          \new Staff \winds
        >>
        \new StaffGroup = "brass" <<
          \new MarkLine \bars
          \new Staff = "trumpet" \with {
            instrumentName = "Trumpet"
            shortInstrumentName = "Tpt"
          } \trumpet
          \new Staff = "trombone" \with {
            instrumentName = "Trombone"
            shortInstrumentName = "Tbn"
          } \trombone
        >>
        \new StaffGroup = "strings" \with {
          instrumentName = "Strings"
          shortInstrumentName = "Strings"
        } <<
          \new MarkLine \bars
          \new Staff = "strings" { \strings }
        >>
      >>
    }

## Modello per gruppo vocale con testo allineato sotto e sopra i righi

Questo modello è fondamentalmente analogo al semplice modello “Complesso vocale”, con l’unica differenza che qui tutti i versi del testo sono posizionati usando `alignAboveContext` e `alignBelowContext`.

    global = {
      \key c \major
      \time 4/4
    }

    sopMusic = \relative c'' {
      c4 c c8[( b)] c4
    }
    sopWords = \lyricmode {
      hi hi hi hi
    }

    altoMusic = \relative c' {
      e4 f d e
    }
    altoWords = \lyricmode {
      ha ha ha ha
    }

    tenorMusic = \relative c' {
      g4 a f g
    }
    tenorWords = \lyricmode {
      hu hu hu hu
    }

    bassMusic = \relative c {
      c4 c g c
    }
    bassWords = \lyricmode {
      ho ho ho ho
    }

    \score {
      \new ChoirStaff <<
        \new Staff = "women" <<
          \new Voice = "sopranos" { \voiceOne << \global \sopMusic >> }
          \new Voice = "altos" { \voiceTwo << \global \altoMusic >> }
        >>
        \new Lyrics \with { alignAboveContext = #"women" }
          \lyricsto "sopranos" \sopWords
        \new Lyrics \with { alignBelowContext = #"women" }
          \lyricsto "altos" \altoWords
        % we could remove the line about this with the line below, since
        % we want the alto lyrics to be below the alto Voice anyway.
        % \new Lyrics \lyricsto "altos" \altoWords

        \new Staff = "men" <<
          \clef bass
          \new Voice = "tenors" { \voiceOne << \global \tenorMusic >> }
          \new Voice = "basses" { \voiceTwo << \global \bassMusic >> }
        >>
        \new Lyrics \with { alignAboveContext = #"men" }
          \lyricsto "tenors" \tenorWords
        \new Lyrics \with { alignBelowContext = #"men" }
          \lyricsto "basses" \bassWords
        % again, we could replace the line above this with the line below.
        % \new Lyrics \lyricsto "basses" \bassWords
      >>
    }

## Modello per gruppo vocale con strofa e ritornello

Questo modello crea una partitura che inizia con una sezione solistica e prosegue in un ritornello a due voci. Illustra anche l’uso delle pause spaziatrici all’interno della variabile `\global` per definire i cambi di tempo (e altri elementi comuni a tutte le parti) nel corso di tutta la partitura.

    global = {
      \key g \major

      % verse
      \time 3/4
      s2.*2
      \break

      % refrain
      \time 2/4
      s2*2
      \bar "|."
    }

    SoloNotes = \relative g' {
      \clef "treble"

      % verse
      g4 g g |
      b4 b b |

      % refrain
      R2*2 |
    }

    SoloLyrics = \lyricmode {
      One two three |
      four five six |
    }

    SopranoNotes = \relative c'' {
      \clef "treble"

      % verse
      R2.*2 |

      % refrain
      c4 c |
      g4 g |
    }

    SopranoLyrics = \lyricmode {
      la la |
      la la |
    }

    BassNotes = \relative c {
      \clef "bass"

      % verse
      R2.*2 |

      % refrain
      c4 e |
      d4 d |
    }

    BassLyrics = \lyricmode {
      dum dum |
      dum dum |
    }

    \score {
      <<
        \new Voice = "SoloVoice" << \global \SoloNotes >>
        \new Lyrics \lyricsto "SoloVoice" \SoloLyrics

        \new ChoirStaff <<
          \new Voice = "SopranoVoice" << \global \SopranoNotes >>
          \new Lyrics \lyricsto "SopranoVoice" \SopranoLyrics

          \new Voice = "BassVoice" << \global \BassNotes >>
          \new Lyrics \lyricsto "BassVoice" \BassLyrics
        >>
      >>
      \layout {
        ragged-right = ##t
        \context { \Staff
          % these lines prevent empty staves from being printed
          \RemoveEmptyStaves
          \override VerticalAxisGroup.remove-first = ##t
        }
      }
    }

#### LilyPond — Frammenti v2.24.4 (ramo stabile).