]> git.donarmstrong.com Git - lilypond.git/blob - scm/music-functions.scm
Merge branch 'dev/staging'
[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-event-function rest
854   "Defining macro returning event functions.
855 Syntax:
856   (define-event-function (parser location arg1 arg2 ...) (arg1-type? arg2-type? ...)
857     ...function body...)
858
859 argX-type can take one of the forms @code{predicate?} for mandatory
860 arguments satisfying the predicate, @code{(predicate?)} for optional
861 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
862 value)}} for optional parameters with a specified default
863 value (evaluated at definition time).  An optional parameter can be
864 omitted in a call only when it can't get confused with a following
865 parameter of different type.
866
867 Predicates with syntactical significance are @code{ly:pitch?},
868 @code{ly:duration?}, @code{ly:music?}, @code{markup?}.  Other
869 predicates require the parameter to be entered as Scheme expression.
870
871 Must return an event expression.  The @code{origin} is automatically
872 set to the @code{location} parameter."
873
874   `(define-syntax-function (ly:event? (make-music 'Event 'void #t)) ,@rest))
875
876 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
877
878 (define-public (cue-substitute quote-music)
879   "Must happen after @code{quote-substitute}."
880
881   (if (vector? (ly:music-property quote-music 'quoted-events))
882       (let* ((dir (ly:music-property quote-music 'quoted-voice-direction))
883              (clef (ly:music-property quote-music 'quoted-music-clef))
884              (main-voice (if (eq? 1 dir) 1 0))
885              (cue-voice (if (eq? 1 dir) 0 1))
886              (main-music (ly:music-property quote-music 'element))
887              (return-value quote-music))
888
889         (if (or (eq? 1 dir) (eq? -1 dir))
890
891             ;; if we have stem dirs, change both quoted and main music
892             ;; to have opposite stems.
893             (begin
894               (set! return-value
895                     ;; cannot context-spec Quote-music, since context
896                     ;; for the quotes is determined in the iterator.
897                     (make-sequential-music
898                      (list
899                       (if (null? clef)
900                           (make-music 'Music)
901                           (make-cue-clef-set clef))
902                       (context-spec-music (make-voice-props-set cue-voice) 'CueVoice "cue")
903                       quote-music
904                       (context-spec-music (make-voice-props-revert) 'CueVoice "cue")
905                       (if (null? clef)
906                           (make-music 'Music)
907                           (make-cue-clef-unset)))))
908               (set! main-music
909                     (make-sequential-music
910                      (list
911                       (make-voice-props-set main-voice)
912                       main-music
913                       (make-voice-props-revert))))
914               (set! (ly:music-property quote-music 'element) main-music)))
915
916         return-value)
917       quote-music))
918
919 (define-public ((quote-substitute quote-tab) music)
920   (let* ((quoted-name (ly:music-property music 'quoted-music-name))
921          (quoted-vector (and (string? quoted-name)
922                              (hash-ref quote-tab quoted-name #f))))
923
924
925     (if (string? quoted-name)
926         (if (vector? quoted-vector)
927             (begin
928               (set! (ly:music-property music 'quoted-events) quoted-vector)
929               (set! (ly:music-property music 'iterator-ctor)
930                     ly:quote-iterator::constructor))
931             (ly:music-warning music (ly:format (_ "cannot find quoted music: `~S'") quoted-name))))
932     music))
933
934
935 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
936 ;; switch it on here, so parsing and init isn't checked (too slow!)
937 ;;
938 ;; automatic music transformations.
939
940 (define (switch-on-debugging m)
941   (if (defined? 'set-debug-cell-accesses!)
942       (set-debug-cell-accesses! 15000))
943   m)
944
945 (define (music-check-error music)
946   (define found #f)
947   (define (signal m)
948     (if (and (ly:music? m)
949              (eq? (ly:music-property m 'error-found) #t))
950         (set! found #t)))
951
952   (for-each signal (ly:music-property music 'elements))
953   (signal (ly:music-property music 'element))
954
955   (if found
956       (set! (ly:music-property music 'error-found) #t))
957   music)
958
959 (define (precompute-music-length music)
960   (set! (ly:music-property music 'length)
961         (ly:music-length music))
962   music)
963
964 (define-public (make-duration-of-length moment)
965  "Make duration of the given @code{moment} length."
966  (ly:make-duration 0 0
967   (ly:moment-main-numerator moment)
968   (ly:moment-main-denominator moment)))
969
970 (define (make-skipped moment bool)
971  "Depending on BOOL, set or unset skipTypesetting,
972 then make SkipMusic of the given MOMENT length, and
973 then revert skipTypesetting."
974  (make-sequential-music
975   (list
976    (context-spec-music (make-property-set 'skipTypesetting bool)
977     'Score)
978    (make-music 'SkipMusic 'duration
979     (make-duration-of-length moment))
980    (context-spec-music (make-property-set 'skipTypesetting (not bool))
981     'Score))))
982
983 (define (skip-as-needed music parser)
984   "Replace MUSIC by
985  << {  \\set skipTypesetting = ##f
986  LENGTHOF(\\showFirstLength)
987  \\set skipTypesetting = ##t
988  LENGTHOF(\\showLastLength) }
989  MUSIC >>
990  if appropriate.
991
992  When only showFirstLength is set,
993  the 'length property of the music is
994  overridden to speed up compiling."
995   (let*
996       ((show-last (ly:parser-lookup parser 'showLastLength))
997        (show-first (ly:parser-lookup parser 'showFirstLength))
998        (show-last-length (and (ly:music? show-last)
999                               (ly:music-length show-last)))
1000        (show-first-length (and (ly:music? show-first)
1001                                (ly:music-length show-first)))
1002        (orig-length (ly:music-length music)))
1003
1004     ;;FIXME: if using either showFirst- or showLastLength,
1005     ;; make sure that skipBars is not set.
1006
1007     (cond
1008
1009      ;; both properties may be set.
1010      ((and show-first-length show-last-length)
1011       (let
1012           ((skip-length (ly:moment-sub orig-length show-last-length)))
1013         (make-simultaneous-music
1014          (list
1015           (make-sequential-music
1016            (list
1017             (make-skipped skip-length #t)
1018             ;; let's draw a separator between the beginning and the end
1019             (context-spec-music (make-property-set 'whichBar "||")
1020                                 'Timing)))
1021           (make-skipped show-first-length #f)
1022           music))))
1023
1024      ;; we may only want to print the last length
1025      (show-last-length
1026       (let
1027           ((skip-length (ly:moment-sub orig-length show-last-length)))
1028         (make-simultaneous-music
1029          (list
1030           (make-skipped skip-length #t)
1031           music))))
1032
1033      ;; we may only want to print the beginning; in this case
1034      ;; only the first length will be processed (much faster).
1035      (show-first-length
1036       ;; the first length must not exceed the original length.
1037       (if (ly:moment<? show-first-length orig-length)
1038           (set! (ly:music-property music 'length)
1039                 show-first-length))
1040       music)
1041
1042      (else music))))
1043
1044
1045 (define-public toplevel-music-functions
1046   (list
1047    (lambda (music parser) (voicify-music music))
1048    (lambda (x parser) (music-map music-check-error x))
1049    (lambda (x parser) (music-map precompute-music-length x))
1050    (lambda (music parser)
1051
1052      (music-map (quote-substitute (ly:parser-lookup parser 'musicQuotes))  music))
1053
1054    ;; switch-on-debugging
1055    (lambda (x parser) (music-map cue-substitute x))
1056
1057    (lambda (x parser)
1058      (skip-as-needed x parser)
1059    )))
1060
1061 ;;;;;;;;;;
1062 ;;; general purpose music functions
1063
1064 (define (shift-octave pitch octave-shift)
1065   (_i "Add @var{octave-shift} to the octave of @var{pitch}.")
1066   (ly:make-pitch
1067      (+ (ly:pitch-octave pitch) octave-shift)
1068      (ly:pitch-notename pitch)
1069      (ly:pitch-alteration pitch)))
1070
1071
1072 ;;;;;;;;;;;;;;;;;
1073 ;; lyrics
1074
1075 (define (apply-durations lyric-music durations)
1076   (define (apply-duration music)
1077     (if (and (not (equal? (ly:music-length music) ZERO-MOMENT))
1078              (ly:duration?  (ly:music-property music 'duration)))
1079         (begin
1080           (set! (ly:music-property music 'duration) (car durations))
1081           (set! durations (cdr durations)))))
1082
1083   (music-map apply-duration lyric-music))
1084
1085
1086 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1087 ;; accidentals
1088
1089 (define (recent-enough? bar-number alteration-def laziness)
1090   (or (number? alteration-def)
1091       (equal? laziness #t)
1092       (<= bar-number (+ (cadr alteration-def) laziness))))
1093
1094 (define (accidental-invalid? alteration-def)
1095   "Checks an alteration entry for being invalid.
1096
1097 Non-key alterations are invalidated when tying into the next bar or
1098 when there is a clef change, since neither repetition nor cancellation
1099 can be omitted when the same note occurs again.
1100
1101 Returns @code{#f} or the reason for the invalidation, a symbol."
1102   (let* ((def (if (pair? alteration-def)
1103                   (car alteration-def)
1104                   alteration-def)))
1105     (and (symbol? def) def)))
1106
1107 (define (extract-alteration alteration-def)
1108   (cond ((number? alteration-def)
1109          alteration-def)
1110         ((pair? alteration-def)
1111          (car alteration-def))
1112         (else 0)))
1113
1114 (define (check-pitch-against-signature context pitch barnum laziness octaveness)
1115   "Checks the need for an accidental and a @q{restore} accidental against
1116 @code{localKeySignature}.  The @var{laziness} is the number of measures
1117 for which reminder accidentals are used (i.e., if @var{laziness} is zero,
1118 only cancel accidentals in the same measure; if @var{laziness} is three,
1119 we cancel accidentals up to three measures after they first appear.
1120 @var{octaveness} is either @code{'same-octave} or @code{'any-octave} and
1121 specifies whether accidentals should be canceled in different octaves."
1122   (let* ((ignore-octave (cond ((equal? octaveness 'any-octave) #t)
1123                               ((equal? octaveness 'same-octave) #f)
1124                               (else
1125                                (ly:warning (_ "Unknown octaveness type: ~S ") octaveness)
1126                                (ly:warning (_ "Defaulting to 'any-octave."))
1127                                #t)))
1128          (key-sig (ly:context-property context 'keySignature))
1129          (local-key-sig (ly:context-property context 'localKeySignature))
1130          (notename (ly:pitch-notename pitch))
1131          (octave (ly:pitch-octave pitch))
1132          (pitch-handle (cons octave notename))
1133          (need-restore #f)
1134          (need-accidental #f)
1135          (previous-alteration #f)
1136          (from-other-octaves #f)
1137          (from-same-octave (assoc-get pitch-handle local-key-sig))
1138          (from-key-sig (or (assoc-get notename local-key-sig)
1139
1140     ;; If no key signature match is found from localKeySignature, we may have a custom
1141     ;; type with octave-specific entries of the form ((octave . pitch) alteration)
1142     ;; instead of (pitch . alteration).  Since this type cannot coexist with entries in
1143     ;; localKeySignature, try extracting from keySignature instead.
1144                            (assoc-get pitch-handle key-sig))))
1145
1146     ;; loop through localKeySignature to search for a notename match from other octaves
1147     (let loop ((l local-key-sig))
1148       (if (pair? l)
1149           (let ((entry (car l)))
1150             (if (and (pair? (car entry))
1151                      (= (cdar entry) notename))
1152                 (set! from-other-octaves (cdr entry))
1153                 (loop (cdr l))))))
1154
1155     ;; find previous alteration-def for comparison with pitch
1156     (cond
1157      ;; from same octave?
1158      ((and (not ignore-octave)
1159            from-same-octave
1160            (recent-enough? barnum from-same-octave laziness))
1161       (set! previous-alteration from-same-octave))
1162
1163      ;; from any octave?
1164      ((and ignore-octave
1165            from-other-octaves
1166            (recent-enough? barnum from-other-octaves laziness))
1167       (set! previous-alteration from-other-octaves))
1168
1169      ;; not recent enough, extract from key signature/local key signature
1170      (from-key-sig
1171       (set! previous-alteration from-key-sig)))
1172
1173     (if (accidental-invalid? previous-alteration)
1174         (set! need-accidental #t)
1175
1176         (let* ((prev-alt (extract-alteration previous-alteration))
1177                (this-alt (ly:pitch-alteration pitch)))
1178
1179           (if (not (= this-alt prev-alt))
1180               (begin
1181                 (set! need-accidental #t)
1182                 (if (and (not (= this-alt 0))
1183                          (and (< (abs this-alt) (abs prev-alt))
1184                              (> (* prev-alt this-alt) 0)))
1185                     (set! need-restore #t))))))
1186
1187     (cons need-restore need-accidental)))
1188
1189 (define-public ((make-accidental-rule octaveness laziness) context pitch barnum measurepos)
1190   "Create an accidental rule that makes its decision based on the octave of
1191 the note and a laziness value.
1192
1193 @var{octaveness} is either @code{'same-octave} or @code{'any-octave} and
1194 defines whether the rule should respond to accidental changes in other
1195 octaves than the current.  @code{'same-octave} is the normal way to typeset
1196 accidentals -- an accidental is made if the alteration is different from the
1197 last active pitch in the same octave.  @code{'any-octave} looks at the last
1198 active pitch in any octave.
1199
1200 @var{laziness} states over how many bars an accidental should be remembered.
1201 @code{0}@tie{}is the default -- accidental lasts over 0@tie{}bar lines, that
1202 is, to the end of current measure.  A positive integer means that the
1203 accidental lasts over that many bar lines.  @w{@code{-1}} is `forget
1204 immediately', that is, only look at key signature.  @code{#t} is `forever'."
1205
1206   (check-pitch-against-signature context pitch barnum laziness octaveness))
1207
1208 (define (key-entry-notename entry)
1209   "Return the pitch of an entry in localKeySignature.  The entry is either of the form
1210   '(notename . alter) or '((octave . notename) . (alter barnum . measurepos))."
1211   (if (number? (car entry))
1212       (car entry)
1213       (cdar entry)))
1214
1215 (define (key-entry-octave entry)
1216   "Return the octave of an entry in localKeySignature (or #f if the entry does not have
1217   an octave)."
1218   (and (pair? (car entry)) (caar entry)))
1219
1220 (define (key-entry-bar-number entry)
1221   "Return the bar number of an entry in localKeySignature (or #f if the entry does not
1222   have a bar number)."
1223   (and (pair? (car entry)) (caddr entry)))
1224
1225 (define (key-entry-measure-position entry)
1226   "Return the measure position of an entry in localKeySignature (or #f if the entry does
1227   not have a measure position)."
1228   (and (pair? (car entry)) (cdddr entry)))
1229
1230 (define (key-entry-alteration entry)
1231   "Return the alteration of an entry in localKeySignature.
1232
1233 For convenience, returns @code{0} if entry is @code{#f}."
1234   (if entry
1235       (if (number? (car entry))
1236           (cdr entry)
1237           (cadr entry))
1238       0))
1239
1240 (define-public (find-pitch-entry keysig pitch accept-global accept-local)
1241   "Return the first entry in @var{keysig} that matches @var{pitch}.
1242 @var{accept-global} states whether key signature entries should be included.
1243 @var{accept-local} states whether local accidentals should be included.
1244 If no matching entry is found, @var{#f} is returned."
1245   (and (pair? keysig)
1246        (let* ((entry (car keysig))
1247               (entryoct (key-entry-octave entry))
1248               (entrynn (key-entry-notename entry))
1249               (oct (ly:pitch-octave pitch))
1250               (nn (ly:pitch-notename pitch)))
1251          (if (and (equal? nn entrynn)
1252                   (or (and accept-global (not entryoct))
1253                       (and accept-local (equal? oct entryoct))))
1254              entry
1255              (find-pitch-entry (cdr keysig) pitch accept-global accept-local)))))
1256
1257 (define-public (neo-modern-accidental-rule context pitch barnum measurepos)
1258   "An accidental rule that typesets an accidental if it differs from the
1259 key signature @emph{and} does not directly follow a note on the same
1260 staff line.  This rule should not be used alone because it does neither
1261 look at bar lines nor different accidentals at the same note name."
1262   (let* ((keysig (ly:context-property context 'localKeySignature))
1263          (entry (find-pitch-entry keysig pitch #t #t)))
1264     (if (not entry)
1265         (cons #f #f)
1266         (let* ((global-entry (find-pitch-entry keysig pitch #t #f))
1267                (key-acc (key-entry-alteration global-entry))
1268                (acc (ly:pitch-alteration pitch))
1269                (entrymp (key-entry-measure-position entry))
1270                (entrybn (key-entry-bar-number entry)))
1271           (cons #f (not (or (equal? acc key-acc)
1272                             (and (equal? entrybn barnum) (equal? entrymp measurepos)))))))))
1273
1274 (define-public (teaching-accidental-rule context pitch barnum measurepos)
1275   "An accidental rule that typesets a cautionary accidental if it is
1276 included in the key signature @emph{and} does not directly follow a note
1277 on the same staff line."
1278   (let* ((keysig (ly:context-property context 'localKeySignature))
1279          (entry (find-pitch-entry keysig pitch #t #t)))
1280     (if (not entry)
1281         (cons #f #f)
1282         (let* ((global-entry (find-pitch-entry keysig pitch #f #f))
1283                (key-acc (key-entry-alteration global-entry))
1284                (acc (ly:pitch-alteration pitch))
1285                (entrymp (key-entry-measure-position entry))
1286                (entrybn (key-entry-bar-number entry)))
1287           (cons #f (not (or (equal? acc key-acc)
1288                             (and (equal? entrybn barnum) (equal? entrymp measurepos)))))))))
1289
1290 (define-public (set-accidentals-properties extra-natural
1291                                            auto-accs auto-cauts
1292                                            context)
1293   (context-spec-music
1294    (make-sequential-music
1295     (append (if (boolean? extra-natural)
1296                 (list (make-property-set 'extraNatural extra-natural))
1297                 '())
1298             (list (make-property-set 'autoAccidentals auto-accs)
1299                   (make-property-set 'autoCautionaries auto-cauts))))
1300    context))
1301
1302 (define-public (set-accidental-style style . rest)
1303   "Set accidental style to @var{style}.  Optionally take a context
1304 argument, e.g. @code{'Staff} or @code{'Voice}.  The context defaults
1305 to @code{Staff}, except for piano styles, which use @code{GrandStaff}
1306 as a context."
1307   (let ((context (if (pair? rest)
1308                      (car rest) 'Staff))
1309         (pcontext (if (pair? rest)
1310                       (car rest) 'GrandStaff)))
1311     (ly:export
1312      (cond
1313       ;; accidentals as they were common in the 18th century.
1314       ((equal? style 'default)
1315        (set-accidentals-properties #t
1316                                    `(Staff ,(make-accidental-rule 'same-octave 0))
1317                                    '()
1318                                    context))
1319       ;; accidentals from one voice do NOT get cancelled in other voices
1320       ((equal? style 'voice)
1321        (set-accidentals-properties #t
1322                                    `(Voice ,(make-accidental-rule 'same-octave 0))
1323                                    '()
1324                                    context))
1325       ;; accidentals as suggested by Kurt Stone, Music Notation in the 20th century.
1326       ;; This includes all the default accidentals, but accidentals also needs cancelling
1327       ;; in other octaves and in the next measure.
1328       ((equal? style 'modern)
1329        (set-accidentals-properties #f
1330                                    `(Staff ,(make-accidental-rule 'same-octave 0)
1331                                            ,(make-accidental-rule 'any-octave 0)
1332                                            ,(make-accidental-rule 'same-octave 1))
1333                                    '()
1334                                    context))
1335       ;; the accidentals that Stone adds to the old standard as cautionaries
1336       ((equal? style 'modern-cautionary)
1337        (set-accidentals-properties #f
1338                                    `(Staff ,(make-accidental-rule 'same-octave 0))
1339                                    `(Staff ,(make-accidental-rule 'any-octave 0)
1340                                            ,(make-accidental-rule 'same-octave 1))
1341                                    context))
1342       ;; same as modern, but accidentals different from the key signature are always
1343       ;; typeset - unless they directly follow a note of the same pitch.
1344       ((equal? style 'neo-modern)
1345        (set-accidentals-properties #f
1346                                    `(Staff ,(make-accidental-rule 'same-octave 0)
1347                                            ,(make-accidental-rule 'any-octave 0)
1348                                            ,(make-accidental-rule 'same-octave 1)
1349                                            ,neo-modern-accidental-rule)
1350                                    '()
1351                                    context))
1352       ((equal? style 'neo-modern-cautionary)
1353        (set-accidentals-properties #f
1354                                    `(Staff ,(make-accidental-rule 'same-octave 0))
1355                                    `(Staff ,(make-accidental-rule 'any-octave 0)
1356                                            ,(make-accidental-rule 'same-octave 1)
1357                                            ,neo-modern-accidental-rule)
1358                                    context))
1359       ((equal? style 'neo-modern-voice)
1360        (set-accidentals-properties #f
1361                                    `(Voice ,(make-accidental-rule 'same-octave 0)
1362                                            ,(make-accidental-rule 'any-octave 0)
1363                                            ,(make-accidental-rule 'same-octave 1)
1364                                            ,neo-modern-accidental-rule
1365                                      Staff ,(make-accidental-rule 'same-octave 0)
1366                                            ,(make-accidental-rule 'any-octave 0)
1367                                            ,(make-accidental-rule 'same-octave 1)
1368                                       ,neo-modern-accidental-rule)
1369                                    '()
1370                                    context))
1371       ((equal? style 'neo-modern-voice-cautionary)
1372        (set-accidentals-properties #f
1373                                    `(Voice ,(make-accidental-rule 'same-octave 0))
1374                                    `(Voice ,(make-accidental-rule 'any-octave 0)
1375                                            ,(make-accidental-rule 'same-octave 1)
1376                                            ,neo-modern-accidental-rule
1377                                      Staff ,(make-accidental-rule 'same-octave 0)
1378                                            ,(make-accidental-rule 'any-octave 0)
1379                                            ,(make-accidental-rule 'same-octave 1)
1380                                            ,neo-modern-accidental-rule)
1381                                    context))
1382       ;; Accidentals as they were common in dodecaphonic music with no tonality.
1383       ;; Each note gets one accidental.
1384       ((equal? style 'dodecaphonic)
1385        (set-accidentals-properties #f
1386                                    `(Staff ,(lambda (c p bn mp) '(#f . #t)))
1387                                    '()
1388                                    context))
1389       ;; Multivoice accidentals to be read both by musicians playing one voice
1390       ;; and musicians playing all voices.
1391       ;; Accidentals are typeset for each voice, but they ARE cancelled across voices.
1392       ((equal? style 'modern-voice)
1393        (set-accidentals-properties  #f
1394                                     `(Voice ,(make-accidental-rule 'same-octave 0)
1395                                             ,(make-accidental-rule 'any-octave 0)
1396                                             ,(make-accidental-rule 'same-octave 1)
1397                                       Staff ,(make-accidental-rule 'same-octave 0)
1398                                             ,(make-accidental-rule 'any-octave 0)
1399                                             ,(make-accidental-rule 'same-octave 1))
1400                                     '()
1401                                     context))
1402       ;; same as modernVoiceAccidental eccept that all special accidentals are typeset
1403       ;; as cautionaries
1404       ((equal? style 'modern-voice-cautionary)
1405        (set-accidentals-properties #f
1406                                    `(Voice ,(make-accidental-rule 'same-octave 0))
1407                                    `(Voice ,(make-accidental-rule 'any-octave 0)
1408                                            ,(make-accidental-rule 'same-octave 1)
1409                                      Staff ,(make-accidental-rule 'same-octave 0)
1410                                            ,(make-accidental-rule 'any-octave 0)
1411                                            ,(make-accidental-rule 'same-octave 1))
1412                                    context))
1413       ;; stone's suggestions for accidentals on grand staff.
1414       ;; Accidentals are cancelled across the staves in the same grand staff as well
1415       ((equal? style 'piano)
1416        (set-accidentals-properties #f
1417                                    `(Staff ,(make-accidental-rule 'same-octave 0)
1418                                            ,(make-accidental-rule 'any-octave 0)
1419                                            ,(make-accidental-rule 'same-octave 1)
1420                                      GrandStaff
1421                                            ,(make-accidental-rule 'any-octave 0)
1422                                            ,(make-accidental-rule 'same-octave 1))
1423                                    '()
1424                                    pcontext))
1425       ((equal? style 'piano-cautionary)
1426        (set-accidentals-properties #f
1427                                    `(Staff ,(make-accidental-rule 'same-octave 0))
1428                                    `(Staff ,(make-accidental-rule 'any-octave 0)
1429                                            ,(make-accidental-rule 'same-octave 1)
1430                                      GrandStaff
1431                                            ,(make-accidental-rule 'any-octave 0)
1432                                            ,(make-accidental-rule 'same-octave 1))
1433                                    pcontext))
1434
1435       ;; same as modern, but cautionary accidentals are printed for all sharp or flat
1436       ;; tones specified by the key signature.
1437        ((equal? style 'teaching)
1438        (set-accidentals-properties #f
1439                                     `(Staff ,(make-accidental-rule 'same-octave 0))
1440                                     `(Staff ,(make-accidental-rule 'same-octave 1)
1441                                            ,teaching-accidental-rule)
1442                                    context))
1443
1444       ;; do not set localKeySignature when a note alterated differently from
1445       ;; localKeySignature is found.
1446       ;; Causes accidentals to be printed at every note instead of
1447       ;; remembered for the duration of a measure.
1448       ;; accidentals not being remembered, causing accidentals always to
1449       ;; be typeset relative to the time signature
1450       ((equal? style 'forget)
1451        (set-accidentals-properties '()
1452                                    `(Staff ,(make-accidental-rule 'same-octave -1))
1453                                    '()
1454                                    context))
1455       ;; Do not reset the key at the start of a measure.  Accidentals will be
1456       ;; printed only once and are in effect until overridden, possibly many
1457       ;; measures later.
1458       ((equal? style 'no-reset)
1459        (set-accidentals-properties '()
1460                                    `(Staff ,(make-accidental-rule 'same-octave #t))
1461                                    '()
1462                                    context))
1463       (else
1464        (ly:warning (_ "unknown accidental style: ~S") style)
1465        (make-sequential-music '()))))))
1466
1467 (define-public (invalidate-alterations context)
1468   "Invalidate alterations in @var{context}.
1469
1470 Elements of @code{'localKeySignature} corresponding to local
1471 alterations of the key signature have the form
1472 @code{'((octave . notename) . (alter barnum . measurepos))}.
1473 Replace them with a version where @code{alter} is set to @code{'clef}
1474 to force a repetition of accidentals.
1475
1476 Entries that conform with the current key signature are not invalidated."
1477   (let* ((keysig (ly:context-property context 'keySignature)))
1478     (set! (ly:context-property context 'localKeySignature)
1479           (map-in-order
1480            (lambda (entry)
1481              (let* ((localalt (key-entry-alteration entry))
1482                     (localoct (key-entry-octave entry)))
1483                (if (or (accidental-invalid? localalt)
1484                        (not localoct)
1485                        (= localalt
1486                           (key-entry-alteration
1487                            (find-pitch-entry
1488                             keysig
1489                             (ly:make-pitch localoct
1490                                            (key-entry-notename entry)
1491                                            0)
1492                             #t #t))))
1493                    entry
1494                    (cons (car entry) (cons 'clef (cddr entry))))))
1495            (ly:context-property context 'localKeySignature)))))
1496                     
1497 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1498
1499 (define-public (skip-of-length mus)
1500   "Create a skip of exactly the same length as @var{mus}."
1501   (let* ((skip
1502           (make-music
1503            'SkipEvent
1504            'duration (ly:make-duration 0 0))))
1505
1506     (make-event-chord (list (ly:music-compress skip (ly:music-length mus))))))
1507
1508 (define-public (mmrest-of-length mus)
1509   "Create a multi-measure rest of exactly the same length as @var{mus}."
1510
1511   (let* ((skip
1512           (make-multi-measure-rest
1513            (ly:make-duration 0 0) '())))
1514     (ly:music-compress skip (ly:music-length mus))
1515     skip))
1516
1517 (define-public (pitch-of-note event-chord)
1518   (let ((evs (filter (lambda (x)
1519                        (music-has-type x 'note-event))
1520                      (ly:music-property event-chord 'elements))))
1521
1522     (and (pair? evs)
1523          (ly:music-property (car evs) 'pitch))))
1524
1525 (define-public (duration-of-note event-chord)
1526   (let ((evs (filter (lambda (x)
1527                        (music-has-type x 'rhythmic-event))
1528                      (ly:music-property event-chord 'elements))))
1529
1530     (and (pair? evs)
1531          (ly:music-property (car evs) 'duration))))
1532
1533 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1534
1535 (define-public (extract-named-music music music-name)
1536   "Return a flat list of all music named @var{music-name} from @var{music}."
1537    (let ((extracted-list
1538           (if (ly:music? music)
1539               (if (eq? (ly:music-property music 'name) music-name)
1540                   (list music)
1541                   (let ((elt (ly:music-property music 'element))
1542                         (elts (ly:music-property music 'elements)))
1543                     (if (ly:music? elt)
1544                         (extract-named-music elt music-name)
1545                         (if (null? elts)
1546                             '()
1547                             (map (lambda(x)
1548                                     (extract-named-music x music-name ))
1549                              elts)))))
1550               '())))
1551      (flatten-list extracted-list)))
1552
1553 (define-public (event-chord-notes event-chord)
1554   "Return a list of all notes from @var{event-chord}."
1555   (filter
1556     (lambda (m) (eq? 'NoteEvent (ly:music-property m 'name)))
1557     (ly:music-property event-chord 'elements)))
1558
1559 (define-public (event-chord-pitches event-chord)
1560   "Return a list of all pitches from @var{event-chord}."
1561   (map (lambda (x) (ly:music-property x 'pitch))
1562        (event-chord-notes event-chord)))