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