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