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