LilyPond snippets: Pitches

# Pitches

These snippets illustrate the Notation Reference, section Pitches.

## Adding ambitus per voice

Ambitus can be added per voice. In this case, the ambitus must be moved manually to prevent collisions.

    \new Staff <<
      \new Voice \with {
        \consists "Ambitus_engraver"
      } \relative c'' {
        \override Ambitus #'X-offset = #2.0
        \voiceOne
        c4 a d e
        f1
      }
      \new Voice \with {
        \consists "Ambitus_engraver"
      } \relative c' {
        \voiceTwo
        es4 f g as
        b1
      }
    >>

## Ambitus with multiple voices

Adding the `Ambitus_engraver` to the `Staff` context creates a single ambitus per staff, even in the case of staves with multiple voices.

    \new Staff \with {
      \consists "Ambitus_engraver"
      }
    <<
      \new Voice \relative c'' {
        \voiceOne
        c4 a d e
        f1
      }
      \new Voice \relative c' {
        \voiceTwo
        es4 f g as
        b1
      }
    >>

## Ambitus

Ambitus indicate pitch ranges for voices.

Accidentals only show up if they are not part of the key signature. `AmbitusNoteHead` grobs also have ledger lines.

    \layout {
      \context {
        \Voice
        \consists "Ambitus_engraver"
      }
    }

    <<
      \new Staff {
        \relative c' {
          \time 2/4
          c4 f'
        }
      }
      \new Staff {
        \relative c' {
          \time  2/4
          \key d \major
          cis4 as'
        }
      }
    >>

## Applying note head styles depending on the step of the scale

The `shapeNoteStyles` property can be used to define various note head styles for each step of the scale (as set by the key signature or the "tonic" property). This property requires a set of symbols, which can be purely arbitrary (geometrical expressions such as `triangle`, `cross`, and `xcircle` are allowed) or based on old American engraving tradition (some latin note names are also allowed).

That said, to imitate old American song books, there are several predefined note head styles available through shortcut commands such as `\aikenHeads` or `\sacredHarpHeads`.

This example shows different ways to obtain shape note heads, and demonstrates the ability to transpose a melody without losing the correspondence between harmonic functions and note head styles.

    fragment = {
      \key c \major
      c2 d
      e2 f
      g2 a
      b2 c
    }

    \score {
      \new Staff {
        \transpose c d
        \relative c' {
          \set shapeNoteStyles = #'#(do re mi fa
                                     #f la ti)
          \fragment
        }

        \break

        \relative c' {
          \set shapeNoteStyles = #'#(cross triangle fa #f
                                     mensural xcircle diamond)
          \fragment
        }
      }
      \layout { ragged-right = ##t }
    }

## Coloring notes depending on their pitch

