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