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