Jump to content

Music within an octave ambitus

From LilyPond wiki

Function to keep the music within an octave ambitus, starting from a reference pitch.
It may be useful for the left-hand of accordion.

\version "2.24.0"

\paper { tagline = ##f }

#(define (within-octave-pitch pitchReference p)
   (let ((o (ly:pitch-octave p))
         (a (ly:pitch-alteration p))
         (n (ly:pitch-notename p))
         (s (ly:pitch-semitones p))
         (r (ly:pitch-semitones pitchReference)))
     (let loop ()
       (cond
        ((< s r)
         (set! o (1+ o))
         (set! p (ly:make-pitch o n a))
         (set! s (ly:pitch-semitones p))
         (loop))
        ((> s (+ r 11))
         (set! o (1- o))
         (set! p (ly:make-pitch o n a))
         (set! s (ly:pitch-semitones p))
         (loop))))
     (ly:make-pitch o n a)))

#(define (within-octave pitchReference 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) (within-octave pitchReference x)) es)))
     (if (ly:music? e)
         (ly:music-set-property!
          music 'element
          (within-octave pitchReference e)))
     (if (ly:pitch? p)
         (begin
          (set! p (within-octave-pitch pitchReference p))
          (ly:music-set-property! music 'pitch p)))
     music))

withinOctave =
#(define-music-function (pitchReference music)
   (ly:pitch? ly:music?)
   (within-octave pitchReference music))

%usage: \withinOctave pitch-reference (pitch) music (muscial expression)

\withinOctave g { a4 b c' d' e' f' g' a' b' c'' }
\withinOctave e' \chordmode { a:m b:dim c:7 }