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