]> git.donarmstrong.com Git - lilypond.git/blob - scm/music-functions.scm
a25deb60e4c958501795e922dbe18c7f3d8b5c69
[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-filter pred? music)
70   "Filter out music expressions that do not satisfy @var{pred?}."
71
72   (define (inner-music-filter pred? music)
73     "Recursive function."
74     (let* ((es (ly:music-property music 'elements))
75            (e (ly:music-property music 'element))
76            (as (ly:music-property music 'articulations))
77            (filtered-as (filter ly:music? (map (lambda (y) (inner-music-filter pred? y)) as)))
78            (filtered-e (if (ly:music? e)
79                            (inner-music-filter pred? e)
80                            e))
81            (filtered-es (filter ly:music? (map (lambda (y) (inner-music-filter pred? y)) es))))
82       (set! (ly:music-property music 'element) filtered-e)
83       (set! (ly:music-property music 'elements) filtered-es)
84       (set! (ly:music-property music 'articulations) filtered-as)
85       ;; if filtering emptied the expression, we remove it completely.
86       (if (or (not (pred? music))
87               (and (eq? filtered-es '()) (not (ly:music? e))
88                    (or (not (eq? es '()))
89                        (ly:music? e))))
90           (set! music '()))
91       music))
92
93   (set! music (inner-music-filter pred? music))
94   (if (ly:music? music)
95       music
96       (make-music 'Music)))       ;must return music.
97
98 (define-public (display-music music)
99   "Display music, not done with @code{music-map} for clarity of
100 presentation."
101
102   (display music)
103   (display ": { ")
104   (let ((es (ly:music-property music 'elements))
105         (e (ly:music-property music 'element)))
106     (display (ly:music-mutable-properties music))
107     (if (pair? es)
108         (begin (display "\nElements: {\n")
109                (map display-music es)
110                (display "}\n")))
111     (if (ly:music? e)
112         (begin
113           (display "\nChild:")
114           (display-music e))))
115   (display " }\n")
116   music)
117
118 ;;;
119 ;;; A scheme music pretty printer
120 ;;;
121 (define (markup-expression->make-markup markup-expression)
122   "Transform `markup-expression' into an equivalent, hopefuly readable, scheme expression.
123 For instance,
124   \\markup \\bold \\italic hello
125 ==>
126   (markup #:line (#:bold (#:italic (#:simple \"hello\"))))"
127   (define (proc->command-keyword proc)
128     "Return a keyword, eg. `#:bold', from the `proc' function, eg. #<procedure bold-markup (layout props arg)>"
129     (let ((cmd-markup (symbol->string (procedure-name proc))))
130       (symbol->keyword (string->symbol (substring cmd-markup 0 (- (string-length cmd-markup)
131                                                                   (string-length "-markup")))))))
132   (define (transform-arg arg)
133     (cond ((and (pair? arg) (markup? (car arg))) ;; a markup list
134            (apply append (map inner-markup->make-markup arg)))
135           ((and (not (string? arg)) (markup? arg)) ;; a markup
136            (inner-markup->make-markup arg))
137           (else                                  ;; scheme arg
138            (music->make-music arg))))
139   (define (inner-markup->make-markup mrkup)
140     (if (string? mrkup)
141         `(#:simple ,mrkup)
142         (let ((cmd (proc->command-keyword (car mrkup)))
143               (args (map transform-arg (cdr mrkup))))
144           `(,cmd ,@args))))
145   ;; body:
146   (if (string? markup-expression)
147       markup-expression
148       `(markup ,@(inner-markup->make-markup markup-expression))))
149
150 (define-public (music->make-music obj)
151   "Generate an expression that, once evaluated, may return an object
152 equivalent to @var{obj}, that is, for a music expression, a
153 @code{(make-music ...)} form."
154   (cond (;; markup expression
155          (markup? obj)
156          (markup-expression->make-markup obj))
157         (;; music expression
158          (ly:music? obj)
159          `(make-music
160            ',(ly:music-property obj 'name)
161            ,@(apply append (map (lambda (prop)
162                                   `(',(car prop)
163                                     ,(music->make-music (cdr prop))))
164                                 (remove (lambda (prop)
165                                           (eqv? (car prop) 'origin))
166                                         (ly:music-mutable-properties obj))))))
167         (;; moment
168          (ly:moment? obj)
169          `(ly:make-moment ,(ly:moment-main-numerator obj)
170                           ,(ly:moment-main-denominator obj)
171                           ,(ly:moment-grace-numerator obj)
172                           ,(ly:moment-grace-denominator obj)))
173         (;; note duration
174          (ly:duration? obj)
175          `(ly:make-duration ,(ly:duration-log obj)
176                             ,(ly:duration-dot-count obj)
177                             ,(car (ly:duration-factor obj))
178                             ,(cdr (ly:duration-factor obj))))
179         (;; note pitch
180          (ly:pitch? obj)
181          `(ly:make-pitch ,(ly:pitch-octave obj)
182                          ,(ly:pitch-notename obj)
183                          ,(ly:pitch-alteration obj)))
184         (;; scheme procedure
185          (procedure? obj)
186          (or (procedure-name obj) obj))
187         (;; a symbol (avoid having an unquoted symbol)
188          (symbol? obj)
189          `',obj)
190         (;; an empty list (avoid having an unquoted empty list)
191          (null? obj)
192          `'())
193         (;; a proper list
194          (list? obj)
195          `(list ,@(map music->make-music obj)))
196         (;; a pair
197          (pair? obj)
198          `(cons ,(music->make-music (car obj))
199                 ,(music->make-music (cdr obj))))
200         (else
201          obj)))
202
203 (use-modules (ice-9 pretty-print))
204 (define*-public (display-scheme-music obj #:optional (port (current-output-port)))
205   "Displays `obj', typically a music expression, in a friendly fashion,
206 which often can be read back in order to generate an equivalent expression.
207
208 Returns `obj'.
209 "
210   (pretty-print (music->make-music obj) port)
211   (newline)
212   obj)
213
214 ;;;
215 ;;; Scheme music expression --> Lily-syntax-using string translator
216 ;;;
217 (use-modules (srfi srfi-39)
218              (scm display-lily))
219
220 (define*-public (display-lily-music expr parser #:key force-duration)
221   "Display the music expression using LilyPond syntax"
222   (memoize-clef-names supported-clefs)
223   (parameterize ((*indent* 0)
224                  (*previous-duration* (ly:make-duration 2))
225                  (*force-duration* force-duration))
226     (display (music->lily-string expr parser))
227     (newline)))
228
229 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
230
231 (define-public (shift-one-duration-log music shift dot)
232   "Add @var{shift} to @code{duration-log} of @code{'duration} in
233 @var{music} and optionally @var{dot} to any note encountered.  This
234 scales the music up by a factor `2^@var{shift} * (2 - (1/2)^@var{dot})'."
235   (let ((d (ly:music-property music 'duration)))
236     (if (ly:duration? d)
237         (let* ((cp (ly:duration-factor d))
238                (nd (ly:make-duration (+ shift (ly:duration-log d))
239                                      (+ 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 ;;; Need to keep this definition for \time calls from parser
518 (define-public (make-time-signature-set num den)
519   "Set properties for time signature @var{num}/@var{den}."
520   (make-music 'TimeSignatureMusic
521               'numerator num
522               'denominator den
523               'beat-structure '()))
524
525 ;;; Used for calls that include beat-grouping setting
526 (define-public (set-time-signature num den . rest)
527   "Set properties for time signature @var{num}/@var{den}.
528 If @var{rest} is present, it is used to set @code{beatStructure}."
529   (ly:export
530    (make-music 'TimeSignatureMusic
531                'numerator num
532                'denominator den
533                'beat-structure (if (null? rest) rest (car rest)))))
534
535 (define-safe-public (make-articulation name)
536   (make-music 'ArticulationEvent
537               'articulation-type name))
538
539 (define-public (make-lyric-event string duration)
540   (make-music 'LyricEvent
541               'duration duration
542               'text string))
543
544 (define-safe-public (make-span-event type span-dir)
545   (make-music type
546               'span-direction span-dir))
547
548 (define-public (override-head-style heads style)
549   "Override style for @var{heads} to @var{style}."
550   (make-sequential-music
551     (if (pair? heads)
552         (map (lambda (h)
553               (make-grob-property-override h 'style style))
554          heads)
555         (list (make-grob-property-override heads 'style style)))))
556
557 (define-public (revert-head-style heads)
558   "Revert style for @var{heads}."
559   (make-sequential-music
560     (if (pair? heads)
561         (map (lambda (h)
562               (make-grob-property-revert h 'style))
563          heads)
564         (list (make-grob-property-revert heads 'style)))))
565
566 (define-public (style-note-heads heads style music)
567  "Set @var{style} for all @var{heads} in @var{music}.  Works both
568 inside of and outside of chord construct."
569   ;; are we inside a <...>?
570   (if (eq? (ly:music-property music 'name) 'NoteEvent)
571       ;; yes -> use a tweak
572       (begin
573         (set! (ly:music-property music 'tweaks)
574               (acons 'style style (ly:music-property music 'tweaks)))
575         music)
576       ;; not in <...>, so use overrides
577       (make-sequential-music
578         (list
579           (override-head-style heads style)
580           music
581           (revert-head-style heads)))))
582
583  (define-public (set-mus-properties! m alist)
584   "Set all of @var{alist} as properties of @var{m}."
585   (if (pair? alist)
586       (begin
587         (set! (ly:music-property m (caar alist)) (cdar alist))
588         (set-mus-properties! m (cdr alist)))))
589
590 (define-public (music-separator? m)
591   "Is @var{m} a separator?"
592   (let ((ts (ly:music-property m 'types)))
593     (memq 'separator ts)))
594
595 ;;; splitting chords into voices.
596 (define (voicify-list lst number)
597   "Make a list of Musics.
598
599 voicify-list :: [ [Music ] ] -> number -> [Music]
600 LST is a list music-lists.
601
602 NUMBER is 0-base, i.e., Voice=1 (upstems) has number 0.
603 "
604   (if (null? lst)
605       '()
606       (cons (context-spec-music
607              (make-sequential-music
608               (list (make-voice-props-set number)
609                     (make-simultaneous-music (car lst))))
610              'Bottom  (number->string (1+ number)))
611             (voicify-list (cdr lst) (1+ number)))))
612
613 (define (voicify-chord ch)
614   "Split the parts of a chord into different Voices using separator"
615   (let ((es (ly:music-property ch 'elements)))
616     (set! (ly:music-property  ch 'elements)
617           (voicify-list (split-list-by-separator es music-separator?) 0))
618     ch))
619
620 (define-public (voicify-music m)
621   "Recursively split chords that are separated with @code{\\\\}."
622   (if (not (ly:music? m))
623       (ly:error (_ "music expected: ~S") m))
624   (let ((es (ly:music-property m 'elements))
625         (e (ly:music-property m 'element)))
626
627     (if (pair? es)
628         (set! (ly:music-property m 'elements) (map voicify-music es)))
629     (if (ly:music? e)
630         (set! (ly:music-property m 'element)  (voicify-music e)))
631     (if (and (equal? (ly:music-property m 'name) 'SimultaneousMusic)
632              (reduce (lambda (x y ) (or x y)) #f (map music-separator? es)))
633         (set! m (context-spec-music (voicify-chord m) 'Staff)))
634     m))
635
636 (define-public (empty-music)
637   (ly:export (make-music 'Music)))
638
639 ;; Make a function that checks score element for being of a specific type.
640 (define-public (make-type-checker symbol)
641   (lambda (elt)
642     (grob::has-interface elt symbol)))
643
644 (define-public ((outputproperty-compatibility func sym val) grob g-context ao-context)
645   (if (func grob)
646       (set! (ly:grob-property grob sym) val)))
647
648
649 (define-public ((set-output-property grob-name symbol val)  grob grob-c context)
650   "Usage example:
651 @code{\\applyoutput #(set-output-property 'Clef 'extra-offset '(0 . 1))}"
652   (let ((meta (ly:grob-property grob 'meta)))
653     (if (equal? (assoc-get 'name meta) grob-name)
654         (set! (ly:grob-property grob symbol) val))))
655
656
657 (define-public (skip->rest mus)
658   "Replace @var{mus} by @code{RestEvent} of the same duration if it is a
659 @code{SkipEvent}.  Useful for extracting parts from crowded scores."
660
661   (if  (memq (ly:music-property mus 'name) '(SkipEvent SkipMusic))
662    (make-music 'RestEvent 'duration (ly:music-property mus 'duration))
663    mus))
664
665
666 (define-public (music-has-type music type)
667   (memq type (ly:music-property music 'types)))
668
669 (define-public (music-clone music)
670   (define (alist->args alist acc)
671     (if (null? alist)
672         acc
673         (alist->args (cdr alist)
674                      (cons (caar alist) (cons (cdar alist) acc)))))
675
676   (apply
677    make-music
678    (ly:music-property music 'name)
679    (alist->args (ly:music-mutable-properties music) '())))
680
681 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
682 ;; warn for bare chords at start.
683
684 (define-public (ly:music-message music msg)
685   (let ((ip (ly:music-property music 'origin)))
686     (if (ly:input-location? ip)
687         (ly:input-message ip msg)
688         (ly:message msg))))
689
690 (define-public (ly:music-warning music msg)
691   (let ((ip (ly:music-property music 'origin)))
692     (if (ly:input-location? ip)
693         (ly:input-warning ip msg)
694         (ly:warning msg))))
695
696 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
697 ;;
698 ;; setting stuff for grace context.
699 ;;
700
701 (define (vector-extend v x)
702   "Make a new vector consisting of V, with X added to the end."
703   (let* ((n (vector-length v))
704          (nv (make-vector (+ n 1) '())))
705     (vector-move-left! v 0 n nv 0)
706     (vector-set! nv n x)
707     nv))
708
709 (define (vector-map f v)
710   "Map F over V.  This function returns nothing."
711   (do ((n (vector-length v))
712        (i 0 (+ i 1)))
713       ((>= i n))
714     (f (vector-ref v i))))
715
716 (define (vector-reverse-map f v)
717   "Map F over V, N to 0 order.  This function returns nothing."
718   (do ((i (- (vector-length v) 1) (- i 1)))
719       ((< i 0))
720     (f (vector-ref v i))))
721
722 (define-public (add-grace-property context-name grob sym val)
723   "Set @var{sym}=@var{val} for @var{grob} in @var{context-name}."
724   (define (set-prop context)
725     (let* ((where (ly:context-property-where-defined context 'graceSettings))
726            (current (ly:context-property where 'graceSettings))
727            (new-settings (append current
728                                  (list (list context-name grob sym val)))))
729       (ly:context-set-property! where 'graceSettings new-settings)))
730   (ly:export (context-spec-music (make-apply-context set-prop) 'Voice)))
731
732 (define-public (remove-grace-property context-name grob sym)
733   "Remove all @var{sym} for @var{grob} in @var{context-name}."
734   (define (sym-grob-context? property sym grob context-name)
735     (and (eq? (car property) context-name)
736          (eq? (cadr property) grob)
737          (eq? (caddr property) sym)))
738   (define (delete-prop context)
739     (let* ((where (ly:context-property-where-defined context 'graceSettings))
740            (current (ly:context-property where 'graceSettings))
741            (prop-settings (filter
742                             (lambda(x) (sym-grob-context? x sym grob context-name))
743                             current))
744            (new-settings current))
745       (for-each (lambda(x)
746                  (set! new-settings (delete x new-settings)))
747                prop-settings)
748       (ly:context-set-property! where 'graceSettings new-settings)))
749   (ly:export (context-spec-music (make-apply-context delete-prop) 'Voice)))
750
751
752
753 (defmacro-public def-grace-function (start stop . docstring)
754   "Helper macro for defining grace music"
755   `(define-music-function (parser location music) (ly:music?)
756      ,@docstring
757      (make-music 'GraceMusic
758                  'origin location
759                  'element (make-music 'SequentialMusic
760                                       'elements (list (ly:music-deep-copy ,start)
761                                                       music
762                                                       (ly:music-deep-copy ,stop))))))
763
764 (defmacro-public define-syntax-function (type args signature . body)
765   "Helper macro for `ly:make-music-function'.
766 Syntax:
767   (define-syntax-function (result-type? parser location arg1 arg2 ...) (result-type? arg1-type arg2-type ...)
768     ...function body...)
769
770 argX-type can take one of the forms @code{predicate?} for mandatory
771 arguments satisfying the predicate, @code{(predicate?)} for optional
772 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
773 value)}} for optional parameters with a specified default
774 value (evaluated at definition time).  An optional parameter can be
775 omitted in a call only when it can't get confused with a following
776 parameter of different type.
777
778 Predicates with syntactical significance are @code{ly:pitch?},
779 @code{ly:duration?}, @code{ly:music?}, @code{markup?}.  Other
780 predicates require the parameter to be entered as Scheme expression.
781
782 @code{result-type?} can specify a default in the same manner as
783 predicates, to be used in case of a type error in arguments or
784 result."
785
786   (set! signature (map (lambda (pred)
787                          (if (pair? pred)
788                              `(cons ,(car pred)
789                                     ,(and (pair? (cdr pred)) (cadr pred)))
790                              pred))
791                        (cons type signature)))
792   (if (and (pair? body) (pair? (car body)) (eqv? '_i (caar body)))
793       ;; When the music function definition contains a i10n doc string,
794       ;; (_i "doc string"), keep the literal string only
795       (let ((docstring (cadar body))
796             (body (cdr body)))
797         `(ly:make-music-function (list ,@signature)
798                                  (lambda ,args
799                                    ,docstring
800                                    ,@body)))
801       `(ly:make-music-function (list ,@signature)
802                                (lambda ,args
803                                  ,@body))))
804
805 (defmacro-public define-music-function rest
806   "Defining macro returning music functions.
807 Syntax:
808   (define-music-function (parser location arg1 arg2 ...) (arg1-type? arg2-type? ...)
809     ...function body...)
810
811 argX-type can take one of the forms @code{predicate?} for mandatory
812 arguments satisfying the predicate, @code{(predicate?)} for optional
813 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
814 value)}} for optional parameters with a specified default
815 value (evaluated at definition time).  An optional parameter can be
816 omitted in a call only when it can't get confused with a following
817 parameter of different type.
818
819 Predicates with syntactical significance are @code{ly:pitch?},
820 @code{ly:duration?}, @code{ly:music?}, @code{markup?}.  Other
821 predicates require the parameter to be entered as Scheme expression.
822
823 Must return a music expression.  The @code{origin} is automatically
824 set to the @code{location} parameter."
825
826   `(define-syntax-function (ly:music? (make-music 'Music 'void #t)) ,@rest))
827
828
829 (defmacro-public define-scheme-function rest
830   "Defining macro returning Scheme functions.
831 Syntax:
832   (define-scheme-function (parser location arg1 arg2 ...) (arg1-type? arg2-type? ...)
833     ...function body...)
834
835 argX-type can take one of the forms @code{predicate?} for mandatory
836 arguments satisfying the predicate, @code{(predicate?)} for optional
837 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
838 value)}} for optional parameters with a specified default
839 value (evaluated at definition time).  An optional parameter can be
840 omitted in a call only when it can't get confused with a following
841 parameter of different type.
842
843 Predicates with syntactical significance are @code{ly:pitch?},
844 @code{ly:duration?}, @code{ly:music?}, @code{markup?}.  Other
845 predicates require the parameter to be entered as Scheme expression.
846
847 Can return arbitrary expressions.  If a music expression is returned,
848 its @code{origin} is automatically set to the @code{location}
849 parameter."
850
851   `(define-syntax-function scheme? ,@rest))
852
853 (defmacro-public define-void-function rest
854   "This defines a Scheme function like @code{define-scheme-function} with
855 void return value (i.e., what most Guile functions with `unspecified'
856 value return).  Use this when defining functions for executing actions
857 rather than returning values, to keep Lilypond from trying to interpret
858 the return value."
859   `(define-syntax-function (void? (begin)) ,@rest #f (begin)))
860
861 (defmacro-public define-event-function rest
862   "Defining macro returning event functions.
863 Syntax:
864   (define-event-function (parser location arg1 arg2 ...) (arg1-type? arg2-type? ...)
865     ...function body...)
866
867 argX-type can take one of the forms @code{predicate?} for mandatory
868 arguments satisfying the predicate, @code{(predicate?)} for optional
869 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
870 value)}} for optional parameters with a specified default
871 value (evaluated at definition time).  An optional parameter can be
872 omitted in a call only when it can't get confused with a following
873 parameter of different type.
874
875 Predicates with syntactical significance are @code{ly:pitch?},
876 @code{ly:duration?}, @code{ly:music?}, @code{markup?}.  Other
877 predicates require the parameter to be entered as Scheme expression.
878
879 Must return an event expression.  The @code{origin} is automatically
880 set to the @code{location} parameter."
881
882   `(define-syntax-function (ly:event? (make-music 'Event 'void #t)) ,@rest))
883
884 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
885
886 (define-public (cue-substitute quote-music)
887   "Must happen after @code{quote-substitute}."
888
889   (if (vector? (ly:music-property quote-music 'quoted-events))
890       (let* ((dir (ly:music-property quote-music 'quoted-voice-direction))
891              (clef (ly:music-property quote-music 'quoted-music-clef))
892              (main-voice (if (eq? 1 dir) 1 0))
893              (cue-voice (if (eq? 1 dir) 0 1))
894              (main-music (ly:music-property quote-music 'element))
895              (return-value quote-music))
896
897         (if (or (eq? 1 dir) (eq? -1 dir))
898
899             ;; if we have stem dirs, change both quoted and main music
900             ;; to have opposite stems.
901             (begin
902               (set! return-value
903                     ;; cannot context-spec Quote-music, since context
904                     ;; for the quotes is determined in the iterator.
905                     (make-sequential-music
906                      (list
907                       (if (null? clef)
908                           (make-music 'Music)
909                           (make-cue-clef-set clef))
910                       (context-spec-music (make-voice-props-set cue-voice) 'CueVoice "cue")
911                       quote-music
912                       (context-spec-music (make-voice-props-revert) 'CueVoice "cue")
913                       (if (null? clef)
914                           (make-music 'Music)
915                           (make-cue-clef-unset)))))
916               (set! main-music
917                     (make-sequential-music
918                      (list
919                       (make-voice-props-set main-voice)
920                       main-music
921                       (make-voice-props-revert))))
922               (set! (ly:music-property quote-music 'element) main-music)))
923
924         return-value)
925       quote-music))
926
927 (define-public ((quote-substitute quote-tab) music)
928   (let* ((quoted-name (ly:music-property music 'quoted-music-name))
929          (quoted-vector (and (string? quoted-name)
930                              (hash-ref quote-tab quoted-name #f))))
931
932
933     (if (string? quoted-name)
934         (if (vector? quoted-vector)
935             (begin
936               (set! (ly:music-property music 'quoted-events) quoted-vector)
937               (set! (ly:music-property music 'iterator-ctor)
938                     ly:quote-iterator::constructor))
939             (ly:music-warning music (ly:format (_ "cannot find quoted music: `~S'") quoted-name))))
940     music))
941
942
943 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
944 ;; switch it on here, so parsing and init isn't checked (too slow!)
945 ;;
946 ;; automatic music transformations.
947
948 (define (switch-on-debugging m)
949   (if (defined? 'set-debug-cell-accesses!)
950       (set-debug-cell-accesses! 15000))
951   m)
952
953 (define (music-check-error music)
954   (define found #f)
955   (define (signal m)
956     (if (and (ly:music? m)
957              (eq? (ly:music-property m 'error-found) #t))
958         (set! found #t)))
959
960   (for-each signal (ly:music-property music 'elements))
961   (signal (ly:music-property music 'element))
962
963   (if found
964       (set! (ly:music-property music 'error-found) #t))
965   music)
966
967 (define (precompute-music-length music)
968   (set! (ly:music-property music 'length)
969         (ly:music-length music))
970   music)
971
972 (define-public (make-duration-of-length moment)
973  "Make duration of the given @code{moment} length."
974  (ly:make-duration 0 0
975   (ly:moment-main-numerator moment)
976   (ly:moment-main-denominator moment)))
977
978 (define (make-skipped moment bool)
979  "Depending on BOOL, set or unset skipTypesetting,
980 then make SkipMusic of the given MOMENT length, and
981 then revert skipTypesetting."
982  (make-sequential-music
983   (list
984    (context-spec-music (make-property-set 'skipTypesetting bool)
985     'Score)
986    (make-music 'SkipMusic 'duration
987     (make-duration-of-length moment))
988    (context-spec-music (make-property-set 'skipTypesetting (not bool))
989     'Score))))
990
991 (define (skip-as-needed music parser)
992   "Replace MUSIC by
993  << {  \\set skipTypesetting = ##f
994  LENGTHOF(\\showFirstLength)
995  \\set skipTypesetting = ##t
996  LENGTHOF(\\showLastLength) }
997  MUSIC >>
998  if appropriate.
999
1000  When only showFirstLength is set,
1001  the 'length property of the music is
1002  overridden to speed up compiling."
1003   (let*
1004       ((show-last (ly:parser-lookup parser 'showLastLength))
1005        (show-first (ly:parser-lookup parser 'showFirstLength))
1006        (show-last-length (and (ly:music? show-last)
1007                               (ly:music-length show-last)))
1008        (show-first-length (and (ly:music? show-first)
1009                                (ly:music-length show-first)))
1010        (orig-length (ly:music-length music)))
1011
1012     ;;FIXME: if using either showFirst- or showLastLength,
1013     ;; make sure that skipBars is not set.
1014
1015     (cond
1016
1017      ;; both properties may be set.
1018      ((and show-first-length show-last-length)
1019       (let
1020           ((skip-length (ly:moment-sub orig-length show-last-length)))
1021         (make-simultaneous-music
1022          (list
1023           (make-sequential-music
1024            (list
1025             (make-skipped skip-length #t)
1026             ;; let's draw a separator between the beginning and the end
1027             (context-spec-music (make-property-set 'whichBar "||")
1028                                 'Timing)))
1029           (make-skipped show-first-length #f)
1030           music))))
1031
1032      ;; we may only want to print the last length
1033      (show-last-length
1034       (let
1035           ((skip-length (ly:moment-sub orig-length show-last-length)))
1036         (make-simultaneous-music
1037          (list
1038           (make-skipped skip-length #t)
1039           music))))
1040
1041      ;; we may only want to print the beginning; in this case
1042      ;; only the first length will be processed (much faster).
1043      (show-first-length
1044       ;; the first length must not exceed the original length.
1045       (if (ly:moment<? show-first-length orig-length)
1046           (set! (ly:music-property music 'length)
1047                 show-first-length))
1048       music)
1049
1050      (else music))))
1051
1052
1053 (define-public toplevel-music-functions
1054   (list
1055    (lambda (music parser) (voicify-music music))
1056    (lambda (x parser) (music-map music-check-error x))
1057    (lambda (x parser) (music-map precompute-music-length x))
1058    (lambda (music parser)
1059
1060      (music-map (quote-substitute (ly:parser-lookup parser 'musicQuotes))  music))
1061
1062    ;; switch-on-debugging
1063    (lambda (x parser) (music-map cue-substitute x))
1064
1065    (lambda (x parser)
1066      (skip-as-needed x parser)
1067    )))
1068
1069 ;;;;;;;;;;
1070 ;;; general purpose music functions
1071
1072 (define (shift-octave pitch octave-shift)
1073   (_i "Add @var{octave-shift} to the octave of @var{pitch}.")
1074   (ly:make-pitch
1075      (+ (ly:pitch-octave pitch) octave-shift)
1076      (ly:pitch-notename pitch)
1077      (ly:pitch-alteration pitch)))
1078
1079
1080 ;;;;;;;;;;;;;;;;;
1081 ;; lyrics
1082
1083 (define (apply-durations lyric-music durations)
1084   (define (apply-duration music)
1085     (if (and (not (equal? (ly:music-length music) ZERO-MOMENT))
1086              (ly:duration?  (ly:music-property music 'duration)))
1087         (begin
1088           (set! (ly:music-property music 'duration) (car durations))
1089           (set! durations (cdr durations)))))
1090
1091   (music-map apply-duration lyric-music))
1092
1093
1094 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1095 ;; accidentals
1096
1097 (define (recent-enough? bar-number alteration-def laziness)
1098   (or (number? alteration-def)
1099       (equal? laziness #t)
1100       (<= bar-number (+ (cadr alteration-def) laziness))))
1101
1102 (define (accidental-invalid? alteration-def)
1103   "Checks an alteration entry for being invalid.
1104
1105 Non-key alterations are invalidated when tying into the next bar or
1106 when there is a clef change, since neither repetition nor cancellation
1107 can be omitted when the same note occurs again.
1108
1109 Returns @code{#f} or the reason for the invalidation, a symbol."
1110   (let* ((def (if (pair? alteration-def)
1111                   (car alteration-def)
1112                   alteration-def)))
1113     (and (symbol? def) def)))
1114
1115 (define (extract-alteration alteration-def)
1116   (cond ((number? alteration-def)
1117          alteration-def)
1118         ((pair? alteration-def)
1119          (car alteration-def))
1120         (else 0)))
1121
1122 (define (check-pitch-against-signature context pitch barnum laziness octaveness)
1123   "Checks the need for an accidental and a @q{restore} accidental against
1124 @code{localKeySignature}.  The @var{laziness} is the number of measures
1125 for which reminder accidentals are used (i.e., if @var{laziness} is zero,
1126 only cancel accidentals in the same measure; if @var{laziness} is three,
1127 we cancel accidentals up to three measures after they first appear.
1128 @var{octaveness} is either @code{'same-octave} or @code{'any-octave} and
1129 specifies whether accidentals should be canceled in different octaves."
1130   (let* ((ignore-octave (cond ((equal? octaveness 'any-octave) #t)
1131                               ((equal? octaveness 'same-octave) #f)
1132                               (else
1133                                (ly:warning (_ "Unknown octaveness type: ~S ") octaveness)
1134                                (ly:warning (_ "Defaulting to 'any-octave."))
1135                                #t)))
1136          (key-sig (ly:context-property context 'keySignature))
1137          (local-key-sig (ly:context-property context 'localKeySignature))
1138          (notename (ly:pitch-notename pitch))
1139          (octave (ly:pitch-octave pitch))
1140          (pitch-handle (cons octave notename))
1141          (need-restore #f)
1142          (need-accidental #f)
1143          (previous-alteration #f)
1144          (from-other-octaves #f)
1145          (from-same-octave (assoc-get pitch-handle local-key-sig))
1146          (from-key-sig (or (assoc-get notename local-key-sig)
1147
1148     ;; If no key signature match is found from localKeySignature, we may have a custom
1149     ;; type with octave-specific entries of the form ((octave . pitch) alteration)
1150     ;; instead of (pitch . alteration).  Since this type cannot coexist with entries in
1151     ;; localKeySignature, try extracting from keySignature instead.
1152                            (assoc-get pitch-handle key-sig))))
1153
1154     ;; loop through localKeySignature to search for a notename match from other octaves
1155     (let loop ((l local-key-sig))
1156       (if (pair? l)
1157           (let ((entry (car l)))
1158             (if (and (pair? (car entry))
1159                      (= (cdar entry) notename))
1160                 (set! from-other-octaves (cdr entry))
1161                 (loop (cdr l))))))
1162
1163     ;; find previous alteration-def for comparison with pitch
1164     (cond
1165      ;; from same octave?
1166      ((and (not ignore-octave)
1167            from-same-octave
1168            (recent-enough? barnum from-same-octave laziness))
1169       (set! previous-alteration from-same-octave))
1170
1171      ;; from any octave?
1172      ((and ignore-octave
1173            from-other-octaves
1174            (recent-enough? barnum from-other-octaves laziness))
1175       (set! previous-alteration from-other-octaves))
1176
1177      ;; not recent enough, extract from key signature/local key signature
1178      (from-key-sig
1179       (set! previous-alteration from-key-sig)))
1180
1181     (if (accidental-invalid? previous-alteration)
1182         (set! need-accidental #t)
1183
1184         (let* ((prev-alt (extract-alteration previous-alteration))
1185                (this-alt (ly:pitch-alteration pitch)))
1186
1187           (if (not (= this-alt prev-alt))
1188               (begin
1189                 (set! need-accidental #t)
1190                 (if (and (not (= this-alt 0))
1191                          (and (< (abs this-alt) (abs prev-alt))
1192                              (> (* prev-alt this-alt) 0)))
1193                     (set! need-restore #t))))))
1194
1195     (cons need-restore need-accidental)))
1196
1197 (define-public ((make-accidental-rule octaveness laziness) context pitch barnum measurepos)
1198   "Create an accidental rule that makes its decision based on the octave of
1199 the note and a laziness value.
1200
1201 @var{octaveness} is either @code{'same-octave} or @code{'any-octave} and
1202 defines whether the rule should respond to accidental changes in other
1203 octaves than the current.  @code{'same-octave} is the normal way to typeset
1204 accidentals -- an accidental is made if the alteration is different from the
1205 last active pitch in the same octave.  @code{'any-octave} looks at the last
1206 active pitch in any octave.
1207
1208 @var{laziness} states over how many bars an accidental should be remembered.
1209 @code{0}@tie{}is the default -- accidental lasts over 0@tie{}bar lines, that
1210 is, to the end of current measure.  A positive integer means that the
1211 accidental lasts over that many bar lines.  @w{@code{-1}} is `forget
1212 immediately', that is, only look at key signature.  @code{#t} is `forever'."
1213
1214   (check-pitch-against-signature context pitch barnum laziness octaveness))
1215
1216 (define (key-entry-notename entry)
1217   "Return the pitch of an entry in localKeySignature.  The entry is either of the form
1218   '(notename . alter) or '((octave . notename) . (alter barnum . measurepos))."
1219   (if (number? (car entry))
1220       (car entry)
1221       (cdar entry)))
1222
1223 (define (key-entry-octave entry)
1224   "Return the octave of an entry in localKeySignature (or #f if the entry does not have
1225   an octave)."
1226   (and (pair? (car entry)) (caar entry)))
1227
1228 (define (key-entry-bar-number entry)
1229   "Return the bar number of an entry in localKeySignature (or #f if the entry does not
1230   have a bar number)."
1231   (and (pair? (car entry)) (caddr entry)))
1232
1233 (define (key-entry-measure-position entry)
1234   "Return the measure position of an entry in localKeySignature (or #f if the entry does
1235   not have a measure position)."
1236   (and (pair? (car entry)) (cdddr entry)))
1237
1238 (define (key-entry-alteration entry)
1239   "Return the alteration of an entry in localKeySignature.
1240
1241 For convenience, returns @code{0} if entry is @code{#f}."
1242   (if entry
1243       (if (number? (car entry))
1244           (cdr entry)
1245           (cadr entry))
1246       0))
1247
1248 (define-public (find-pitch-entry keysig pitch accept-global accept-local)
1249   "Return the first entry in @var{keysig} that matches @var{pitch}.
1250 @var{accept-global} states whether key signature entries should be included.
1251 @var{accept-local} states whether local accidentals should be included.
1252 If no matching entry is found, @var{#f} is returned."
1253   (and (pair? keysig)
1254        (let* ((entry (car keysig))
1255               (entryoct (key-entry-octave entry))
1256               (entrynn (key-entry-notename entry))
1257               (oct (ly:pitch-octave pitch))
1258               (nn (ly:pitch-notename pitch)))
1259          (if (and (equal? nn entrynn)
1260                   (or (and accept-global (not entryoct))
1261                       (and accept-local (equal? oct entryoct))))
1262              entry
1263              (find-pitch-entry (cdr keysig) pitch accept-global accept-local)))))
1264
1265 (define-public (neo-modern-accidental-rule context pitch barnum measurepos)
1266   "An accidental rule that typesets an accidental if it differs from the
1267 key signature @emph{and} does not directly follow a note on the same
1268 staff line.  This rule should not be used alone because it does neither
1269 look at bar lines nor different accidentals at the same note name."
1270   (let* ((keysig (ly:context-property context 'localKeySignature))
1271          (entry (find-pitch-entry keysig pitch #t #t)))
1272     (if (not entry)
1273         (cons #f #f)
1274         (let* ((global-entry (find-pitch-entry keysig pitch #t #f))
1275                (key-acc (key-entry-alteration global-entry))
1276                (acc (ly:pitch-alteration pitch))
1277                (entrymp (key-entry-measure-position entry))
1278                (entrybn (key-entry-bar-number entry)))
1279           (cons #f (not (or (equal? acc key-acc)
1280                             (and (equal? entrybn barnum) (equal? entrymp measurepos)))))))))
1281
1282 (define-public (teaching-accidental-rule context pitch barnum measurepos)
1283   "An accidental rule that typesets a cautionary accidental if it is
1284 included in the key signature @emph{and} does not directly follow a note
1285 on the same staff line."
1286   (let* ((keysig (ly:context-property context 'localKeySignature))
1287          (entry (find-pitch-entry keysig pitch #t #t)))
1288     (if (not entry)
1289         (cons #f #f)
1290         (let* ((global-entry (find-pitch-entry keysig pitch #f #f))
1291                (key-acc (key-entry-alteration global-entry))
1292                (acc (ly:pitch-alteration pitch))
1293                (entrymp (key-entry-measure-position entry))
1294                (entrybn (key-entry-bar-number entry)))
1295           (cons #f (not (or (equal? acc key-acc)
1296                             (and (equal? entrybn barnum) (equal? entrymp measurepos)))))))))
1297
1298 (define-public (set-accidentals-properties extra-natural
1299                                            auto-accs auto-cauts
1300                                            context)
1301   (context-spec-music
1302    (make-sequential-music
1303     (append (if (boolean? extra-natural)
1304                 (list (make-property-set 'extraNatural extra-natural))
1305                 '())
1306             (list (make-property-set 'autoAccidentals auto-accs)
1307                   (make-property-set 'autoCautionaries auto-cauts))))
1308    context))
1309
1310 (define-public (set-accidental-style style . rest)
1311   "Set accidental style to @var{style}.  Optionally take a context
1312 argument, e.g. @code{'Staff} or @code{'Voice}.  The context defaults
1313 to @code{Staff}, except for piano styles, which use @code{GrandStaff}
1314 as a context."
1315   (let ((context (if (pair? rest)
1316                      (car rest) 'Staff))
1317         (pcontext (if (pair? rest)
1318                       (car rest) 'GrandStaff)))
1319     (ly:export
1320      (cond
1321       ;; accidentals as they were common in the 18th century.
1322       ((equal? style 'default)
1323        (set-accidentals-properties #t
1324                                    `(Staff ,(make-accidental-rule 'same-octave 0))
1325                                    '()
1326                                    context))
1327       ;; accidentals from one voice do NOT get cancelled in other voices
1328       ((equal? style 'voice)
1329        (set-accidentals-properties #t
1330                                    `(Voice ,(make-accidental-rule 'same-octave 0))
1331                                    '()
1332                                    context))
1333       ;; accidentals as suggested by Kurt Stone, Music Notation in the 20th century.
1334       ;; This includes all the default accidentals, but accidentals also needs cancelling
1335       ;; in other octaves and in the next measure.
1336       ((equal? style 'modern)
1337        (set-accidentals-properties #f
1338                                    `(Staff ,(make-accidental-rule 'same-octave 0)
1339                                            ,(make-accidental-rule 'any-octave 0)
1340                                            ,(make-accidental-rule 'same-octave 1))
1341                                    '()
1342                                    context))
1343       ;; the accidentals that Stone adds to the old standard as cautionaries
1344       ((equal? style 'modern-cautionary)
1345        (set-accidentals-properties #f
1346                                    `(Staff ,(make-accidental-rule 'same-octave 0))
1347                                    `(Staff ,(make-accidental-rule 'any-octave 0)
1348                                            ,(make-accidental-rule 'same-octave 1))
1349                                    context))
1350       ;; same as modern, but accidentals different from the key signature are always
1351       ;; typeset - unless they directly follow a note of the same pitch.
1352       ((equal? style 'neo-modern)
1353        (set-accidentals-properties #f
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-cautionary)
1361        (set-accidentals-properties #f
1362                                    `(Staff ,(make-accidental-rule 'same-octave 0))
1363                                    `(Staff ,(make-accidental-rule 'any-octave 0)
1364                                            ,(make-accidental-rule 'same-octave 1)
1365                                            ,neo-modern-accidental-rule)
1366                                    context))
1367       ((equal? style 'neo-modern-voice)
1368        (set-accidentals-properties #f
1369                                    `(Voice ,(make-accidental-rule 'same-octave 0)
1370                                            ,(make-accidental-rule 'any-octave 0)
1371                                            ,(make-accidental-rule 'same-octave 1)
1372                                            ,neo-modern-accidental-rule
1373                                      Staff ,(make-accidental-rule 'same-octave 0)
1374                                            ,(make-accidental-rule 'any-octave 0)
1375                                            ,(make-accidental-rule 'same-octave 1)
1376                                       ,neo-modern-accidental-rule)
1377                                    '()
1378                                    context))
1379       ((equal? style 'neo-modern-voice-cautionary)
1380        (set-accidentals-properties #f
1381                                    `(Voice ,(make-accidental-rule 'same-octave 0))
1382                                    `(Voice ,(make-accidental-rule 'any-octave 0)
1383                                            ,(make-accidental-rule 'same-octave 1)
1384                                            ,neo-modern-accidental-rule
1385                                      Staff ,(make-accidental-rule 'same-octave 0)
1386                                            ,(make-accidental-rule 'any-octave 0)
1387                                            ,(make-accidental-rule 'same-octave 1)
1388                                            ,neo-modern-accidental-rule)
1389                                    context))
1390       ;; Accidentals as they were common in dodecaphonic music with no tonality.
1391       ;; Each note gets one accidental.
1392       ((equal? style 'dodecaphonic)
1393        (set-accidentals-properties #f
1394                                    `(Staff ,(lambda (c p bn mp) '(#f . #t)))
1395                                    '()
1396                                    context))
1397       ;; Multivoice accidentals to be read both by musicians playing one voice
1398       ;; and musicians playing all voices.
1399       ;; Accidentals are typeset for each voice, but they ARE cancelled across voices.
1400       ((equal? style 'modern-voice)
1401        (set-accidentals-properties  #f
1402                                     `(Voice ,(make-accidental-rule 'same-octave 0)
1403                                             ,(make-accidental-rule 'any-octave 0)
1404                                             ,(make-accidental-rule 'same-octave 1)
1405                                       Staff ,(make-accidental-rule 'same-octave 0)
1406                                             ,(make-accidental-rule 'any-octave 0)
1407                                             ,(make-accidental-rule 'same-octave 1))
1408                                     '()
1409                                     context))
1410       ;; same as modernVoiceAccidental eccept that all special accidentals are typeset
1411       ;; as cautionaries
1412       ((equal? style 'modern-voice-cautionary)
1413        (set-accidentals-properties #f
1414                                    `(Voice ,(make-accidental-rule 'same-octave 0))
1415                                    `(Voice ,(make-accidental-rule 'any-octave 0)
1416                                            ,(make-accidental-rule 'same-octave 1)
1417                                      Staff ,(make-accidental-rule 'same-octave 0)
1418                                            ,(make-accidental-rule 'any-octave 0)
1419                                            ,(make-accidental-rule 'same-octave 1))
1420                                    context))
1421       ;; stone's suggestions for accidentals on grand staff.
1422       ;; Accidentals are cancelled across the staves in the same grand staff as well
1423       ((equal? style 'piano)
1424        (set-accidentals-properties #f
1425                                    `(Staff ,(make-accidental-rule 'same-octave 0)
1426                                            ,(make-accidental-rule 'any-octave 0)
1427                                            ,(make-accidental-rule 'same-octave 1)
1428                                      GrandStaff
1429                                            ,(make-accidental-rule 'any-octave 0)
1430                                            ,(make-accidental-rule 'same-octave 1))
1431                                    '()
1432                                    pcontext))
1433       ((equal? style 'piano-cautionary)
1434        (set-accidentals-properties #f
1435                                    `(Staff ,(make-accidental-rule 'same-octave 0))
1436                                    `(Staff ,(make-accidental-rule 'any-octave 0)
1437                                            ,(make-accidental-rule 'same-octave 1)
1438                                      GrandStaff
1439                                            ,(make-accidental-rule 'any-octave 0)
1440                                            ,(make-accidental-rule 'same-octave 1))
1441                                    pcontext))
1442
1443       ;; same as modern, but cautionary accidentals are printed for all sharp or flat
1444       ;; tones specified by the key signature.
1445        ((equal? style 'teaching)
1446        (set-accidentals-properties #f
1447                                     `(Staff ,(make-accidental-rule 'same-octave 0))
1448                                     `(Staff ,(make-accidental-rule 'same-octave 1)
1449                                            ,teaching-accidental-rule)
1450                                    context))
1451
1452       ;; do not set localKeySignature when a note alterated differently from
1453       ;; localKeySignature is found.
1454       ;; Causes accidentals to be printed at every note instead of
1455       ;; remembered for the duration of a measure.
1456       ;; accidentals not being remembered, causing accidentals always to
1457       ;; be typeset relative to the time signature
1458       ((equal? style 'forget)
1459        (set-accidentals-properties '()
1460                                    `(Staff ,(make-accidental-rule 'same-octave -1))
1461                                    '()
1462                                    context))
1463       ;; Do not reset the key at the start of a measure.  Accidentals will be
1464       ;; printed only once and are in effect until overridden, possibly many
1465       ;; measures later.
1466       ((equal? style 'no-reset)
1467        (set-accidentals-properties '()
1468                                    `(Staff ,(make-accidental-rule 'same-octave #t))
1469                                    '()
1470                                    context))
1471       (else
1472        (ly:warning (_ "unknown accidental style: ~S") style)
1473        (make-sequential-music '()))))))
1474
1475 (define-public (invalidate-alterations context)
1476   "Invalidate alterations in @var{context}.
1477
1478 Elements of @code{'localKeySignature} corresponding to local
1479 alterations of the key signature have the form
1480 @code{'((octave . notename) . (alter barnum . measurepos))}.
1481 Replace them with a version where @code{alter} is set to @code{'clef}
1482 to force a repetition of accidentals.
1483
1484 Entries that conform with the current key signature are not invalidated."
1485   (let* ((keysig (ly:context-property context 'keySignature)))
1486     (set! (ly:context-property context 'localKeySignature)
1487           (map-in-order
1488            (lambda (entry)
1489              (let* ((localalt (key-entry-alteration entry))
1490                     (localoct (key-entry-octave entry)))
1491                (if (or (accidental-invalid? localalt)
1492                        (not localoct)
1493                        (= localalt
1494                           (key-entry-alteration
1495                            (find-pitch-entry
1496                             keysig
1497                             (ly:make-pitch localoct
1498                                            (key-entry-notename entry)
1499                                            0)
1500                             #t #t))))
1501                    entry
1502                    (cons (car entry) (cons 'clef (cddr entry))))))
1503            (ly:context-property context 'localKeySignature)))))
1504                     
1505 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1506
1507 (define-public (skip-of-length mus)
1508   "Create a skip of exactly the same length as @var{mus}."
1509   (let* ((skip
1510           (make-music
1511            'SkipEvent
1512            'duration (ly:make-duration 0 0))))
1513
1514     (make-event-chord (list (ly:music-compress skip (ly:music-length mus))))))
1515
1516 (define-public (mmrest-of-length mus)
1517   "Create a multi-measure rest of exactly the same length as @var{mus}."
1518
1519   (let* ((skip
1520           (make-multi-measure-rest
1521            (ly:make-duration 0 0) '())))
1522     (ly:music-compress skip (ly:music-length mus))
1523     skip))
1524
1525 (define-public (pitch-of-note event-chord)
1526   (let ((evs (filter (lambda (x)
1527                        (music-has-type x 'note-event))
1528                      (ly:music-property event-chord 'elements))))
1529
1530     (and (pair? evs)
1531          (ly:music-property (car evs) 'pitch))))
1532
1533 (define-public (duration-of-note event-chord)
1534   (let ((evs (filter (lambda (x)
1535                        (music-has-type x 'rhythmic-event))
1536                      (ly:music-property event-chord 'elements))))
1537
1538     (and (pair? evs)
1539          (ly:music-property (car evs) 'duration))))
1540
1541 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1542
1543 (define-public (extract-named-music music music-name)
1544   "Return a flat list of all music named @var{music-name} from @var{music}."
1545    (let ((extracted-list
1546           (if (ly:music? music)
1547               (if (eq? (ly:music-property music 'name) music-name)
1548                   (list music)
1549                   (let ((elt (ly:music-property music 'element))
1550                         (elts (ly:music-property music 'elements)))
1551                     (if (ly:music? elt)
1552                         (extract-named-music elt music-name)
1553                         (if (null? elts)
1554                             '()
1555                             (map (lambda(x)
1556                                     (extract-named-music x music-name ))
1557                              elts)))))
1558               '())))
1559      (flatten-list extracted-list)))
1560
1561 (define-public (event-chord-notes event-chord)
1562   "Return a list of all notes from @var{event-chord}."
1563   (filter
1564     (lambda (m) (eq? 'NoteEvent (ly:music-property m 'name)))
1565     (ly:music-property event-chord 'elements)))
1566
1567 (define-public (event-chord-pitches event-chord)
1568   "Return a list of all pitches from @var{event-chord}."
1569   (map (lambda (x) (ly:music-property x 'pitch))
1570        (event-chord-notes event-chord)))