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