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