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