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