]> git.donarmstrong.com Git - lilypond.git/blob - scm/music-functions.scm
Merge branch 'translation' into staging
[lilypond.git] / scm / music-functions.scm
1 ;;;; This file is part of LilyPond, the GNU music typesetter.
2 ;;;;
3 ;;;; Copyright (C) 1998--2012 Jan Nieuwenhuizen <janneke@gnu.org>
4 ;;;;                 Han-Wen Nienhuys <hanwen@xs4all.nl>
5 ;;;;
6 ;;;; LilyPond is free software: you can redistribute it and/or modify
7 ;;;; it under the terms of the GNU General Public License as published by
8 ;;;; the Free Software Foundation, either version 3 of the License, or
9 ;;;; (at your option) any later version.
10 ;;;;
11 ;;;; LilyPond is distributed in the hope that it will be useful,
12 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 ;;;; GNU General Public License for more details.
15 ;;;;
16 ;;;; You should have received a copy of the GNU General Public License
17 ;;;; along with LilyPond.  If not, see <http://www.gnu.org/licenses/>.
18
19 ; for define-safe-public when byte-compiling using Guile V2
20 (use-modules (scm safe-utility-defs))
21
22 (use-modules (ice-9 optargs))
23
24 ;;; ly:music-property with setter
25 ;;; (ly:music-property my-music 'elements)
26 ;;;   ==> the 'elements property
27 ;;; (set! (ly:music-property my-music 'elements) value)
28 ;;;   ==> set the 'elements property and return it
29 (define-public ly:music-property
30   (make-procedure-with-setter ly:music-property
31                               ly:music-set-property!))
32
33 (define-safe-public (music-is-of-type? mus type)
34   "Does @code{mus} belong to the music class @code{type}?"
35   (memq type (ly:music-property mus 'types)))
36
37 ;; TODO move this
38 (define-public ly:grob-property
39   (make-procedure-with-setter ly:grob-property
40                               ly:grob-set-property!))
41
42 (define-public ly:grob-object
43   (make-procedure-with-setter ly:grob-object
44                               ly:grob-set-object!))
45
46 (define-public ly:grob-parent
47   (make-procedure-with-setter ly:grob-parent
48                               ly:grob-set-parent!))
49
50 (define-public ly:prob-property
51   (make-procedure-with-setter ly:prob-property
52                               ly:prob-set-property!))
53
54 (define-public ly:context-property
55   (make-procedure-with-setter ly:context-property
56                               ly:context-set-property!))
57
58 (define-public (music-map function music)
59   "Apply @var{function} to @var{music} and all of the music it contains.
60
61 First it recurses over the children, then the function is applied to
62 @var{music}."
63   (let ((es (ly:music-property music 'elements))
64         (e (ly:music-property music 'element)))
65     (if (pair? es)
66         (set! (ly:music-property music 'elements)
67               (map (lambda (y) (music-map function y)) es)))
68     (if (ly:music? e)
69         (set! (ly:music-property music 'element)
70               (music-map function  e)))
71     (function music)))
72
73 (define-public (music-filter pred? music)
74   "Filter out music expressions that do not satisfy @var{pred?}."
75
76   (define (inner-music-filter pred? music)
77     "Recursive function."
78     (let* ((es (ly:music-property music 'elements))
79            (e (ly:music-property music 'element))
80            (as (ly:music-property music 'articulations))
81            (filtered-as (filter ly:music? (map (lambda (y) (inner-music-filter pred? y)) as)))
82            (filtered-e (if (ly:music? e)
83                            (inner-music-filter pred? e)
84                            e))
85            (filtered-es (filter ly:music? (map (lambda (y) (inner-music-filter pred? y)) es))))
86       (if (not (null? e))
87           (set! (ly:music-property music 'element) filtered-e))
88       (if (not (null? es))
89           (set! (ly:music-property music 'elements) filtered-es))
90       (if (not (null? as))
91           (set! (ly:music-property music 'articulations) filtered-as))
92       ;; if filtering emptied the expression, we remove it completely.
93       (if (or (not (pred? music))
94               (and (eq? filtered-es '()) (not (ly:music? e))
95                    (or (not (eq? es '()))
96                        (ly:music? e))))
97           (set! music '()))
98       music))
99
100   (set! music (inner-music-filter pred? music))
101   (if (ly:music? music)
102       music
103       (make-music 'Music)))       ;must return music.
104
105 (define*-public (display-music music #:optional (port (current-output-port)))
106   "Display music, not done with @code{music-map} for clarity of
107 presentation."
108   (display music port)
109   (display ": { " port)
110   (let ((es (ly:music-property music 'elements))
111         (e (ly:music-property music 'element)))
112     (display (ly:music-mutable-properties music) port)
113     (if (pair? es)
114         (begin (display "\nElements: {\n" port)
115                (for-each (lambda (m) (display-music m port)) es)
116                (display "}\n" port)))
117     (if (ly:music? e)
118         (begin
119           (display "\nChild:" port)
120           (display-music e port))))
121   (display " }\n" port)
122   music)
123
124 ;;;
125 ;;; A scheme music pretty printer
126 ;;;
127 (define (markup-expression->make-markup markup-expression)
128   "Transform `markup-expression' into an equivalent, hopefuly readable, scheme expression.
129 For instance,
130   \\markup \\bold \\italic hello
131 ==>
132   (markup #:line (#:bold (#:italic (#:simple \"hello\"))))"
133   (define (proc->command-keyword proc)
134     "Return a keyword, eg. `#:bold', from the `proc' function, eg. #<procedure bold-markup (layout props arg)>"
135     (let ((cmd-markup (symbol->string (procedure-name proc))))
136       (symbol->keyword (string->symbol (substring cmd-markup 0 (- (string-length cmd-markup)
137                                                                   (string-length "-markup")))))))
138   (define (transform-arg arg)
139     (cond ((and (pair? arg) (markup? (car arg))) ;; a markup list
140            (apply append (map inner-markup->make-markup arg)))
141           ((and (not (string? arg)) (markup? arg)) ;; a markup
142            (inner-markup->make-markup arg))
143           (else                                  ;; scheme arg
144            (music->make-music arg))))
145   (define (inner-markup->make-markup mrkup)
146     (if (string? mrkup)
147         `(#:simple ,mrkup)
148         (let ((cmd (proc->command-keyword (car mrkup)))
149               (args (map transform-arg (cdr mrkup))))
150           `(,cmd ,@args))))
151   ;; body:
152   (if (string? markup-expression)
153       markup-expression
154       `(markup ,@(inner-markup->make-markup markup-expression))))
155
156 (define-public (music->make-music obj)
157   "Generate an expression that, once evaluated, may return an object
158 equivalent to @var{obj}, that is, for a music expression, a
159 @code{(make-music ...)} form."
160   (cond (;; markup expression
161          (markup? obj)
162          (markup-expression->make-markup obj))
163         (;; music expression
164          (ly:music? obj)
165          `(make-music
166            ',(ly:music-property obj 'name)
167            ,@(apply append (map (lambda (prop)
168                                   `(',(car prop)
169                                     ,(music->make-music (cdr prop))))
170                                 (remove (lambda (prop)
171                                           (eqv? (car prop) 'origin))
172                                         (ly:music-mutable-properties obj))))))
173         (;; moment
174          (ly:moment? obj)
175          `(ly:make-moment ,(ly:moment-main-numerator obj)
176                           ,(ly:moment-main-denominator obj)
177                           ,(ly:moment-grace-numerator obj)
178                           ,(ly:moment-grace-denominator obj)))
179         (;; note duration
180          (ly:duration? obj)
181          `(ly:make-duration ,(ly:duration-log obj)
182                             ,(ly:duration-dot-count obj)
183                             ,(ly:duration-scale obj)))
184         (;; note pitch
185          (ly:pitch? obj)
186          `(ly:make-pitch ,(ly:pitch-octave obj)
187                          ,(ly:pitch-notename obj)
188                          ,(ly:pitch-alteration obj)))
189         (;; scheme procedure
190          (procedure? obj)
191          (or (procedure-name obj) obj))
192         (;; a symbol (avoid having an unquoted symbol)
193          (symbol? obj)
194          `',obj)
195         (;; an empty list (avoid having an unquoted empty list)
196          (null? obj)
197          `'())
198         (;; a proper list
199          (list? obj)
200          `(list ,@(map music->make-music obj)))
201         (;; a pair
202          (pair? obj)
203          `(cons ,(music->make-music (car obj))
204                 ,(music->make-music (cdr obj))))
205         (else
206          obj)))
207
208 (use-modules (ice-9 pretty-print))
209 (define*-public (display-scheme-music obj #:optional (port (current-output-port)))
210   "Displays `obj', typically a music expression, in a friendly fashion,
211 which often can be read back in order to generate an equivalent expression."
212   (pretty-print (music->make-music obj) port)
213   (newline port))
214
215 ;;;
216 ;;; Scheme music expression --> Lily-syntax-using string translator
217 ;;;
218 (use-modules (srfi srfi-39)
219              (scm display-lily))
220
221 (define*-public (display-lily-music expr parser #:optional (port (current-output-port))
222                                     #:key force-duration)
223   "Display the music expression using LilyPond syntax"
224   (memoize-clef-names supported-clefs)
225   (parameterize ((*indent* 0)
226                  (*previous-duration* (ly:make-duration 2))
227                  (*force-duration* force-duration))
228     (display (music->lily-string expr parser) port)
229     (newline port)))
230
231 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
232
233 (define-public (shift-one-duration-log music shift dot)
234   "Add @var{shift} to @code{duration-log} of @code{'duration} in
235 @var{music} and optionally @var{dot} to any note encountered.
236 The number of dots in the shifted music may not be less than zero."
237   (let ((d (ly:music-property music 'duration)))
238     (if (ly:duration? d)
239         (let* ((cp (ly:duration-scale d))
240                (nd (ly:make-duration
241                     (+ shift (ly:duration-log d))
242                     (max 0 (+ dot (ly:duration-dot-count d)))
243                     cp)))
244           (set! (ly:music-property music 'duration) nd)))
245     music))
246
247 (define-public (shift-duration-log music shift dot)
248   (music-map (lambda (x) (shift-one-duration-log x shift dot))
249              music))
250
251 (define-public (make-repeat name times main alts)
252   "Create a repeat music expression, with all properties initialized
253 properly."
254   (define (first-note-duration music)
255     "Finds the duration of the first NoteEvent by searching depth-first
256 through MUSIC."
257     ;; NoteEvent or a non-expanded chord-repetition
258     ;; We just take anything that actually sports an announced duration.
259     (if (ly:duration? (ly:music-property music 'duration))
260         (ly:music-property music 'duration)
261         (let loop ((elts (if (ly:music? (ly:music-property music 'element))
262                              (list (ly:music-property music 'element))
263                              (ly:music-property music 'elements))))
264           (and (pair? elts)
265                (let ((dur (first-note-duration (car elts))))
266                  (if (ly:duration? dur)
267                      dur
268                      (loop (cdr elts))))))))
269
270   (let ((talts (if (< times (length alts))
271                    (begin
272                      (ly:warning (_ "More alternatives than repeats.  Junking excess alternatives"))
273                      (take alts times))
274                    alts))
275         (r (make-repeated-music name)))
276     (set! (ly:music-property r 'element) main)
277     (set! (ly:music-property r 'repeat-count) (max times 1))
278     (set! (ly:music-property r 'elements) talts)
279     (if (and (equal? name "tremolo")
280              (pair? (extract-named-music main '(EventChord NoteEvent))))
281         ;; This works for single-note and multi-note tremolos!
282         (let* ((children (if (music-is-of-type? main 'sequential-music)
283                              ;; \repeat tremolo n { ... }
284                              (length (extract-named-music main '(EventChord
285                                                                  NoteEvent)))
286                              ;; \repeat tremolo n c4
287                              1))
288                ;; # of dots is equal to the 1 in bitwise representation (minus 1)!
289                (dots (1- (logcount (* times children))))
290                ;; The remaining missing multiplicator to scale the notes by
291                ;; times * children
292                (mult (/ (* times children (ash 1 dots)) (1- (ash 2 dots))))
293                (shift (- (ly:intlog2 (floor mult))))
294                (note-duration (first-note-duration r))
295                (duration-log (if (ly:duration? note-duration)
296                                  (ly:duration-log note-duration)
297                                  1))
298                (tremolo-type (ash 1 duration-log)))
299           (set! (ly:music-property r 'tremolo-type) tremolo-type)
300           (if (not (and (integer? mult) (= (logcount mult) 1)))
301               (ly:music-warning
302                main
303                (ly:format (_ "invalid tremolo repeat count: ~a") times)))
304           ;; Adjust the time of the notes
305           (ly:music-compress r (ly:make-moment 1 children))
306           ;; Adjust the displayed note durations
307           (shift-duration-log r shift dots))
308         r)))
309
310 (define (calc-repeat-slash-count music)
311   "Given the child-list @var{music} in @code{PercentRepeatMusic},
312 calculate the number of slashes based on the durations.  Returns @code{0}
313 if durations in @var{music} vary, allowing slash beats and double-percent
314 beats to be distinguished."
315   (let* ((durs (map duration-of-note
316                     (extract-named-music music '(EventChord NoteEvent
317                                                  RestEvent SkipEvent))))
318          (first-dur (car durs)))
319
320     (if (every (lambda (d) (equal? d first-dur)) durs)
321         (max (- (ly:duration-log first-dur) 2) 1)
322         0)))
323
324 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
325 ;; clusters.
326
327 (define-public (note-to-cluster music)
328   "Replace @code{NoteEvents} by @code{ClusterNoteEvents}."
329   (if (eq? (ly:music-property music 'name) 'NoteEvent)
330       (make-music 'ClusterNoteEvent
331                   'pitch (ly:music-property music 'pitch)
332                   'duration (ly:music-property music 'duration))
333       music))
334
335 (define-public (notes-to-clusters music)
336   (music-map note-to-cluster music))
337
338 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
339 ;; repeats.
340
341 (define-public (unfold-repeats music)
342   "Replace all repeats with unfolded repeats."
343
344   (let ((es (ly:music-property music 'elements))
345         (e (ly:music-property music 'element)))
346
347     (if (music-is-of-type? music 'repeated-music)
348         (let* ((props (ly:music-mutable-properties music))
349                (old-name (ly:music-property music 'name))
350                (flattened (flatten-alist props)))
351           (set! music (apply make-music (cons 'UnfoldedRepeatedMusic
352                                               flattened)))
353
354           (if (and (equal? old-name 'TremoloRepeatedMusic)
355                    (pair? (extract-named-music e '(EventChord NoteEvent))))
356               ;; This works for single-note and multi-note tremolos!
357               (let* ((children (if (music-is-of-type? e 'sequential-music)
358                                    ;; \repeat tremolo n { ... }
359                                    (length (extract-named-music e '(EventChord
360                                                                        NoteEvent)))
361                                    ;; \repeat tremolo n c4
362                                    1))
363                      (times (ly:music-property music 'repeat-count))
364
365                      ;; # of dots is equal to the 1 in bitwise representation (minus 1)!
366                      (dots (1- (logcount (* times children))))
367                      ;; The remaining missing multiplicator to scale the notes by
368                      ;; times * children
369                      (mult (/ (* times children (ash 1 dots)) (1- (ash 2 dots))))
370                      (shift (- (ly:intlog2 (floor mult)))))
371
372                 ;; Adjust the time of the notes
373                 (ly:music-compress music (ly:make-moment children 1))
374                 ;; Adjust the displayed note durations
375                 (shift-duration-log music (- shift) (- dots))))))
376
377     (if (pair? es)
378         (set! (ly:music-property music 'elements)
379               (map unfold-repeats es)))
380     (if (ly:music? e)
381         (set! (ly:music-property music 'element)
382               (unfold-repeats e)))
383     music))
384
385 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
386 ;; property setting music objs.
387
388 (define-public (make-grob-property-set grob gprop val)
389   "Make a @code{Music} expression that sets @var{gprop} to @var{val} in
390 @var{grob}.  Does a pop first, i.e., this is not an override."
391   (make-music 'OverrideProperty
392               'symbol grob
393               'grob-property gprop
394               'grob-value val
395               'pop-first #t))
396
397 (define-public (make-grob-property-override grob gprop val)
398   "Make a @code{Music} expression that overrides @var{gprop} to @var{val}
399 in @var{grob}."
400   (make-music 'OverrideProperty
401               'symbol grob
402               'grob-property gprop
403               'grob-value val))
404
405 (define-public (make-grob-property-revert grob gprop)
406   "Revert the grob property @var{gprop} for @var{grob}."
407   (make-music 'RevertProperty
408               'symbol grob
409               'grob-property gprop))
410
411 (define direction-polyphonic-grobs
412   '(AccidentalSuggestion
413     DotColumn
414     Dots
415     Fingering
416     LaissezVibrerTie
417     LigatureBracket
418     PhrasingSlur
419     RepeatTie
420     Rest
421     Script
422     Slur
423     Stem
424     TextScript
425     Tie
426     TupletBracket
427     TrillSpanner))
428
429 (define-safe-public (make-voice-props-set n)
430   (make-sequential-music
431    (append
432     (map (lambda (x) (make-grob-property-set x 'direction
433                                                   (if (odd? n) -1 1)))
434          direction-polyphonic-grobs)
435     (list
436      (make-property-set 'graceSettings
437                         ;; TODO: take this from voicedGraceSettings or similar.
438                         '((Voice Stem font-size -3)
439                           (Voice Flag font-size -3)
440                           (Voice NoteHead font-size -3)
441                           (Voice TabNoteHead font-size -4)
442                           (Voice Dots font-size -3)
443                           (Voice Stem length-fraction 0.8)
444                           (Voice Stem no-stem-extend #t)
445                           (Voice Beam beam-thickness 0.384)
446                           (Voice Beam length-fraction 0.8)
447                           (Voice Accidental font-size -4)
448                           (Voice AccidentalCautionary font-size -4)
449                           (Voice Script font-size -3)
450                           (Voice Fingering font-size -8)
451                           (Voice StringNumber font-size -8)))
452
453      (make-grob-property-set 'NoteColumn 'horizontal-shift (quotient n 2))
454      (make-grob-property-set 'MultiMeasureRest 'staff-position (if (odd? n) -4 4))))))
455
456 (define-safe-public (make-voice-props-override n)
457   (make-sequential-music
458    (append
459     (map (lambda (x) (make-grob-property-override x 'direction
460                                                   (if (odd? n) -1 1)))
461          direction-polyphonic-grobs)
462     (list
463      (make-property-set 'graceSettings
464                         ;; TODO: take this from voicedGraceSettings or similar.
465                         '((Voice Stem font-size -3)
466                           (Voice Flag font-size -3)
467                           (Voice NoteHead font-size -3)
468                           (Voice TabNoteHead font-size -4)
469                           (Voice Dots font-size -3)
470                           (Voice Stem length-fraction 0.8)
471                           (Voice Stem no-stem-extend #t)
472                           (Voice Beam beam-thickness 0.384)
473                           (Voice Beam length-fraction 0.8)
474                           (Voice Accidental font-size -4)
475                           (Voice AccidentalCautionary font-size -4)
476                           (Voice Script font-size -3)
477                           (Voice Fingering font-size -8)
478                           (Voice StringNumber font-size -8)))
479
480      (make-grob-property-override 'NoteColumn 'horizontal-shift (quotient n 2))
481      (make-grob-property-override 'MultiMeasureRest 'staff-position (if (odd? n) -4 4))))))
482
483 (define-safe-public (make-voice-props-revert)
484   (make-sequential-music
485    (append
486     (map (lambda (x) (make-grob-property-revert x 'direction))
487          direction-polyphonic-grobs)
488     (list (make-property-unset 'graceSettings)
489           (make-grob-property-revert 'NoteColumn 'horizontal-shift)
490           (make-grob-property-revert 'MultiMeasureRest 'staff-position)))))
491
492
493 (define-safe-public (context-spec-music m context #:optional id)
494   "Add \\context CONTEXT = ID to M."
495   (let ((cm (make-music 'ContextSpeccedMusic
496                         'element m
497                         'context-type context)))
498     (if (string? id)
499         (set! (ly:music-property cm 'context-id) id))
500     cm))
501
502 (define-public (descend-to-context m context)
503   "Like @code{context-spec-music}, but only descending."
504   (let ((cm (context-spec-music m context)))
505     (ly:music-set-property! cm 'descend-only #t)
506     cm))
507
508 (define-public (make-non-relative-music mus)
509   (make-music 'UnrelativableMusic
510               'element mus))
511
512 (define-public (make-apply-context func)
513   (make-music 'ApplyContext
514               'procedure func))
515
516 (define-public (make-sequential-music elts)
517   (make-music 'SequentialMusic
518               'elements elts))
519
520 (define-public (make-simultaneous-music elts)
521   (make-music 'SimultaneousMusic
522               'elements elts))
523
524 (define-safe-public (make-event-chord elts)
525   (make-music 'EventChord
526               'elements elts))
527
528 (define-public (make-skip-music dur)
529   (make-music 'SkipMusic
530               'duration dur))
531
532 (define-public (make-grace-music music)
533   (make-music 'GraceMusic
534               'element music))
535
536 ;;;;;;;;;;;;;;;;
537
538 ;; mmrest
539 (define-public (make-multi-measure-rest duration location)
540   (make-music 'MultiMeasureRestMusic
541               'origin location
542               'duration duration))
543
544 (define-public (make-property-set sym val)
545   (make-music 'PropertySet
546               'symbol sym
547               'value val))
548
549 (define-public (make-property-unset sym)
550   (make-music 'PropertyUnset
551               'symbol sym))
552
553 (define-safe-public (make-articulation name)
554   (make-music 'ArticulationEvent
555               'articulation-type name))
556
557 (define-public (make-lyric-event string duration)
558   (make-music 'LyricEvent
559               'duration duration
560               'text string))
561
562 (define-safe-public (make-span-event type span-dir)
563   (make-music type
564               'span-direction span-dir))
565
566 (define-public (override-head-style heads style)
567   "Override style for @var{heads} to @var{style}."
568   (make-sequential-music
569     (if (pair? heads)
570         (map (lambda (h)
571               (make-grob-property-override h 'style style))
572          heads)
573         (list (make-grob-property-override heads 'style style)))))
574
575 (define-public (revert-head-style heads)
576   "Revert style for @var{heads}."
577   (make-sequential-music
578     (if (pair? heads)
579         (map (lambda (h)
580               (make-grob-property-revert h 'style))
581          heads)
582         (list (make-grob-property-revert heads 'style)))))
583
584 (define-public (style-note-heads heads style music)
585  "Set @var{style} for all @var{heads} in @var{music}.  Works both
586 inside of and outside of chord construct."
587   ;; are we inside a <...>?
588   (if (eq? (ly:music-property music 'name) 'NoteEvent)
589       ;; yes -> use a tweak
590       (begin
591         (set! (ly:music-property music 'tweaks)
592               (acons 'style style (ly:music-property music 'tweaks)))
593         music)
594       ;; not in <...>, so use overrides
595       (make-sequential-music
596         (list
597           (override-head-style heads style)
598           music
599           (revert-head-style heads)))))
600
601  (define-public (set-mus-properties! m alist)
602   "Set all of @var{alist} as properties of @var{m}."
603   (if (pair? alist)
604       (begin
605         (set! (ly:music-property m (caar alist)) (cdar alist))
606         (set-mus-properties! m (cdr alist)))))
607
608 (define-public (music-separator? m)
609   "Is @var{m} a separator?"
610   (let ((ts (ly:music-property m 'types)))
611     (memq 'separator ts)))
612
613 ;;; expanding repeat chords
614 (define-public (copy-repeat-chord original-chord repeat-chord duration
615                                   event-types)
616   "Copies all events in @var{event-types} (be sure to include
617 @code{rhythmic-events}) from @var{original-chord} over to
618 @var{repeat-chord} with their articulations filtered as well.  Any
619 duration is replaced with the specified @var{duration}."
620   ;; First remove everything from event-types that can already be
621   ;; found in the repeated chord.  We don't need to look for
622   ;; articulations on individual events since they can't actually get
623   ;; into a repeat chord given its input syntax.
624
625   (define (keep-element? m)
626     (any (lambda (t) (music-is-of-type? m t))
627          event-types))
628   (define origin (ly:music-property repeat-chord 'origin #f))
629   (define (set-origin! l)
630     (if origin
631         (for-each (lambda (m) (set! (ly:music-property m 'origin) origin)) l))
632     l)
633
634   (for-each
635    (lambda (field)
636      (for-each (lambda (e)
637                  (for-each (lambda (x)
638                              (set! event-types (delq x event-types)))
639                            (ly:music-property e 'types)))
640                (ly:music-property repeat-chord field)))
641    '(elements articulations))
642
643   ;; now treat the elements
644   (set! (ly:music-property repeat-chord 'elements)
645         (let ((elts
646                (set-origin! (ly:music-deep-copy
647                              (filter keep-element?
648                                      (ly:music-property original-chord
649                                                         'elements))))))
650           (for-each
651            (lambda (m)
652              (let ((arts (ly:music-property m 'articulations)))
653                (if (pair? arts)
654                    (set! (ly:music-property m 'articulations)
655                          (set-origin! (filter! keep-element? arts))))
656                (if (ly:duration? (ly:music-property m 'duration))
657                    (set! (ly:music-property m 'duration) duration))))
658            elts)
659           (append! elts (ly:music-property repeat-chord 'elements))))
660   (let ((arts (filter keep-element?
661                       (ly:music-property original-chord
662                                          'articulations))))
663     (if (pair? arts)
664         (set! (ly:music-property repeat-chord 'articulations)
665               (append!
666                (set-origin! (ly:music-deep-copy arts))
667                (ly:music-property repeat-chord 'articulations))))))
668
669
670 (define-public (expand-repeat-chords! event-types music)
671   "Walks through @var{music} and fills repeated chords (notable by
672 having a duration in @code{duration}) with the notes from their
673 respective predecessor chord."
674   (let loop ((music music) (last-chord #f))
675     (if (music-is-of-type? music 'event-chord)
676         (let ((chord-repeat (ly:music-property music 'duration)))
677           (cond
678            ((not (ly:duration? chord-repeat))
679             (if (any (lambda (m) (ly:duration?
680                                   (ly:music-property m 'duration)))
681                      (ly:music-property music 'elements))
682                 music
683                 last-chord))
684            (last-chord
685             (set! (ly:music-property music 'duration) '())
686             (copy-repeat-chord last-chord music chord-repeat event-types)
687             music)
688            (else
689             (ly:music-warning music (_ "Bad chord repetition"))
690             #f)))
691         (let ((elt (ly:music-property music 'element)))
692           (fold loop (if (ly:music? elt) (loop elt last-chord) last-chord)
693                 (ly:music-property music 'elements)))))
694   music)
695
696 ;;; splitting chords into voices.
697 (define (voicify-list lst number)
698   "Make a list of Musics.
699
700 voicify-list :: [ [Music ] ] -> number -> [Music]
701 LST is a list music-lists.
702
703 NUMBER is 0-base, i.e., Voice=1 (upstems) has number 0.
704 "
705   (if (null? lst)
706       '()
707       (cons (context-spec-music
708              (make-sequential-music
709               (list (make-voice-props-set number)
710                     (make-simultaneous-music (car lst))))
711              'Bottom  (number->string (1+ number)))
712             (voicify-list (cdr lst) (1+ number)))))
713
714 (define (voicify-chord ch)
715   "Split the parts of a chord into different Voices using separator"
716   (let ((es (ly:music-property ch 'elements)))
717     (set! (ly:music-property  ch 'elements)
718           (voicify-list (split-list-by-separator es music-separator?) 0))
719     ch))
720
721 (define-public (voicify-music m)
722   "Recursively split chords that are separated with @code{\\\\}."
723   (if (not (ly:music? m))
724       (ly:error (_ "music expected: ~S") m))
725   (let ((es (ly:music-property m 'elements))
726         (e (ly:music-property m 'element)))
727
728     (if (pair? es)
729         (set! (ly:music-property m 'elements) (map voicify-music es)))
730     (if (ly:music? e)
731         (set! (ly:music-property m 'element)  (voicify-music e)))
732     (if (and (equal? (ly:music-property m 'name) 'SimultaneousMusic)
733              (reduce (lambda (x y ) (or x y)) #f (map music-separator? es)))
734         (set! m (context-spec-music (voicify-chord m) 'Staff)))
735     m))
736
737 (define-public (empty-music)
738   (make-music 'Music))
739
740 ;; Make a function that checks score element for being of a specific type.
741 (define-public (make-type-checker symbol)
742   (lambda (elt)
743     (grob::has-interface elt symbol)))
744
745 (define-public ((outputproperty-compatibility func sym val) grob g-context ao-context)
746   (if (func grob)
747       (set! (ly:grob-property grob sym) val)))
748
749
750 (define-public ((set-output-property grob-name symbol val)  grob grob-c context)
751   "Usage example:
752 @code{\\applyoutput #(set-output-property 'Clef 'extra-offset '(0 . 1))}"
753   (let ((meta (ly:grob-property grob 'meta)))
754     (if (equal? (assoc-get 'name meta) grob-name)
755         (set! (ly:grob-property grob symbol) val))))
756
757
758 (define-public (skip->rest mus)
759   "Replace @var{mus} by @code{RestEvent} of the same duration if it is a
760 @code{SkipEvent}.  Useful for extracting parts from crowded scores."
761
762   (if  (memq (ly:music-property mus 'name) '(SkipEvent SkipMusic))
763    (make-music 'RestEvent 'duration (ly:music-property mus 'duration))
764    mus))
765
766
767 (define-public (music-has-type music type)
768   (memq type (ly:music-property music 'types)))
769
770 (define-public (music-clone music)
771   (define (alist->args alist acc)
772     (if (null? alist)
773         acc
774         (alist->args (cdr alist)
775                      (cons (caar alist) (cons (cdar alist) acc)))))
776
777   (apply
778    make-music
779    (ly:music-property music 'name)
780    (alist->args (ly:music-mutable-properties music) '())))
781
782 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
783 ;; warn for bare chords at start.
784
785 (define-public (ly:music-message music msg)
786   (let ((ip (ly:music-property music 'origin)))
787     (if (ly:input-location? ip)
788         (ly:input-message ip msg)
789         (ly:message msg))))
790
791 (define-public (ly:music-warning music msg)
792   (let ((ip (ly:music-property music 'origin)))
793     (if (ly:input-location? ip)
794         (ly:input-warning ip msg)
795         (ly:warning msg))))
796
797 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
798 ;;
799 ;; setting stuff for grace context.
800 ;;
801
802 (define (vector-extend v x)
803   "Make a new vector consisting of V, with X added to the end."
804   (let* ((n (vector-length v))
805          (nv (make-vector (+ n 1) '())))
806     (vector-move-left! v 0 n nv 0)
807     (vector-set! nv n x)
808     nv))
809
810 (define (vector-map f v)
811   "Map F over V.  This function returns nothing."
812   (do ((n (vector-length v))
813        (i 0 (+ i 1)))
814       ((>= i n))
815     (f (vector-ref v i))))
816
817 (define (vector-reverse-map f v)
818   "Map F over V, N to 0 order.  This function returns nothing."
819   (do ((i (- (vector-length v) 1) (- i 1)))
820       ((< i 0))
821     (f (vector-ref v i))))
822
823 (define-public (add-grace-property context-name grob sym val)
824   "Set @var{sym}=@var{val} for @var{grob} in @var{context-name}."
825   (define (set-prop context)
826     (let* ((where (ly:context-property-where-defined context 'graceSettings))
827            (current (ly:context-property where 'graceSettings))
828            (new-settings (append current
829                                  (list (list context-name grob sym val)))))
830       (ly:context-set-property! where 'graceSettings new-settings)))
831   (context-spec-music (make-apply-context set-prop) 'Voice))
832
833 (define-public (remove-grace-property context-name grob sym)
834   "Remove all @var{sym} for @var{grob} in @var{context-name}."
835   (define (sym-grob-context? property sym grob context-name)
836     (and (eq? (car property) context-name)
837          (eq? (cadr property) grob)
838          (eq? (caddr property) sym)))
839   (define (delete-prop context)
840     (let* ((where (ly:context-property-where-defined context 'graceSettings))
841            (current (ly:context-property where 'graceSettings))
842            (prop-settings (filter
843                             (lambda(x) (sym-grob-context? x sym grob context-name))
844                             current))
845            (new-settings current))
846       (for-each (lambda(x)
847                  (set! new-settings (delete x new-settings)))
848                prop-settings)
849       (ly:context-set-property! where 'graceSettings new-settings)))
850   (context-spec-music (make-apply-context delete-prop) 'Voice))
851
852
853
854 (defmacro-public def-grace-function (start stop . docstring)
855   "Helper macro for defining grace music"
856   `(define-music-function (parser location music) (ly:music?)
857      ,@docstring
858      (make-music 'GraceMusic
859                  'origin location
860                  'element (make-music 'SequentialMusic
861                                       'elements (list (ly:music-deep-copy ,start)
862                                                       music
863                                                       (ly:music-deep-copy ,stop))))))
864
865 (defmacro-public define-syntax-function (type args signature . body)
866   "Helper macro for `ly:make-music-function'.
867 Syntax:
868   (define-syntax-function result-type? (parser location arg1 arg2 ...) (arg1-type arg2-type ...)
869     ...function body...)
870
871 argX-type can take one of the forms @code{predicate?} for mandatory
872 arguments satisfying the predicate, @code{(predicate?)} for optional
873 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
874 value)}} for optional parameters with a specified default
875 value (evaluated at definition time).  An optional parameter can be
876 omitted in a call only when it can't get confused with a following
877 parameter of different type.
878
879 Predicates with syntactical significance are @code{ly:pitch?},
880 @code{ly:duration?}, @code{ly:music?}, @code{markup?}.  Other
881 predicates require the parameter to be entered as Scheme expression.
882
883 @code{result-type?} can specify a default in the same manner as
884 predicates, to be used in case of a type error in arguments or
885 result."
886
887   (set! signature (map (lambda (pred)
888                          (if (pair? pred)
889                              `(cons ,(car pred)
890                                     ,(and (pair? (cdr pred)) (cadr pred)))
891                              pred))
892                        (cons type signature)))
893   (if (and (pair? body) (pair? (car body)) (eqv? '_i (caar body)))
894       ;; When the music function definition contains a i10n doc string,
895       ;; (_i "doc string"), keep the literal string only
896       (let ((docstring (cadar body))
897             (body (cdr body)))
898         `(ly:make-music-function (list ,@signature)
899                                  (lambda ,args
900                                    ,docstring
901                                    ,@body)))
902       `(ly:make-music-function (list ,@signature)
903                                (lambda ,args
904                                  ,@body))))
905
906 (defmacro-public define-music-function rest
907   "Defining macro returning music functions.
908 Syntax:
909   (define-music-function (parser location arg1 arg2 ...) (arg1-type? arg2-type? ...)
910     ...function body...)
911
912 argX-type can take one of the forms @code{predicate?} for mandatory
913 arguments satisfying the predicate, @code{(predicate?)} for optional
914 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
915 value)}} for optional parameters with a specified default
916 value (evaluated at definition time).  An optional parameter can be
917 omitted in a call only when it can't get confused with a following
918 parameter of different type.
919
920 Predicates with syntactical significance are @code{ly:pitch?},
921 @code{ly:duration?}, @code{ly:music?}, @code{markup?}.  Other
922 predicates require the parameter to be entered as Scheme expression.
923
924 Must return a music expression.  The @code{origin} is automatically
925 set to the @code{location} parameter."
926
927   `(define-syntax-function (ly:music? (make-music 'Music 'void #t)) ,@rest))
928
929
930 (defmacro-public define-scheme-function rest
931   "Defining macro returning Scheme functions.
932 Syntax:
933   (define-scheme-function (parser location arg1 arg2 ...) (arg1-type? arg2-type? ...)
934     ...function body...)
935
936 argX-type can take one of the forms @code{predicate?} for mandatory
937 arguments satisfying the predicate, @code{(predicate?)} for optional
938 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
939 value)}} for optional parameters with a specified default
940 value (evaluated at definition time).  An optional parameter can be
941 omitted in a call only when it can't get confused with a following
942 parameter of different type.
943
944 Predicates with syntactical significance are @code{ly:pitch?},
945 @code{ly:duration?}, @code{ly:music?}, @code{markup?}.  Other
946 predicates require the parameter to be entered as Scheme expression.
947
948 Can return arbitrary expressions.  If a music expression is returned,
949 its @code{origin} is automatically set to the @code{location}
950 parameter."
951
952   `(define-syntax-function scheme? ,@rest))
953
954 (defmacro-public define-void-function rest
955   "This defines a Scheme function like @code{define-scheme-function} with
956 void return value (i.e., what most Guile functions with `unspecified'
957 value return).  Use this when defining functions for executing actions
958 rather than returning values, to keep Lilypond from trying to interpret
959 the return value."
960   `(define-syntax-function (void? *unspecified*) ,@rest *unspecified*))
961
962 (defmacro-public define-event-function rest
963   "Defining macro returning event functions.
964 Syntax:
965   (define-event-function (parser location arg1 arg2 ...) (arg1-type? arg2-type? ...)
966     ...function body...)
967
968 argX-type can take one of the forms @code{predicate?} for mandatory
969 arguments satisfying the predicate, @code{(predicate?)} for optional
970 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
971 value)}} for optional parameters with a specified default
972 value (evaluated at definition time).  An optional parameter can be
973 omitted in a call only when it can't get confused with a following
974 parameter of different type.
975
976 Predicates with syntactical significance are @code{ly:pitch?},
977 @code{ly:duration?}, @code{ly:music?}, @code{markup?}.  Other
978 predicates require the parameter to be entered as Scheme expression.
979
980 Must return an event expression.  The @code{origin} is automatically
981 set to the @code{location} parameter."
982
983   `(define-syntax-function (ly:event? (make-music 'Event 'void #t)) ,@rest))
984
985 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
986
987 (define-public (cue-substitute quote-music)
988   "Must happen after @code{quote-substitute}."
989
990   (if (vector? (ly:music-property quote-music 'quoted-events))
991       (let* ((dir (ly:music-property quote-music 'quoted-voice-direction))
992              (clef (ly:music-property quote-music 'quoted-music-clef #f))
993              (main-voice (case dir ((1) 1) ((-1) 0) (else #f)))
994              (cue-voice (and main-voice (- 1 main-voice)))
995              (main-music (ly:music-property quote-music 'element))
996              (return-value quote-music))
997
998         (if main-voice
999             (set! (ly:music-property quote-music 'element)
1000                   (make-sequential-music
1001                    (list
1002                     (make-voice-props-override main-voice)
1003                     main-music
1004                     (make-voice-props-revert)))))
1005
1006         ;; if we have stem dirs, change both quoted and main music
1007         ;; to have opposite stems.
1008
1009         ;; cannot context-spec Quote-music, since context
1010         ;; for the quotes is determined in the iterator.
1011
1012         (make-sequential-music
1013          (delq! #f
1014                 (list
1015                  (and clef (make-cue-clef-set clef))
1016
1017                  ;; Need to establish CueVoice context even in #CENTER case
1018                  (context-spec-music
1019                   (if cue-voice
1020                       (make-voice-props-override cue-voice)
1021                       (make-music 'Music))
1022                   'CueVoice "cue")
1023                  quote-music
1024                  (and cue-voice
1025                       (context-spec-music
1026                        (make-voice-props-revert) 'CueVoice "cue"))
1027                  (and clef (make-cue-clef-unset))))))
1028       quote-music))
1029
1030 (define-public ((quote-substitute quote-tab) music)
1031   (let* ((quoted-name (ly:music-property music 'quoted-music-name))
1032          (quoted-vector (and (string? quoted-name)
1033                              (hash-ref quote-tab quoted-name #f))))
1034
1035
1036     (if (string? quoted-name)
1037         (if (vector? quoted-vector)
1038             (begin
1039               (set! (ly:music-property music 'quoted-events) quoted-vector)
1040               (set! (ly:music-property music 'iterator-ctor)
1041                     ly:quote-iterator::constructor))
1042             (ly:music-warning music (ly:format (_ "cannot find quoted music: `~S'") quoted-name))))
1043     music))
1044
1045
1046 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1047 ;; switch it on here, so parsing and init isn't checked (too slow!)
1048 ;;
1049 ;; automatic music transformations.
1050
1051 (define (switch-on-debugging m)
1052   (if (defined? 'set-debug-cell-accesses!)
1053       (set-debug-cell-accesses! 15000))
1054   m)
1055
1056 (define (music-check-error music)
1057   (define found #f)
1058   (define (signal m)
1059     (if (and (ly:music? m)
1060              (eq? (ly:music-property m 'error-found) #t))
1061         (set! found #t)))
1062
1063   (for-each signal (ly:music-property music 'elements))
1064   (signal (ly:music-property music 'element))
1065
1066   (if found
1067       (set! (ly:music-property music 'error-found) #t))
1068   music)
1069
1070 (define (precompute-music-length music)
1071   (set! (ly:music-property music 'length)
1072         (ly:music-length music))
1073   music)
1074
1075 (define-public (make-duration-of-length moment)
1076  "Make duration of the given @code{moment} length."
1077  (ly:make-duration 0 0
1078   (ly:moment-main-numerator moment)
1079   (ly:moment-main-denominator moment)))
1080
1081 (define (make-skipped moment bool)
1082  "Depending on BOOL, set or unset skipTypesetting,
1083 then make SkipMusic of the given MOMENT length, and
1084 then revert skipTypesetting."
1085  (make-sequential-music
1086   (list
1087    (context-spec-music (make-property-set 'skipTypesetting bool)
1088     'Score)
1089    (make-music 'SkipMusic 'duration
1090     (make-duration-of-length moment))
1091    (context-spec-music (make-property-set 'skipTypesetting (not bool))
1092     'Score))))
1093
1094 (define (skip-as-needed music parser)
1095   "Replace MUSIC by
1096  << {  \\set skipTypesetting = ##f
1097  LENGTHOF(\\showFirstLength)
1098  \\set skipTypesetting = ##t
1099  LENGTHOF(\\showLastLength) }
1100  MUSIC >>
1101  if appropriate.
1102
1103  When only showFirstLength is set,
1104  the 'length property of the music is
1105  overridden to speed up compiling."
1106   (let*
1107       ((show-last (ly:parser-lookup parser 'showLastLength))
1108        (show-first (ly:parser-lookup parser 'showFirstLength))
1109        (show-last-length (and (ly:music? show-last)
1110                               (ly:music-length show-last)))
1111        (show-first-length (and (ly:music? show-first)
1112                                (ly:music-length show-first)))
1113        (orig-length (ly:music-length music)))
1114
1115     ;;FIXME: if using either showFirst- or showLastLength,
1116     ;; make sure that skipBars is not set.
1117
1118     (cond
1119
1120      ;; both properties may be set.
1121      ((and show-first-length show-last-length)
1122       (let
1123           ((skip-length (ly:moment-sub orig-length show-last-length)))
1124         (make-simultaneous-music
1125          (list
1126           (make-sequential-music
1127            (list
1128             (make-skipped skip-length #t)
1129             ;; let's draw a separator between the beginning and the end
1130             (context-spec-music (make-property-set 'whichBar "||")
1131                                 'Timing)))
1132           (make-skipped show-first-length #f)
1133           music))))
1134
1135      ;; we may only want to print the last length
1136      (show-last-length
1137       (let
1138           ((skip-length (ly:moment-sub orig-length show-last-length)))
1139         (make-simultaneous-music
1140          (list
1141           (make-skipped skip-length #t)
1142           music))))
1143
1144      ;; we may only want to print the beginning; in this case
1145      ;; only the first length will be processed (much faster).
1146      (show-first-length
1147       ;; the first length must not exceed the original length.
1148       (if (ly:moment<? show-first-length orig-length)
1149           (set! (ly:music-property music 'length)
1150                 show-first-length))
1151       music)
1152
1153      (else music))))
1154
1155
1156 (define-public toplevel-music-functions
1157   (list
1158    (lambda (music parser) (expand-repeat-chords!
1159                            (cons 'rhythmic-event
1160                                  (ly:parser-lookup parser '$chord-repeat-events))
1161                            music))
1162    (lambda (music parser) (voicify-music music))
1163    (lambda (x parser) (music-map music-check-error x))
1164    (lambda (x parser) (music-map precompute-music-length x))
1165    (lambda (music parser)
1166
1167      (music-map (quote-substitute (ly:parser-lookup parser 'musicQuotes))  music))
1168
1169    ;; switch-on-debugging
1170    (lambda (x parser) (music-map cue-substitute x))
1171
1172    (lambda (x parser)
1173      (skip-as-needed x parser)
1174    )))
1175
1176 ;;;;;;;;;;
1177 ;;; general purpose music functions
1178
1179 (define (shift-octave pitch octave-shift)
1180   (_i "Add @var{octave-shift} to the octave of @var{pitch}.")
1181   (ly:make-pitch
1182      (+ (ly:pitch-octave pitch) octave-shift)
1183      (ly:pitch-notename pitch)
1184      (ly:pitch-alteration pitch)))
1185
1186
1187 ;;;;;;;;;;;;;;;;;
1188 ;; lyrics
1189
1190 (define (apply-durations lyric-music durations)
1191   (define (apply-duration music)
1192     (if (and (not (equal? (ly:music-length music) ZERO-MOMENT))
1193              (ly:duration?  (ly:music-property music 'duration)))
1194         (begin
1195           (set! (ly:music-property music 'duration) (car durations))
1196           (set! durations (cdr durations)))))
1197
1198   (music-map apply-duration lyric-music))
1199
1200
1201 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1202 ;; accidentals
1203
1204 (define (recent-enough? bar-number alteration-def laziness)
1205   (or (number? alteration-def)
1206       (equal? laziness #t)
1207       (<= bar-number (+ (cadr alteration-def) laziness))))
1208
1209 (define (accidental-invalid? alteration-def)
1210   "Checks an alteration entry for being invalid.
1211
1212 Non-key alterations are invalidated when tying into the next bar or
1213 when there is a clef change, since neither repetition nor cancellation
1214 can be omitted when the same note occurs again.
1215
1216 Returns @code{#f} or the reason for the invalidation, a symbol."
1217   (let* ((def (if (pair? alteration-def)
1218                   (car alteration-def)
1219                   alteration-def)))
1220     (and (symbol? def) def)))
1221
1222 (define (extract-alteration alteration-def)
1223   (cond ((number? alteration-def)
1224          alteration-def)
1225         ((pair? alteration-def)
1226          (car alteration-def))
1227         (else 0)))
1228
1229 (define (check-pitch-against-signature context pitch barnum laziness octaveness)
1230   "Checks the need for an accidental and a @q{restore} accidental against
1231 @code{localKeySignature}.  The @var{laziness} is the number of measures
1232 for which reminder accidentals are used (i.e., if @var{laziness} is zero,
1233 only cancel accidentals in the same measure; if @var{laziness} is three,
1234 we cancel accidentals up to three measures after they first appear.
1235 @var{octaveness} is either @code{'same-octave} or @code{'any-octave} and
1236 specifies whether accidentals should be canceled in different octaves."
1237   (let* ((ignore-octave (cond ((equal? octaveness 'any-octave) #t)
1238                               ((equal? octaveness 'same-octave) #f)
1239                               (else
1240                                (ly:warning (_ "Unknown octaveness type: ~S ") octaveness)
1241                                (ly:warning (_ "Defaulting to 'any-octave."))
1242                                #t)))
1243          (key-sig (ly:context-property context 'keySignature))
1244          (local-key-sig (ly:context-property context 'localKeySignature))
1245          (notename (ly:pitch-notename pitch))
1246          (octave (ly:pitch-octave pitch))
1247          (pitch-handle (cons octave notename))
1248          (need-restore #f)
1249          (need-accidental #f)
1250          (previous-alteration #f)
1251          (from-other-octaves #f)
1252          (from-same-octave (assoc-get pitch-handle local-key-sig))
1253          (from-key-sig (or (assoc-get notename local-key-sig)
1254
1255     ;; If no key signature match is found from localKeySignature, we may have a custom
1256     ;; type with octave-specific entries of the form ((octave . pitch) alteration)
1257     ;; instead of (pitch . alteration).  Since this type cannot coexist with entries in
1258     ;; localKeySignature, try extracting from keySignature instead.
1259                            (assoc-get pitch-handle key-sig))))
1260
1261     ;; loop through localKeySignature to search for a notename match from other octaves
1262     (let loop ((l local-key-sig))
1263       (if (pair? l)
1264           (let ((entry (car l)))
1265             (if (and (pair? (car entry))
1266                      (= (cdar entry) notename))
1267                 (set! from-other-octaves (cdr entry))
1268                 (loop (cdr l))))))
1269
1270     ;; find previous alteration-def for comparison with pitch
1271     (cond
1272      ;; from same octave?
1273      ((and (not ignore-octave)
1274            from-same-octave
1275            (recent-enough? barnum from-same-octave laziness))
1276       (set! previous-alteration from-same-octave))
1277
1278      ;; from any octave?
1279      ((and ignore-octave
1280            from-other-octaves
1281            (recent-enough? barnum from-other-octaves laziness))
1282       (set! previous-alteration from-other-octaves))
1283
1284      ;; not recent enough, extract from key signature/local key signature
1285      (from-key-sig
1286       (set! previous-alteration from-key-sig)))
1287
1288     (if (accidental-invalid? previous-alteration)
1289         (set! need-accidental #t)
1290
1291         (let* ((prev-alt (extract-alteration previous-alteration))
1292                (this-alt (ly:pitch-alteration pitch)))
1293
1294           (if (not (= this-alt prev-alt))
1295               (begin
1296                 (set! need-accidental #t)
1297                 (if (and (not (= this-alt 0))
1298                          (and (< (abs this-alt) (abs prev-alt))
1299                              (> (* prev-alt this-alt) 0)))
1300                     (set! need-restore #t))))))
1301
1302     (cons need-restore need-accidental)))
1303
1304 (define-public ((make-accidental-rule octaveness laziness) context pitch barnum measurepos)
1305   "Create an accidental rule that makes its decision based on the octave of
1306 the note and a laziness value.
1307
1308 @var{octaveness} is either @code{'same-octave} or @code{'any-octave} and
1309 defines whether the rule should respond to accidental changes in other
1310 octaves than the current.  @code{'same-octave} is the normal way to typeset
1311 accidentals -- an accidental is made if the alteration is different from the
1312 last active pitch in the same octave.  @code{'any-octave} looks at the last
1313 active pitch in any octave.
1314
1315 @var{laziness} states over how many bars an accidental should be remembered.
1316 @code{0}@tie{}is the default -- accidental lasts over 0@tie{}bar lines, that
1317 is, to the end of current measure.  A positive integer means that the
1318 accidental lasts over that many bar lines.  @w{@code{-1}} is `forget
1319 immediately', that is, only look at key signature.  @code{#t} is `forever'."
1320
1321   (check-pitch-against-signature context pitch barnum laziness octaveness))
1322
1323 (define (key-entry-notename entry)
1324   "Return the pitch of an @var{entry} in @code{localKeySignature}.
1325 The @samp{car} of the entry is either of the form @code{notename} or
1326 of the form @code{(octave . notename)}.  The latter form is used for special
1327 key signatures or to indicate an explicit accidental.
1328
1329 The @samp{cdr} of the entry is either a rational @code{alter} indicating
1330 a key signature alteration, or of the form
1331 @code{(alter . (barnum . measurepos))} indicating an alteration caused by
1332 an accidental in music."
1333   (if (pair? (car entry))
1334       (cdar entry)
1335       (car entry)))
1336
1337 (define (key-entry-octave entry)
1338   "Return the octave of an entry in @code{localKeySignature}
1339 or @code{#f} if the entry does not have an octave.
1340 See @code{key-entry-notename} for details."
1341   (and (pair? (car entry)) (caar entry)))
1342
1343 (define (key-entry-bar-number entry)
1344   "Return the bar number of an entry in @code{localKeySignature}
1345 or @code {#f} if the entry does not have a bar number.
1346 See @code{key-entry-notename} for details."
1347   (and (pair? (cdr entry)) (caddr entry)))
1348
1349 (define (key-entry-measure-position entry)
1350   "Return the measure position of an entry in @code{localKeySignature}
1351 or @code {#f} if the entry does not have a measure position.
1352 See @code{key-entry-notename} for details."
1353   (and (pair? (cdr entry)) (cdddr entry)))
1354
1355 (define (key-entry-alteration entry)
1356   "Return the alteration of an entry in localKeySignature.
1357
1358 For convenience, returns @code{0} if entry is @code{#f}."
1359   (if entry
1360       (if (number? (cdr entry))
1361           (cdr entry)
1362           (cadr entry))
1363       0))
1364
1365 (define-public (find-pitch-entry keysig pitch accept-global accept-local)
1366   "Return the first entry in @var{keysig} that matches @var{pitch}.
1367 @var{accept-global} states whether key signature entries should be included.
1368 @var{accept-local} states whether local accidentals should be included.
1369 If no matching entry is found, @var{#f} is returned."
1370   (and (pair? keysig)
1371        (let* ((entry (car keysig))
1372               (entryoct (key-entry-octave entry))
1373               (entrynn (key-entry-notename entry))
1374               (nn (ly:pitch-notename pitch)))
1375          (if (and (equal? nn entrynn)
1376                   (or (not entryoct)
1377                       (= entryoct (ly:pitch-octave pitch)))
1378                   (if (key-entry-bar-number entry)
1379                       accept-local
1380                       accept-global))
1381              entry
1382              (find-pitch-entry (cdr keysig) pitch accept-global accept-local)))))
1383
1384 (define-public (neo-modern-accidental-rule context pitch barnum measurepos)
1385   "An accidental rule that typesets an accidental if it differs from the
1386 key signature @emph{and} does not directly follow a note on the same
1387 staff line.  This rule should not be used alone because it does neither
1388 look at bar lines nor different accidentals at the same note name."
1389   (let* ((keysig (ly:context-property context 'localKeySignature))
1390          (entry (find-pitch-entry keysig pitch #t #t)))
1391     (if (not entry)
1392         (cons #f #f)
1393         (let* ((global-entry (find-pitch-entry keysig pitch #t #f))
1394                (key-acc (key-entry-alteration global-entry))
1395                (acc (ly:pitch-alteration pitch))
1396                (entrymp (key-entry-measure-position entry))
1397                (entrybn (key-entry-bar-number entry)))
1398           (cons #f (not (or (equal? acc key-acc)
1399                             (and (equal? entrybn barnum) (equal? entrymp measurepos)))))))))
1400
1401 (define-public (teaching-accidental-rule context pitch barnum measurepos)
1402   "An accidental rule that typesets a cautionary accidental if it is
1403 included in the key signature @emph{and} does not directly follow a note
1404 on the same staff line."
1405   (let* ((keysig (ly:context-property context 'localKeySignature))
1406          (entry (find-pitch-entry keysig pitch #t #t)))
1407     (if (not entry)
1408         (cons #f #f)
1409         (let* ((entrymp (key-entry-measure-position entry))
1410                (entrybn (key-entry-bar-number entry)))
1411           (cons #f (not (and (equal? entrybn barnum) (equal? entrymp measurepos))))))))
1412
1413 (define-public (set-accidentals-properties extra-natural
1414                                            auto-accs auto-cauts
1415                                            context)
1416   (context-spec-music
1417    (make-sequential-music
1418     (append (if (boolean? extra-natural)
1419                 (list (make-property-set 'extraNatural extra-natural))
1420                 '())
1421             (list (make-property-set 'autoAccidentals auto-accs)
1422                   (make-property-set 'autoCautionaries auto-cauts))))
1423    context))
1424
1425 (define-public (set-accidental-style style . rest)
1426   "Set accidental style to @var{style}.  Optionally take a context
1427 argument, e.g. @code{'Staff} or @code{'Voice}.  The context defaults
1428 to @code{Staff}, except for piano styles, which use @code{GrandStaff}
1429 as a context."
1430   (let ((context (if (pair? rest)
1431                      (car rest) 'Staff))
1432         (pcontext (if (pair? rest)
1433                       (car rest) 'GrandStaff)))
1434     (cond
1435       ;; accidentals as they were common in the 18th century.
1436       ((equal? style 'default)
1437        (set-accidentals-properties #t
1438                                    `(Staff ,(make-accidental-rule 'same-octave 0))
1439                                    '()
1440                                    context))
1441       ;; accidentals from one voice do NOT get canceled in other voices
1442       ((equal? style 'voice)
1443        (set-accidentals-properties #t
1444                                    `(Voice ,(make-accidental-rule 'same-octave 0))
1445                                    '()
1446                                    context))
1447       ;; accidentals as suggested by Kurt Stone, Music Notation in the 20th century.
1448       ;; This includes all the default accidentals, but accidentals also needs canceling
1449       ;; in other octaves and in the next measure.
1450       ((equal? style 'modern)
1451        (set-accidentals-properties #f
1452                                    `(Staff ,(make-accidental-rule 'same-octave 0)
1453                                            ,(make-accidental-rule 'any-octave 0)
1454                                            ,(make-accidental-rule 'same-octave 1))
1455                                    '()
1456                                    context))
1457       ;; the accidentals that Stone adds to the old standard as cautionaries
1458       ((equal? style 'modern-cautionary)
1459        (set-accidentals-properties #f
1460                                    `(Staff ,(make-accidental-rule 'same-octave 0))
1461                                    `(Staff ,(make-accidental-rule 'any-octave 0)
1462                                            ,(make-accidental-rule 'same-octave 1))
1463                                    context))
1464       ;; same as modern, but accidentals different from the key signature are always
1465       ;; typeset - unless they directly follow a note of the same pitch.
1466       ((equal? style 'neo-modern)
1467        (set-accidentals-properties #f
1468                                    `(Staff ,(make-accidental-rule 'same-octave 0)
1469                                            ,(make-accidental-rule 'any-octave 0)
1470                                            ,(make-accidental-rule 'same-octave 1)
1471                                            ,neo-modern-accidental-rule)
1472                                    '()
1473                                    context))
1474       ((equal? style 'neo-modern-cautionary)
1475        (set-accidentals-properties #f
1476                                    `(Staff ,(make-accidental-rule 'same-octave 0))
1477                                    `(Staff ,(make-accidental-rule 'any-octave 0)
1478                                            ,(make-accidental-rule 'same-octave 1)
1479                                            ,neo-modern-accidental-rule)
1480                                    context))
1481       ((equal? style 'neo-modern-voice)
1482        (set-accidentals-properties #f
1483                                    `(Voice ,(make-accidental-rule 'same-octave 0)
1484                                            ,(make-accidental-rule 'any-octave 0)
1485                                            ,(make-accidental-rule 'same-octave 1)
1486                                            ,neo-modern-accidental-rule
1487                                      Staff ,(make-accidental-rule 'same-octave 0)
1488                                            ,(make-accidental-rule 'any-octave 0)
1489                                            ,(make-accidental-rule 'same-octave 1)
1490                                       ,neo-modern-accidental-rule)
1491                                    '()
1492                                    context))
1493       ((equal? style 'neo-modern-voice-cautionary)
1494        (set-accidentals-properties #f
1495                                    `(Voice ,(make-accidental-rule 'same-octave 0))
1496                                    `(Voice ,(make-accidental-rule 'any-octave 0)
1497                                            ,(make-accidental-rule 'same-octave 1)
1498                                            ,neo-modern-accidental-rule
1499                                      Staff ,(make-accidental-rule 'same-octave 0)
1500                                            ,(make-accidental-rule 'any-octave 0)
1501                                            ,(make-accidental-rule 'same-octave 1)
1502                                            ,neo-modern-accidental-rule)
1503                                    context))
1504       ;; Accidentals as they were common in dodecaphonic music with no tonality.
1505       ;; Each note gets one accidental.
1506       ((equal? style 'dodecaphonic)
1507        (set-accidentals-properties #f
1508                                    `(Staff ,(lambda (c p bn mp) '(#f . #t)))
1509                                    '()
1510                                    context))
1511       ;; Multivoice accidentals to be read both by musicians playing one voice
1512       ;; and musicians playing all voices.
1513       ;; Accidentals are typeset for each voice, but they ARE canceled across voices.
1514       ((equal? style 'modern-voice)
1515        (set-accidentals-properties  #f
1516                                     `(Voice ,(make-accidental-rule 'same-octave 0)
1517                                             ,(make-accidental-rule 'any-octave 0)
1518                                             ,(make-accidental-rule 'same-octave 1)
1519                                       Staff ,(make-accidental-rule 'same-octave 0)
1520                                             ,(make-accidental-rule 'any-octave 0)
1521                                             ,(make-accidental-rule 'same-octave 1))
1522                                     '()
1523                                     context))
1524       ;; same as modernVoiceAccidental eccept that all special accidentals are typeset
1525       ;; as cautionaries
1526       ((equal? style 'modern-voice-cautionary)
1527        (set-accidentals-properties #f
1528                                    `(Voice ,(make-accidental-rule 'same-octave 0))
1529                                    `(Voice ,(make-accidental-rule 'any-octave 0)
1530                                            ,(make-accidental-rule 'same-octave 1)
1531                                      Staff ,(make-accidental-rule 'same-octave 0)
1532                                            ,(make-accidental-rule 'any-octave 0)
1533                                            ,(make-accidental-rule 'same-octave 1))
1534                                    context))
1535       ;; stone's suggestions for accidentals on grand staff.
1536       ;; Accidentals are canceled across the staves in the same grand staff as well
1537       ((equal? style 'piano)
1538        (set-accidentals-properties #f
1539                                    `(Staff ,(make-accidental-rule 'same-octave 0)
1540                                            ,(make-accidental-rule 'any-octave 0)
1541                                            ,(make-accidental-rule 'same-octave 1)
1542                                      GrandStaff
1543                                            ,(make-accidental-rule 'any-octave 0)
1544                                            ,(make-accidental-rule 'same-octave 1))
1545                                    '()
1546                                    pcontext))
1547       ((equal? style 'piano-cautionary)
1548        (set-accidentals-properties #f
1549                                    `(Staff ,(make-accidental-rule 'same-octave 0))
1550                                    `(Staff ,(make-accidental-rule 'any-octave 0)
1551                                            ,(make-accidental-rule 'same-octave 1)
1552                                      GrandStaff
1553                                            ,(make-accidental-rule 'any-octave 0)
1554                                            ,(make-accidental-rule 'same-octave 1))
1555                                    pcontext))
1556
1557       ;; same as modern, but cautionary accidentals are printed for all sharp or flat
1558       ;; tones specified by the key signature.
1559        ((equal? style 'teaching)
1560        (set-accidentals-properties #f
1561                                     `(Staff ,(make-accidental-rule 'same-octave 0))
1562                                     `(Staff ,(make-accidental-rule 'same-octave 1)
1563                                            ,teaching-accidental-rule)
1564                                    context))
1565
1566       ;; do not set localKeySignature when a note alterated differently from
1567       ;; localKeySignature is found.
1568       ;; Causes accidentals to be printed at every note instead of
1569       ;; remembered for the duration of a measure.
1570       ;; accidentals not being remembered, causing accidentals always to
1571       ;; be typeset relative to the time signature
1572       ((equal? style 'forget)
1573        (set-accidentals-properties '()
1574                                    `(Staff ,(make-accidental-rule 'same-octave -1))
1575                                    '()
1576                                    context))
1577       ;; Do not reset the key at the start of a measure.  Accidentals will be
1578       ;; printed only once and are in effect until overridden, possibly many
1579       ;; measures later.
1580       ((equal? style 'no-reset)
1581        (set-accidentals-properties '()
1582                                    `(Staff ,(make-accidental-rule 'same-octave #t))
1583                                    '()
1584                                    context))
1585       (else
1586        (ly:warning (_ "unknown accidental style: ~S") style)
1587        (make-sequential-music '())))))
1588
1589 (define-public (invalidate-alterations context)
1590   "Invalidate alterations in @var{context}.
1591
1592 Elements of @code{'localKeySignature} corresponding to local
1593 alterations of the key signature have the form
1594 @code{'((octave . notename) . (alter barnum . measurepos))}.
1595 Replace them with a version where @code{alter} is set to @code{'clef}
1596 to force a repetition of accidentals.
1597
1598 Entries that conform with the current key signature are not invalidated."
1599   (let* ((keysig (ly:context-property context 'keySignature)))
1600     (set! (ly:context-property context 'localKeySignature)
1601           (map-in-order
1602            (lambda (entry)
1603              (let* ((localalt (key-entry-alteration entry)))
1604                (if (or (accidental-invalid? localalt)
1605                        (not (key-entry-bar-number entry))
1606                        (= localalt
1607                           (key-entry-alteration
1608                            (find-pitch-entry
1609                             keysig
1610                             (ly:make-pitch (key-entry-octave entry)
1611                                            (key-entry-notename entry)
1612                                            0)
1613                             #t #t))))
1614                    entry
1615                    (cons (car entry) (cons 'clef (cddr entry))))))
1616            (ly:context-property context 'localKeySignature)))))
1617
1618 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1619
1620 (define-public (skip-of-length mus)
1621   "Create a skip of exactly the same length as @var{mus}."
1622   (let* ((skip
1623           (make-music
1624            'SkipEvent
1625            'duration (ly:make-duration 0 0))))
1626
1627     (make-event-chord (list (ly:music-compress skip (ly:music-length mus))))))
1628
1629 (define-public (mmrest-of-length mus)
1630   "Create a multi-measure rest of exactly the same length as @var{mus}."
1631
1632   (let* ((skip
1633           (make-multi-measure-rest
1634            (ly:make-duration 0 0) '())))
1635     (ly:music-compress skip (ly:music-length mus))
1636     skip))
1637
1638 (define-public (pitch-of-note event-chord)
1639   (let ((evs (filter (lambda (x)
1640                        (music-has-type x 'note-event))
1641                      (ly:music-property event-chord 'elements))))
1642
1643     (and (pair? evs)
1644          (ly:music-property (car evs) 'pitch))))
1645
1646 (define-public (duration-of-note event-chord)
1647   (cond
1648    ((pair? event-chord)
1649     (or (duration-of-note (car event-chord))
1650         (duration-of-note (cdr event-chord))))
1651    ((ly:music? event-chord)
1652     (let ((dur (ly:music-property event-chord 'duration)))
1653       (if (ly:duration? dur)
1654           dur
1655           (duration-of-note (ly:music-property event-chord 'elements)))))
1656    (else #f)))
1657
1658 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1659
1660 (define-public (map-some-music map? music)
1661   "Walk through @var{music}, transform all elements calling @var{map?}
1662 and only recurse if this returns @code{#f}."
1663   (let loop ((music music))
1664     (or (map? music)
1665         (let ((elt (ly:music-property music 'element))
1666               (elts (ly:music-property music 'elements))
1667               (arts (ly:music-property music 'articulations)))
1668           (if (ly:music? elt)
1669               (set! (ly:music-property music 'element)
1670                     (loop elt)))
1671           (if (pair? elts)
1672               (set! (ly:music-property music 'elements)
1673                     (map loop elts)))
1674           (if (pair? arts)
1675               (set! (ly:music-property music 'articulations)
1676                     (map loop arts)))
1677           music))))
1678
1679 (define-public (for-some-music stop? music)
1680   "Walk through @var{music}, process all elements calling @var{stop?}
1681 and only recurse if this returns @code{#f}."
1682   (let loop ((music music))
1683     (if (not (stop? music))
1684         (let ((elt (ly:music-property music 'element)))
1685           (if (ly:music? elt)
1686               (loop elt))
1687           (for-each loop (ly:music-property music 'elements))
1688           (for-each loop (ly:music-property music 'articulations))))))
1689
1690 (define-public (fold-some-music pred? proc init music)
1691   "This works recursively on music like @code{fold} does on a list,
1692 calling @samp{(@var{pred?} music)} on every music element.  If
1693 @code{#f} is returned for an element, it is processed recursively
1694 with the same initial value of @samp{previous}, otherwise
1695 @samp{(@var{proc} music previous)} replaces @samp{previous}
1696 and no recursion happens.
1697 The top @var{music} is processed using @var{init} for @samp{previous}."
1698   (let loop ((music music) (previous init))
1699     (if (pred? music)
1700         (proc music previous)
1701         (fold loop
1702               (fold loop
1703                     (let ((elt (ly:music-property music 'element)))
1704                       (if (null? elt)
1705                           previous
1706                           (loop elt previous)))
1707                     (ly:music-property music 'elements))
1708               (ly:music-property music 'articulations)))))
1709
1710 (define-public (extract-music music pred?)
1711   "Return a flat list of all music matching @var{pred?} inside of
1712 @var{music}, not recursing into matches themselves."
1713   (reverse! (fold-some-music pred? cons '() music)))
1714
1715 (define-public (extract-named-music music music-name)
1716   "Return a flat list of all music named @var{music-name} (either a
1717 single event symbol or a list of alternatives) inside of @var{music},
1718 not recursing into matches themselves."
1719   (extract-music
1720    music
1721    (if (cheap-list? music-name)
1722        (lambda (m) (memq (ly:music-property m 'name) music-name))
1723        (lambda (m) (eq? (ly:music-property m 'name) music-name)))))
1724
1725 (define-public (extract-typed-music music type)
1726   "Return a flat list of all music with @var{type} (either a single
1727 type symbol or a list of alternatives) inside of @var{music}, not
1728 recursing into matches themselves."
1729   (extract-music
1730    music
1731    (if (cheap-list? type)
1732        (lambda (m)
1733          (any (lambda (t) (music-is-of-type? m t)) type))
1734        (lambda (m) (music-is-of-type? m type)))))
1735
1736 (define*-public (event-chord-wrap! music #:optional parser)
1737   "Wrap isolated rhythmic events and non-postevent events in
1738 @var{music} inside of an @code{EventChord}.  If the optional
1739 @var{parser} argument is given, chord repeats @samp{q} are expanded
1740 using the default settings.  Otherwise, you need to cater for them
1741 yourself."
1742   (map-some-music
1743    (lambda (m)
1744      (cond ((music-is-of-type? m 'event-chord)
1745             (if (pair? (ly:music-property m 'articulations))
1746                 (begin
1747                   (set! (ly:music-property m 'elements)
1748                         (append (ly:music-property m 'elements)
1749                                 (ly:music-property m 'articulations)))
1750                   (set! (ly:music-property m 'articulations) '())))
1751             m)
1752            ((music-is-of-type? m 'rhythmic-event)
1753             (let ((arts (ly:music-property m 'articulations)))
1754               (if (pair? arts)
1755                   (set! (ly:music-property m 'articulations) '()))
1756               (make-event-chord (cons m arts))))
1757            (else #f)))
1758    (if parser
1759        (expand-repeat-chords!
1760         (cons 'rhythmic-event
1761               (ly:parser-lookup parser '$chord-repeat-events))
1762         music)
1763        music)))
1764
1765 (define-public (event-chord-notes event-chord)
1766   "Return a list of all notes from @var{event-chord}."
1767   (filter
1768     (lambda (m) (eq? 'NoteEvent (ly:music-property m 'name)))
1769     (ly:music-property event-chord 'elements)))
1770
1771 (define-public (event-chord-pitches event-chord)
1772   "Return a list of all pitches from @var{event-chord}."
1773   (map (lambda (x) (ly:music-property x 'pitch))
1774        (event-chord-notes event-chord)))
1775
1776 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1777 ; The following functions are all associated with the crossStaff
1778 ;  function
1779
1780 (define (close-enough? x y)
1781   "Values are close enough to ignore the difference"
1782    (< (abs (- x y)) 0.0001))
1783
1784 (define (extent-combine extents)
1785   "Combine a list of extents"
1786   (if (pair? (cdr extents))
1787       (interval-union (car extents) (extent-combine (cdr extents)))
1788       (car extents)))
1789
1790 (define ((stem-connectable? ref root) stem)
1791   "Check if the stem is connectable to the root"
1792   ; The root is always connectable to itself
1793   (or (eq? root stem)
1794       (and
1795       ; Horizontal positions of the stems must be almost the same
1796         (close-enough? (car (ly:grob-extent root ref X))
1797           (car (ly:grob-extent stem ref X)))
1798         ; The stem must be in the direction away from the root's notehead
1799         (positive? (* (ly:grob-property root 'direction)
1800                      (- (car (ly:grob-extent stem ref Y))
1801                        (car (ly:grob-extent root ref Y))))))))
1802
1803 (define (stem-span-stencil span)
1804   "Connect stems if we have at least one stem connectable to the root"
1805   (let* ((system (ly:grob-system span))
1806           (root (ly:grob-parent span X))
1807           (stems (filter (stem-connectable? system root)
1808                          (ly:grob-object span 'stems))))
1809      (if (<= 2 (length stems))
1810          (let* ((yextents (map (lambda (st)
1811                                  (ly:grob-extent st system Y)) stems))
1812                 (yextent (extent-combine yextents))
1813                 (layout (ly:grob-layout root))
1814                 (blot (ly:output-def-lookup layout 'blot-diameter)))
1815            ; Hide spanned stems
1816            (map (lambda (st)
1817                   (set! (ly:grob-property st 'transparent) #t))
1818              stems)
1819            ; Draw a nice looking stem with rounded corners
1820            (ly:round-filled-box (ly:grob-extent root root X) yextent blot))
1821          ; Nothing to connect, don't draw the span
1822          #f)))
1823
1824 (define ((make-stem-span! stems trans) root)
1825   "Create a stem span as a child of the cross-staff stem (the root)"
1826   (let ((span (ly:engraver-make-grob trans 'Stem '())))
1827     (ly:grob-set-parent! span X root)
1828     (set! (ly:grob-object span 'stems) stems)
1829     ; Suppress positioning, the stem code is confused by this weird stem
1830     (set! (ly:grob-property span 'X-offset) 0)
1831     (set! (ly:grob-property span 'stencil) stem-span-stencil)))
1832
1833 (define-public (cross-staff-connect stem)
1834   "Set cross-staff property of the stem to this function to connect it to
1835 other stems automatically"
1836    #t)
1837
1838 (define (stem-is-root? stem)
1839   "Check if automatic connecting of the stem was requested.  Stems connected
1840 to cross-staff beams are cross-staff, but they should not be connected to
1841 other stems just because of that."
1842   (eq? cross-staff-connect (ly:grob-property-data stem 'cross-staff)))
1843
1844 (define (make-stem-spans! ctx stems trans)
1845   "Create stem spans for cross-staff stems"
1846   ; Cannot do extensive checks here, just make sure there are at least
1847   ; two stems at this musical moment
1848   (if (<= 2 (length stems))
1849     (let ((roots (filter stem-is-root? stems)))
1850     (map (make-stem-span! stems trans) roots))))
1851
1852 (define-public (Span_stem_engraver ctx)
1853   "Connect cross-staff stems to the stems above in the system"
1854   (let ((stems '()))
1855     (make-engraver
1856       ; Record all stems for the given moment
1857       (acknowledgers
1858         ((stem-interface trans grob source)
1859         (set! stems (cons grob stems))))
1860       ; Process stems and reset the stem list to empty
1861       ((process-acknowledged trans)
1862         (make-stem-spans! ctx stems trans)
1863         (set! stems '())))))
1864
1865 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1866 ;; The following is used by the alterBroken function.
1867
1868 (define-public ((value-for-spanner-piece arg) grob)
1869   "Associate a piece of broken spanner @var{grob} with an element
1870 of list @var{arg}."
1871   (let* ((orig (ly:grob-original grob))
1872          (siblings (ly:spanner-broken-into orig)))
1873
1874    (define (helper sibs arg)
1875      (if (null? arg)
1876          arg
1877          (if (eq? (car sibs) grob)
1878              (car arg)
1879              (helper (cdr sibs) (cdr arg)))))
1880
1881    (if (>= (length siblings) 2)
1882        (helper siblings arg)
1883        (car arg))))