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