Changing the width of ledger lines for a group of notes

If you want to temporary modify the width of ledger lines you have to specify \stopStaff \startStaff before overriding the ledger line values.

\version "2.24"

%% http://lsr.di.unimi.it/LSR/Item?id=928
% => http://lilypond.1069038.n5.nabble.com/Re-Shorten-ledger-lines-tt164380.html
% by Paul Morris

scaleLedgers =
#(define-music-function (s) (number?)
   "Changes the width of ledger lines. 0.25 is default value
    for both length-fraction and minimum-length-fraction
    properties.  By default ledger lines extend beyond the note
    head by 0.25 times the width of the notehead.
    Scales the default value by s."
   (define x (* 0.25 s))
   #{
     \stopStaff
     \startStaff
     \override Staff.LedgerLineSpanner.length-fraction = #x
     \override Staff.LedgerLineSpanner.minimum-length-fraction = #x
   #})

scaleLedgersBetweenBars =
#(define-music-function (s) (number?)
   #{
     % A hidden bar line corrects the gap created by \stopStaff
     % and \startStaff when \scaleLedgers is not called at a
     % bar line, but increases spacing between notes.
     \once \hide Staff.BarLine
     \bar "|"
     \scaleLedgers #s
   #})

\score {
  \relative c' {
    g d c d
    \scaleLedgers #2
    g d c d
    \scaleLedgers #0.5
    g d c d
    \scaleLedgers #1
    g d c d
    c d
    \scaleLedgersBetweenBars #2
    g d
    c d c d
    c d
    \scaleLedgersBetweenBars #0.5
    g d
    c d c d
  }
  \layout {}
}