It is possible to color note heads depending on their pitch and/or their names: the function used in this example even makes it possible to distinguish enharmonics.

    %Association list of pitches to colors.
    #(define color-mapping
      (list
        (cons (ly:make-pitch 0 0 0) (x11-color 'red))
        (cons (ly:make-pitch 0 0 1/2) (x11-color 'green))
        (cons (ly:make-pitch 0 1 -1/2) (x11-color 'green))
        (cons (ly:make-pitch 0 2 0) (x11-color 'red))
        (cons (ly:make-pitch 0 2 1/2) (x11-color 'green))
        (cons (ly:make-pitch 0 3 -1/2) (x11-color 'red))
        (cons (ly:make-pitch 0 3 0) (x11-color 'green))
        (cons (ly:make-pitch 0 4 1/2) (x11-color 'red))
        (cons (ly:make-pitch 0 5 0) (x11-color 'green))
        (cons (ly:make-pitch 0 5 -1/2) (x11-color 'red))
        (cons (ly:make-pitch 0 6 1/2) (x11-color 'red))
        (cons (ly:make-pitch 0 1 0) (x11-color 'blue))
        (cons (ly:make-pitch 0 3 1/2) (x11-color 'blue))
        (cons (ly:make-pitch 0 4 -1/2) (x11-color 'blue))
        (cons (ly:make-pitch 0 5 1/2) (x11-color 'blue))
        (cons (ly:make-pitch 0 6 -1/2) (x11-color 'blue))))

    %Compare pitch and alteration (not octave).
    #(define (pitch-equals? p1 p2)
      (and
        (= (ly:pitch-alteration p1) (ly:pitch-alteration p2))
        (= (ly:pitch-notename p1) (ly:pitch-notename p2))))

    #(define (pitch-to-color pitch)
      (let ((color (assoc pitch color-mapping pitch-equals?)))
        (if color
          (cdr color))))

    #(define (color-notehead grob)
      (pitch-to-color
        (ly:event-property (event-cause grob) 'pitch)))

    \score {
      \new Staff \relative c' {
        \override NoteHead #'color = #color-notehead
        c8 b d dis ees f g aes
      }
    }

## Creating a sequence of notes on various pitches

In music that contains many occurrences of the same sequence of notes at different pitches, the following music function may prove useful. It takes a note, of which only the pitch is used. The supporting Scheme functions were borrowed from the "Tips and tricks" document in the manual for version 2.10. This example creates the rhythm used throughout Mars, from Gustav Holst’s The Planets.

    #(define (make-note-req p d)
       (make-music 'NoteEvent
    	       'duration d
    	       'pitch p))

    #(define (make-note p d)
       (make-music 'EventChord
    	       'elements (list (make-note-req p d))))

    #(define (make-triplet elt)
       (make-music 'TimeScaledMusic
    	       'denominator 3
    	       'numerator 2
    	       'element elt))

    rhythm =
    #(define-music-function (parser location note) (ly:music?)
       "Make the rhythm in Mars (the Planets) at the given note's pitch"
       (let ((p (ly:music-property
                 (car (ly:music-property note 'elements))
                 'pitch)))
         (make-sequential-music
          (list
           (make-triplet (make-sequential-music
                          (list
                           (make-note p (ly:make-duration 3 0 2 3))
                           (make-note p (ly:make-duration 3 0 2 3))
                           (make-note p (ly:make-duration 3 0 2 3)))))
           (make-note p (ly:make-duration 2 0))
           (make-note p (ly:make-duration 2 0))
           (make-note p (ly:make-duration 3 0))
           (make-note p (ly:make-duration 3 0))
           (make-note p (ly:make-duration 2 0))))))

    \new Staff {
      \time 5/4
      \rhythm c'
      \rhythm c''
      \rhythm g
    }

## Dodecaphonic-style accidentals for each note including naturals

In early 20th century works, starting with Schoenberg, Berg and Webern (the "Second" Viennese school), every pitch in the twelve-tone scale has to be regarded as equal, without any hierarchy such as the classical (tonal) degrees. Therefore, these composers print one accidental for each note, even at natural pitches, to emphasize their new approach to music theory and language.

This snippet shows how to achieve such notation rules.

    \score {
      \new Staff {
        #(set-accidental-style 'dodecaphonic)
        c'4 dis' cis' cis'
        c'4 dis' cis' cis'
        c'4 c' dis' des'
      }
      \layout {
        \context {
          \Staff
          \remove "Key_engraver"
        }
      }
    }

## Generating random notes

This Scheme-based snippet generates 24 random notes (or as many as required), based on the current time (or any randomish number specified instead, in order to obtain the same random notes each time): i.e., to get different random note patterns, just change this number.

    \score {
      {
        #(let ((random-state (seed->random-state (current-time))))
           (ly:export
            (make-sequential-music
             (map (lambda (x)
                    (let ((idx (random 12 random-state)))
                      (make-event-chord
                       (list
                        (make-music 'NoteEvent
                                    'duration (ly:make-duration 2 0 1 1)
                                    'pitch (ly:make-pitch
                                            (quotient idx 7)
                                            (remainder idx 7)
                                            0))))))
                  (make-list 24)))))
      }
    }

## Makam example

Makam is a type of melody from Turkey using 1/9th-tone microtonal alterations. Consult the initialization file ‘`ly/makam.ly`’ for details of pitch names and alterations.

    % Initialize makam settings
    \include "makam.ly"

    \relative c' {
      \set Staff.keySignature = #`((3 . ,BAKIYE) (6 . ,(- KOMA)))
      c4 cc db fk
      gbm4 gfc gfb efk
      fk4 db cc c
    }

## Non-traditional key signatures

The commonly used `\key` command sets the `keySignature` property, in the `Staff` context.

To create non-standard key signatures, set this property directly. The format of this command is a list:

`\set Staff.keySignature = #`(((octave . step) . alter) ((octave . step) . alter) ...)` where, for each element in the list, `octave` specifies the octave (0 being the octave from middle C to the B above), `step` specifies the note within the octave (0 means C and 6 means B), and `alter` is `,SHARP ,FLAT ,DOUBLE-SHARP` etc. (Note the leading comma.) The accidentals in the key signature will appear in the reverse order to that in which they are specified.

Alternatively, for each item in the list, using the more concise format `(step . alter)` specifies that the same alteration should hold in all octaves.

For microtonal scales where a "sharp" is not 100 cents, `alter` refers to the alteration as a proportion of a 200-cent whole tone.

Here is an example of a possible key signature for generating a whole-tone scale:

    \relative c' {
      \set Staff.keySignature = #`(((0 . 3) . ,SHARP)
                                   ((0 . 5) . ,FLAT)
                                   ((0 . 6) . ,FLAT))
      c4 d e fis
      aes4 bes c2
    }

## Ottava text

Internally, `\ottava` sets the properties `ottavation` (for example, to `"8va"` or `"8vb"`) and `middleCPosition`. To override the text of the bracket, set `ottavation` after invoking `\ottava`.

    {
      \ottava #1
      \set Staff.ottavation = #"8"
      c''1
      \ottava #0
      c'1
      \ottava #1
      \set Staff.ottavation = #"Text"
      c''1
    }

## Preventing extra naturals from being automatically added

In accordance with standard typesetting rules, a natural sign is printed before a sharp or flat if a previous accidental on the same note needs to be canceled. To change this behavior, set the `extraNatural` property to "false" in the `Staff` context.

    \relative c'' {
      aeses4 aes ais a
      \set Staff.extraNatural = ##f
      aeses4 aes ais a
    }

## Preventing natural signs from being printed when the key signature changes

When the key signature changes, natural signs are automatically printed to cancel any accidentals from previous key signatures. This may be prevented by setting to "false" the `printKeyCancellation` property in the `Staff` context.

    \relative c' {
      \key d \major
      a4 b cis d
      \key g \minor
      a4 bes c d
      \set Staff.printKeyCancellation = ##f
      \key d \major
      a4 b cis d
      \key g \minor
      a4 bes c d
    }

## Quoting another voice with transposition

Quotations take into account the transposition of both source and target. In this example, all instruments play sounding middle C; the target is an instrument in F. The target part may be transposed using `\transpose`. In this case, all the pitches (including the quoted ones) are transposed.

    \addQuote clarinet {
      \transposition bes
      \repeat unfold 8 { d'16 d' d'8 }
    }

    \addQuote sax {
      \transposition es'
      \repeat unfold 16 { a8 }
    }

    quoteTest = {
      % french horn
      \transposition f
      g'4
      << \quoteDuring #"clarinet" { \skip 4 } s4^"clar." >>
      << \quoteDuring #"sax" { \skip 4 } s4^"sax." >>
      g'4
    }

    {
      \set Staff.instrumentName =
        \markup {
          \center-column { Horn \line { in F } }
        }
      \quoteTest
      \transpose c' d' << \quoteTest s4_"up a tone" >>
    }

## Separating key cancellations from key signature changes

By default, the accidentals used for key cancellations are placed adjacent to those for key signature changes. This behavior can be changed by overriding the `'break-align-orders` property of the `BreakAlignment` grob.

The value of `'break-align-orders` is a vector of length 3, with quoted lists of breakable items as elements. This example only modifies the second list, moving `key-cancellation` before `staff-bar`; by modifying the second list, break alignment behavior only changes in the middle of a system, not at the beginning or the end.

    \new Staff {
      \override Score.BreakAlignment #'break-align-orders =
        #'#((left-edge ambitus breathing-sign clef staff-bar
                       key-cancellation key-signature time-signature custos)

            (left-edge ambitus breathing-sign clef key-cancellation
                       staff-bar key-signature time-signature custos)

            (left-edge ambitus breathing-sign clef key-cancellation
                       key-signature staff-bar time-signature custos))

      \key des \major
      c'1
      \bar "||"
      \key bes \major
      c'1
    }

## Transposing pitches with minimum accidentals ("Smart" transpose)

This example uses some Scheme code to enforce enharmonic modifications for notes in order to have the minimum number of accidentals. In this case, the following rules apply:

Double accidentals should be removed

B sharp -> C

E sharp -> F

C flat -> B

F flat -> E

In this manner, the most natural enharmonic notes are chosen.

    #(define (naturalize-pitch p)
      (let ((o (ly:pitch-octave p))
            (a (* 4 (ly:pitch-alteration p)))
            ;; alteration, a, in quarter tone steps,
            ;; for historical reasons
            (n (ly:pitch-notename p)))
        (cond
         ((and (> a 1) (or (eq? n 6) (eq? n 2)))
          (set! a (- a 2))
          (set! n (+ n 1)))
         ((and (< a -1) (or (eq? n 0) (eq? n 3)))
          (set! a (+ a 2))
          (set! n (- n 1))))
        (cond
         ((> a 2) (set! a (- a 4)) (set! n (+ n 1)))
         ((< a -2) (set! a (+ a 4)) (set! n (- n 1))))
        (if (< n 0) (begin (set! o (- o 1)) (set! n (+ n 7))))
        (if (> n 6) (begin (set! o (+ o 1)) (set! n (- n 7))))
        (ly:make-pitch o n (/ a 4))))

    #(define (naturalize music)
      (let ((es (ly:music-property music 'elements))
            (e (ly:music-property music 'element))
            (p (ly:music-property music 'pitch)))
        (if (pair? es)
           (ly:music-set-property!
             music 'elements
             (map (lambda (x) (naturalize x)) es)))
        (if (ly:music? e)
           (ly:music-set-property!
             music 'element
             (naturalize e)))
        (if (ly:pitch? p)
           (begin
             (set! p (naturalize-pitch p))
             (ly:music-set-property! music 'pitch p)))
        music))

    naturalizeMusic =
    #(define-music-function (parser location m)
      (ly:music?)
      (naturalize m))

    music = \relative c' { c4 d e g }

    \score {
      \new Staff {
        \transpose c ais { \music }
        \naturalizeMusic \transpose c ais { \music }
        \transpose c deses { \music }
        \naturalizeMusic \transpose c deses { \music }
      }
      \layout { }
    }

## Tweaking clef properties

The command `\clef "treble_8"` is equivalent to setting `clefGlyph`, `clefPosition` (which controls the vertical position of the clef), `middleCPosition` and `clefOctavation`. A clef is printed when any of the properties except `middleCPosition` are changed.

Note that changing the glyph, the position of the clef, or the octavation does not in itself change the position of subsequent notes on the staff: the position of middle C must also be specified to do this. The positional parameters are relative to the staff center line, positive numbers displacing upwards, counting one for each line and space. The `clefOctavation` value would normally be set to 7, -7, 15 or -15, but other values are valid.

When a clef change takes place at a line break the new clef symbol is printed at both the end of the previous line and the beginning of the new line by default. If the warning clef at the end of the previous line is not required it can be suppressed by setting the `Staff` property `explicitClefVisibility` to the value `end-of-line-invisible`. The default behavior can be recovered with `\unset Staff.explicitClefVisibility`.

The following examples show the possibilities when setting these properties manually. On the first line, the manual changes preserve the standard relative positioning of clefs and notes, whereas on the second line, they do not.

    \layout { ragged-right = ##t }

    {
      % The default treble clef
      c'1
      % The standard bass clef
      \set Staff.clefGlyph = #"clefs.F"
      \set Staff.clefPosition = #2
      \set Staff.middleCPosition = #6
      c'1
      % The baritone clef
      \set Staff.clefGlyph = #"clefs.C"
      \set Staff.clefPosition = #4
      \set Staff.middleCPosition = #4
      c'1
      % The standard choral tenor clef
      \set Staff.clefGlyph = #"clefs.G"
      \set Staff.clefPosition = #-2
      \set Staff.clefOctavation = #-7
      \set Staff.middleCPosition = #1
      c'1
      % A non-standard clef
      \set Staff.clefPosition = #0
      \set Staff.clefOctavation = #0
      \set Staff.middleCPosition = #-4
      c'1 \break

      % The following clef changes do not preserve
      % the normal relationship between notes and clefs:

      \set Staff.clefGlyph = #"clefs.F"
      \set Staff.clefPosition = #2
      c'1
      \set Staff.clefGlyph = #"clefs.G"
      c'1
      \set Staff.clefGlyph = #"clefs.C"
      c'1
      \set Staff.clefOctavation = #7
      c'1
      \set Staff.clefOctavation = #0
      \set Staff.clefPosition = #0
      c'1

      % Return to the normal clef:

      \set Staff.middleCPosition = #0
      c'1
    }

#### Snippets List