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