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