]> git.donarmstrong.com Git - lilypond.git/blob - scm/music-functions.scm
Issue 1471: Invalidate alterations upon key change rather than forgetting them.
[lilypond.git] / scm / music-functions.scm
1 ;;;; This file is part of LilyPond, the GNU music typesetter.
2 ;;;;
3 ;;;; Copyright (C) 1998--2011 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 ;; (use-modules (ice-9 optargs))
20
21 ;;; ly:music-property with setter
22 ;;; (ly:music-property my-music 'elements)
23 ;;;   ==> the 'elements property
24 ;;; (set! (ly:music-property my-music 'elements) value)
25 ;;;   ==> set the 'elements property and return it
26 (define-public ly:music-property
27   (make-procedure-with-setter ly:music-property
28                               ly:music-set-property!))
29
30 (define-safe-public (music-is-of-type? mus type)
31   "Does @code{mus} belong to the music class @code{type}?"
32   (memq type (ly:music-property mus 'types)))
33
34 ;; TODO move this
35 (define-public ly:grob-property
36   (make-procedure-with-setter ly:grob-property
37                               ly:grob-set-property!))
38
39 (define-public ly:grob-object
40   (make-procedure-with-setter ly:grob-object
41                               ly:grob-set-object!))
42
43 (define-public ly:grob-parent
44   (make-procedure-with-setter ly:grob-parent
45                               ly:grob-set-parent!))
46
47 (define-public ly:prob-property
48   (make-procedure-with-setter ly:prob-property
49                               ly:prob-set-property!))
50
51 (define-public ly:context-property
52   (make-procedure-with-setter ly:context-property
53                               ly:context-set-property!))
54
55 (define-public (music-map function music)
56   "Apply @var{function} to @var{music} and all of the music it contains.
57
58 First it recurses over the children, then the function is applied to
59 @var{music}."
60   (let ((es (ly:music-property music 'elements))
61         (e (ly:music-property music 'element)))
62     (set! (ly:music-property music 'elements)
63           (map (lambda (y) (music-map function y)) es))
64     (if (ly:music? e)
65         (set! (ly:music-property music 'element)
66               (music-map function  e)))
67     (function music)))
68
69 (define-public (music-filter pred? music)
70   "Filter out music expressions that do not satisfy @var{pred?}."
71
72   (define (inner-music-filter pred? music)
73     "Recursive function."
74     (let* ((es (ly:music-property music 'elements))
75            (e (ly:music-property music 'element))
76            (as (ly:music-property music 'articulations))
77            (filtered-as (filter ly:music? (map (lambda (y) (inner-music-filter pred? y)) as)))
78            (filtered-e (if (ly:music? e)
79                            (inner-music-filter pred? e)
80                            e))
81            (filtered-es (filter ly:music? (map (lambda (y) (inner-music-filter pred? y)) es))))
82       (set! (ly:music-property music 'element) filtered-e)
83       (set! (ly:music-property music 'elements) filtered-es)
84       (set! (ly:music-property music 'articulations) filtered-as)
85       ;; if filtering emptied the expression, we remove it completely.
86       (if (or (not (pred? music))
87               (and (eq? filtered-es '()) (not (ly:music? e))
88                    (or (not (eq? es '()))
89                        (ly:music? e))))
90           (set! music '()))
91       music))
92
93   (set! music (inner-music-filter pred? music))
94   (if (ly:music? music)
95       music
96       (make-music 'Music)))       ;must return music.
97
98 (define-public (display-music music)
99   "Display music, not done with @code{music-map} for clarity of
100 presentation."
101
102   (display music)
103   (display ": { ")
104   (let ((es (ly:music-property music 'elements))
105         (e (ly:music-property music 'element)))
106     (display (ly:music-mutable-properties music))
107     (if (pair? es)
108         (begin (display "\nElements: {\n")
109                (map display-music es)
110                (display "}\n")))
111     (if (ly:music? e)
112         (begin
113           (display "\nChild:")
114           (display-music e))))
115   (display " }\n")
116   music)
117
118 ;;;
119 ;;; A scheme music pretty printer
120 ;;;
121 (define (markup-expression->make-markup markup-expression)
122   "Transform `markup-expression' into an equivalent, hopefuly readable, scheme expression.
123 For instance,
124   \\markup \\bold \\italic hello
125 ==>
126   (markup #:line (#:bold (#:italic (#:simple \"hello\"))))"
127   (define (proc->command-keyword proc)
128     "Return a keyword, eg. `#:bold', from the `proc' function, eg. #<procedure bold-markup (layout props arg)>"
129     (let ((cmd-markup (symbol->string (procedure-name proc))))
130       (symbol->keyword (string->symbol (substring cmd-markup 0 (- (string-length cmd-markup)
131                                                                   (string-length "-markup")))))))
132   (define (transform-arg arg)
133     (cond ((and (pair? arg) (markup? (car arg))) ;; a markup list
134            (apply append (map inner-markup->make-markup arg)))
135           ((and (not (string? arg)) (markup? arg)) ;; a markup
136            (inner-markup->make-markup arg))
137           (else                                  ;; scheme arg
138            (music->make-music arg))))
139   (define (inner-markup->make-markup mrkup)
140     (if (string? mrkup)
141         `(#:simple ,mrkup)
142         (let ((cmd (proc->command-keyword (car mrkup)))
143               (args (map transform-arg (cdr mrkup))))
144           `(,cmd ,@args))))
145   ;; body:
146   (if (string? markup-expression)
147       markup-expression
148       `(markup ,@(inner-markup->make-markup markup-expression))))
149
150 (define-public (music->make-music obj)
151   "Generate an expression that, once evaluated, may return an object
152 equivalent to @var{obj}, that is, for a music expression, a
153 @code{(make-music ...)} form."
154   (cond (;; markup expression
155          (markup? obj)
156          (markup-expression->make-markup obj))
157         (;; music expression
158          (ly:music? obj)
159          `(make-music
160            ',(ly:music-property obj 'name)
161            ,@(apply append (map (lambda (prop)
162                                   `(',(car prop)
163                                     ,(music->make-music (cdr prop))))
164                                 (remove (lambda (prop)
165                                           (eqv? (car prop) 'origin))
166                                         (ly:music-mutable-properties obj))))))
167         (;; moment
168          (ly:moment? obj)
169          `(ly:make-moment ,(ly:moment-main-numerator obj)
170                           ,(ly:moment-main-denominator obj)
171                           ,(ly:moment-grace-numerator obj)
172                           ,(ly:moment-grace-denominator obj)))
173         (;; note duration
174          (ly:duration? obj)
175          `(ly:make-duration ,(ly:duration-log obj)
176                             ,(ly:duration-dot-count obj)
177                             ,(car (ly:duration-factor obj))
178                             ,(cdr (ly:duration-factor obj))))
179         (;; note pitch
180          (ly:pitch? obj)
181          `(ly:make-pitch ,(ly:pitch-octave obj)
182                          ,(ly:pitch-notename obj)
183                          ,(ly:pitch-alteration obj)))
184         (;; scheme procedure
185          (procedure? obj)
186          (or (procedure-name obj) obj))
187         (;; a symbol (avoid having an unquoted symbol)
188          (symbol? obj)
189          `',obj)
190         (;; an empty list (avoid having an unquoted empty list)
191          (null? obj)
192          `'())
193         (;; a proper list
194          (list? obj)
195          `(list ,@(map music->make-music obj)))
196         (;; a pair
197          (pair? obj)
198          `(cons ,(music->make-music (car obj))
199                 ,(music->make-music (cdr obj))))
200         (else
201          obj)))
202
203 (use-modules (ice-9 pretty-print))
204 (define*-public (display-scheme-music obj #:optional (port (current-output-port)))
205   "Displays `obj', typically a music expression, in a friendly fashion,
206 which often can be read back in order to generate an equivalent expression.
207
208 Returns `obj'.
209 "
210   (pretty-print (music->make-music obj) port)
211   (newline)
212   obj)
213
214 ;;;
215 ;;; Scheme music expression --> Lily-syntax-using string translator
216 ;;;
217 (use-modules (srfi srfi-39)
218              (scm display-lily))
219
220 (define*-public (display-lily-music expr parser #:key force-duration)
221   "Display the music expression using LilyPond syntax"
222   (memoize-clef-names supported-clefs)
223   (parameterize ((*indent* 0)
224                  (*previous-duration* (ly:make-duration 2))
225                  (*force-duration* force-duration))
226     (display (music->lily-string expr parser))
227     (newline)))
228
229 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
230
231 (define-public (shift-one-duration-log music shift dot)
232   "Add @var{shift} to @code{duration-log} of @code{'duration} in
233 @var{music} and optionally @var{dot} to any note encountered.  This
234 scales the music up by a factor `2^@var{shift} * (2 - (1/2)^@var{dot})'."
235   (let ((d (ly:music-property music 'duration)))
236     (if (ly:duration? d)
237         (let* ((cp (ly:duration-factor d))
238                (nd (ly:make-duration (+ shift (ly:duration-log d))
239                                      (+ dot (ly:duration-dot-count d))
240                                      (car cp)
241                                      (cdr cp))))
242           (set! (ly:music-property music 'duration) nd)))
243     music))
244
245 (define-public (shift-duration-log music shift dot)
246   (music-map (lambda (x) (shift-one-duration-log x shift dot))
247              music))
248
249 (define-public (make-repeat name times main alts)
250   "Create a repeat music expression, with all properties initialized
251 properly."
252   (define (first-note-duration music)
253     "Finds the duration of the first NoteEvent by searching depth-first
254 through MUSIC."
255     (if (memq 'note-event (ly:music-property music 'types))
256         (ly:music-property music 'duration)
257         (let loop ((elts (if (ly:music? (ly:music-property music 'element))
258                              (list (ly:music-property music 'element))
259                              (ly:music-property music 'elements))))
260           (and (pair? elts)
261                (let ((dur (first-note-duration (car elts))))
262                  (if (ly:duration? dur)
263                      dur
264                      (loop (cdr elts))))))))
265
266   (let ((talts (if (< times (length alts))
267                    (begin
268                      (ly:warning (_ "More alternatives than repeats.  Junking excess alternatives"))
269                      (take alts times))
270                    alts))
271         (r (make-repeated-music name)))
272     (set! (ly:music-property r 'element) main)
273     (set! (ly:music-property r 'repeat-count) (max times 1))
274     (set! (ly:music-property r 'elements) talts)
275     (if (and (equal? name "tremolo")
276              (or (pair? (ly:music-property main 'elements))
277                  (ly:music? (ly:music-property main 'element))))
278         ;; This works for single-note and multi-note tremolos!
279         (let* ((children (if (music-is-of-type? main 'sequential-music)
280                              ;; \repeat tremolo n { ... }
281                              (length (ly:music-property main 'elements))
282                              ;; \repeat tremolo n c4
283                              1))
284                ;; # of dots is equal to the 1 in bitwise representation (minus 1)!
285                (dots (1- (logcount (* times children))))
286                ;; The remaining missing multiplicator to scale the notes by
287                ;; times * children
288                (mult (/ (* times children (ash 1 dots)) (1- (ash 2 dots))))
289                (shift (- (ly:intlog2 (floor mult))))
290                (note-duration (first-note-duration r))
291                (duration-log (if (ly:duration? note-duration)
292                                  (ly:duration-log note-duration)
293                                  1))
294                (tremolo-type (ash 1 duration-log)))
295           (set! (ly:music-property r 'tremolo-type) tremolo-type)
296           (if (not (integer?  mult))
297               (ly:warning (_ "invalid tremolo repeat count: ~a") times))
298           ;; Adjust the time of the notes
299           (ly:music-compress r (ly:make-moment 1 children))
300           ;; Adjust the displayed note durations
301           (shift-duration-log r shift dots))
302         r)))
303
304 (define (calc-repeat-slash-count music)
305   "Given the child-list @var{music} in @code{PercentRepeatMusic},
306 calculate the number of slashes based on the durations.  Returns @code{0}
307 if durations in in @var{music} vary, allowing slash beats and double-percent
308 beats to be distinguished."
309   (let* ((durs (map (lambda (elt)
310                       (duration-of-note elt))
311                     (extract-named-music music 'EventChord)))
312          (first-dur (car durs)))
313
314     (if (every (lambda (d) (equal? d first-dur)) durs)
315         (max (- (ly:duration-log first-dur) 2) 1)
316         0)))
317
318 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
319 ;; clusters.
320
321 (define-public (note-to-cluster music)
322   "Replace @code{NoteEvents} by @code{ClusterNoteEvents}."
323   (if (eq? (ly:music-property music 'name) 'NoteEvent)
324       (make-music 'ClusterNoteEvent
325                   'pitch (ly:music-property music 'pitch)
326                   'duration (ly:music-property music 'duration))
327       music))
328
329 (define-public (notes-to-clusters music)
330   (music-map note-to-cluster music))
331
332 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
333 ;; repeats.
334
335 (define-public (unfold-repeats music)
336   "Replace all repeats with unfolded repeats."
337
338   (let ((es (ly:music-property music 'elements))
339         (e (ly:music-property music 'element)))
340
341     (if (memq 'repeated-music (ly:music-property music 'types))
342         (let* ((props (ly:music-mutable-properties music))
343                (old-name (ly:music-property music 'name))
344                (flattened (flatten-alist props)))
345           (set! music (apply make-music (cons 'UnfoldedRepeatedMusic
346                                               flattened)))
347
348           (if (equal? old-name 'TremoloRepeatedMusic)
349               (let* ((seq-arg? (memq 'sequential-music
350                                      (ly:music-property e 'types)))
351                      (count (ly:music-property music 'repeat-count))
352                      (dot-shift (if (= 0 (remainder count 3))
353                                     -1 0))
354                      (child-count (if seq-arg?
355                                       (length (ly:music-property e 'elements))
356                                       0)))
357
358                 (if (= 0 -1)
359                     (set! count (* 2 (quotient count 3))))
360
361                 (shift-duration-log music (+ (if (= 2 child-count)
362                                                  1 0)
363                                              (ly:intlog2 count)) dot-shift)
364
365                 (if seq-arg?
366                     (ly:music-compress e (ly:make-moment child-count 1)))))))
367
368     (if (pair? es)
369         (set! (ly:music-property music 'elements)
370               (map unfold-repeats es)))
371     (if (ly:music? e)
372         (set! (ly:music-property music 'element)
373               (unfold-repeats e)))
374     music))
375
376 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
377 ;; property setting music objs.
378
379 (define-public (make-grob-property-set grob gprop val)
380   "Make a @code{Music} expression that sets @var{gprop} to @var{val} in
381 @var{grob}.  Does a pop first, i.e., this is not an override."
382   (make-music 'OverrideProperty
383               'symbol grob
384               'grob-property gprop
385               'grob-value val
386               'pop-first #t))
387
388 (define-public (make-grob-property-override grob gprop val)
389   "Make a @code{Music} expression that overrides @var{gprop} to @var{val}
390 in @var{grob}."
391   (make-music 'OverrideProperty
392               'symbol grob
393               'grob-property gprop
394               'grob-value val))
395
396 (define-public (make-grob-property-revert grob gprop)
397   "Revert the grob property @var{gprop} for @var{grob}."
398   (make-music 'RevertProperty
399               'symbol grob
400               'grob-property gprop))
401
402 (define direction-polyphonic-grobs
403   '(DotColumn
404     Dots
405     Fingering
406     LaissezVibrerTie
407     PhrasingSlur
408     RepeatTie
409     Rest
410     Script
411     Slur
412     Stem
413     TextScript
414     Tie))
415
416 (define-safe-public (make-voice-props-set n)
417   (make-sequential-music
418    (append
419     (map (lambda (x) (make-grob-property-set x 'direction
420                                              (if (odd? n) -1 1)))
421          direction-polyphonic-grobs)
422     (list
423      (make-property-set 'graceSettings
424                         ;; TODO: take this from voicedGraceSettings or similar.
425                         '((Voice Stem font-size -3)
426                           (Voice NoteHead font-size -3)
427                           (Voice TabNoteHead font-size -4)
428                           (Voice Dots font-size -3)
429                           (Voice Stem length-fraction 0.8)
430                           (Voice Stem no-stem-extend #t)
431                           (Voice Beam beam-thickness 0.384)
432                           (Voice Beam length-fraction 0.8)
433                           (Voice Accidental font-size -4)
434                           (Voice AccidentalCautionary font-size -4)
435                           (Voice Script font-size -3)
436                           (Voice Fingering font-size -8)
437                           (Voice StringNumber font-size -8)))
438
439      (make-grob-property-set 'NoteColumn 'horizontal-shift (quotient n 2))
440      (make-grob-property-set 'MultiMeasureRest 'staff-position (if (odd? n) -4 4))))))
441
442 (define-safe-public (make-voice-props-revert)
443   (make-sequential-music
444    (append
445     (map (lambda (x) (make-grob-property-revert x 'direction))
446          direction-polyphonic-grobs)
447     (list (make-property-unset 'graceSettings)
448           (make-grob-property-revert 'NoteColumn 'horizontal-shift)
449           (make-grob-property-revert 'MultiMeasureRest 'staff-position)))))
450
451
452 (define-safe-public (context-spec-music m context #:optional id)
453   "Add \\context CONTEXT = ID to M."
454   (let ((cm (make-music 'ContextSpeccedMusic
455                         'element m
456                         'context-type context)))
457     (if (string? id)
458         (set! (ly:music-property cm 'context-id) id))
459     cm))
460
461 (define-public (descend-to-context m context)
462   "Like @code{context-spec-music}, but only descending."
463   (let ((cm (context-spec-music m context)))
464     (ly:music-set-property! cm 'descend-only #t)
465     cm))
466
467 (define-public (make-non-relative-music mus)
468   (make-music 'UnrelativableMusic
469               'element mus))
470
471 (define-public (make-apply-context func)
472   (make-music 'ApplyContext
473               'procedure func))
474
475 (define-public (make-sequential-music elts)
476   (make-music 'SequentialMusic
477               'elements elts))
478
479 (define-public (make-simultaneous-music elts)
480   (make-music 'SimultaneousMusic
481               'elements elts))
482
483 (define-safe-public (make-event-chord elts)
484   (make-music 'EventChord
485               'elements elts))
486
487 (define-public (make-skip-music dur)
488   (make-music 'SkipMusic
489               'duration dur))
490
491 (define-public (make-grace-music music)
492   (make-music 'GraceMusic
493               'element music))
494
495 ;;;;;;;;;;;;;;;;
496
497 ;; mmrest
498 (define-public (make-multi-measure-rest duration location)
499   (make-music 'MultiMeasureRestMusic
500               'origin location
501               'duration duration))
502
503 (define-public (make-property-set sym val)
504   (make-music 'PropertySet
505               'symbol sym
506               'value val))
507
508 (define-public (make-property-unset sym)
509   (make-music 'PropertyUnset
510               'symbol sym))
511
512 ;;; Need to keep this definition for \time calls from parser
513 (define-public (make-time-signature-set num den)
514   "Set properties for time signature @var{num}/@var{den}."
515   (make-music 'TimeSignatureMusic
516               'numerator num
517               'denominator den
518               'beat-structure '()))
519
520 ;;; Used for calls that include beat-grouping setting
521 (define-public (set-time-signature num den . rest)
522   "Set properties for time signature @var{num}/@var{den}.
523 If @var{rest} is present, it is used to set @code{beatStructure}."
524   (ly:export
525    (make-music 'TimeSignatureMusic
526                'numerator num
527                'denominator den
528                'beat-structure (if (null? rest) rest (car rest)))))
529
530 (define-safe-public (make-articulation name)
531   (make-music 'ArticulationEvent
532               'articulation-type name))
533
534 (define-public (make-lyric-event string duration)
535   (make-music 'LyricEvent
536               'duration duration
537               'text string))
538
539 (define-safe-public (make-span-event type span-dir)
540   (make-music type
541               'span-direction span-dir))
542
543 (define-public (override-head-style heads style)
544   "Override style for @var{heads} to @var{style}."
545   (make-sequential-music
546     (if (pair? heads)
547         (map (lambda (h)
548               (make-grob-property-override h 'style style))
549          heads)
550         (list (make-grob-property-override heads 'style style)))))
551
552 (define-public (revert-head-style heads)
553   "Revert style for @var{heads}."
554   (make-sequential-music
555     (if (pair? heads)
556         (map (lambda (h)
557               (make-grob-property-revert h 'style))
558          heads)
559         (list (make-grob-property-revert heads 'style)))))
560
561 (define-public (style-note-heads heads style music)
562  "Set @var{style} for all @var{heads} in @var{music}.  Works both
563 inside of and outside of chord construct."
564   ;; are we inside a <...>?
565   (if (eq? (ly:music-property music 'name) 'NoteEvent)
566       ;; yes -> use a tweak
567       (begin
568         (set! (ly:music-property music 'tweaks)
569               (acons 'style style (ly:music-property music 'tweaks)))
570         music)
571       ;; not in <...>, so use overrides
572       (make-sequential-music
573         (list
574           (override-head-style heads style)
575           music
576           (revert-head-style heads)))))
577
578  (define-public (set-mus-properties! m alist)
579   "Set all of @var{alist} as properties of @var{m}."
580   (if (pair? alist)
581       (begin
582         (set! (ly:music-property m (caar alist)) (cdar alist))
583         (set-mus-properties! m (cdr alist)))))
584
585 (define-public (music-separator? m)
586   "Is @var{m} a separator?"
587   (let ((ts (ly:music-property m 'types)))
588     (memq 'separator ts)))
589
590 ;;; splitting chords into voices.
591 (define (voicify-list lst number)
592   "Make a list of Musics.
593
594 voicify-list :: [ [Music ] ] -> number -> [Music]
595 LST is a list music-lists.
596
597 NUMBER is 0-base, i.e., Voice=1 (upstems) has number 0.
598 "
599   (if (null? lst)
600       '()
601       (cons (context-spec-music
602              (make-sequential-music
603               (list (make-voice-props-set number)
604                     (make-simultaneous-music (car lst))))
605              'Bottom  (number->string (1+ number)))
606             (voicify-list (cdr lst) (1+ number)))))
607
608 (define (voicify-chord ch)
609   "Split the parts of a chord into different Voices using separator"
610   (let ((es (ly:music-property ch 'elements)))
611     (set! (ly:music-property  ch 'elements)
612           (voicify-list (split-list-by-separator es music-separator?) 0))
613     ch))
614
615 (define-public (voicify-music m)
616   "Recursively split chords that are separated with @code{\\\\}."
617   (if (not (ly:music? m))
618       (ly:error (_ "music expected: ~S") m))
619   (let ((es (ly:music-property m 'elements))
620         (e (ly:music-property m 'element)))
621
622     (if (pair? es)
623         (set! (ly:music-property m 'elements) (map voicify-music es)))
624     (if (ly:music? e)
625         (set! (ly:music-property m 'element)  (voicify-music e)))
626     (if (and (equal? (ly:music-property m 'name) 'SimultaneousMusic)
627              (reduce (lambda (x y ) (or x y)) #f (map music-separator? es)))
628         (set! m (context-spec-music (voicify-chord m) 'Staff)))
629     m))
630
631 (define-public (empty-music)
632   (ly:export (make-music 'Music)))
633
634 ;; Make a function that checks score element for being of a specific type.
635 (define-public (make-type-checker symbol)
636   (lambda (elt)
637     (grob::has-interface elt symbol)))
638
639 (define-public ((outputproperty-compatibility func sym val) grob g-context ao-context)
640   (if (func grob)
641       (set! (ly:grob-property grob sym) val)))
642
643
644 (define-public ((set-output-property grob-name symbol val)  grob grob-c context)
645   "Usage example:
646 @code{\\applyoutput #(set-output-property 'Clef 'extra-offset '(0 . 1))}"
647   (let ((meta (ly:grob-property grob 'meta)))
648     (if (equal? (assoc-get 'name meta) grob-name)
649         (set! (ly:grob-property grob symbol) val))))
650
651
652 ;;
653 (define-public (smart-bar-check n)
654   "Make a bar check that checks for a specific bar number."
655   (let ((m (make-music 'ApplyContext)))
656     (define (checker tr)
657       (let* ((bn (ly:context-property tr 'currentBarNumber)))
658         (if (= bn n)
659             #t
660             (ly:error
661              ;; FIXME: uncomprehensable message
662              (_ "Bar check failed.  Expect to be at ~a, instead at ~a")
663              n bn))))
664     (set! (ly:music-property m 'procedure) checker)
665     m))
666
667
668 (define-public (skip->rest mus)
669   "Replace @var{mus} by @code{RestEvent} of the same duration if it is a
670 @code{SkipEvent}.  Useful for extracting parts from crowded scores."
671
672   (if  (memq (ly:music-property mus 'name) '(SkipEvent SkipMusic))
673    (make-music 'RestEvent 'duration (ly:music-property mus 'duration))
674    mus))
675
676
677 (define-public (music-has-type music type)
678   (memq type (ly:music-property music 'types)))
679
680 (define-public (music-clone music)
681   (define (alist->args alist acc)
682     (if (null? alist)
683         acc
684         (alist->args (cdr alist)
685                      (cons (caar alist) (cons (cdar alist) acc)))))
686
687   (apply
688    make-music
689    (ly:music-property music 'name)
690    (alist->args (ly:music-mutable-properties music) '())))
691
692 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
693 ;; warn for bare chords at start.
694
695
696 (define-public (ly:music-message music msg)
697   (let ((ip (ly:music-property music 'origin)))
698     (if (ly:input-location? ip)
699         (ly:input-message ip msg)
700         (ly:warning msg))))
701
702 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
703 ;;
704 ;; setting stuff for grace context.
705 ;;
706
707 (define (vector-extend v x)
708   "Make a new vector consisting of V, with X added to the end."
709   (let* ((n (vector-length v))
710          (nv (make-vector (+ n 1) '())))
711     (vector-move-left! v 0 n nv 0)
712     (vector-set! nv n x)
713     nv))
714
715 (define (vector-map f v)
716   "Map F over V.  This function returns nothing."
717   (do ((n (vector-length v))
718        (i 0 (+ i 1)))
719       ((>= i n))
720     (f (vector-ref v i))))
721
722 (define (vector-reverse-map f v)
723   "Map F over V, N to 0 order.  This function returns nothing."
724   (do ((i (- (vector-length v) 1) (- i 1)))
725       ((< i 0))
726     (f (vector-ref v i))))
727
728 (define-public (add-grace-property context-name grob sym val)
729   "Set @var{sym}=@var{val} for @var{grob} in @var{context-name}."
730   (define (set-prop context)
731     (let* ((where (ly:context-property-where-defined context 'graceSettings))
732            (current (ly:context-property where 'graceSettings))
733            (new-settings (append current
734                                  (list (list context-name grob sym val)))))
735       (ly:context-set-property! where 'graceSettings new-settings)))
736   (ly:export (context-spec-music (make-apply-context set-prop) 'Voice)))
737
738 (define-public (remove-grace-property context-name grob sym)
739   "Remove all @var{sym} for @var{grob} in @var{context-name}."
740   (define (sym-grob-context? property sym grob context-name)
741     (and (eq? (car property) context-name)
742          (eq? (cadr property) grob)
743          (eq? (caddr property) sym)))
744   (define (delete-prop context)
745     (let* ((where (ly:context-property-where-defined context 'graceSettings))
746            (current (ly:context-property where 'graceSettings))
747            (prop-settings (filter
748                             (lambda(x) (sym-grob-context? x sym grob context-name))
749                             current))
750            (new-settings current))
751       (for-each (lambda(x)
752                  (set! new-settings (delete x new-settings)))
753                prop-settings)
754       (ly:context-set-property! where 'graceSettings new-settings)))
755   (ly:export (context-spec-music (make-apply-context delete-prop) 'Voice)))
756
757
758
759 (defmacro-public def-grace-function (start stop . docstring)
760   "Helper macro for defining grace music"
761   `(define-music-function (parser location music) (ly:music?)
762      ,@docstring
763      (make-music 'GraceMusic
764                  'origin location
765                  'element (make-music 'SequentialMusic
766                                       'elements (list (ly:music-deep-copy ,start)
767                                                       music
768                                                       (ly:music-deep-copy ,stop))))))
769
770 (defmacro-public define-music-function (args signature . body)
771   "Helper macro for `ly:make-music-function'.
772 Syntax:
773   (define-music-function (parser location arg1 arg2 ...) (arg1-type? arg2-type? ...)
774     ...function body...)
775 "
776 (if (and (pair? body) (pair? (car body)) (eqv? '_i (caar body)))
777       ;; When the music function definition contains a i10n doc string,
778       ;; (_i "doc string"), keep the literal string only
779       (let ((docstring (cadar body))
780             (body (cdr body)))
781         `(ly:make-music-function (list ,@signature)
782                                  (lambda (,@args)
783                                    ,docstring
784                                    ,@body)))
785       `(ly:make-music-function (list ,@signature)
786                                (lambda (,@args)
787                                  ,@body))))
788
789
790 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
791
792 (define-public (cue-substitute quote-music)
793   "Must happen after @code{quote-substitute}."
794
795   (if (vector? (ly:music-property quote-music 'quoted-events))
796       (let* ((dir (ly:music-property quote-music 'quoted-voice-direction))
797              (clef (ly:music-property quote-music 'quoted-music-clef))
798              (main-voice (if (eq? 1 dir) 1 0))
799              (cue-voice (if (eq? 1 dir) 0 1))
800              (main-music (ly:music-property quote-music 'element))
801              (return-value quote-music))
802
803         (if (or (eq? 1 dir) (eq? -1 dir))
804
805             ;; if we have stem dirs, change both quoted and main music
806             ;; to have opposite stems.
807             (begin
808               (set! return-value
809                     ;; cannot context-spec Quote-music, since context
810                     ;; for the quotes is determined in the iterator.
811                     (make-sequential-music
812                      (list
813                       (if (null? clef)
814                           (make-music 'Music)
815                           (make-cue-clef-set clef))
816                       (context-spec-music (make-voice-props-set cue-voice) 'CueVoice "cue")
817                       quote-music
818                       (context-spec-music (make-voice-props-revert) 'CueVoice "cue")
819                       (if (null? clef)
820                           (make-music 'Music)
821                           (make-cue-clef-unset)))))
822               (set! main-music
823                     (make-sequential-music
824                      (list
825                       (make-voice-props-set main-voice)
826                       main-music
827                       (make-voice-props-revert))))
828               (set! (ly:music-property quote-music 'element) main-music)))
829
830         return-value)
831       quote-music))
832
833 (define-public ((quote-substitute quote-tab) music)
834   (let* ((quoted-name (ly:music-property music 'quoted-music-name))
835          (quoted-vector (if (string? quoted-name)
836                             (hash-ref quote-tab quoted-name #f)
837                             #f)))
838
839
840     (if (string? quoted-name)
841         (if (vector? quoted-vector)
842             (begin
843               (set! (ly:music-property music 'quoted-events) quoted-vector)
844               (set! (ly:music-property music 'iterator-ctor)
845                     ly:quote-iterator::constructor))
846             (ly:warning (_ "cannot find quoted music: `~S'") quoted-name)))
847     music))
848
849
850 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
851 ;; switch it on here, so parsing and init isn't checked (too slow!)
852 ;;
853 ;; automatic music transformations.
854
855 (define (switch-on-debugging m)
856   (if (defined? 'set-debug-cell-accesses!)
857       (set-debug-cell-accesses! 15000))
858   m)
859
860 (define (music-check-error music)
861   (define found #f)
862   (define (signal m)
863     (if (and (ly:music? m)
864              (eq? (ly:music-property m 'error-found) #t))
865         (set! found #t)))
866
867   (for-each signal (ly:music-property music 'elements))
868   (signal (ly:music-property music 'element))
869
870   (if found
871       (set! (ly:music-property music 'error-found) #t))
872   music)
873
874 (define (precompute-music-length music)
875   (set! (ly:music-property music 'length)
876         (ly:music-length music))
877   music)
878
879 (define-public (make-duration-of-length moment)
880  "Make duration of the given @code{moment} length."
881  (ly:make-duration 0 0
882   (ly:moment-main-numerator moment)
883   (ly:moment-main-denominator moment)))
884
885 (define (make-skipped moment bool)
886  "Depending on BOOL, set or unset skipTypesetting,
887 then make SkipMusic of the given MOMENT length, and
888 then revert skipTypesetting."
889  (make-sequential-music
890   (list
891    (context-spec-music (make-property-set 'skipTypesetting bool)
892     'Score)
893    (make-music 'SkipMusic 'duration
894     (make-duration-of-length moment))
895    (context-spec-music (make-property-set 'skipTypesetting (not bool))
896     'Score))))
897
898 (define (skip-as-needed music parser)
899   "Replace MUSIC by
900  << {  \\set skipTypesetting = ##f
901  LENGTHOF(\\showFirstLength)
902  \\set skipTypesetting = ##t
903  LENGTHOF(\\showLastLength) }
904  MUSIC >>
905  if appropriate.
906
907  When only showFirstLength is set,
908  the 'length property of the music is
909  overridden to speed up compiling."
910   (let*
911       ((show-last (ly:parser-lookup parser 'showLastLength))
912        (show-first (ly:parser-lookup parser 'showFirstLength))
913        (show-last-length (if (ly:music? show-last)
914                              (ly:music-length show-last)
915                              #f))
916        (show-first-length (if (ly:music? show-first)
917                               (ly:music-length show-first)
918                               #f))
919        (orig-length (ly:music-length music)))
920
921     ;;FIXME: if using either showFirst- or showLastLength,
922     ;; make sure that skipBars is not set.
923
924     (cond
925
926      ;; both properties may be set.
927      ((and show-first-length show-last-length)
928       (let
929           ((skip-length (ly:moment-sub orig-length show-last-length)))
930         (make-simultaneous-music
931          (list
932           (make-sequential-music
933            (list
934             (make-skipped skip-length #t)
935             ;; let's draw a separator between the beginning and the end
936             (context-spec-music (make-property-set 'whichBar "||")
937                                 'Timing)))
938           (make-skipped show-first-length #f)
939           music))))
940
941      ;; we may only want to print the last length
942      (show-last-length
943       (let
944           ((skip-length (ly:moment-sub orig-length show-last-length)))
945         (make-simultaneous-music
946          (list
947           (make-skipped skip-length #t)
948           music))))
949
950      ;; we may only want to print the beginning; in this case
951      ;; only the first length will be processed (much faster).
952      (show-first-length
953       ;; the first length must not exceed the original length.
954       (if (ly:moment<? show-first-length orig-length)
955           (set! (ly:music-property music 'length)
956                 show-first-length))
957       music)
958
959      (else music))))
960
961
962 (define-public toplevel-music-functions
963   (list
964    (lambda (music parser) (voicify-music music))
965    (lambda (x parser) (music-map music-check-error x))
966    (lambda (x parser) (music-map precompute-music-length x))
967    (lambda (music parser)
968
969      (music-map (quote-substitute (ly:parser-lookup parser 'musicQuotes))  music))
970
971    ;; switch-on-debugging
972    (lambda (x parser) (music-map cue-substitute x))
973
974    (lambda (x parser)
975      (skip-as-needed x parser)
976    )))
977
978 ;;;;;;;;;;
979 ;;; general purpose music functions
980
981 (define (shift-octave pitch octave-shift)
982   (_i "Add @var{octave-shift} to the octave of @var{pitch}.")
983   (ly:make-pitch
984      (+ (ly:pitch-octave pitch) octave-shift)
985      (ly:pitch-notename pitch)
986      (ly:pitch-alteration pitch)))
987
988
989 ;;;;;;;;;;;;;;;;;
990 ;; lyrics
991
992 (define (apply-durations lyric-music durations)
993   (define (apply-duration music)
994     (if (and (not (equal? (ly:music-length music) ZERO-MOMENT))
995              (ly:duration?  (ly:music-property music 'duration)))
996         (begin
997           (set! (ly:music-property music 'duration) (car durations))
998           (set! durations (cdr durations)))))
999
1000   (music-map apply-duration lyric-music))
1001
1002
1003 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1004 ;; accidentals
1005
1006 (define (recent-enough? bar-number alteration-def laziness)
1007   (if (or (number? alteration-def)
1008           (equal? laziness #t))
1009       #t
1010       (<= bar-number (+ (cadr alteration-def) laziness))))
1011
1012 (define (accidental-voided? alteration-def)
1013   "Checks an alteration entry for being voided.
1014
1015 Non-key alterations are voided when tying into the next bar or when
1016 there is a clef change, since neither repetition nor cancellation can
1017 be omitted when the same note occurs again.
1018
1019 Returns @code{#f} or the reason for the voiding, a symbol."
1020   (let* ((def (if (pair? alteration-def)
1021                   (car alteration-def)
1022                   alteration-def)))
1023     (and (symbol? def) def)))
1024
1025 (define (extract-alteration alteration-def)
1026   (cond ((number? alteration-def)
1027          alteration-def)
1028         ((pair? alteration-def)
1029          (car alteration-def))
1030         (else 0)))
1031
1032 (define (check-pitch-against-signature context pitch barnum laziness octaveness)
1033   "Checks the need for an accidental and a @q{restore} accidental against
1034 @code{localKeySignature}.  The @var{laziness} is the number of measures
1035 for which reminder accidentals are used (i.e., if @var{laziness} is zero,
1036 only cancel accidentals in the same measure; if @var{laziness} is three,
1037 we cancel accidentals up to three measures after they first appear.
1038 @var{octaveness} is either @code{'same-octave} or @code{'any-octave} and
1039 specifies whether accidentals should be canceled in different octaves."
1040   (let* ((ignore-octave (cond ((equal? octaveness 'any-octave) #t)
1041                               ((equal? octaveness 'same-octave) #f)
1042                               (else
1043                                (ly:warning (_ "Unknown octaveness type: ~S ") octaveness)
1044                                (ly:warning (_ "Defaulting to 'any-octave."))
1045                                #t)))
1046          (key-sig (ly:context-property context 'keySignature))
1047          (local-key-sig (ly:context-property context 'localKeySignature))
1048          (notename (ly:pitch-notename pitch))
1049          (octave (ly:pitch-octave pitch))
1050          (pitch-handle (cons octave notename))
1051          (need-restore #f)
1052          (need-accidental #f)
1053          (previous-alteration #f)
1054          (from-other-octaves #f)
1055          (from-same-octave (assoc-get pitch-handle local-key-sig))
1056          (from-key-sig (assoc-get notename local-key-sig)))
1057
1058     ;; If no key signature match is found from localKeySignature, we may have a custom
1059     ;; type with octave-specific entries of the form ((octave . pitch) alteration)
1060     ;; instead of (pitch . alteration).  Since this type cannot coexist with entries in
1061     ;; localKeySignature, try extracting from keySignature instead.
1062     (if (equal? from-key-sig #f)
1063         (set! from-key-sig (assoc-get pitch-handle key-sig)))
1064
1065     ;; loop through localKeySignature to search for a notename match from other octaves
1066     (let loop ((l local-key-sig))
1067       (if (pair? l)
1068           (let ((entry (car l)))
1069             (if (and (pair? (car entry))
1070                      (= (cdar entry) notename))
1071                 (set! from-other-octaves (cdr entry))
1072                 (loop (cdr l))))))
1073
1074     ;; find previous alteration-def for comparison with pitch
1075     (cond
1076      ;; from same octave?
1077      ((and (eq? ignore-octave #f)
1078            (not (equal? from-same-octave #f))
1079            (recent-enough? barnum from-same-octave laziness))
1080       (set! previous-alteration from-same-octave))
1081
1082      ;; from any octave?
1083      ((and (eq? ignore-octave #t)
1084            (not (equal? from-other-octaves #f))
1085            (recent-enough? barnum from-other-octaves laziness))
1086       (set! previous-alteration from-other-octaves))
1087
1088      ;; not recent enough, extract from key signature/local key signature
1089      ((not (equal? from-key-sig #f))
1090       (set! previous-alteration from-key-sig)))
1091
1092     (if (accidental-voided? previous-alteration)
1093         (set! need-accidental #t)
1094
1095         (let* ((prev-alt (extract-alteration previous-alteration))
1096                (this-alt (ly:pitch-alteration pitch)))
1097
1098           (if (not (= this-alt prev-alt))
1099               (begin
1100                 (set! need-accidental #t)
1101                 (if (and (not (= this-alt 0))
1102                          (or (< (abs this-alt) (abs prev-alt))
1103                              (< (* prev-alt this-alt) 0)))
1104                     (set! need-restore #t))))))
1105
1106     (cons need-restore need-accidental)))
1107
1108 (define-public ((make-accidental-rule octaveness laziness) context pitch barnum measurepos)
1109   "Create an accidental rule that makes its decision based on the octave of
1110 the note and a laziness value.
1111
1112 @var{octaveness} is either @code{'same-octave} or @code{'any-octave} and
1113 defines whether the rule should respond to accidental changes in other
1114 octaves than the current.  @code{'same-octave} is the normal way to typeset
1115 accidentals -- an accidental is made if the alteration is different from the
1116 last active pitch in the same octave.  @code{'any-octave} looks at the last
1117 active pitch in any octave.
1118
1119 @var{laziness} states over how many bars an accidental should be remembered.
1120 @code{0}@tie{}is the default -- accidental lasts over 0@tie{}bar lines, that
1121 is, to the end of current measure.  A positive integer means that the
1122 accidental lasts over that many bar lines.  @code{-1} is `forget
1123 immediately', that is, only look at key signature.  @code{#t} is `forever'."
1124
1125   (check-pitch-against-signature context pitch barnum laziness octaveness))
1126
1127 (define (key-entry-notename entry)
1128   "Return the pitch of an entry in localKeySignature.  The entry is either of the form
1129   '(notename . alter) or '((octave . notename) . (alter barnum . measurepos))."
1130   (if (number? (car entry))
1131       (car entry)
1132       (cdar entry)))
1133
1134 (define (key-entry-octave entry)
1135   "Return the octave of an entry in localKeySignature (or #f if the entry does not have
1136   an octave)."
1137   (and (pair? (car entry)) (caar entry)))
1138
1139 (define (key-entry-bar-number entry)
1140   "Return the bar number of an entry in localKeySignature (or #f if the entry does not
1141   have a bar number)."
1142   (and (pair? (car entry)) (caddr entry)))
1143
1144 (define (key-entry-measure-position entry)
1145   "Return the measure position of an entry in localKeySignature (or #f if the entry does
1146   not have a measure position)."
1147   (and (pair? (car entry)) (cdddr entry)))
1148
1149 (define (key-entry-alteration entry)
1150   "Return the alteration of an entry in localKeySignature.
1151
1152 For convenience, returns @code{0} if entry is @code{#f}."
1153   (if entry
1154       (if (number? (car entry))
1155           (cdr entry)
1156           (cadr entry))
1157       0))
1158
1159 (define-public (find-pitch-entry keysig pitch accept-global accept-local)
1160   "Return the first entry in @var{keysig} that matches @var{pitch}.
1161 @var{accept-global} states whether key signature entries should be included.
1162 @var{accept-local} states whether local accidentals should be included.
1163 If no matching entry is found, @var{#f} is returned."
1164   (if (pair? keysig)
1165       (let* ((entry (car keysig))
1166              (entryoct (key-entry-octave entry))
1167              (entrynn (key-entry-notename entry))
1168              (oct (ly:pitch-octave pitch))
1169              (nn (ly:pitch-notename pitch)))
1170         (if (and (equal? nn entrynn)
1171                  (or (and accept-global (equal? #f entryoct))
1172                      (and accept-local (equal? oct entryoct))))
1173             entry
1174             (find-pitch-entry (cdr keysig) pitch accept-global accept-local)))
1175       #f))
1176
1177 (define-public (neo-modern-accidental-rule context pitch barnum measurepos)
1178   "An accidental rule that typesets an accidental if it differs from the
1179 key signature @emph{and} does not directly follow a note on the same
1180 staff line.  This rule should not be used alone because it does neither
1181 look at bar lines nor different accidentals at the same note name."
1182   (let* ((keysig (ly:context-property context 'localKeySignature))
1183          (entry (find-pitch-entry keysig pitch #t #t)))
1184     (if (equal? #f entry)
1185         (cons #f #f)
1186         (let* ((global-entry (find-pitch-entry keysig pitch #t #f))
1187                (key-acc (key-entry-alteration global-entry))
1188                (acc (ly:pitch-alteration pitch))
1189                (entrymp (key-entry-measure-position entry))
1190                (entrybn (key-entry-bar-number entry)))
1191           (cons #f (not (or (equal? acc key-acc)
1192                             (and (equal? entrybn barnum) (equal? entrymp measurepos)))))))))
1193
1194 (define-public (teaching-accidental-rule context pitch barnum measurepos)
1195   "An accidental rule that typesets a cautionary accidental if it is
1196 included in the key signature @emph{and} does not directly follow a note
1197 on the same staff line."
1198   (let* ((keysig (ly:context-property context 'localKeySignature))
1199          (entry (find-pitch-entry keysig pitch #t #t)))
1200     (if (equal? #f entry)
1201         (cons #f #f)
1202         (let* ((global-entry (find-pitch-entry keysig pitch #f #f))
1203                (key-acc (key-entry-alteration global-entry))
1204                (acc (ly:pitch-alteration pitch))
1205                (entrymp (key-entry-measure-position entry))
1206                (entrybn (key-entry-bar-number entry)))
1207           (cons #f (not (or (equal? acc key-acc)
1208                             (and (equal? entrybn barnum) (equal? entrymp measurepos)))))))))
1209
1210 (define-public (set-accidentals-properties extra-natural
1211                                            auto-accs auto-cauts
1212                                            context)
1213   (context-spec-music
1214    (make-sequential-music
1215     (append (if (boolean? extra-natural)
1216                 (list (make-property-set 'extraNatural extra-natural))
1217                 '())
1218             (list (make-property-set 'autoAccidentals auto-accs)
1219                   (make-property-set 'autoCautionaries auto-cauts))))
1220    context))
1221
1222 (define-public (set-accidental-style style . rest)
1223   "Set accidental style to @var{style}.  Optionally take a context
1224 argument, e.g. @code{'Staff} or @code{'Voice}.  The context defaults
1225 to @code{Staff}, except for piano styles, which use @code{GrandStaff}
1226 as a context."
1227   (let ((context (if (pair? rest)
1228                      (car rest) 'Staff))
1229         (pcontext (if (pair? rest)
1230                       (car rest) 'GrandStaff)))
1231     (ly:export
1232      (cond
1233       ;; accidentals as they were common in the 18th century.
1234       ((equal? style 'default)
1235        (set-accidentals-properties #t
1236                                    `(Staff ,(make-accidental-rule 'same-octave 0))
1237                                    '()
1238                                    context))
1239       ;; accidentals from one voice do NOT get cancelled in other voices
1240       ((equal? style 'voice)
1241        (set-accidentals-properties #t
1242                                    `(Voice ,(make-accidental-rule 'same-octave 0))
1243                                    '()
1244                                    context))
1245       ;; accidentals as suggested by Kurt Stone, Music Notation in the 20th century.
1246       ;; This includes all the default accidentals, but accidentals also needs cancelling
1247       ;; in other octaves and in the next measure.
1248       ((equal? style 'modern)
1249        (set-accidentals-properties #f
1250                                    `(Staff ,(make-accidental-rule 'same-octave 0)
1251                                            ,(make-accidental-rule 'any-octave 0)
1252                                            ,(make-accidental-rule 'same-octave 1))
1253                                    '()
1254                                    context))
1255       ;; the accidentals that Stone adds to the old standard as cautionaries
1256       ((equal? style 'modern-cautionary)
1257        (set-accidentals-properties #f
1258                                    `(Staff ,(make-accidental-rule 'same-octave 0))
1259                                    `(Staff ,(make-accidental-rule 'any-octave 0)
1260                                            ,(make-accidental-rule 'same-octave 1))
1261                                    context))
1262       ;; same as modern, but accidentals different from the key signature are always
1263       ;; typeset - unless they directly follow a note of the same pitch.
1264       ((equal? style 'neo-modern)
1265        (set-accidentals-properties #f
1266                                    `(Staff ,(make-accidental-rule 'same-octave 0)
1267                                            ,(make-accidental-rule 'any-octave 0)
1268                                            ,(make-accidental-rule 'same-octave 1)
1269                                            ,neo-modern-accidental-rule)
1270                                    '()
1271                                    context))
1272       ((equal? style 'neo-modern-cautionary)
1273        (set-accidentals-properties #f
1274                                    `(Staff ,(make-accidental-rule 'same-octave 0))
1275                                    `(Staff ,(make-accidental-rule 'any-octave 0)
1276                                            ,(make-accidental-rule 'same-octave 1)
1277                                            ,neo-modern-accidental-rule)
1278                                    context))
1279       ((equal? style 'neo-modern-voice)
1280        (set-accidentals-properties #f
1281                                    `(Voice ,(make-accidental-rule 'same-octave 0)
1282                                            ,(make-accidental-rule 'any-octave 0)
1283                                            ,(make-accidental-rule 'same-octave 1)
1284                                            ,neo-modern-accidental-rule
1285                                      Staff ,(make-accidental-rule 'same-octave 0)
1286                                            ,(make-accidental-rule 'any-octave 0)
1287                                            ,(make-accidental-rule 'same-octave 1)
1288                                       ,neo-modern-accidental-rule)
1289                                    '()
1290                                    context))
1291       ((equal? style 'neo-modern-voice-cautionary)
1292        (set-accidentals-properties #f
1293                                    `(Voice ,(make-accidental-rule 'same-octave 0))
1294                                    `(Voice ,(make-accidental-rule 'any-octave 0)
1295                                            ,(make-accidental-rule 'same-octave 1)
1296                                            ,neo-modern-accidental-rule
1297                                      Staff ,(make-accidental-rule 'same-octave 0)
1298                                            ,(make-accidental-rule 'any-octave 0)
1299                                            ,(make-accidental-rule 'same-octave 1)
1300                                            ,neo-modern-accidental-rule)
1301                                    context))
1302       ;; Accidentals as they were common in dodecaphonic music with no tonality.
1303       ;; Each note gets one accidental.
1304       ((equal? style 'dodecaphonic)
1305        (set-accidentals-properties #f
1306                                    `(Staff ,(lambda (c p bn mp) '(#f . #t)))
1307                                    '()
1308                                    context))
1309       ;; Multivoice accidentals to be read both by musicians playing one voice
1310       ;; and musicians playing all voices.
1311       ;; Accidentals are typeset for each voice, but they ARE cancelled across voices.
1312       ((equal? style 'modern-voice)
1313        (set-accidentals-properties  #f
1314                                     `(Voice ,(make-accidental-rule 'same-octave 0)
1315                                             ,(make-accidental-rule 'any-octave 0)
1316                                             ,(make-accidental-rule 'same-octave 1)
1317                                       Staff ,(make-accidental-rule 'same-octave 0)
1318                                             ,(make-accidental-rule 'any-octave 0)
1319                                             ,(make-accidental-rule 'same-octave 1))
1320                                     '()
1321                                     context))
1322       ;; same as modernVoiceAccidental eccept that all special accidentals are typeset
1323       ;; as cautionaries
1324       ((equal? style 'modern-voice-cautionary)
1325        (set-accidentals-properties #f
1326                                    `(Voice ,(make-accidental-rule 'same-octave 0))
1327                                    `(Voice ,(make-accidental-rule 'any-octave 0)
1328                                            ,(make-accidental-rule 'same-octave 1)
1329                                      Staff ,(make-accidental-rule 'same-octave 0)
1330                                            ,(make-accidental-rule 'any-octave 0)
1331                                            ,(make-accidental-rule 'same-octave 1))
1332                                    context))
1333       ;; stone's suggestions for accidentals on grand staff.
1334       ;; Accidentals are cancelled across the staves in the same grand staff as well
1335       ((equal? style 'piano)
1336        (set-accidentals-properties #f
1337                                    `(Staff ,(make-accidental-rule 'same-octave 0)
1338                                            ,(make-accidental-rule 'any-octave 0)
1339                                            ,(make-accidental-rule 'same-octave 1)
1340                                      GrandStaff
1341                                            ,(make-accidental-rule 'any-octave 0)
1342                                            ,(make-accidental-rule 'same-octave 1))
1343                                    '()
1344                                    pcontext))
1345       ((equal? style 'piano-cautionary)
1346        (set-accidentals-properties #f
1347                                    `(Staff ,(make-accidental-rule 'same-octave 0))
1348                                    `(Staff ,(make-accidental-rule 'any-octave 0)
1349                                            ,(make-accidental-rule 'same-octave 1)
1350                                      GrandStaff
1351                                            ,(make-accidental-rule 'any-octave 0)
1352                                            ,(make-accidental-rule 'same-octave 1))
1353                                    pcontext))
1354
1355       ;; same as modern, but cautionary accidentals are printed for all sharp or flat
1356       ;; tones specified by the key signature.
1357        ((equal? style 'teaching)
1358        (set-accidentals-properties #f
1359                                     `(Staff ,(make-accidental-rule 'same-octave 0))
1360                                     `(Staff ,(make-accidental-rule 'same-octave 1)
1361                                            ,teaching-accidental-rule)
1362                                    context))
1363
1364       ;; do not set localKeySignature when a note alterated differently from
1365       ;; localKeySignature is found.
1366       ;; Causes accidentals to be printed at every note instead of
1367       ;; remembered for the duration of a measure.
1368       ;; accidentals not being remembered, causing accidentals always to
1369       ;; be typeset relative to the time signature
1370       ((equal? style 'forget)
1371        (set-accidentals-properties '()
1372                                    `(Staff ,(make-accidental-rule 'same-octave -1))
1373                                    '()
1374                                    context))
1375       ;; Do not reset the key at the start of a measure.  Accidentals will be
1376       ;; printed only once and are in effect until overridden, possibly many
1377       ;; measures later.
1378       ((equal? style 'no-reset)
1379        (set-accidentals-properties '()
1380                                    `(Staff ,(make-accidental-rule 'same-octave #t))
1381                                    '()
1382                                    context))
1383       (else
1384        (ly:warning (_ "unknown accidental style: ~S") style)
1385        (make-sequential-music '()))))))
1386
1387 (define-public (invalidate-alterations context)
1388   "Invalidate alterations in @var{context}.
1389
1390 Elements of @code{'localKeySignature} corresponding to local
1391 alterations of the key signature have the form
1392 @code{'((octave . notename) . (alter barnum . measurepos))}.
1393 Replace them with a version where @code{alter} is set to @code{'clef}
1394 to force a repetition of accidentals.
1395
1396 Entries that conform with the current key signature are not invalidated."
1397   (let* ((keysig (ly:context-property context 'keySignature)))
1398     (set! (ly:context-property context 'localKeySignature)
1399           (map-in-order
1400            (lambda (entry)
1401              (let* ((localalt (key-entry-alteration entry))
1402                     (localoct (key-entry-octave entry)))
1403                (if (or (accidental-voided? localalt)
1404                        (not localoct)
1405                        (= localalt
1406                           (key-entry-alteration
1407                            (find-pitch-entry
1408                             keysig
1409                             (ly:make-pitch localoct
1410                                            (key-entry-notename entry)
1411                                            0)
1412                             #t #t))))
1413                    entry
1414                    (cons (car entry) (cons 'clef (cddr entry))))))
1415            (ly:context-property context 'localKeySignature)))))
1416                     
1417 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1418
1419 (define-public (skip-of-length mus)
1420   "Create a skip of exactly the same length as @var{mus}."
1421   (let* ((skip
1422           (make-music
1423            'SkipEvent
1424            'duration (ly:make-duration 0 0))))
1425
1426     (make-event-chord (list (ly:music-compress skip (ly:music-length mus))))))
1427
1428 (define-public (mmrest-of-length mus)
1429   "Create a multi-measure rest of exactly the same length as @var{mus}."
1430
1431   (let* ((skip
1432           (make-multi-measure-rest
1433            (ly:make-duration 0 0) '())))
1434     (ly:music-compress skip (ly:music-length mus))
1435     skip))
1436
1437 (define-public (pitch-of-note event-chord)
1438   (let ((evs (filter (lambda (x)
1439                        (music-has-type x 'note-event))
1440                      (ly:music-property event-chord 'elements))))
1441
1442     (and (pair? evs)
1443          (ly:music-property (car evs) 'pitch))))
1444
1445 (define-public (duration-of-note event-chord)
1446   (let ((evs (filter (lambda (x)
1447                        (music-has-type x 'rhythmic-event))
1448                      (ly:music-property event-chord 'elements))))
1449
1450     (and (pair? evs)
1451          (ly:music-property (car evs) 'duration))))
1452
1453 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1454
1455 (define-public (extract-named-music music music-name)
1456   "Return a flat list of all music named @var{music-name} from @var{music}."
1457    (let ((extracted-list
1458           (if (ly:music? music)
1459               (if (eq? (ly:music-property music 'name) music-name)
1460                   (list music)
1461                   (let ((elt (ly:music-property music 'element))
1462                         (elts (ly:music-property music 'elements)))
1463                     (if (ly:music? elt)
1464                         (extract-named-music elt music-name)
1465                         (if (null? elts)
1466                             '()
1467                             (map (lambda(x)
1468                                     (extract-named-music x music-name ))
1469                              elts)))))
1470               '())))
1471      (flatten-list extracted-list)))
1472
1473 (define-public (event-chord-notes event-chord)
1474   "Return a list of all notes from @var{event-chord}."
1475   (filter
1476     (lambda (m) (eq? 'NoteEvent (ly:music-property m 'name)))
1477     (ly:music-property event-chord 'elements)))
1478
1479 (define-public (event-chord-pitches event-chord)
1480   "Return a list of all pitches from @var{event-chord}."
1481   (map (lambda (x) (ly:music-property x 'pitch))
1482        (event-chord-notes event-chord)))