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. Each list describes the default order of prefatory matter at the end, in the middle, and at the beginning of a line, respectively. We are only interested in changing the behaviour in the middle of a line.

If you look up the definition of break-align-orders in LilyPond’s Internal Reference (see the BreakAlignment grob), you get the following order in the second element:

...
staff-bar
key-cancellation
key-signature
...

We want to change that, moving key-cancellation before staff-bar. To make this happen we use the grob-transformer function, which gives us access to the original vector as the second argument of the lambda function, here called orig (we don’t need the first argument, grob). We return a new vector, with unchanged first and last elements. For the middle element, we first remove key-cancellation from the list, then adding it again before staff-bar.

#(define (insert-before where what lst)
   (cond
    ((null? lst)           ; If the list is empty,
     (list what))          ; return a single-element list.
    ((eq? where (car lst)) ; If we find symbol `where`,
     (cons what lst))      ; insert `what` before curr. position.
    (else                  ; Otherwise keep building the list by
     (cons (car lst)       ; adding the current element and
                           ; recursing with the next element.
           (insert-before where what (cdr lst))))))

cancellationFirst =
\override Score.BreakAlignment.break-align-orders =
#(grob-transformer
  'break-align-orders
  (lambda (grob orig)
    (let* ((middle (vector-ref orig 1))
           (middle (delq 'key-cancellation middle))
           (middle (insert-before
                    'staff-bar 'key-cancellation middle)))
      (vector
       ;; end of line
       (vector-ref orig 0)
       ;; middle of line
       middle
       ;; beginning of line
       (vector-ref orig 2)))))

music = { \key es \major d'1 \bar "||"
          \key a \major d'1 }

{ <>^\markup "default"
  \music }

{ <>^\markup "cancellation first"
  \cancellationFirst
  \music }

\paper { tagline = ##f }

[image of music]


LilyPond snippets v2.25.20 (development-branch).