]> 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--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 (extract-named-music main 'EventChord))
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 @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     TupletBracket))
416
417 (define-safe-public (make-voice-props-set n)
418   (make-sequential-music
419    (append
420     (map (lambda (x) (make-grob-property-set x 'direction
421                                              (if (odd? n) -1 1)))
422          direction-polyphonic-grobs)
423     (list
424      (make-property-set 'graceSettings
425                         ;; TODO: take this from voicedGraceSettings or similar.
426                         '((Voice Stem font-size -3)
427                           (Voice Flag font-size -3)
428                           (Voice NoteHead font-size -3)
429                           (Voice TabNoteHead font-size -4)
430                           (Voice Dots font-size -3)
431                           (Voice Stem length-fraction 0.8)
432                           (Voice Stem no-stem-extend #t)
433                           (Voice Beam beam-thickness 0.384)
434                           (Voice Beam length-fraction 0.8)
435                           (Voice Accidental font-size -4)
436                           (Voice AccidentalCautionary font-size -4)
437                           (Voice Script font-size -3)
438                           (Voice Fingering font-size -8)
439                           (Voice StringNumber font-size -8)))
440
441      (make-grob-property-set 'NoteColumn 'horizontal-shift (quotient n 2))
442      (make-grob-property-set 'MultiMeasureRest 'staff-position (if (odd? n) -4 4))))))
443
444 (define-safe-public (make-voice-props-revert)
445   (make-sequential-music
446    (append
447     (map (lambda (x) (make-grob-property-revert x 'direction))
448          direction-polyphonic-grobs)
449     (list (make-property-unset 'graceSettings)
450           (make-grob-property-revert 'NoteColumn 'horizontal-shift)
451           (make-grob-property-revert 'MultiMeasureRest 'staff-position)))))
452
453
454 (define-safe-public (context-spec-music m context #:optional id)
455   "Add \\context CONTEXT = ID to M."
456   (let ((cm (make-music 'ContextSpeccedMusic
457                         'element m
458                         'context-type context)))
459     (if (string? id)
460         (set! (ly:music-property cm 'context-id) id))
461     cm))
462
463 (define-public (descend-to-context m context)
464   "Like @code{context-spec-music}, but only descending."
465   (let ((cm (context-spec-music m context)))
466     (ly:music-set-property! cm 'descend-only #t)
467     cm))
468
469 (define-public (make-non-relative-music mus)
470   (make-music 'UnrelativableMusic
471               'element mus))
472
473 (define-public (make-apply-context func)
474   (make-music 'ApplyContext
475               'procedure func))
476
477 (define-public (make-sequential-music elts)
478   (make-music 'SequentialMusic
479               'elements elts))
480
481 (define-public (make-simultaneous-music elts)
482   (make-music 'SimultaneousMusic
483               'elements elts))
484
485 (define-safe-public (make-event-chord elts)
486   (make-music 'EventChord
487               'elements elts))
488
489 (define-public (make-skip-music dur)
490   (make-music 'SkipMusic
491               'duration dur))
492
493 (define-public (make-grace-music music)
494   (make-music 'GraceMusic
495               'element music))
496
497 ;;;;;;;;;;;;;;;;
498
499 ;; mmrest
500 (define-public (make-multi-measure-rest duration location)
501   (make-music 'MultiMeasureRestMusic
502               'origin location
503               'duration duration))
504
505 (define-public (make-property-set sym val)
506   (make-music 'PropertySet
507               'symbol sym
508               'value val))
509
510 (define-public (make-property-unset sym)
511   (make-music 'PropertyUnset
512               'symbol sym))
513
514 ;;; Need to keep this definition for \time calls from parser
515 (define-public (make-time-signature-set num den)
516   "Set properties for time signature @var{num}/@var{den}."
517   (make-music 'TimeSignatureMusic
518               'numerator num
519               'denominator den
520               'beat-structure '()))
521
522 ;;; Used for calls that include beat-grouping setting
523 (define-public (set-time-signature num den . rest)
524   "Set properties for time signature @var{num}/@var{den}.
525 If @var{rest} is present, it is used to set @code{beatStructure}."
526   (ly:export
527    (make-music 'TimeSignatureMusic
528                'numerator num
529                'denominator den
530                'beat-structure (if (null? rest) rest (car rest)))))
531
532 (define-safe-public (make-articulation name)
533   (make-music 'ArticulationEvent
534               'articulation-type name))
535
536 (define-public (make-lyric-event string duration)
537   (make-music 'LyricEvent
538               'duration duration
539               'text string))
540
541 (define-safe-public (make-span-event type span-dir)
542   (make-music type
543               'span-direction span-dir))
544
545 (define-public (override-head-style heads style)
546   "Override style for @var{heads} to @var{style}."
547   (make-sequential-music
548     (if (pair? heads)
549         (map (lambda (h)
550               (make-grob-property-override h 'style style))
551          heads)
552         (list (make-grob-property-override heads 'style style)))))
553
554 (define-public (revert-head-style heads)
555   "Revert style for @var{heads}."
556   (make-sequential-music
557     (if (pair? heads)
558         (map (lambda (h)
559               (make-grob-property-revert h 'style))
560          heads)
561         (list (make-grob-property-revert heads 'style)))))
562
563 (define-public (style-note-heads heads style music)
564  "Set @var{style} for all @var{heads} in @var{music}.  Works both
565 inside of and outside of chord construct."
566   ;; are we inside a <...>?
567   (if (eq? (ly:music-property music 'name) 'NoteEvent)
568       ;; yes -> use a tweak
569       (begin
570         (set! (ly:music-property music 'tweaks)
571               (acons 'style style (ly:music-property music 'tweaks)))
572         music)
573       ;; not in <...>, so use overrides
574       (make-sequential-music
575         (list
576           (override-head-style heads style)
577           music
578           (revert-head-style heads)))))
579
580  (define-public (set-mus-properties! m alist)
581   "Set all of @var{alist} as properties of @var{m}."
582   (if (pair? alist)
583       (begin
584         (set! (ly:music-property m (caar alist)) (cdar alist))
585         (set-mus-properties! m (cdr alist)))))
586
587 (define-public (music-separator? m)
588   "Is @var{m} a separator?"
589   (let ((ts (ly:music-property m 'types)))
590     (memq 'separator ts)))
591
592 ;;; splitting chords into voices.
593 (define (voicify-list lst number)
594   "Make a list of Musics.
595
596 voicify-list :: [ [Music ] ] -> number -> [Music]
597 LST is a list music-lists.
598
599 NUMBER is 0-base, i.e., Voice=1 (upstems) has number 0.
600 "
601   (if (null? lst)
602       '()
603       (cons (context-spec-music
604              (make-sequential-music
605               (list (make-voice-props-set number)
606                     (make-simultaneous-music (car lst))))
607              'Bottom  (number->string (1+ number)))
608             (voicify-list (cdr lst) (1+ number)))))
609
610 (define (voicify-chord ch)
611   "Split the parts of a chord into different Voices using separator"
612   (let ((es (ly:music-property ch 'elements)))
613     (set! (ly:music-property  ch 'elements)
614           (voicify-list (split-list-by-separator es music-separator?) 0))
615     ch))
616
617 (define-public (voicify-music m)
618   "Recursively split chords that are separated with @code{\\\\}."
619   (if (not (ly:music? m))
620       (ly:error (_ "music expected: ~S") m))
621   (let ((es (ly:music-property m 'elements))
622         (e (ly:music-property m 'element)))
623
624     (if (pair? es)
625         (set! (ly:music-property m 'elements) (map voicify-music es)))
626     (if (ly:music? e)
627         (set! (ly:music-property m 'element)  (voicify-music e)))
628     (if (and (equal? (ly:music-property m 'name) 'SimultaneousMusic)
629              (reduce (lambda (x y ) (or x y)) #f (map music-separator? es)))
630         (set! m (context-spec-music (voicify-chord m) 'Staff)))
631     m))
632
633 (define-public (empty-music)
634   (ly:export (make-music 'Music)))
635
636 ;; Make a function that checks score element for being of a specific type.
637 (define-public (make-type-checker symbol)
638   (lambda (elt)
639     (grob::has-interface elt symbol)))
640
641 (define-public ((outputproperty-compatibility func sym val) grob g-context ao-context)
642   (if (func grob)
643       (set! (ly:grob-property grob sym) val)))
644
645
646 (define-public ((set-output-property grob-name symbol val)  grob grob-c context)
647   "Usage example:
648 @code{\\applyoutput #(set-output-property 'Clef 'extra-offset '(0 . 1))}"
649   (let ((meta (ly:grob-property grob 'meta)))
650     (if (equal? (assoc-get 'name meta) grob-name)
651         (set! (ly:grob-property grob symbol) val))))
652
653
654 (define-public (skip->rest mus)
655   "Replace @var{mus} by @code{RestEvent} of the same duration if it is a
656 @code{SkipEvent}.  Useful for extracting parts from crowded scores."
657
658   (if  (memq (ly:music-property mus 'name) '(SkipEvent SkipMusic))
659    (make-music 'RestEvent 'duration (ly:music-property mus 'duration))
660    mus))
661
662
663 (define-public (music-has-type music type)
664   (memq type (ly:music-property music 'types)))
665
666 (define-public (music-clone music)
667   (define (alist->args alist acc)
668     (if (null? alist)
669         acc
670         (alist->args (cdr alist)
671                      (cons (caar alist) (cons (cdar alist) acc)))))
672
673   (apply
674    make-music
675    (ly:music-property music 'name)
676    (alist->args (ly:music-mutable-properties music) '())))
677
678 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
679 ;; warn for bare chords at start.
680
681 (define-public (ly:music-message music msg)
682   (let ((ip (ly:music-property music 'origin)))
683     (if (ly:input-location? ip)
684         (ly:input-message ip msg)
685         (ly:message msg))))
686
687 (define-public (ly:music-warning music msg)
688   (let ((ip (ly:music-property music 'origin)))
689     (if (ly:input-location? ip)
690         (ly:input-warning ip msg)
691         (ly:warning msg))))
692
693 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
694 ;;
695 ;; setting stuff for grace context.
696 ;;
697
698 (define (vector-extend v x)
699   "Make a new vector consisting of V, with X added to the end."
700   (let* ((n (vector-length v))
701          (nv (make-vector (+ n 1) '())))
702     (vector-move-left! v 0 n nv 0)
703     (vector-set! nv n x)
704     nv))
705
706 (define (vector-map f v)
707   "Map F over V.  This function returns nothing."
708   (do ((n (vector-length v))
709        (i 0 (+ i 1)))
710       ((>= i n))
711     (f (vector-ref v i))))
712
713 (define (vector-reverse-map f v)
714   "Map F over V, N to 0 order.  This function returns nothing."
715   (do ((i (- (vector-length v) 1) (- i 1)))
716       ((< i 0))
717     (f (vector-ref v i))))
718
719 (define-public (add-grace-property context-name grob sym val)
720   "Set @var{sym}=@var{val} for @var{grob} in @var{context-name}."
721   (define (set-prop context)
722     (let* ((where (ly:context-property-where-defined context 'graceSettings))
723            (current (ly:context-property where 'graceSettings))
724            (new-settings (append current
725                                  (list (list context-name grob sym val)))))
726       (ly:context-set-property! where 'graceSettings new-settings)))
727   (ly:export (context-spec-music (make-apply-context set-prop) 'Voice)))
728
729 (define-public (remove-grace-property context-name grob sym)
730   "Remove all @var{sym} for @var{grob} in @var{context-name}."
731   (define (sym-grob-context? property sym grob context-name)
732     (and (eq? (car property) context-name)
733          (eq? (cadr property) grob)
734          (eq? (caddr property) sym)))
735   (define (delete-prop context)
736     (let* ((where (ly:context-property-where-defined context 'graceSettings))
737            (current (ly:context-property where 'graceSettings))
738            (prop-settings (filter
739                             (lambda(x) (sym-grob-context? x sym grob context-name))
740                             current))
741            (new-settings current))
742       (for-each (lambda(x)
743                  (set! new-settings (delete x new-settings)))
744                prop-settings)
745       (ly:context-set-property! where 'graceSettings new-settings)))
746   (ly:export (context-spec-music (make-apply-context delete-prop) 'Voice)))
747
748
749
750 (defmacro-public def-grace-function (start stop . docstring)
751   "Helper macro for defining grace music"
752   `(define-music-function (parser location music) (ly:music?)
753      ,@docstring
754      (make-music 'GraceMusic
755                  'origin location
756                  'element (make-music 'SequentialMusic
757                                       'elements (list (ly:music-deep-copy ,start)
758                                                       music
759                                                       (ly:music-deep-copy ,stop))))))
760
761 (defmacro-public define-music-function (args signature . body)
762   "Helper macro for `ly:make-music-function'.
763 Syntax:
764   (define-music-function (parser location arg1 arg2 ...) (arg1-type? arg2-type? ...)
765     ...function body...)
766 "
767 (if (and (pair? body) (pair? (car body)) (eqv? '_i (caar body)))
768       ;; When the music function definition contains a i10n doc string,
769       ;; (_i "doc string"), keep the literal string only
770       (let ((docstring (cadar body))
771             (body (cdr body)))
772         `(ly:make-music-function (list ,@signature)
773                                  (lambda (,@args)
774                                    ,docstring
775                                    ,@body)))
776       `(ly:make-music-function (list ,@signature)
777                                (lambda (,@args)
778                                  ,@body))))
779
780
781 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
782
783 (define-public (cue-substitute quote-music)
784   "Must happen after @code{quote-substitute}."
785
786   (if (vector? (ly:music-property quote-music 'quoted-events))
787       (let* ((dir (ly:music-property quote-music 'quoted-voice-direction))
788              (clef (ly:music-property quote-music 'quoted-music-clef))
789              (main-voice (if (eq? 1 dir) 1 0))
790              (cue-voice (if (eq? 1 dir) 0 1))
791              (main-music (ly:music-property quote-music 'element))
792              (return-value quote-music))
793
794         (if (or (eq? 1 dir) (eq? -1 dir))
795
796             ;; if we have stem dirs, change both quoted and main music
797             ;; to have opposite stems.
798             (begin
799               (set! return-value
800                     ;; cannot context-spec Quote-music, since context
801                     ;; for the quotes is determined in the iterator.
802                     (make-sequential-music
803                      (list
804                       (if (null? clef)
805                           (make-music 'Music)
806                           (make-cue-clef-set clef))
807                       (context-spec-music (make-voice-props-set cue-voice) 'CueVoice "cue")
808                       quote-music
809                       (context-spec-music (make-voice-props-revert) 'CueVoice "cue")
810                       (if (null? clef)
811                           (make-music 'Music)
812                           (make-cue-clef-unset)))))
813               (set! main-music
814                     (make-sequential-music
815                      (list
816                       (make-voice-props-set main-voice)
817                       main-music
818                       (make-voice-props-revert))))
819               (set! (ly:music-property quote-music 'element) main-music)))
820
821         return-value)
822       quote-music))
823
824 (define-public ((quote-substitute quote-tab) music)
825   (let* ((quoted-name (ly:music-property music 'quoted-music-name))
826          (quoted-vector (and (string? quoted-name)
827                              (hash-ref quote-tab quoted-name #f))))
828
829
830     (if (string? quoted-name)
831         (if (vector? quoted-vector)
832             (begin
833               (set! (ly:music-property music 'quoted-events) quoted-vector)
834               (set! (ly:music-property music 'iterator-ctor)
835                     ly:quote-iterator::constructor))
836             (ly:music-warning music (ly:format (_ "cannot find quoted music: `~S'") quoted-name))))
837     music))
838
839
840 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
841 ;; switch it on here, so parsing and init isn't checked (too slow!)
842 ;;
843 ;; automatic music transformations.
844
845 (define (switch-on-debugging m)
846   (if (defined? 'set-debug-cell-accesses!)
847       (set-debug-cell-accesses! 15000))
848   m)
849
850 (define (music-check-error music)
851   (define found #f)
852   (define (signal m)
853     (if (and (ly:music? m)
854              (eq? (ly:music-property m 'error-found) #t))
855         (set! found #t)))
856
857   (for-each signal (ly:music-property music 'elements))
858   (signal (ly:music-property music 'element))
859
860   (if found
861       (set! (ly:music-property music 'error-found) #t))
862   music)
863
864 (define (precompute-music-length music)
865   (set! (ly:music-property music 'length)
866         (ly:music-length music))
867   music)
868
869 (define-public (make-duration-of-length moment)
870  "Make duration of the given @code{moment} length."
871  (ly:make-duration 0 0
872   (ly:moment-main-numerator moment)
873   (ly:moment-main-denominator moment)))
874
875 (define (make-skipped moment bool)
876  "Depending on BOOL, set or unset skipTypesetting,
877 then make SkipMusic of the given MOMENT length, and
878 then revert skipTypesetting."
879  (make-sequential-music
880   (list
881    (context-spec-music (make-property-set 'skipTypesetting bool)
882     'Score)
883    (make-music 'SkipMusic 'duration
884     (make-duration-of-length moment))
885    (context-spec-music (make-property-set 'skipTypesetting (not bool))
886     'Score))))
887
888 (define (skip-as-needed music parser)
889   "Replace MUSIC by
890  << {  \\set skipTypesetting = ##f
891  LENGTHOF(\\showFirstLength)
892  \\set skipTypesetting = ##t
893  LENGTHOF(\\showLastLength) }
894  MUSIC >>
895  if appropriate.
896
897  When only showFirstLength is set,
898  the 'length property of the music is
899  overridden to speed up compiling."
900   (let*
901       ((show-last (ly:parser-lookup parser 'showLastLength))
902        (show-first (ly:parser-lookup parser 'showFirstLength))
903        (show-last-length (and (ly:music? show-last)
904                               (ly:music-length show-last)))
905        (show-first-length (and (ly:music? show-first)
906                                (ly:music-length show-first)))
907        (orig-length (ly:music-length music)))
908
909     ;;FIXME: if using either showFirst- or showLastLength,
910     ;; make sure that skipBars is not set.
911
912     (cond
913
914      ;; both properties may be set.
915      ((and show-first-length show-last-length)
916       (let
917           ((skip-length (ly:moment-sub orig-length show-last-length)))
918         (make-simultaneous-music
919          (list
920           (make-sequential-music
921            (list
922             (make-skipped skip-length #t)
923             ;; let's draw a separator between the beginning and the end
924             (context-spec-music (make-property-set 'whichBar "||")
925                                 'Timing)))
926           (make-skipped show-first-length #f)
927           music))))
928
929      ;; we may only want to print the last length
930      (show-last-length
931       (let
932           ((skip-length (ly:moment-sub orig-length show-last-length)))
933         (make-simultaneous-music
934          (list
935           (make-skipped skip-length #t)
936           music))))
937
938      ;; we may only want to print the beginning; in this case
939      ;; only the first length will be processed (much faster).
940      (show-first-length
941       ;; the first length must not exceed the original length.
942       (if (ly:moment<? show-first-length orig-length)
943           (set! (ly:music-property music 'length)
944                 show-first-length))
945       music)
946
947      (else music))))
948
949
950 (define-public toplevel-music-functions
951   (list
952    (lambda (music parser) (voicify-music music))
953    (lambda (x parser) (music-map music-check-error x))
954    (lambda (x parser) (music-map precompute-music-length x))
955    (lambda (music parser)
956
957      (music-map (quote-substitute (ly:parser-lookup parser 'musicQuotes))  music))
958
959    ;; switch-on-debugging
960    (lambda (x parser) (music-map cue-substitute x))
961
962    (lambda (x parser)
963      (skip-as-needed x parser)
964    )))
965
966 ;;;;;;;;;;
967 ;;; general purpose music functions
968
969 (define (shift-octave pitch octave-shift)
970   (_i "Add @var{octave-shift} to the octave of @var{pitch}.")
971   (ly:make-pitch
972      (+ (ly:pitch-octave pitch) octave-shift)
973      (ly:pitch-notename pitch)
974      (ly:pitch-alteration pitch)))
975
976
977 ;;;;;;;;;;;;;;;;;
978 ;; lyrics
979
980 (define (apply-durations lyric-music durations)
981   (define (apply-duration music)
982     (if (and (not (equal? (ly:music-length music) ZERO-MOMENT))
983              (ly:duration?  (ly:music-property music 'duration)))
984         (begin
985           (set! (ly:music-property music 'duration) (car durations))
986           (set! durations (cdr durations)))))
987
988   (music-map apply-duration lyric-music))
989
990
991 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
992 ;; accidentals
993
994 (define (recent-enough? bar-number alteration-def laziness)
995   (or (number? alteration-def)
996       (equal? laziness #t)
997       (<= bar-number (+ (cadr alteration-def) laziness))))
998
999 (define (accidental-invalid? alteration-def)
1000   "Checks an alteration entry for being invalid.
1001
1002 Non-key alterations are invalidated when tying into the next bar or
1003 when there is a clef change, since neither repetition nor cancellation
1004 can be omitted when the same note occurs again.
1005
1006 Returns @code{#f} or the reason for the invalidation, a symbol."
1007   (let* ((def (if (pair? alteration-def)
1008                   (car alteration-def)
1009                   alteration-def)))
1010     (and (symbol? def) def)))
1011
1012 (define (extract-alteration alteration-def)
1013   (cond ((number? alteration-def)
1014          alteration-def)
1015         ((pair? alteration-def)
1016          (car alteration-def))
1017         (else 0)))
1018
1019 (define (check-pitch-against-signature context pitch barnum laziness octaveness)
1020   "Checks the need for an accidental and a @q{restore} accidental against
1021 @code{localKeySignature}.  The @var{laziness} is the number of measures
1022 for which reminder accidentals are used (i.e., if @var{laziness} is zero,
1023 only cancel accidentals in the same measure; if @var{laziness} is three,
1024 we cancel accidentals up to three measures after they first appear.
1025 @var{octaveness} is either @code{'same-octave} or @code{'any-octave} and
1026 specifies whether accidentals should be canceled in different octaves."
1027   (let* ((ignore-octave (cond ((equal? octaveness 'any-octave) #t)
1028                               ((equal? octaveness 'same-octave) #f)
1029                               (else
1030                                (ly:warning (_ "Unknown octaveness type: ~S ") octaveness)
1031                                (ly:warning (_ "Defaulting to 'any-octave."))
1032                                #t)))
1033          (key-sig (ly:context-property context 'keySignature))
1034          (local-key-sig (ly:context-property context 'localKeySignature))
1035          (notename (ly:pitch-notename pitch))
1036          (octave (ly:pitch-octave pitch))
1037          (pitch-handle (cons octave notename))
1038          (need-restore #f)
1039          (need-accidental #f)
1040          (previous-alteration #f)
1041          (from-other-octaves #f)
1042          (from-same-octave (assoc-get pitch-handle local-key-sig))
1043          (from-key-sig (or (assoc-get notename local-key-sig)
1044
1045     ;; If no key signature match is found from localKeySignature, we may have a custom
1046     ;; type with octave-specific entries of the form ((octave . pitch) alteration)
1047     ;; instead of (pitch . alteration).  Since this type cannot coexist with entries in
1048     ;; localKeySignature, try extracting from keySignature instead.
1049                            (assoc-get pitch-handle key-sig))))
1050
1051     ;; loop through localKeySignature to search for a notename match from other octaves
1052     (let loop ((l local-key-sig))
1053       (if (pair? l)
1054           (let ((entry (car l)))
1055             (if (and (pair? (car entry))
1056                      (= (cdar entry) notename))
1057                 (set! from-other-octaves (cdr entry))
1058                 (loop (cdr l))))))
1059
1060     ;; find previous alteration-def for comparison with pitch
1061     (cond
1062      ;; from same octave?
1063      ((and (not ignore-octave)
1064            from-same-octave
1065            (recent-enough? barnum from-same-octave laziness))
1066       (set! previous-alteration from-same-octave))
1067
1068      ;; from any octave?
1069      ((and ignore-octave
1070            from-other-octaves
1071            (recent-enough? barnum from-other-octaves laziness))
1072       (set! previous-alteration from-other-octaves))
1073
1074      ;; not recent enough, extract from key signature/local key signature
1075      (from-key-sig
1076       (set! previous-alteration from-key-sig)))
1077
1078     (if (accidental-invalid? previous-alteration)
1079         (set! need-accidental #t)
1080
1081         (let* ((prev-alt (extract-alteration previous-alteration))
1082                (this-alt (ly:pitch-alteration pitch)))
1083
1084           (if (not (= this-alt prev-alt))
1085               (begin
1086                 (set! need-accidental #t)
1087                 (if (and (not (= this-alt 0))
1088                          (and (< (abs this-alt) (abs prev-alt))
1089                              (> (* prev-alt this-alt) 0)))
1090                     (set! need-restore #t))))))
1091
1092     (cons need-restore need-accidental)))
1093
1094 (define-public ((make-accidental-rule octaveness laziness) context pitch barnum measurepos)
1095   "Create an accidental rule that makes its decision based on the octave of
1096 the note and a laziness value.
1097
1098 @var{octaveness} is either @code{'same-octave} or @code{'any-octave} and
1099 defines whether the rule should respond to accidental changes in other
1100 octaves than the current.  @code{'same-octave} is the normal way to typeset
1101 accidentals -- an accidental is made if the alteration is different from the
1102 last active pitch in the same octave.  @code{'any-octave} looks at the last
1103 active pitch in any octave.
1104
1105 @var{laziness} states over how many bars an accidental should be remembered.
1106 @code{0}@tie{}is the default -- accidental lasts over 0@tie{}bar lines, that
1107 is, to the end of current measure.  A positive integer means that the
1108 accidental lasts over that many bar lines.  @w{@code{-1}} is `forget
1109 immediately', that is, only look at key signature.  @code{#t} is `forever'."
1110
1111   (check-pitch-against-signature context pitch barnum laziness octaveness))
1112
1113 (define (key-entry-notename entry)
1114   "Return the pitch of an entry in localKeySignature.  The entry is either of the form
1115   '(notename . alter) or '((octave . notename) . (alter barnum . measurepos))."
1116   (if (number? (car entry))
1117       (car entry)
1118       (cdar entry)))
1119
1120 (define (key-entry-octave entry)
1121   "Return the octave of an entry in localKeySignature (or #f if the entry does not have
1122   an octave)."
1123   (and (pair? (car entry)) (caar entry)))
1124
1125 (define (key-entry-bar-number entry)
1126   "Return the bar number of an entry in localKeySignature (or #f if the entry does not
1127   have a bar number)."
1128   (and (pair? (car entry)) (caddr entry)))
1129
1130 (define (key-entry-measure-position entry)
1131   "Return the measure position of an entry in localKeySignature (or #f if the entry does
1132   not have a measure position)."
1133   (and (pair? (car entry)) (cdddr entry)))
1134
1135 (define (key-entry-alteration entry)
1136   "Return the alteration of an entry in localKeySignature.
1137
1138 For convenience, returns @code{0} if entry is @code{#f}."
1139   (if entry
1140       (if (number? (car entry))
1141           (cdr entry)
1142           (cadr entry))
1143       0))
1144
1145 (define-public (find-pitch-entry keysig pitch accept-global accept-local)
1146   "Return the first entry in @var{keysig} that matches @var{pitch}.
1147 @var{accept-global} states whether key signature entries should be included.
1148 @var{accept-local} states whether local accidentals should be included.
1149 If no matching entry is found, @var{#f} is returned."
1150   (and (pair? keysig)
1151        (let* ((entry (car keysig))
1152               (entryoct (key-entry-octave entry))
1153               (entrynn (key-entry-notename entry))
1154               (oct (ly:pitch-octave pitch))
1155               (nn (ly:pitch-notename pitch)))
1156          (if (and (equal? nn entrynn)
1157                   (or (and accept-global (not entryoct))
1158                       (and accept-local (equal? oct entryoct))))
1159              entry
1160              (find-pitch-entry (cdr keysig) pitch accept-global accept-local)))))
1161
1162 (define-public (neo-modern-accidental-rule context pitch barnum measurepos)
1163   "An accidental rule that typesets an accidental if it differs from the
1164 key signature @emph{and} does not directly follow a note on the same
1165 staff line.  This rule should not be used alone because it does neither
1166 look at bar lines nor different accidentals at the same note name."
1167   (let* ((keysig (ly:context-property context 'localKeySignature))
1168          (entry (find-pitch-entry keysig pitch #t #t)))
1169     (if (not entry)
1170         (cons #f #f)
1171         (let* ((global-entry (find-pitch-entry keysig pitch #t #f))
1172                (key-acc (key-entry-alteration global-entry))
1173                (acc (ly:pitch-alteration pitch))
1174                (entrymp (key-entry-measure-position entry))
1175                (entrybn (key-entry-bar-number entry)))
1176           (cons #f (not (or (equal? acc key-acc)
1177                             (and (equal? entrybn barnum) (equal? entrymp measurepos)))))))))
1178
1179 (define-public (teaching-accidental-rule context pitch barnum measurepos)
1180   "An accidental rule that typesets a cautionary accidental if it is
1181 included in the key signature @emph{and} does not directly follow a note
1182 on the same staff line."
1183   (let* ((keysig (ly:context-property context 'localKeySignature))
1184          (entry (find-pitch-entry keysig pitch #t #t)))
1185     (if (not entry)
1186         (cons #f #f)
1187         (let* ((global-entry (find-pitch-entry keysig pitch #f #f))
1188                (key-acc (key-entry-alteration global-entry))
1189                (acc (ly:pitch-alteration pitch))
1190                (entrymp (key-entry-measure-position entry))
1191                (entrybn (key-entry-bar-number entry)))
1192           (cons #f (not (or (equal? acc key-acc)
1193                             (and (equal? entrybn barnum) (equal? entrymp measurepos)))))))))
1194
1195 (define-public (set-accidentals-properties extra-natural
1196                                            auto-accs auto-cauts
1197                                            context)
1198   (context-spec-music
1199    (make-sequential-music
1200     (append (if (boolean? extra-natural)
1201                 (list (make-property-set 'extraNatural extra-natural))
1202                 '())
1203             (list (make-property-set 'autoAccidentals auto-accs)
1204                   (make-property-set 'autoCautionaries auto-cauts))))
1205    context))
1206
1207 (define-public (set-accidental-style style . rest)
1208   "Set accidental style to @var{style}.  Optionally take a context
1209 argument, e.g. @code{'Staff} or @code{'Voice}.  The context defaults
1210 to @code{Staff}, except for piano styles, which use @code{GrandStaff}
1211 as a context."
1212   (let ((context (if (pair? rest)
1213                      (car rest) 'Staff))
1214         (pcontext (if (pair? rest)
1215                       (car rest) 'GrandStaff)))
1216     (ly:export
1217      (cond
1218       ;; accidentals as they were common in the 18th century.
1219       ((equal? style 'default)
1220        (set-accidentals-properties #t
1221                                    `(Staff ,(make-accidental-rule 'same-octave 0))
1222                                    '()
1223                                    context))
1224       ;; accidentals from one voice do NOT get cancelled in other voices
1225       ((equal? style 'voice)
1226        (set-accidentals-properties #t
1227                                    `(Voice ,(make-accidental-rule 'same-octave 0))
1228                                    '()
1229                                    context))
1230       ;; accidentals as suggested by Kurt Stone, Music Notation in the 20th century.
1231       ;; This includes all the default accidentals, but accidentals also needs cancelling
1232       ;; in other octaves and in the next measure.
1233       ((equal? style 'modern)
1234        (set-accidentals-properties #f
1235                                    `(Staff ,(make-accidental-rule 'same-octave 0)
1236                                            ,(make-accidental-rule 'any-octave 0)
1237                                            ,(make-accidental-rule 'same-octave 1))
1238                                    '()
1239                                    context))
1240       ;; the accidentals that Stone adds to the old standard as cautionaries
1241       ((equal? style 'modern-cautionary)
1242        (set-accidentals-properties #f
1243                                    `(Staff ,(make-accidental-rule 'same-octave 0))
1244                                    `(Staff ,(make-accidental-rule 'any-octave 0)
1245                                            ,(make-accidental-rule 'same-octave 1))
1246                                    context))
1247       ;; same as modern, but accidentals different from the key signature are always
1248       ;; typeset - unless they directly follow a note of the same pitch.
1249       ((equal? style 'neo-modern)
1250        (set-accidentals-properties #f
1251                                    `(Staff ,(make-accidental-rule 'same-octave 0)
1252                                            ,(make-accidental-rule 'any-octave 0)
1253                                            ,(make-accidental-rule 'same-octave 1)
1254                                            ,neo-modern-accidental-rule)
1255                                    '()
1256                                    context))
1257       ((equal? style 'neo-modern-cautionary)
1258        (set-accidentals-properties #f
1259                                    `(Staff ,(make-accidental-rule 'same-octave 0))
1260                                    `(Staff ,(make-accidental-rule 'any-octave 0)
1261                                            ,(make-accidental-rule 'same-octave 1)
1262                                            ,neo-modern-accidental-rule)
1263                                    context))
1264       ((equal? style 'neo-modern-voice)
1265        (set-accidentals-properties #f
1266                                    `(Voice ,(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                                      Staff ,(make-accidental-rule 'same-octave 0)
1271                                            ,(make-accidental-rule 'any-octave 0)
1272                                            ,(make-accidental-rule 'same-octave 1)
1273                                       ,neo-modern-accidental-rule)
1274                                    '()
1275                                    context))
1276       ((equal? style 'neo-modern-voice-cautionary)
1277        (set-accidentals-properties #f
1278                                    `(Voice ,(make-accidental-rule 'same-octave 0))
1279                                    `(Voice ,(make-accidental-rule 'any-octave 0)
1280                                            ,(make-accidental-rule 'same-octave 1)
1281                                            ,neo-modern-accidental-rule
1282                                      Staff ,(make-accidental-rule 'same-octave 0)
1283                                            ,(make-accidental-rule 'any-octave 0)
1284                                            ,(make-accidental-rule 'same-octave 1)
1285                                            ,neo-modern-accidental-rule)
1286                                    context))
1287       ;; Accidentals as they were common in dodecaphonic music with no tonality.
1288       ;; Each note gets one accidental.
1289       ((equal? style 'dodecaphonic)
1290        (set-accidentals-properties #f
1291                                    `(Staff ,(lambda (c p bn mp) '(#f . #t)))
1292                                    '()
1293                                    context))
1294       ;; Multivoice accidentals to be read both by musicians playing one voice
1295       ;; and musicians playing all voices.
1296       ;; Accidentals are typeset for each voice, but they ARE cancelled across voices.
1297       ((equal? style 'modern-voice)
1298        (set-accidentals-properties  #f
1299                                     `(Voice ,(make-accidental-rule 'same-octave 0)
1300                                             ,(make-accidental-rule 'any-octave 0)
1301                                             ,(make-accidental-rule 'same-octave 1)
1302                                       Staff ,(make-accidental-rule 'same-octave 0)
1303                                             ,(make-accidental-rule 'any-octave 0)
1304                                             ,(make-accidental-rule 'same-octave 1))
1305                                     '()
1306                                     context))
1307       ;; same as modernVoiceAccidental eccept that all special accidentals are typeset
1308       ;; as cautionaries
1309       ((equal? style 'modern-voice-cautionary)
1310        (set-accidentals-properties #f
1311                                    `(Voice ,(make-accidental-rule 'same-octave 0))
1312                                    `(Voice ,(make-accidental-rule 'any-octave 0)
1313                                            ,(make-accidental-rule 'same-octave 1)
1314                                      Staff ,(make-accidental-rule 'same-octave 0)
1315                                            ,(make-accidental-rule 'any-octave 0)
1316                                            ,(make-accidental-rule 'same-octave 1))
1317                                    context))
1318       ;; stone's suggestions for accidentals on grand staff.
1319       ;; Accidentals are cancelled across the staves in the same grand staff as well
1320       ((equal? style 'piano)
1321        (set-accidentals-properties #f
1322                                    `(Staff ,(make-accidental-rule 'same-octave 0)
1323                                            ,(make-accidental-rule 'any-octave 0)
1324                                            ,(make-accidental-rule 'same-octave 1)
1325                                      GrandStaff
1326                                            ,(make-accidental-rule 'any-octave 0)
1327                                            ,(make-accidental-rule 'same-octave 1))
1328                                    '()
1329                                    pcontext))
1330       ((equal? style 'piano-cautionary)
1331        (set-accidentals-properties #f
1332                                    `(Staff ,(make-accidental-rule 'same-octave 0))
1333                                    `(Staff ,(make-accidental-rule 'any-octave 0)
1334                                            ,(make-accidental-rule 'same-octave 1)
1335                                      GrandStaff
1336                                            ,(make-accidental-rule 'any-octave 0)
1337                                            ,(make-accidental-rule 'same-octave 1))
1338                                    pcontext))
1339
1340       ;; same as modern, but cautionary accidentals are printed for all sharp or flat
1341       ;; tones specified by the key signature.
1342        ((equal? style 'teaching)
1343        (set-accidentals-properties #f
1344                                     `(Staff ,(make-accidental-rule 'same-octave 0))
1345                                     `(Staff ,(make-accidental-rule 'same-octave 1)
1346                                            ,teaching-accidental-rule)
1347                                    context))
1348
1349       ;; do not set localKeySignature when a note alterated differently from
1350       ;; localKeySignature is found.
1351       ;; Causes accidentals to be printed at every note instead of
1352       ;; remembered for the duration of a measure.
1353       ;; accidentals not being remembered, causing accidentals always to
1354       ;; be typeset relative to the time signature
1355       ((equal? style 'forget)
1356        (set-accidentals-properties '()
1357                                    `(Staff ,(make-accidental-rule 'same-octave -1))
1358                                    '()
1359                                    context))
1360       ;; Do not reset the key at the start of a measure.  Accidentals will be
1361       ;; printed only once and are in effect until overridden, possibly many
1362       ;; measures later.
1363       ((equal? style 'no-reset)
1364        (set-accidentals-properties '()
1365                                    `(Staff ,(make-accidental-rule 'same-octave #t))
1366                                    '()
1367                                    context))
1368       (else
1369        (ly:warning (_ "unknown accidental style: ~S") style)
1370        (make-sequential-music '()))))))
1371
1372 (define-public (invalidate-alterations context)
1373   "Invalidate alterations in @var{context}.
1374
1375 Elements of @code{'localKeySignature} corresponding to local
1376 alterations of the key signature have the form
1377 @code{'((octave . notename) . (alter barnum . measurepos))}.
1378 Replace them with a version where @code{alter} is set to @code{'clef}
1379 to force a repetition of accidentals.
1380
1381 Entries that conform with the current key signature are not invalidated."
1382   (let* ((keysig (ly:context-property context 'keySignature)))
1383     (set! (ly:context-property context 'localKeySignature)
1384           (map-in-order
1385            (lambda (entry)
1386              (let* ((localalt (key-entry-alteration entry))
1387                     (localoct (key-entry-octave entry)))
1388                (if (or (accidental-invalid? localalt)
1389                        (not localoct)
1390                        (= localalt
1391                           (key-entry-alteration
1392                            (find-pitch-entry
1393                             keysig
1394                             (ly:make-pitch localoct
1395                                            (key-entry-notename entry)
1396                                            0)
1397                             #t #t))))
1398                    entry
1399                    (cons (car entry) (cons 'clef (cddr entry))))))
1400            (ly:context-property context 'localKeySignature)))))
1401                     
1402 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1403
1404 (define-public (skip-of-length mus)
1405   "Create a skip of exactly the same length as @var{mus}."
1406   (let* ((skip
1407           (make-music
1408            'SkipEvent
1409            'duration (ly:make-duration 0 0))))
1410
1411     (make-event-chord (list (ly:music-compress skip (ly:music-length mus))))))
1412
1413 (define-public (mmrest-of-length mus)
1414   "Create a multi-measure rest of exactly the same length as @var{mus}."
1415
1416   (let* ((skip
1417           (make-multi-measure-rest
1418            (ly:make-duration 0 0) '())))
1419     (ly:music-compress skip (ly:music-length mus))
1420     skip))
1421
1422 (define-public (pitch-of-note event-chord)
1423   (let ((evs (filter (lambda (x)
1424                        (music-has-type x 'note-event))
1425                      (ly:music-property event-chord 'elements))))
1426
1427     (and (pair? evs)
1428          (ly:music-property (car evs) 'pitch))))
1429
1430 (define-public (duration-of-note event-chord)
1431   (let ((evs (filter (lambda (x)
1432                        (music-has-type x 'rhythmic-event))
1433                      (ly:music-property event-chord 'elements))))
1434
1435     (and (pair? evs)
1436          (ly:music-property (car evs) 'duration))))
1437
1438 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1439
1440 (define-public (extract-named-music music music-name)
1441   "Return a flat list of all music named @var{music-name} from @var{music}."
1442    (let ((extracted-list
1443           (if (ly:music? music)
1444               (if (eq? (ly:music-property music 'name) music-name)
1445                   (list music)
1446                   (let ((elt (ly:music-property music 'element))
1447                         (elts (ly:music-property music 'elements)))
1448                     (if (ly:music? elt)
1449                         (extract-named-music elt music-name)
1450                         (if (null? elts)
1451                             '()
1452                             (map (lambda(x)
1453                                     (extract-named-music x music-name ))
1454                              elts)))))
1455               '())))
1456      (flatten-list extracted-list)))
1457
1458 (define-public (event-chord-notes event-chord)
1459   "Return a list of all notes from @var{event-chord}."
1460   (filter
1461     (lambda (m) (eq? 'NoteEvent (ly:music-property m 'name)))
1462     (ly:music-property event-chord 'elements)))
1463
1464 (define-public (event-chord-pitches event-chord)
1465   "Return a list of all pitches from @var{event-chord}."
1466   (map (lambda (x) (ly:music-property x 'pitch))
1467        (event-chord-notes event-chord)))