]> git.donarmstrong.com Git - lilypond.git/blob - scm/music-functions.scm
132f2f236947c4b9395a37df53255556d7b0ed33
[lilypond.git] / scm / music-functions.scm
1 ;;;; This file is part of LilyPond, the GNU music typesetter.
2 ;;;;
3 ;;;; Copyright (C) 1998--2015 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 (use-modules (srfi srfi-11))
24
25 ;;; ly:music-property with setter
26 ;;; (ly:music-property my-music 'elements)
27 ;;;   ==> the 'elements property
28 ;;; (set! (ly:music-property my-music 'elements) value)
29 ;;;   ==> set the 'elements property and return it
30 (define-public ly:music-property
31   (make-procedure-with-setter ly:music-property
32                               ly:music-set-property!))
33
34 (define-safe-public (music-is-of-type? mus type)
35   "Does @code{mus} belong to the music class @code{type}?"
36   (memq type (ly:music-property mus 'types)))
37
38 (define-safe-public (music-type-predicate types)
39   "Returns a predicate function that can be used for checking
40 music to have one of the types listed in @var{types}."
41    (if (cheap-list? types)
42        (lambda (m)
43          (any (lambda (t) (music-is-of-type? m t)) types))
44        (lambda (m) (music-is-of-type? m types))))
45
46 ;; TODO move this
47 (define-public ly:grob-property
48   (make-procedure-with-setter ly:grob-property
49                               ly:grob-set-property!))
50
51 (define-public ly:grob-object
52   (make-procedure-with-setter ly:grob-object
53                               ly:grob-set-object!))
54
55 (define-public ly:grob-parent
56   (make-procedure-with-setter ly:grob-parent
57                               ly:grob-set-parent!))
58
59 (define-public ly:prob-property
60   (make-procedure-with-setter ly:prob-property
61                               ly:prob-set-property!))
62
63 (define-public ly:context-property
64   (make-procedure-with-setter ly:context-property
65                               ly:context-set-property!))
66
67 (define-public (music-map function music)
68   "Apply @var{function} to @var{music} and all of the music it contains.
69
70 First it recurses over the children, then the function is applied to
71 @var{music}."
72   (let ((es (ly:music-property music 'elements))
73         (e (ly:music-property music 'element)))
74     (if (pair? es)
75         (set! (ly:music-property music 'elements)
76               (map (lambda (y) (music-map function y)) es)))
77     (if (ly:music? e)
78         (set! (ly:music-property music 'element)
79               (music-map function  e)))
80     (function music)))
81
82 (define-public (music-filter pred? music)
83   "Filter out music expressions that do not satisfy @var{pred?}."
84
85   (define (inner-music-filter pred? music)
86     "Recursive function."
87     (let* ((es (ly:music-property music 'elements))
88            (e (ly:music-property music 'element))
89            (as (ly:music-property music 'articulations))
90            (filtered-as (filter ly:music? (map (lambda (y) (inner-music-filter pred? y)) as)))
91            (filtered-e (if (ly:music? e)
92                            (inner-music-filter pred? e)
93                            e))
94            (filtered-es (filter ly:music? (map (lambda (y) (inner-music-filter pred? y)) es))))
95       (if (not (null? e))
96           (set! (ly:music-property music 'element) filtered-e))
97       (if (not (null? es))
98           (set! (ly:music-property music 'elements) filtered-es))
99       (if (not (null? as))
100           (set! (ly:music-property music 'articulations) filtered-as))
101       ;; if filtering emptied the expression, we remove it completely.
102       (if (or (not (pred? music))
103               (and (eq? filtered-es '()) (not (ly:music? e))
104                    (or (not (eq? es '()))
105                        (ly:music? e))))
106           (set! music '()))
107       music))
108
109   (set! music (inner-music-filter pred? music))
110   (if (ly:music? music)
111       music
112       (make-music 'Music)))       ;must return music.
113
114 (define*-public (display-music music #:optional (port (current-output-port)))
115   "Display music, not done with @code{music-map} for clarity of
116 presentation."
117   (display music port)
118   (display ": { " port)
119   (let ((es (ly:music-property music 'elements))
120         (e (ly:music-property music 'element)))
121     (display (ly:music-mutable-properties music) port)
122     (if (pair? es)
123         (begin (display "\nElements: {\n" port)
124                (for-each (lambda (m) (display-music m port)) es)
125                (display "}\n" port)))
126     (if (ly:music? e)
127         (begin
128           (display "\nChild:" port)
129           (display-music e port))))
130   (display " }\n" port)
131   music)
132
133 ;;;
134 ;;; A scheme music pretty printer
135 ;;;
136 (define (markup-expression->make-markup markup-expression)
137   "Transform `markup-expression' into an equivalent, hopefuly readable, scheme expression.
138 For instance,
139   \\markup \\bold \\italic hello
140 ==>
141   (markup #:line (#:bold (#:italic (#:simple \"hello\"))))"
142   (define (proc->command-keyword proc)
143     "Return a keyword, eg. `#:bold', from the `proc' function, eg. #<procedure bold-markup (layout props arg)>"
144     (let ((cmd-markup (symbol->string (procedure-name proc))))
145       (symbol->keyword (string->symbol (substring cmd-markup 0 (- (string-length cmd-markup)
146                                                                   (string-length "-markup")))))))
147   (define (transform-arg arg)
148     (cond ((and (pair? arg) (markup? (car arg))) ;; a markup list
149            (append-map inner-markup->make-markup arg))
150           ((and (not (string? arg)) (markup? arg)) ;; a markup
151            (inner-markup->make-markup arg))
152           (else                                  ;; scheme arg
153            (music->make-music arg))))
154   (define (inner-markup->make-markup mrkup)
155     (if (string? mrkup)
156         `(#:simple ,mrkup)
157         (let ((cmd (proc->command-keyword (car mrkup)))
158               (args (map transform-arg (cdr mrkup))))
159           `(,cmd ,@args))))
160   ;; body:
161   (if (string? markup-expression)
162       markup-expression
163       `(markup ,@(inner-markup->make-markup markup-expression))))
164
165 (define-public (music->make-music obj)
166   "Generate an expression that, once evaluated, may return an object
167 equivalent to @var{obj}, that is, for a music expression, a
168 @code{(make-music ...)} form."
169   (define (if-nonzero num)
170     (if (zero? num) '() (list num)))
171   (cond (;; markup expression
172          (markup? obj)
173          (markup-expression->make-markup obj))
174         (;; music expression
175          (ly:music? obj)
176          `(make-music
177            ',(ly:music-property obj 'name)
178            ,@(append-map (lambda (prop)
179                            `(',(car prop)
180                              ,(music->make-music (cdr prop))))
181                          (remove (lambda (prop)
182                                    (eqv? (car prop) 'origin))
183                                  (ly:music-mutable-properties obj)))))
184         (;; moment
185          (ly:moment? obj)
186          `(ly:make-moment
187            ,@(let ((main (ly:moment-main obj))
188                    (grace (ly:moment-grace obj)))
189                (cond ((zero? grace) (list main))
190                      ((negative? grace) (list main grace))
191                      (else ;;positive grace requires 4-arg form
192                       (list (numerator main)
193                             (denominator main)
194                             (numerator grace)
195                             (denominator grace)))))))
196         (;; note duration
197          (ly:duration? obj)
198          `(ly:make-duration ,(ly:duration-log obj)
199                             ,@(if (= (ly:duration-scale obj) 1)
200                                   (if-nonzero (ly:duration-dot-count obj))
201                                   (list (ly:duration-dot-count obj)
202                                         (ly:duration-scale obj)))))
203         (;; note pitch
204          (ly:pitch? obj)
205          `(ly:make-pitch ,(ly:pitch-octave obj)
206                          ,(ly:pitch-notename obj)
207                          ,@(if-nonzero (ly:pitch-alteration obj))))
208         (;; scheme procedure
209          (procedure? obj)
210          (or (procedure-name obj) obj))
211         (;; a symbol (avoid having an unquoted symbol)
212          (symbol? obj)
213          `',obj)
214         (;; an empty list (avoid having an unquoted empty list)
215          (null? obj)
216          `'())
217         (;; a proper list
218          (list? obj)
219          `(list ,@(map music->make-music obj)))
220         (;; a pair
221          (pair? obj)
222          `(cons ,(music->make-music (car obj))
223                 ,(music->make-music (cdr obj))))
224         (else
225          obj)))
226
227 (use-modules (ice-9 pretty-print))
228 (define*-public (display-scheme-music obj #:optional (port (current-output-port)))
229   "Displays `obj', typically a music expression, in a friendly fashion,
230 which often can be read back in order to generate an equivalent expression."
231   (pretty-print (music->make-music obj) port)
232   (newline port))
233
234 ;;;
235 ;;; Scheme music expression --> Lily-syntax-using string translator
236 ;;;
237 (use-modules (srfi srfi-39)
238              (scm display-lily))
239
240 (define*-public (display-lily-music expr #:optional (port (current-output-port))
241                                     #:key force-duration)
242   "Display the music expression using LilyPond syntax"
243   (memoize-clef-names supported-clefs)
244   (parameterize ((*indent* 0)
245                  (*omit-duration* #f))
246                 (display (music->lily-string expr) port)
247                 (newline port)))
248
249 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
250
251 (define-public (shift-one-duration-log music shift dot)
252   "Add @var{shift} to @code{duration-log} of @code{'duration} in
253 @var{music} and optionally @var{dot} to any note encountered.
254 The number of dots in the shifted music may not be less than zero."
255   (let ((d (ly:music-property music 'duration)))
256     (if (ly:duration? d)
257         (let* ((cp (ly:duration-scale d))
258                (nd (ly:make-duration
259                     (+ shift (ly:duration-log d))
260                     (max 0 (+ dot (ly:duration-dot-count d)))
261                     cp)))
262           (set! (ly:music-property music 'duration) nd)))
263     ;clear cached length, since it's no longer valid
264     (set! (ly:music-property music 'length) '())
265     music))
266
267 (define-public (shift-duration-log music shift dot)
268   (music-map (lambda (x) (shift-one-duration-log x shift dot))
269              music))
270
271 (define-public (tremolo::get-music-list tremolo)
272   "Given a tremolo repeat, return a list of music to engrave for it.
273 This will be a stretched copy of its body, plus a TremoloEvent or
274 TremoloSpanEvent.
275
276 This is called only by Chord_tremolo_iterator."
277   (define (first-note-duration music)
278     "Finds the duration of the first NoteEvent by searching
279 depth-first through MUSIC."
280     ;; NoteEvent or a non-expanded chord-repetition
281     ;; We just take anything that actually sports an announced duration.
282     (if (ly:duration? (ly:music-property music 'duration))
283         (ly:music-property music 'duration)
284         (let loop ((elts (if (ly:music? (ly:music-property music 'element))
285                              (list (ly:music-property music 'element))
286                              (ly:music-property music 'elements))))
287           (and (pair? elts)
288                (let ((dur (first-note-duration (car elts))))
289                  (if (ly:duration? dur)
290                      dur
291                      (loop (cdr elts))))))))
292   (let* ((times (ly:music-property tremolo 'repeat-count))
293          (body (ly:music-property tremolo 'element))
294          (children (if (music-is-of-type? body 'sequential-music)
295                        ;; \repeat tremolo n { ... }
296                        (count duration-of-note ; do not count empty <>
297                               (extract-named-music body
298                                                    '(EventChord NoteEvent)))
299                        ;; \repeat tremolo n c4
300                        1))
301          (tremolo-type (if (positive? children)
302                            (let* ((note-duration (first-note-duration body))
303                                   (duration-log (if (ly:duration? note-duration)
304                                                     (ly:duration-log note-duration)
305                                                     1)))
306                              (ash 1 duration-log))
307                            '()))
308          (stretched (ly:music-deep-copy body)))
309     (if (positive? children)
310         ;; # of dots is equal to the 1 in bitwise representation (minus 1)!
311         (let* ((dots (1- (logcount (* times children))))
312                ;; The remaining missing multiplier to scale the notes by
313                ;; times * children
314                (mult (/ (* times children (ash 1 dots)) (1- (ash 2 dots))))
315                (shift (- (ly:intlog2 (floor mult)))))
316           (if (not (and (integer? mult) (= (logcount mult) 1)))
317               (ly:music-warning
318                body
319                (ly:format (_ "invalid tremolo repeat count: ~a") times)))
320           ;; Make each note take the full duration
321           (ly:music-compress stretched (ly:make-moment 1 children))
322           ;; Adjust the displayed note durations
323           (shift-duration-log stretched shift dots)))
324     ;; Return the stretched body plus a tremolo event
325     (if (= children 1)
326         (list (make-music 'TremoloEvent
327                           'repeat-count times
328                           'tremolo-type tremolo-type
329                           'origin (ly:music-property tremolo 'origin))
330               stretched)
331         (list (make-music 'TremoloSpanEvent
332                           'span-direction START
333                           'repeat-count times
334                           'tremolo-type tremolo-type
335                           'origin (ly:music-property tremolo 'origin))
336               stretched
337               (make-music 'TremoloSpanEvent
338                           'span-direction STOP
339                           'origin (ly:music-property tremolo 'origin))))))
340
341 (define-public (make-repeat name times main alts)
342   "Create a repeat music expression, with all properties initialized
343 properly."
344   (let ((type (or (assoc-get name '(("volta" . VoltaRepeatedMusic)
345                                     ("unfold" . UnfoldedRepeatedMusic)
346                                     ("percent" . PercentRepeatedMusic)
347                                     ("tremolo" . TremoloRepeatedMusic)))
348                   (begin (ly:warning (_ "unknown repeat type `~S': must be volta, unfold, percent, or tremolo") name)
349                          'VoltaRepeatedMusic)))
350         (talts (if (< times (length alts))
351                    (begin
352                      (ly:warning (_ "More alternatives than repeats.  Junking excess alternatives"))
353                      (take alts times))
354                    alts)))
355     (make-music type
356                 'element main
357                 'repeat-count (max times 1)
358                 'elements talts)))
359
360 (define (calc-repeat-slash-count music)
361   "Given the child-list @var{music} in @code{PercentRepeatMusic},
362 calculate the number of slashes based on the durations.  Returns @code{0}
363 if durations in @var{music} vary, allowing slash beats and double-percent
364 beats to be distinguished."
365   (let* ((durs (map duration-of-note
366                     (extract-named-music music '(EventChord NoteEvent
367                                                             RestEvent SkipEvent))))
368          (first-dur (car durs)))
369
370     (if (every (lambda (d) (equal? d first-dur)) durs)
371         (max (- (ly:duration-log first-dur) 2) 1)
372         0)))
373
374 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
375 ;; clusters.
376
377 (define-public (note-to-cluster music)
378   "Replace @code{NoteEvents} by @code{ClusterNoteEvents}."
379   (if (eq? (ly:music-property music 'name) 'NoteEvent)
380       (make-music 'ClusterNoteEvent
381                   'pitch (ly:music-property music 'pitch)
382                   'duration (ly:music-property music 'duration))
383       music))
384
385 (define-public (notes-to-clusters music)
386   (music-map note-to-cluster music))
387
388 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
389 ;; repeats.
390
391 (define-public (unfold-repeats music)
392   "Replace all repeats with unfolded repeats."
393   (let ((es (ly:music-property music 'elements))
394         (e (ly:music-property music 'element)))
395     (if (music-is-of-type? music 'repeated-music)
396         (set! music (make-music 'UnfoldedRepeatedMusic music)))
397     (if (pair? es)
398         (set! (ly:music-property music 'elements)
399               (map unfold-repeats es)))
400     (if (ly:music? e)
401         (set! (ly:music-property music 'element)
402               (unfold-repeats e)))
403     music))
404
405 (define-public (unfold-repeats-fully music)
406   "Unfolds repeats and expands the resulting @code{unfolded-repeated-music}."
407   (map-some-music
408    (lambda (m)
409      (and (music-is-of-type? m 'unfolded-repeated-music)
410           (make-sequential-music
411            (ly:music-deep-copy (make-unfolded-set m)))))
412    (unfold-repeats music)))
413
414 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
415 ;; property setting music objs.
416
417 (define-safe-public (check-grob-path path #:optional location
418                                      #:key
419                                      (start 0)
420                                      default
421                                      (min 1)
422                                      max)
423   "Check a grob path specification @var{path}, a symbol list (or a
424 single symbol), for validity and possibly complete it.  Returns the
425 completed specification, or @code{#f} if invalid.  If optional
426 @var{parser} is given, a syntax error is raised in that case,
427 optionally using @var{location}.  If an optional keyword argument
428 @code{#:start @var{start}} is given, the parsing starts at the given
429 index in the sequence @samp{Context.Grob.property.sub-property...},
430 with the default of @samp{0} implying the full path.
431
432 If there is no valid first element of @var{path} fitting at the given
433 path location, an optionally given @code{#:default @var{default}} is
434 used as the respective element instead without checking it for
435 validity at this position.
436
437 The resulting path after possibly prepending @var{default} can be
438 constrained in length by optional arguments @code{#:min @var{min}} and
439 @code{#:max @var{max}}, defaulting to @samp{1} and unlimited,
440 respectively."
441   (let ((path (if (symbol? path) (list path) path)))
442     ;; A Guile 1.x bug specific to optargs precludes moving the
443     ;; defines out of the let
444     (define (unspecial? s)
445       (not (or (object-property s 'is-grob?)
446                (object-property s 'backend-type?))))
447     (define (grob? s)
448       (object-property s 'is-grob?))
449     (define (property? s)
450       (object-property s 'backend-type?))
451     (define (check c p) (c p))
452
453     (let* ((checkers
454             (and (< start 3)
455                  (drop (list unspecial? grob? property?) start)))
456            (res
457             (cond
458              ((null? path)
459               ;; tricky.  Should we make use of the default when the
460               ;; list is empty?  In most cases, this question should be
461               ;; academical as an empty list can only be generated by
462               ;; Scheme and is likely an error.  We consider this a case
463               ;; of "no valid first element, and default given".
464               ;; Usually, invalid use cases should be caught later using
465               ;; the #:min argument, and if the user explicitly does not
466               ;; catch this, we just follow through.
467               (if default (list default) '()))
468              ((not checkers)
469               ;; no checkers, so we have a valid first element and just
470               ;; take the path as-is.
471               path)
472              (default
473                (if ((car checkers) (car path))
474                    (and (every check (cdr checkers) (cdr path))
475                         path)
476                    (and (every check (cdr checkers) path)
477                         (cons default path))))
478              (else
479               (and (every check checkers path)
480                    path)))))
481       (if (and res
482                (if max (<= min (length res) max)
483                    (<= min (length res))))
484           res
485           (begin
486             (ly:parser-error
487              (format #f (_ "bad grob property path ~a")
488                      path)
489              location)
490             #f)))))
491
492 (define-safe-public (check-context-path path #:optional location)
493   "Check a context property path specification @var{path}, a symbol
494 list (or a single symbol), for validity and possibly complete it.
495 Returns the completed specification, or @code{#f} when rising an
496 error (using optionally @code{location})."
497   (let* ((path (if (symbol? path) (list path) path)))
498     ;; A Guile 1.x bug specific to optargs precludes moving the
499     ;; defines out of the let
500     (define (property? s)
501       (object-property s 'translation-type?))
502     (define (unspecial? s)
503       (not (property? s)))
504     (define (check c p) (c p))
505     (or (case (length path)
506           ((1) (and (property? (car path)) (cons 'Bottom path)))
507           ((2) (and (unspecial? (car path)) (property? (cadr path)) path))
508           (else #f))
509         (begin
510           (ly:parser-error
511            (format #f (_ "bad context property ~a")
512                    path)
513            location)
514           #f))))
515
516 (define-public (make-grob-property-set grob gprop val)
517   "Make a @code{Music} expression that sets @var{gprop} to @var{val} in
518 @var{grob}.  Does a pop first, i.e., this is not an override."
519   (make-music 'OverrideProperty
520               'symbol grob
521               'grob-property gprop
522               'grob-value val
523               'pop-first #t))
524
525 (define-public (make-grob-property-override grob gprop val)
526   "Make a @code{Music} expression that overrides @var{gprop} to @var{val}
527 in @var{grob}."
528   (make-music 'OverrideProperty
529               'symbol grob
530               'grob-property gprop
531               'grob-value val))
532
533 (define-public (make-grob-property-revert grob gprop)
534   "Revert the grob property @var{gprop} for @var{grob}."
535   (make-music 'RevertProperty
536               'symbol grob
537               'grob-property gprop))
538
539 (define direction-polyphonic-grobs
540   '(AccidentalSuggestion
541     DotColumn
542     Dots
543     Fingering
544     LaissezVibrerTie
545     LigatureBracket
546     MultiMeasureRest
547     PhrasingSlur
548     RepeatTie
549     Rest
550     Script
551     Slur
552     Stem
553     TextScript
554     Tie
555     TupletBracket
556     TrillSpanner))
557
558 (define general-grace-settings
559   `((Voice Stem font-size -3)
560     (Voice Flag font-size -3)
561     (Voice NoteHead font-size -3)
562     (Voice TabNoteHead font-size -4)
563     (Voice Dots font-size -3)
564     (Voice Stem length-fraction 0.8)
565     (Voice Stem no-stem-extend #t)
566     (Voice Beam beam-thickness 0.384)
567     (Voice Beam length-fraction 0.8)
568     (Voice Accidental font-size -4)
569     (Voice AccidentalCautionary font-size -4)
570     (Voice Script font-size -3)
571     (Voice Fingering font-size -8)
572     (Voice StringNumber font-size -8)))
573
574 (define-public score-grace-settings
575   (append
576     `((Voice Stem direction ,UP)
577       (Voice Slur direction ,DOWN))
578     general-grace-settings))
579
580 ;; Getting a unique context id name
581
582 (define-session unique-counter -1)
583 (define-safe-public (get-next-unique-voice-name)
584   (set! unique-counter (1+ unique-counter))
585   (format #f "uniqueContext~s" unique-counter))
586
587
588 (define-safe-public (make-voice-props-set n)
589   (make-sequential-music
590    (append
591     (map (lambda (x) (make-grob-property-set x 'direction
592                                              (if (odd? n) -1 1)))
593          direction-polyphonic-grobs)
594     (list
595      (make-property-set 'graceSettings general-grace-settings)
596      (make-grob-property-set 'NoteColumn 'horizontal-shift (quotient n 2))))))
597
598 (define-safe-public (make-voice-props-override n)
599   (make-sequential-music
600    (append
601     (map (lambda (x) (make-grob-property-override x 'direction
602                                                   (if (odd? n) -1 1)))
603          direction-polyphonic-grobs)
604     (list
605      (make-property-set 'graceSettings general-grace-settings)
606      (make-grob-property-override 'NoteColumn 'horizontal-shift (quotient n 2))))))
607
608 (define-safe-public (make-voice-props-revert)
609   (make-sequential-music
610    (append
611     (map (lambda (x) (make-grob-property-revert x 'direction))
612          direction-polyphonic-grobs)
613     (list (make-property-unset 'graceSettings)
614           (make-grob-property-revert 'NoteColumn 'horizontal-shift)))))
615
616
617 (define-safe-public (context-spec-music m context #:optional id)
618   "Add \\context CONTEXT = ID to M."
619   (let ((cm (make-music 'ContextSpeccedMusic
620                         'element m
621                         'context-type context)))
622     (if (string? id)
623         (set! (ly:music-property cm 'context-id) id))
624     cm))
625
626 (define-public (descend-to-context m context)
627   "Like @code{context-spec-music}, but only descending."
628   (let ((cm (context-spec-music m context)))
629     (ly:music-set-property! cm 'descend-only #t)
630     cm))
631
632 (define-public (make-non-relative-music mus)
633   (make-music 'UnrelativableMusic
634               'element mus))
635
636 (define-public (make-apply-context func)
637   (make-music 'ApplyContext
638               'procedure func))
639
640 (define-public (make-sequential-music elts)
641   (make-music 'SequentialMusic
642               'elements elts))
643
644 (define-public (make-simultaneous-music elts)
645   (make-music 'SimultaneousMusic
646               'elements elts))
647
648 (define-safe-public (make-event-chord elts)
649   (make-music 'EventChord
650               'elements elts))
651
652 (define-public (make-skip-music dur)
653   (make-music 'SkipMusic
654               'duration dur))
655
656 (define-public (make-grace-music music)
657   (make-music 'GraceMusic
658               'element music))
659
660 ;;;;;;;;;;;;;;;;
661
662 ;; mmrest
663 (define-public (make-multi-measure-rest duration location)
664   (make-music 'MultiMeasureRestMusic
665               'origin location
666               'duration duration))
667
668 (define-public (make-property-set sym val)
669   (make-music 'PropertySet
670               'symbol sym
671               'value val))
672
673 (define-public (make-property-unset sym)
674   (make-music 'PropertyUnset
675               'symbol sym))
676
677 (define-safe-public (make-articulation name . properties)
678   (apply make-music 'ArticulationEvent
679          'articulation-type name
680          properties))
681
682 (define-public (make-lyric-event string duration)
683   (make-music 'LyricEvent
684               'duration duration
685               'text string))
686
687 (define-safe-public (make-span-event type span-dir)
688   (make-music type
689               'span-direction span-dir))
690
691 (define-public (override-head-style heads style)
692   "Override style for @var{heads} to @var{style}."
693   (make-sequential-music
694    (if (pair? heads)
695        (map (lambda (h)
696               (make-grob-property-override h 'style style))
697             heads)
698        (list (make-grob-property-override heads 'style style)))))
699
700 (define-public (revert-head-style heads)
701   "Revert style for @var{heads}."
702   (make-sequential-music
703    (if (pair? heads)
704        (map (lambda (h)
705               (make-grob-property-revert h 'style))
706             heads)
707        (list (make-grob-property-revert heads 'style)))))
708
709 (define-public (style-note-heads heads style music)
710   "Set @var{style} for all @var{heads} in @var{music}.  Works both
711 inside of and outside of chord construct."
712   ;; are we inside a <...>?
713   (if (eq? (ly:music-property music 'name) 'NoteEvent)
714       ;; yes -> use a tweak
715       (begin
716         (set! (ly:music-property music 'tweaks)
717               (acons 'style style (ly:music-property music 'tweaks)))
718         music)
719       ;; not in <...>, so use overrides
720       (make-sequential-music
721        (list
722         (override-head-style heads style)
723         music
724         (revert-head-style heads)))))
725
726 (define-public (set-mus-properties! m alist)
727   "Set all of @var{alist} as properties of @var{m}."
728   (if (pair? alist)
729       (begin
730         (set! (ly:music-property m (caar alist)) (cdar alist))
731         (set-mus-properties! m (cdr alist)))))
732
733 (define-public (music-separator? m)
734   "Is @var{m} a separator?"
735   (let ((ts (ly:music-property m 'types)))
736     (memq 'separator ts)))
737
738 ;;; expanding repeat chords
739 (define-public (copy-repeat-chord original-chord repeat-chord duration
740                                   event-types)
741   "Copies all events in @var{event-types} (be sure to include
742 @code{rhythmic-events}) from @var{original-chord} over to
743 @var{repeat-chord} with their articulations filtered as well.  Any
744 duration is replaced with the specified @var{duration}."
745   ;; First remove everything from event-types that can already be
746   ;; found in the repeated chord.  We don't need to look for
747   ;; articulations on individual events since they can't actually get
748   ;; into a repeat chord given its input syntax.
749
750   (define (keep-element? m)
751     (any (lambda (t) (music-is-of-type? m t))
752          event-types))
753
754   (for-each
755    (lambda (field)
756      (for-each (lambda (e)
757                  (for-each (lambda (x)
758                              (set! event-types (delq x event-types)))
759                            (ly:music-property e 'types)))
760                (ly:music-property repeat-chord field)))
761    '(elements articulations))
762
763   ;; now treat the elements
764   (set! (ly:music-property repeat-chord 'elements)
765         (let ((elts
766                (ly:music-deep-copy (filter keep-element?
767                                            (ly:music-property original-chord
768                                                               'elements))
769                                    repeat-chord)))
770           (for-each
771            (lambda (m)
772              (let ((arts (ly:music-property m 'articulations)))
773                (if (pair? arts)
774                    (set! (ly:music-property m 'articulations)
775                          (ly:set-origin! (filter! keep-element? arts)
776                                          repeat-chord)))
777                (if (ly:duration? (ly:music-property m 'duration))
778                    (set! (ly:music-property m 'duration) duration))
779                (if (ly:music-property m 'cautionary #f)
780                    (set! (ly:music-property m 'cautionary) #f))
781                (if (ly:music-property m 'force-accidental #f)
782                    (set! (ly:music-property m 'force-accidental) #f))))
783            elts)
784           (append! elts (ly:music-property repeat-chord 'elements))))
785   (let ((arts (filter keep-element?
786                       (ly:music-property original-chord
787                                          'articulations))))
788     (if (pair? arts)
789         (set! (ly:music-property repeat-chord 'articulations)
790               (append!
791                (ly:music-deep-copy arts repeat-chord)
792                (ly:music-property repeat-chord 'articulations)))))
793   repeat-chord)
794
795
796 (define-public (expand-repeat-chords! event-types music)
797   "Walks through @var{music} and fills repeated chords (notable by
798 having a duration in @code{duration}) with the notes from their
799 respective predecessor chord."
800   (let loop ((music music) (last-chord #f))
801     (if (music-is-of-type? music 'event-chord)
802         (let ((chord-repeat (ly:music-property music 'duration)))
803           (cond
804            ((not (ly:duration? chord-repeat))
805             (if (any (lambda (m) (ly:duration?
806                                   (ly:music-property m 'duration)))
807                      (ly:music-property music 'elements))
808                 music
809                 last-chord))
810            (last-chord
811             (set! (ly:music-property music 'duration) '())
812             (copy-repeat-chord last-chord music chord-repeat event-types))
813            (else
814             (ly:music-warning music (_ "Bad chord repetition"))
815             #f)))
816         (let ((elt (ly:music-property music 'element)))
817           (fold loop (if (ly:music? elt) (loop elt last-chord) last-chord)
818                 (ly:music-property music 'elements)))))
819   music)
820
821 ;;; This does _not_ copy any articulations.  Rationale: one main
822 ;;; incentive for pitch-repeating durations is after ties, such that
823 ;;; 4~2~8. can stand in for a 15/16 note in \partial 4 position.  In
824 ;;; this use case, any repeated articulations will be a nuisance.
825 ;;;
826 ;;; String assignments in TabStaff might seem like a worthwhile
827 ;;; exception, but they would be better tackled by the respective
828 ;;; engravers themselves (see issue 3662).
829 ;;;
830 ;;; Repeating chords as well seems problematic for things like
831 ;;; \score {
832 ;;;   <<
833 ;;;     \new Staff { c4 c c <c e> }
834 ;;;     \new RhythmicStaff { 4 4 4 4 }
835 ;;;   >>
836 ;;; }
837 ;;;
838 ;;; However, because of MIDI it is not advisable to use RhythmicStaff
839 ;;; without any initial pitch/drum-type.  For music functions taking
840 ;;; pure rhythms as an argument, the running of expand-repeat-notes!
841 ;;; at scorification time is irrelevant: at that point of time, the
842 ;;; music function has already run.
843
844 (define-public (expand-repeat-notes! music)
845   "Walks through @var{music} and gives pitchless notes (not having a
846 pitch in code{pitch} or a drum type in @code{drum-type}) the pitch(es)
847 from the predecessor note/chord if available."
848   (let ((last-pitch #f))
849     (map-some-music
850      (lambda (m)
851        (define (set-and-ret last)
852          (set! last-pitch last)
853          m)
854        (cond
855         ((music-is-of-type? m 'event-chord)
856          (if (any (lambda (m) (music-is-of-type? m 'rhythmic-event))
857                   (ly:music-property m 'elements))
858              (set! last-pitch m))
859          m)
860         ((music-is-of-type? m 'note-event)
861          (cond
862           ((or (ly:music-property m 'pitch #f)
863                (ly:music-property m 'drum-type #f))
864            => set-and-ret)
865           ;; ok, naked rhythm.  Go through the various cases of
866           ;; last-pitch
867           ;; nothing available: just keep as-is
868           ((not last-pitch) m)
869           ((ly:pitch? last-pitch)
870            (set! (ly:music-property m 'pitch) last-pitch)
871            m)
872           ((symbol? last-pitch)
873            (set! (ly:music-property m 'drum-type) last-pitch)
874            m)
875           ;; Ok, this is the big bad one: the reference is a chord.
876           ;; For now, we use the repeat chord logic.  That's not
877           ;; really efficient as cleaning out all articulations is
878           ;; quite simpler than what copy-repeat-chord does.
879           (else
880            (copy-repeat-chord last-pitch
881                               (make-music 'EventChord
882                                           'elements
883                                           (ly:music-property m 'articulations)
884                                           'origin
885                                           (ly:music-property m 'origin))
886                               (ly:music-property m 'duration)
887                               '(rhythmic-event)))))
888         (else #f)))
889      music)))
890
891 ;;; splitting chords into voices.
892 (define (voicify-list lst number)
893   "Make a list of Musics.
894
895 voicify-list :: [ [Music ] ] -> number -> [Music]
896 LST is a list music-lists.
897
898 NUMBER is 0-base, i.e., Voice=1 (upstems) has number 0.
899 "
900   (if (null? lst)
901       '()
902       (cons (context-spec-music
903              (make-sequential-music
904               (list (make-voice-props-set number)
905                     (make-simultaneous-music (car lst))))
906              'Bottom  (number->string (1+ number)))
907             (voicify-list (cdr lst) (1+ number)))))
908
909 (define (voicify-chord ch)
910   "Split the parts of a chord into different Voices using separator"
911   (let ((es (ly:music-property ch 'elements)))
912     (set! (ly:music-property  ch 'elements)
913           (voicify-list (split-list-by-separator es music-separator?) 0))
914     ch))
915
916 (define-public (voicify-music m)
917   "Recursively split chords that are separated with @code{\\\\}."
918   (if (not (ly:music? m))
919       (ly:error (_ "music expected: ~S") m))
920   (let ((es (ly:music-property m 'elements))
921         (e (ly:music-property m 'element)))
922
923     (if (pair? es)
924         (set! (ly:music-property m 'elements) (map voicify-music es)))
925     (if (ly:music? e)
926         (set! (ly:music-property m 'element)  (voicify-music e)))
927     (if (and (equal? (ly:music-property m 'name) 'SimultaneousMusic)
928              (any music-separator? es))
929         (set! m (context-spec-music (voicify-chord m) 'Staff)))
930     m))
931
932 (define-public (empty-music)
933   (make-music 'Music))
934
935 ;; Make a function that checks score element for being of a specific type.
936 (define-public (make-type-checker symbol)
937   (lambda (elt)
938     (grob::has-interface elt symbol)))
939
940 (define ((outputproperty-compatibility func sym val) grob g-context ao-context)
941   (if (func grob)
942       (set! (ly:grob-property grob sym) val)))
943 (export outputproperty-compatibility)
944
945
946 (define ((set-output-property grob-name symbol val)  grob grob-c context)
947   "Usage example:
948 @code{\\applyoutput #(set-output-property 'Clef 'extra-offset '(0 . 1))}"
949   (let ((meta (ly:grob-property grob 'meta)))
950     (if (equal? (assoc-get 'name meta) grob-name)
951         (set! (ly:grob-property grob symbol) val))))
952 (export set-output-property)
953
954
955 (define-public (skip->rest mus)
956   "Replace @var{mus} by @code{RestEvent} of the same duration if it is a
957 @code{SkipEvent}.  Useful for extracting parts from crowded scores."
958
959   (if  (memq (ly:music-property mus 'name) '(SkipEvent SkipMusic))
960        (make-music 'RestEvent 'duration (ly:music-property mus 'duration))
961        mus))
962
963
964 (define-public (music-clone music . music-properties)
965   "Clone @var{music} and set properties according to
966 @var{music-properties}, a list of alternating property symbols and
967 values:
968 @example\n(music-clone start-span 'span-direction STOP)
969 @end example
970 Only properties that are not overriden by @var{music-properties} are
971 actually fully cloned."
972   (let ((old-props (list-copy (ly:music-mutable-properties music)))
973         (new-props '())
974         (m (ly:make-music (ly:prob-immutable-properties music))))
975     (define (set-props mus-props)
976       (if (and (not (null? mus-props))
977                (not (null? (cdr mus-props))))
978           (begin
979             (set! old-props (assq-remove! old-props (car mus-props)))
980             (set! new-props
981                   (assq-set! new-props
982                              (car mus-props) (cadr mus-props)))
983             (set-props (cddr mus-props)))))
984     (set-props music-properties)
985     (for-each
986      (lambda (pair)
987        (set! (ly:music-property m (car pair))
988              (ly:music-deep-copy (cdr pair))))
989      old-props)
990     (for-each
991      (lambda (pair)
992        (set! (ly:music-property m (car pair)) (cdr pair)))
993      new-props)
994     m))
995
996 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
997 ;; warn for bare chords at start.
998
999 (define-public (ly:music-message music msg . rest)
1000   (let ((ip (ly:music-property music 'origin)))
1001     (if (ly:input-location? ip)
1002         (apply ly:input-message ip msg rest)
1003         (apply ly:message msg rest))))
1004
1005 (define-public (ly:music-warning music msg . rest)
1006   (let ((ip (ly:music-property music 'origin)))
1007     (if (ly:input-location? ip)
1008         (apply ly:input-warning ip msg rest)
1009         (apply ly:warning msg rest))))
1010
1011 (define-public (ly:event-warning event msg . rest)
1012   (let ((ip (ly:event-property event 'origin)))
1013     (if (ly:input-location? ip)
1014         (apply ly:input-warning ip msg rest)
1015         (apply ly:warning msg rest))))
1016
1017 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1018 ;;
1019 ;; setting stuff for grace context.
1020 ;;
1021
1022 (define (vector-extend v x)
1023   "Make a new vector consisting of V, with X added to the end."
1024   (let* ((n (vector-length v))
1025          (nv (make-vector (+ n 1) '())))
1026     (vector-move-left! v 0 n nv 0)
1027     (vector-set! nv n x)
1028     nv))
1029
1030 (define (vector-map f v)
1031   "Map F over V.  This function returns nothing."
1032   (do ((n (vector-length v))
1033        (i 0 (+ i 1)))
1034       ((>= i n))
1035     (f (vector-ref v i))))
1036
1037 (define (vector-reverse-map f v)
1038   "Map F over V, N to 0 order.  This function returns nothing."
1039   (do ((i (- (vector-length v) 1) (- i 1)))
1040       ((< i 0))
1041     (f (vector-ref v i))))
1042
1043 (define-public (add-grace-property context-name grob sym val)
1044   "Set @var{sym}=@var{val} for @var{grob} in @var{context-name}."
1045   (define (set-prop context)
1046     (let* ((where (or (ly:context-find context context-name) context))
1047            (current (ly:context-property where 'graceSettings))
1048            (new-settings (append current
1049                                  (list (list context-name grob sym val)))))
1050       (ly:context-set-property! where 'graceSettings new-settings)))
1051   (make-apply-context set-prop))
1052
1053 (define-public (remove-grace-property context-name grob sym)
1054   "Remove all @var{sym} for @var{grob} in @var{context-name}."
1055   (define (sym-grob-context? property sym grob context-name)
1056     (and (eq? (car property) context-name)
1057          (eq? (cadr property) grob)
1058          (eq? (caddr property) sym)))
1059   (define (delete-prop context)
1060     (let* ((where (or (ly:context-find context context-name) context))
1061            (current (ly:context-property where 'graceSettings))
1062            (prop-settings (filter
1063                            (lambda(x) (sym-grob-context? x sym grob context-name))
1064                            current))
1065            (new-settings current))
1066       (for-each (lambda(x)
1067                   (set! new-settings (delete x new-settings)))
1068                 prop-settings)
1069       (ly:context-set-property! where 'graceSettings new-settings)))
1070   (make-apply-context delete-prop))
1071
1072
1073 (defmacro-public def-grace-function (start stop . docstring)
1074   "Helper macro for defining grace music"
1075   `(define-music-function (music) (ly:music?)
1076      ,@docstring
1077      (make-music 'GraceMusic
1078                  'element (make-music 'SequentialMusic
1079                                       'elements (list (ly:music-deep-copy ,start)
1080                                                       music
1081                                                       (ly:music-deep-copy ,stop))))))
1082
1083 (defmacro-public define-syntax-function (type args signature . body)
1084   "Helper macro for `ly:make-music-function'.
1085 Syntax:
1086   (define-syntax-function result-type? (arg1 arg2 ...) (arg1-type arg2-type ...)
1087     ...function body...)
1088
1089 argX-type can take one of the forms @code{predicate?} for mandatory
1090 arguments satisfying the predicate, @code{(predicate?)} for optional
1091 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
1092 value)}} for optional parameters with a specified default
1093 value (evaluated at definition time).  An optional parameter can be
1094 omitted in a call only when it can't get confused with a following
1095 parameter of different type.
1096
1097 @code{result-type?} can specify a default in the same manner as
1098 predicates, to be used in case of a type error in arguments or
1099 result."
1100
1101   (define (has-parser/location? arg where)
1102     (let loop ((arg arg))
1103       (if (list? arg)
1104           (any loop arg)
1105           (memq arg where))))
1106   (define (currying-lambda args doc-string? body)
1107     (if (and (pair? args)
1108              (pair? (car args)))
1109         (currying-lambda (car args) doc-string?
1110                          `((lambda ,(cdr args) ,@body)))
1111         (let* ((compatibility? (if (list? args)
1112                                    (= (length args) (+ 2 (length signature)))
1113                                    (and (pair? args) (pair? (cdr args))
1114                                         (eq? (car args) 'parser))))
1115                (realargs (if compatibility? (cddr args) args)))
1116           `(lambda ,realargs
1117              ,(format #f "~a\n~a" realargs (or doc-string? ""))
1118              ,@(if (and compatibility?
1119                         (has-parser/location? body (take args 2)))
1120                    `((let ((,(car args) (*parser*)) (,(cadr args) (*location*)))
1121                        ,@body))
1122                    body)))))
1123
1124   (let ((docstring
1125          (and (pair? body) (pair? (cdr body))
1126               (if (string? (car body))
1127                   (car body)
1128                   (and (pair? (car body))
1129                        (eq? '_i (caar body))
1130                        (pair? (cdar body))
1131                        (string? (cadar body))
1132                        (null? (cddar body))
1133                        (cadar body))))))
1134     ;; When the music function definition contains an i10n doc string,
1135     ;; (_i "doc string"), keep the literal string only
1136     `(ly:make-music-function
1137       (list ,@(map (lambda (pred)
1138                      (if (pair? pred)
1139                          `(cons ,(car pred)
1140                                 ,(and (pair? (cdr pred)) (cadr pred)))
1141                          pred))
1142                    (cons type signature)))
1143       ,(currying-lambda args docstring (if docstring (cdr body) body)))))
1144
1145 (defmacro-public define-music-function rest
1146   "Defining macro returning music functions.
1147 Syntax:
1148   (define-music-function (arg1 arg2 ...) (arg1-type? arg2-type? ...)
1149     ...function body...)
1150
1151 argX-type can take one of the forms @code{predicate?} for mandatory
1152 arguments satisfying the predicate, @code{(predicate?)} for optional
1153 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
1154 value)}} for optional parameters with a specified default
1155 value (evaluated at definition time).  An optional parameter can be
1156 omitted in a call only when it can't get confused with a following
1157 parameter of different type.
1158
1159 Must return a music expression.  The @code{origin} is automatically
1160 set to the @code{location} parameter."
1161
1162   `(define-syntax-function (ly:music? (make-music 'Music 'void #t)) ,@rest))
1163
1164
1165 (defmacro-public define-scheme-function rest
1166   "Defining macro returning Scheme functions.
1167 Syntax:
1168   (define-scheme-function (arg1 arg2 ...) (arg1-type? arg2-type? ...)
1169     ...function body...)
1170
1171 argX-type can take one of the forms @code{predicate?} for mandatory
1172 arguments satisfying the predicate, @code{(predicate?)} for optional
1173 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
1174 value)}} for optional parameters with a specified default
1175 value (evaluated at definition time).  An optional parameter can be
1176 omitted in a call only when it can't get confused with a following
1177 parameter of different type.
1178
1179 Can return arbitrary expressions.  If a music expression is returned,
1180 its @code{origin} is automatically set to the @code{location}
1181 parameter."
1182
1183   `(define-syntax-function scheme? ,@rest))
1184
1185 (defmacro-public define-void-function rest
1186   "This defines a Scheme function like @code{define-scheme-function} with
1187 void return value (i.e., what most Guile functions with `unspecified'
1188 value return).  Use this when defining functions for executing actions
1189 rather than returning values, to keep Lilypond from trying to interpret
1190 the return value."
1191   `(define-syntax-function (void? *unspecified*) ,@rest *unspecified*))
1192
1193 (defmacro-public define-event-function rest
1194   "Defining macro returning event functions.
1195 Syntax:
1196   (define-event-function (arg1 arg2 ...) (arg1-type? arg2-type? ...)
1197     ...function body...)
1198
1199 argX-type can take one of the forms @code{predicate?} for mandatory
1200 arguments satisfying the predicate, @code{(predicate?)} for optional
1201 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
1202 value)}} for optional parameters with a specified default
1203 value (evaluated at definition time).  An optional parameter can be
1204 omitted in a call only when it can't get confused with a following
1205 parameter of different type.
1206
1207 Must return an event expression.  The @code{origin} is automatically
1208 set to the @code{location} parameter."
1209
1210   `(define-syntax-function (ly:event? (make-music 'Event 'void #t)) ,@rest))
1211
1212 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1213
1214 (define-public (cue-substitute quote-music)
1215   "Must happen after @code{quote-substitute}."
1216
1217   (if (vector? (ly:music-property quote-music 'quoted-events))
1218       (let* ((dir (ly:music-property quote-music 'quoted-voice-direction))
1219              (clef (ly:music-property quote-music 'quoted-music-clef #f))
1220              (main-voice (case dir ((1) 1) ((-1) 0) (else #f)))
1221              (cue-voice (and main-voice (- 1 main-voice)))
1222              (cue-type (ly:music-property quote-music 'quoted-context-type #f))
1223              (cue-id (ly:music-property quote-music 'quoted-context-id))
1224              (main-music (ly:music-property quote-music 'element))
1225              (return-value quote-music))
1226
1227         (if main-voice
1228             (set! (ly:music-property quote-music 'element)
1229                   (make-sequential-music
1230                    (list
1231                     (make-voice-props-override main-voice)
1232                     main-music
1233                     (make-voice-props-revert)))))
1234
1235         ;; if we have stem dirs, change both quoted and main music
1236         ;; to have opposite stems.
1237
1238         ;; cannot context-spec Quote-music, since context
1239         ;; for the quotes is determined in the iterator.
1240
1241         (make-sequential-music
1242          (delq! #f
1243                 (list
1244                  (and clef (make-cue-clef-set clef))
1245                  (and cue-type cue-voice
1246                       (context-spec-music
1247                        (make-voice-props-override cue-voice)
1248                        cue-type cue-id))
1249                  quote-music
1250                  (and cue-type cue-voice
1251                       (context-spec-music
1252                        (make-voice-props-revert)
1253                        cue-type cue-id))
1254                  (and clef (make-cue-clef-unset))))))
1255       quote-music))
1256
1257 (define ((quote-substitute quote-tab) music)
1258   (let* ((quoted-name (ly:music-property music 'quoted-music-name))
1259          (quoted-vector (and (string? quoted-name)
1260                              (hash-ref quote-tab quoted-name #f))))
1261
1262
1263     (if (string? quoted-name)
1264         (if (vector? quoted-vector)
1265             (begin
1266               (set! (ly:music-property music 'quoted-events) quoted-vector)
1267               (set! (ly:music-property music 'iterator-ctor)
1268                     ly:quote-iterator::constructor))
1269             (ly:music-warning music (ly:format (_ "cannot find quoted music: `~S'") quoted-name))))
1270     music))
1271 (export quote-substitute)
1272
1273
1274 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1275 ;; switch it on here, so parsing and init isn't checked (too slow!)
1276 ;;
1277 ;; automatic music transformations.
1278
1279 (define (switch-on-debugging m)
1280   (if (defined? 'set-debug-cell-accesses!)
1281       (set-debug-cell-accesses! 15000))
1282   m)
1283
1284 (define (music-check-error music)
1285   (define found #f)
1286   (define (signal m)
1287     (if (and (ly:music? m)
1288              (eq? (ly:music-property m 'error-found) #t))
1289         (set! found #t)))
1290
1291   (for-each signal (ly:music-property music 'elements))
1292   (signal (ly:music-property music 'element))
1293
1294   (if found
1295       (set! (ly:music-property music 'error-found) #t))
1296   music)
1297
1298 (define (precompute-music-length music)
1299   (set! (ly:music-property music 'length)
1300         (ly:music-length music))
1301   music)
1302
1303 (define-public (make-duration-of-length moment)
1304   "Make duration of the given @code{moment} length."
1305   (ly:make-duration 0 0
1306                     (ly:moment-main-numerator moment)
1307                     (ly:moment-main-denominator moment)))
1308
1309 (define (make-skipped moment bool)
1310   "Depending on BOOL, set or unset skipTypesetting,
1311 then make SkipMusic of the given MOMENT length, and
1312 then revert skipTypesetting."
1313   (make-sequential-music
1314    (list
1315     (context-spec-music (make-property-set 'skipTypesetting bool)
1316                         'Score)
1317     (make-music 'SkipMusic 'duration
1318                 (make-duration-of-length moment))
1319     (context-spec-music (make-property-set 'skipTypesetting (not bool))
1320                         'Score))))
1321
1322 (define (skip-as-needed music)
1323   "Replace MUSIC by
1324  << {  \\set skipTypesetting = ##f
1325  LENGTHOF(\\showFirstLength)
1326  \\set skipTypesetting = ##t
1327  LENGTHOF(\\showLastLength) }
1328  MUSIC >>
1329  if appropriate.
1330
1331  When only showFirstLength is set,
1332  the 'length property of the music is
1333  overridden to speed up compiling."
1334   (let*
1335       ((show-last (ly:parser-lookup 'showLastLength))
1336        (show-first (ly:parser-lookup 'showFirstLength))
1337        (show-last-length (and (ly:music? show-last)
1338                               (ly:music-length show-last)))
1339        (show-first-length (and (ly:music? show-first)
1340                                (ly:music-length show-first)))
1341        (orig-length (ly:music-length music)))
1342
1343     ;;FIXME: if using either showFirst- or showLastLength,
1344     ;; make sure that skipBars is not set.
1345
1346     (cond
1347
1348      ;; both properties may be set.
1349      ((and show-first-length show-last-length)
1350       (let
1351           ((skip-length (ly:moment-sub orig-length show-last-length)))
1352         (make-simultaneous-music
1353          (list
1354           (make-sequential-music
1355            (list
1356             (make-skipped skip-length #t)
1357             ;; let's draw a separator between the beginning and the end
1358             (context-spec-music (make-property-set 'whichBar "||")
1359                                 'Timing)))
1360           (make-skipped show-first-length #f)
1361           music))))
1362
1363      ;; we may only want to print the last length
1364      (show-last-length
1365       (let
1366           ((skip-length (ly:moment-sub orig-length show-last-length)))
1367         (make-simultaneous-music
1368          (list
1369           (make-skipped skip-length #t)
1370           music))))
1371
1372      ;; we may only want to print the beginning; in this case
1373      ;; only the first length will be processed (much faster).
1374      (show-first-length
1375       ;; the first length must not exceed the original length.
1376       (if (ly:moment<? show-first-length orig-length)
1377           (set! (ly:music-property music 'length)
1378                 show-first-length))
1379       music)
1380
1381      (else music))))
1382
1383
1384 (define-session-public toplevel-music-functions
1385   (list
1386    (lambda (music) (expand-repeat-chords!
1387                     (cons 'rhythmic-event
1388                           (ly:parser-lookup '$chord-repeat-events))
1389                     music))
1390    expand-repeat-notes!
1391    voicify-music
1392    (lambda (x) (music-map music-check-error x))
1393    (lambda (x) (music-map precompute-music-length x))
1394    (lambda (music)
1395      (music-map (quote-substitute (ly:parser-lookup 'musicQuotes))  music))
1396
1397    ;; switch-on-debugging
1398    (lambda (x) (music-map cue-substitute x))
1399
1400    skip-as-needed))
1401
1402 ;;;;;;;;;;
1403 ;;; general purpose music functions
1404
1405 (define (shift-octave pitch octave-shift)
1406   (_i "Add @var{octave-shift} to the octave of @var{pitch}.")
1407   (ly:make-pitch
1408    (+ (ly:pitch-octave pitch) octave-shift)
1409    (ly:pitch-notename pitch)
1410    (ly:pitch-alteration pitch)))
1411
1412
1413 ;;;;;;;;;;;;;;;;;
1414 ;; lyrics
1415
1416 (define (apply-durations lyric-music durations)
1417   (define (apply-duration music)
1418     (if (and (not (equal? (ly:music-length music) ZERO-MOMENT))
1419              (ly:duration?  (ly:music-property music 'duration)))
1420         (begin
1421           (set! (ly:music-property music 'duration) (car durations))
1422           (set! durations (cdr durations)))))
1423
1424   (music-map apply-duration lyric-music))
1425
1426
1427 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1428 ;; accidentals
1429
1430 (define (recent-enough? bar-number alteration-def laziness)
1431   (or (number? alteration-def)
1432       (equal? laziness #t)
1433       (<= bar-number (+ (cadr alteration-def) laziness))))
1434
1435 (define (accidental-invalid? alteration-def)
1436   "Checks an alteration entry for being invalid.
1437
1438 Non-key alterations are invalidated when tying into the next bar or
1439 when there is a clef change, since neither repetition nor cancellation
1440 can be omitted when the same note occurs again.
1441
1442 Returns @code{#f} or the reason for the invalidation, a symbol."
1443   (let* ((def (if (pair? alteration-def)
1444                   (car alteration-def)
1445                   alteration-def)))
1446     (and (symbol? def) def)))
1447
1448 (define (extract-alteration alteration-def)
1449   (cond ((number? alteration-def)
1450          alteration-def)
1451         ((pair? alteration-def)
1452          (car alteration-def))
1453         (else 0)))
1454
1455 (define (check-pitch-against-signature context pitch barnum laziness octaveness all-naturals)
1456   "Checks the need for an accidental and a @q{restore} accidental against
1457 @code{localAlterations} and @code{keyAlterations}.
1458 The @var{laziness} is the number of measures
1459 for which reminder accidentals are used (i.e., if @var{laziness} is zero,
1460 only cancel accidentals in the same measure; if @var{laziness} is three,
1461 we cancel accidentals up to three measures after they first appear.
1462 @var{octaveness} is either @code{'same-octave} or @code{'any-octave} and
1463 specifies whether accidentals should be canceled in different octaves.
1464 If @var{all-naturals} is ##t, notes that do not occur in @code{keyAlterations}
1465 also get an accidental."
1466   (let* ((ignore-octave (cond ((equal? octaveness 'any-octave) #t)
1467                               ((equal? octaveness 'same-octave) #f)
1468                               (else
1469                                (ly:warning (_ "Unknown octaveness type: ~S ") octaveness)
1470                                (ly:warning (_ "Defaulting to 'any-octave."))
1471                                #t)))
1472          (key (ly:context-property context 'keyAlterations))
1473          (local (ly:context-property context 'localAlterations))
1474          (notename (ly:pitch-notename pitch))
1475          (octave (ly:pitch-octave pitch))
1476          (pitch-handle (cons octave notename))
1477          (need-restore #f)
1478          (need-accidental #f)
1479          (previous-alteration #f)
1480          (from-other-octaves #f)
1481          (from-same-octave (assoc-get pitch-handle local))
1482          (from-key-sig (or (assoc-get notename local)
1483
1484                            ;; If no notename match is found from localAlterations, we may have a custom
1485                            ;; type with octave-specific entries of the form ((octave . pitch) alteration)
1486                            ;; instead of (pitch . alteration).  Since this type cannot coexist with entries in
1487                            ;; localAlterations, try extracting from keyAlterations instead.
1488                            (assoc-get pitch-handle key))))
1489
1490     ;; loop through localAlterations to search for a notename match from other octaves
1491     (let loop ((l local))
1492       (if (pair? l)
1493           (let ((entry (car l)))
1494             (if (and (pair? (car entry))
1495                      (= (cdar entry) notename))
1496                 (set! from-other-octaves (cdr entry))
1497                 (loop (cdr l))))))
1498
1499     ;; find previous alteration-def for comparison with pitch
1500     (cond
1501      ;; from same octave?
1502      ((and (not ignore-octave)
1503            from-same-octave
1504            (recent-enough? barnum from-same-octave laziness))
1505       (set! previous-alteration from-same-octave))
1506
1507      ;; from any octave?
1508      ((and ignore-octave
1509            from-other-octaves
1510            (recent-enough? barnum from-other-octaves laziness))
1511       (set! previous-alteration from-other-octaves))
1512
1513      ;; not recent enough, extract from key signature/local key signature
1514      (from-key-sig
1515       (set! previous-alteration from-key-sig)))
1516
1517     (if (accidental-invalid? previous-alteration)
1518         (set! need-accidental #t)
1519
1520         (let* ((prev-alt (extract-alteration previous-alteration))
1521                (this-alt (ly:pitch-alteration pitch)))
1522
1523           (if (or (and all-naturals (eq? #f previous-alteration)) (not (= this-alt prev-alt)))
1524               (begin
1525                 (set! need-accidental #t)
1526                 (if (and (not (= this-alt 0))
1527                          (and (< (abs this-alt) (abs prev-alt))
1528                               (> (* prev-alt this-alt) 0)))
1529                     (set! need-restore #t))))))
1530
1531     (cons need-restore need-accidental)))
1532
1533 (define ((make-accidental-rule octaveness laziness) context pitch barnum measurepos)
1534   "Create an accidental rule that makes its decision based on the octave of
1535 the note and a laziness value.
1536
1537 @var{octaveness} is either @code{'same-octave} or @code{'any-octave} and
1538 defines whether the rule should respond to accidental changes in other
1539 octaves than the current.  @code{'same-octave} is the normal way to typeset
1540 accidentals -- an accidental is made if the alteration is different from the
1541 last active pitch in the same octave.  @code{'any-octave} looks at the last
1542 active pitch in any octave.
1543
1544 @var{laziness} states over how many bars an accidental should be remembered.
1545 @code{0}@tie{}is the default -- accidental lasts over 0@tie{}bar lines, that
1546 is, to the end of current measure.  A positive integer means that the
1547 accidental lasts over that many bar lines.  @w{@code{-1}} is `forget
1548 immediately', that is, only look at key signature.  @code{#t} is `forever'."
1549
1550   (check-pitch-against-signature context pitch barnum laziness octaveness #f))
1551 (export make-accidental-rule)
1552
1553 (define ((make-accidental-dodecaphonic-rule octaveness laziness) context pitch barnum measurepos)
1554   "Variation on function make-accidental-rule that creates an dodecaphonic
1555 accidental rule."
1556
1557   (check-pitch-against-signature context pitch barnum laziness octaveness #t))
1558 (export make-accidental-dodecaphonic-rule)
1559
1560 (define (key-entry-notename entry)
1561   "Return the pitch of an @var{entry} in @code{localAlterations}.
1562 The @samp{car} of the entry is either of the form @code{notename} or
1563 of the form @code{(octave . notename)}.  The latter form is used for special
1564 key signatures or to indicate an explicit accidental.
1565
1566 The @samp{cdr} of the entry is either a rational @code{alter} indicating
1567 a key signature alteration, or of the form
1568 @code{(alter . (barnum . measurepos))} indicating an alteration caused by
1569 an accidental in music."
1570   (if (pair? (car entry))
1571       (cdar entry)
1572       (car entry)))
1573
1574 (define (key-entry-octave entry)
1575   "Return the octave of an entry in @code{localAlterations}
1576 or @code{#f} if the entry does not have an octave.
1577 See @code{key-entry-notename} for details."
1578   (and (pair? (car entry)) (caar entry)))
1579
1580 (define (key-entry-bar-number entry)
1581   "Return the bar number of an entry in @code{localAlterations}
1582 or @code {#f} if the entry does not have a bar number.
1583 See @code{key-entry-notename} for details."
1584   (and (pair? (cdr entry)) (caddr entry)))
1585
1586 (define (key-entry-measure-position entry)
1587   "Return the measure position of an entry in @code{localAlterations}
1588 or @code {#f} if the entry does not have a measure position.
1589 See @code{key-entry-notename} for details."
1590   (and (pair? (cdr entry)) (cdddr entry)))
1591
1592 (define (key-entry-alteration entry)
1593   "Return the alteration of an entry in localAlterations
1594
1595 For convenience, returns @code{0} if entry is @code{#f}."
1596   (if entry
1597       (if (number? (cdr entry))
1598           (cdr entry)
1599           (cadr entry))
1600       0))
1601
1602 (define-public (find-pitch-entry keysig pitch accept-global accept-local)
1603   "Return the first entry in @var{keysig} that matches @var{pitch}
1604 by notename and octave.  Alteration is not considered.
1605 @var{accept-global} states whether key signature entries should be included.
1606 @var{accept-local} states whether local accidentals should be included.
1607 If no matching entry is found, @var{#f} is returned."
1608   (and (pair? keysig)
1609        (let* ((entry (car keysig))
1610               (entryoct (key-entry-octave entry))
1611               (entrynn (key-entry-notename entry))
1612               (nn (ly:pitch-notename pitch)))
1613          (if (and (equal? nn entrynn)
1614                   (or (not entryoct)
1615                       (= entryoct (ly:pitch-octave pitch)))
1616                   (if (key-entry-bar-number entry)
1617                       accept-local
1618                       accept-global))
1619              entry
1620              (find-pitch-entry (cdr keysig) pitch accept-global accept-local)))))
1621
1622 (define-public (neo-modern-accidental-rule context pitch barnum measurepos)
1623   "An accidental rule that typesets an accidental if it differs from the
1624 key signature @emph{and} does not directly follow a note on the same
1625 staff line.  This rule should not be used alone because it does neither
1626 look at bar lines nor different accidentals at the same note name."
1627   (let* ((keysig (ly:context-property context 'localAlterations))
1628          (entry (find-pitch-entry keysig pitch #t #t)))
1629     (if (not entry)
1630         (cons #f #f)
1631         (let* ((global-entry (find-pitch-entry keysig pitch #t #f))
1632                (key-acc (key-entry-alteration global-entry))
1633                (acc (ly:pitch-alteration pitch))
1634                (entrymp (key-entry-measure-position entry))
1635                (entrybn (key-entry-bar-number entry)))
1636           (cons #f (not (or (equal? acc key-acc)
1637                             (and (equal? entrybn barnum) (equal? entrymp measurepos)))))))))
1638
1639 (define-public (dodecaphonic-no-repeat-rule context pitch barnum measurepos)
1640   "An accidental rule that typesets an accidental before every
1641 note (just as in the dodecaphonic accidental style) @emph{except} if
1642 the note is immediately preceded by a note with the same pitch. This
1643 is a common accidental style in contemporary notation."
1644    (let* ((keysig (ly:context-property context 'localAlterations))
1645           (entry (find-pitch-entry keysig pitch #f #t)))
1646      (if (not entry)
1647          (cons #f #t)
1648          (let ((entrymp (key-entry-measure-position entry))
1649                (entrybn (key-entry-bar-number entry))
1650                (entryalt (key-entry-alteration entry))
1651                (alt (ly:pitch-alteration pitch)))
1652            (cons #t
1653                  (not (and (equal? entrybn barnum)
1654                            (or (equal? measurepos entrymp)
1655                                (ly:moment<? measurepos entrymp))
1656                            (equal? entryalt alt))))))))
1657
1658 (define-public (teaching-accidental-rule context pitch barnum measurepos)
1659   "An accidental rule that typesets a cautionary accidental if it is
1660 included in the key signature @emph{and} does not directly follow a note
1661 on the same staff line."
1662   (let* ((keysig (ly:context-property context 'localAlterations))
1663          (entry (find-pitch-entry keysig pitch #t #t)))
1664     (if (not entry)
1665         (cons #f #f)
1666         (let* ((global-entry (find-pitch-entry keysig pitch #f #f))
1667                (key-acc (key-entry-alteration global-entry))
1668                (acc (ly:pitch-alteration pitch))
1669                (entrymp (key-entry-measure-position entry))
1670                (entrybn (key-entry-bar-number entry)))
1671           (cons #f (not (or (equal? acc key-acc)
1672                             (and (equal? entrybn barnum) (equal? entrymp measurepos)))))))))
1673
1674 (define-public (set-accidentals-properties extra-natural
1675                                            auto-accs auto-cauts
1676                                            context)
1677   (context-spec-music
1678    (make-sequential-music
1679     (append (if (boolean? extra-natural)
1680                 (list (make-property-set 'extraNatural extra-natural))
1681                 '())
1682             (list (make-property-set 'autoAccidentals auto-accs)
1683                   (make-property-set 'autoCautionaries auto-cauts))))
1684    context))
1685
1686 (define-public (set-accidental-style style . rest)
1687   "Set accidental style to @var{style}.  Optionally take a context
1688 argument, e.g. @code{'Staff} or @code{'Voice}.  The context defaults
1689 to @code{Staff}, except for piano styles, which use @code{GrandStaff}
1690 as a context."
1691   (let ((context (if (pair? rest)
1692                      (car rest) 'Staff))
1693         (pcontext (if (pair? rest)
1694                       (car rest) 'GrandStaff)))
1695     (cond
1696      ;; accidentals as they were common in the 18th century.
1697      ((equal? style 'default)
1698       (set-accidentals-properties #t
1699                                   `(Staff ,(make-accidental-rule 'same-octave 0))
1700                                   '()
1701                                   context))
1702      ;; accidentals from one voice do NOT get canceled in other voices
1703      ((equal? style 'voice)
1704       (set-accidentals-properties #t
1705                                   `(Voice ,(make-accidental-rule 'same-octave 0))
1706                                   '()
1707                                   context))
1708      ;; accidentals as suggested by Kurt Stone, Music Notation in the 20th century.
1709      ;; This includes all the default accidentals, but accidentals also needs canceling
1710      ;; in other octaves and in the next measure.
1711      ((equal? style 'modern)
1712       (set-accidentals-properties #f
1713                                   `(Staff ,(make-accidental-rule 'same-octave 0)
1714                                           ,(make-accidental-rule 'any-octave 0)
1715                                           ,(make-accidental-rule 'same-octave 1))
1716                                   '()
1717                                   context))
1718      ;; the accidentals that Stone adds to the old standard as cautionaries
1719      ((equal? style 'modern-cautionary)
1720       (set-accidentals-properties #f
1721                                   `(Staff ,(make-accidental-rule 'same-octave 0))
1722                                   `(Staff ,(make-accidental-rule 'any-octave 0)
1723                                           ,(make-accidental-rule 'same-octave 1))
1724                                   context))
1725      ;; same as modern, but accidentals different from the key signature are always
1726      ;; typeset - unless they directly follow a note of the same pitch.
1727      ((equal? style 'neo-modern)
1728       (set-accidentals-properties #f
1729                                   `(Staff ,(make-accidental-rule 'same-octave 0)
1730                                           ,(make-accidental-rule 'any-octave 0)
1731                                           ,(make-accidental-rule 'same-octave 1)
1732                                           ,neo-modern-accidental-rule)
1733                                   '()
1734                                   context))
1735      ((equal? style 'neo-modern-cautionary)
1736       (set-accidentals-properties #f
1737                                   `(Staff ,(make-accidental-rule 'same-octave 0))
1738                                   `(Staff ,(make-accidental-rule 'any-octave 0)
1739                                           ,(make-accidental-rule 'same-octave 1)
1740                                           ,neo-modern-accidental-rule)
1741                                   context))
1742      ((equal? style 'neo-modern-voice)
1743       (set-accidentals-properties #f
1744                                   `(Voice ,(make-accidental-rule 'same-octave 0)
1745                                           ,(make-accidental-rule 'any-octave 0)
1746                                           ,(make-accidental-rule 'same-octave 1)
1747                                           ,neo-modern-accidental-rule
1748                                           Staff ,(make-accidental-rule 'same-octave 0)
1749                                           ,(make-accidental-rule 'any-octave 0)
1750                                           ,(make-accidental-rule 'same-octave 1)
1751                                           ,neo-modern-accidental-rule)
1752                                   '()
1753                                   context))
1754      ((equal? style 'neo-modern-voice-cautionary)
1755       (set-accidentals-properties #f
1756                                   `(Voice ,(make-accidental-rule 'same-octave 0))
1757                                   `(Voice ,(make-accidental-rule 'any-octave 0)
1758                                           ,(make-accidental-rule 'same-octave 1)
1759                                           ,neo-modern-accidental-rule
1760                                           Staff ,(make-accidental-rule 'same-octave 0)
1761                                           ,(make-accidental-rule 'any-octave 0)
1762                                           ,(make-accidental-rule 'same-octave 1)
1763                                           ,neo-modern-accidental-rule)
1764                                   context))
1765      ;; Accidentals as they were common in dodecaphonic music with no tonality.
1766      ;; Each note gets one accidental.
1767      ((equal? style 'dodecaphonic)
1768       (set-accidentals-properties #f
1769                                   `(Staff ,(lambda (c p bn mp) '(#f . #t)))
1770                                   '()
1771                                   context))
1772      ;; As in dodecaphonic style with the exception that immediately
1773      ;; repeated notes (in the same voice) don't get an accidental
1774      ((equal? style 'dodecaphonic-no-repeat)
1775       (set-accidentals-properties #f
1776                                   `(Staff ,dodecaphonic-no-repeat-rule)
1777                                   '()
1778                                   context))
1779      ;; Variety of the dodecaphonic style. Each note gets an accidental,
1780      ;; except notes that were already handled in the same measure.
1781      ((equal? style 'dodecaphonic-first)
1782       (set-accidentals-properties #f
1783                                   `(Staff ,(make-accidental-dodecaphonic-rule 'same-octave 0))
1784                                   '()
1785                                   context))
1786
1787      ;; Multivoice accidentals to be read both by musicians playing one voice
1788      ;; and musicians playing all voices.
1789      ;; Accidentals are typeset for each voice, but they ARE canceled across voices.
1790      ((equal? style 'modern-voice)
1791       (set-accidentals-properties  #f
1792                                    `(Voice ,(make-accidental-rule 'same-octave 0)
1793                                            ,(make-accidental-rule 'any-octave 0)
1794                                            ,(make-accidental-rule 'same-octave 1)
1795                                            Staff ,(make-accidental-rule 'same-octave 0)
1796                                            ,(make-accidental-rule 'any-octave 0)
1797                                            ,(make-accidental-rule 'same-octave 1))
1798                                    '()
1799                                    context))
1800      ;; same as modernVoiceAccidental eccept that all special accidentals are typeset
1801      ;; as cautionaries
1802      ((equal? style 'modern-voice-cautionary)
1803       (set-accidentals-properties #f
1804                                   `(Voice ,(make-accidental-rule 'same-octave 0))
1805                                   `(Voice ,(make-accidental-rule 'any-octave 0)
1806                                           ,(make-accidental-rule 'same-octave 1)
1807                                           Staff ,(make-accidental-rule 'same-octave 0)
1808                                           ,(make-accidental-rule 'any-octave 0)
1809                                           ,(make-accidental-rule 'same-octave 1))
1810                                   context))
1811      ;; stone's suggestions for accidentals on grand staff.
1812      ;; Accidentals are canceled across the staves in the same grand staff as well
1813      ((equal? style 'piano)
1814       (set-accidentals-properties #f
1815                                   `(Staff ,(make-accidental-rule 'same-octave 0)
1816                                           ,(make-accidental-rule 'any-octave 0)
1817                                           ,(make-accidental-rule 'same-octave 1)
1818                                           GrandStaff
1819                                           ,(make-accidental-rule 'any-octave 0)
1820                                           ,(make-accidental-rule 'same-octave 1))
1821                                   '()
1822                                   pcontext))
1823      ((equal? style 'piano-cautionary)
1824       (set-accidentals-properties #f
1825                                   `(Staff ,(make-accidental-rule 'same-octave 0))
1826                                   `(Staff ,(make-accidental-rule 'any-octave 0)
1827                                           ,(make-accidental-rule 'same-octave 1)
1828                                           GrandStaff
1829                                           ,(make-accidental-rule 'any-octave 0)
1830                                           ,(make-accidental-rule 'same-octave 1))
1831                                   pcontext))
1832
1833      ;; same as modern, but cautionary accidentals are printed for all sharp or flat
1834      ;; tones specified by the key signature.
1835      ((equal? style 'teaching)
1836       (set-accidentals-properties #f
1837                                   `(Staff ,(make-accidental-rule 'same-octave 0))
1838                                   `(Staff ,(make-accidental-rule 'same-octave 1)
1839                                           ,teaching-accidental-rule)
1840                                   context))
1841
1842      ;; do not set localAlterations when a note alterated differently from
1843      ;; localAlterations is found.
1844      ;; Causes accidentals to be printed at every note instead of
1845      ;; remembered for the duration of a measure.
1846      ;; accidentals not being remembered, causing accidentals always to
1847      ;; be typeset relative to the time signature
1848      ((equal? style 'forget)
1849       (set-accidentals-properties '()
1850                                   `(Staff ,(make-accidental-rule 'same-octave -1))
1851                                   '()
1852                                   context))
1853      ;; Do not reset the key at the start of a measure.  Accidentals will be
1854      ;; printed only once and are in effect until overridden, possibly many
1855      ;; measures later.
1856      ((equal? style 'no-reset)
1857       (set-accidentals-properties '()
1858                                   `(Staff ,(make-accidental-rule 'same-octave #t))
1859                                   '()
1860                                   context))
1861      (else
1862       (ly:warning (_ "unknown accidental style: ~S") style)
1863       (make-sequential-music '())))))
1864
1865 (define-public (invalidate-alterations context)
1866   "Invalidate alterations in @var{context}.
1867
1868 Elements of @code{'localAlterations} corresponding to local
1869 alterations of the key signature have the form
1870 @code{'((octave . notename) . (alter barnum . measurepos))}.
1871 Replace them with a version where @code{alter} is set to @code{'clef}
1872 to force a repetition of accidentals.
1873
1874 Entries that conform with the current key signature are not invalidated."
1875   (let* ((keysig (ly:context-property context 'keyAlterations)))
1876     (set! (ly:context-property context 'localAlterations)
1877           (map-in-order
1878            (lambda (entry)
1879              (let* ((localalt (key-entry-alteration entry)))
1880                (if (or (accidental-invalid? localalt)
1881                        (not (key-entry-bar-number entry))
1882                        (= localalt
1883                           (key-entry-alteration
1884                            (find-pitch-entry
1885                             keysig
1886                             (ly:make-pitch (key-entry-octave entry)
1887                                            (key-entry-notename entry)
1888                                            0)
1889                             #t #t))))
1890                    entry
1891                    (cons (car entry) (cons 'clef (cddr entry))))))
1892            (ly:context-property context 'localAlterations)))))
1893
1894 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1895
1896 (define-public (skip-of-length mus)
1897   "Create a skip of exactly the same length as @var{mus}."
1898   (let* ((skip
1899           (make-music
1900            'SkipEvent
1901            'duration (ly:make-duration 0 0))))
1902
1903     (make-event-chord (list (ly:music-compress skip (ly:music-length mus))))))
1904
1905 (define-public (mmrest-of-length mus)
1906   "Create a multi-measure rest of exactly the same length as @var{mus}."
1907
1908   (let* ((skip
1909           (make-multi-measure-rest
1910            (ly:make-duration 0 0) '())))
1911     (ly:music-compress skip (ly:music-length mus))
1912     skip))
1913
1914 (define-public (pitch-of-note event-chord)
1915   (let ((evs (filter (lambda (x)
1916                        (music-is-of-type? x 'note-event))
1917                      (ly:music-property event-chord 'elements))))
1918
1919     (and (pair? evs)
1920          (ly:music-property (car evs) 'pitch))))
1921
1922 (define-public (duration-of-note event-chord)
1923   (cond
1924    ((pair? event-chord)
1925     (or (duration-of-note (car event-chord))
1926         (duration-of-note (cdr event-chord))))
1927    ((ly:music? event-chord)
1928     (let ((dur (ly:music-property event-chord 'duration)))
1929       (if (ly:duration? dur)
1930           dur
1931           (duration-of-note (ly:music-property event-chord 'elements)))))
1932    (else #f)))
1933
1934 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1935
1936 (define-public (map-some-music map? music)
1937   "Walk through @var{music}, transform all elements calling @var{map?}
1938 and only recurse if this returns @code{#f}.  @code{elements} or
1939 @code{articulations} that are not music expressions are discarded:
1940 this allows some amount of filtering.
1941
1942 @code{map-some-music} may overwrite the original @var{music}."
1943   (let loop ((music music))
1944     (or (map? music)
1945         (let ((elt (ly:music-property music 'element))
1946               (elts (ly:music-property music 'elements))
1947               (arts (ly:music-property music 'articulations)))
1948           (if (ly:music? elt)
1949               (set! (ly:music-property music 'element)
1950                     (loop elt)))
1951           (if (pair? elts)
1952               (set! (ly:music-property music 'elements)
1953                     (filter! ly:music? (map! loop elts))))
1954           (if (pair? arts)
1955               (set! (ly:music-property music 'articulations)
1956                     (filter! ly:music? (map! loop arts))))
1957           music))))
1958
1959 (define-public (for-some-music stop? music)
1960   "Walk through @var{music}, process all elements calling @var{stop?}
1961 and only recurse if this returns @code{#f}."
1962   (let loop ((music music))
1963     (if (not (stop? music))
1964         (let ((elt (ly:music-property music 'element)))
1965           (if (ly:music? elt)
1966               (loop elt))
1967           (for-each loop (ly:music-property music 'elements))
1968           (for-each loop (ly:music-property music 'articulations))))))
1969
1970 (define-public (fold-some-music pred? proc init music)
1971   "This works recursively on music like @code{fold} does on a list,
1972 calling @samp{(@var{pred?} music)} on every music element.  If
1973 @code{#f} is returned for an element, it is processed recursively
1974 with the same initial value of @samp{previous}, otherwise
1975 @samp{(@var{proc} music previous)} replaces @samp{previous}
1976 and no recursion happens.
1977 The top @var{music} is processed using @var{init} for @samp{previous}."
1978   (let loop ((music music) (previous init))
1979     (if (pred? music)
1980         (proc music previous)
1981         (fold loop
1982               (fold loop
1983                     (let ((elt (ly:music-property music 'element)))
1984                       (if (null? elt)
1985                           previous
1986                           (loop elt previous)))
1987                     (ly:music-property music 'elements))
1988               (ly:music-property music 'articulations)))))
1989
1990 (define-public (extract-music music pred?)
1991   "Return a flat list of all music matching @var{pred?} inside of
1992 @var{music}, not recursing into matches themselves."
1993   (reverse! (fold-some-music pred? cons '() music)))
1994
1995 (define-public (extract-named-music music music-name)
1996   "Return a flat list of all music named @var{music-name} (either a
1997 single event symbol or a list of alternatives) inside of @var{music},
1998 not recursing into matches themselves."
1999   (extract-music
2000    music
2001    (if (cheap-list? music-name)
2002        (lambda (m) (memq (ly:music-property m 'name) music-name))
2003        (lambda (m) (eq? (ly:music-property m 'name) music-name)))))
2004
2005 (define-public (extract-typed-music music type)
2006   "Return a flat list of all music with @var{type} (either a single
2007 type symbol or a list of alternatives) inside of @var{music}, not
2008 recursing into matches themselves."
2009   (extract-music
2010    music
2011    (if (cheap-list? type)
2012        (lambda (m)
2013          (any (lambda (t) (music-is-of-type? m t)) type))
2014        (lambda (m) (music-is-of-type? m type)))))
2015
2016 (define*-public (event-chord-wrap! music)
2017   "Wrap isolated rhythmic events and non-postevent events in
2018 @var{music} inside of an @code{EventChord}.  Chord repeats @samp{q}
2019 are expanded using the default settings of the parser."
2020   (map-some-music
2021    (lambda (m)
2022      (cond ((music-is-of-type? m 'event-chord)
2023             (if (pair? (ly:music-property m 'articulations))
2024                 (begin
2025                   (set! (ly:music-property m 'elements)
2026                         (append (ly:music-property m 'elements)
2027                                 (ly:music-property m 'articulations)))
2028                   (set! (ly:music-property m 'articulations) '())))
2029             m)
2030            ((music-is-of-type? m 'rhythmic-event)
2031             (let ((arts (ly:music-property m 'articulations)))
2032               (if (pair? arts)
2033                   (set! (ly:music-property m 'articulations) '()))
2034               (make-event-chord (cons m arts))))
2035            (else #f)))
2036    (expand-repeat-chords!
2037     (cons 'rhythmic-event
2038           (ly:parser-lookup '$chord-repeat-events))
2039     music)))
2040
2041 (define-public (event-chord-notes event-chord)
2042   "Return a list of all notes from @var{event-chord}."
2043   (filter
2044    (lambda (m) (eq? 'NoteEvent (ly:music-property m 'name)))
2045    (ly:music-property event-chord 'elements)))
2046
2047 (define-public (event-chord-pitches event-chord)
2048   "Return a list of all pitches from @var{event-chord}."
2049   (map (lambda (x) (ly:music-property x 'pitch))
2050        (event-chord-notes event-chord)))
2051
2052 (define-public (event-chord-reduce music)
2053   "Reduces event chords in @var{music} to their first note event,
2054 retaining only the chord articulations.  Returns the modified music."
2055   (map-some-music
2056    (lambda (m)
2057      (and (music-is-of-type? m 'event-chord)
2058           (let*-values (((notes arts) (partition
2059                                        (lambda (mus)
2060                                          (music-is-of-type? mus 'rhythmic-event))
2061                                        (ly:music-property m 'elements)))
2062                         ((dur) (ly:music-property m 'duration))
2063                         ((full-arts) (append arts
2064                                              (ly:music-property m 'articulations)))
2065                         ((first-note) (and (pair? notes) (car notes))))
2066             (cond (first-note
2067                    (set! (ly:music-property first-note 'articulations)
2068                          full-arts)
2069                    first-note)
2070                   ((ly:duration? dur)
2071                    ;; A repeat chord. Produce an unpitched note.
2072                    (make-music 'NoteEvent
2073                                'duration dur
2074                                'articulations full-arts))
2075                   (else
2076                    (ly:music-error m (_ "Missing duration"))
2077                    (make-music 'NoteEvent
2078                                'duration (ly:make-duration 2 0 0)
2079                                'articulations full-arts))))))
2080    music))
2081
2082
2083 (defmacro-public make-relative (variables reference music)
2084   "The list of pitch or music variables in @var{variables} is used as
2085 a sequence for creating relativable music from @var{music}.
2086
2087 When the constructed music is used outside of @code{\\relative}, it
2088 just reflects plugging in the @var{variables} into @var{music}.
2089
2090 The action inside of @code{\\relative}, however, is determined by
2091 first relativizing the surrogate @var{reference} with the variables
2092 plugged in and then using the variables relativized as a side effect
2093 of relativizing @var{reference} for evaluating @var{music}.
2094
2095 Since pitches don't have the object identity required for tracing the
2096 effect of the reference call, they are replaced @emph{only} for the
2097 purpose of evaluating @var{reference} with simple pitched note events.
2098
2099 The surrogate @var{reference} expression has to be written with that
2100 in mind.  In addition, it must @emph{not} contain @emph{copies} of
2101 music that is supposed to be relativized but rather the
2102 @emph{originals}.  This @emph{includes} the pitch expressions.  As a
2103 rule, inside of @code{#@{@dots{}#@}} variables must @emph{only} be
2104 introduced using @code{#}, never via the copying construct @code{$}.
2105 The reference expression will usually just be a sequential or chord
2106 expression naming all variables in sequence, implying that following
2107 music will be relativized according to the resulting pitch of the last
2108 or first variable, respectively.
2109
2110 Since the usual purpose is to create more complex music from general
2111 arguments and since music expression parts must not occur more than
2112 once, one @emph{does} generally need to use copying operators in the
2113 @emph{replacement} expression @var{music} when using an argument more
2114 than once there.  Using an argument more than once in @var{reference},
2115 in contrast, does not make sense.
2116
2117 There is another fine point to mind: @var{music} must @emph{only}
2118 contain freshly constructed elements or copied constructs.  This will
2119 be the case anyway for regular LilyPond code inside of
2120 @code{#@{@dots{}#@}}, but any other elements (apart from the
2121 @var{variables} themselves which are already copied) must be created
2122 or copied as well.
2123
2124 The reason is that it is usually permitted to change music in-place as
2125 long as one does a @var{ly:music-deep-copy} on it, and such a copy of
2126 the whole resulting expression will @emph{not} be able to copy
2127 variables/values inside of closures where the information for
2128 relativization is being stored.
2129 "
2130
2131   ;; pitch and music generator might be stored instead in music
2132   ;; properties, and it might make sense to create a music type of its
2133   ;; own for this kind of construct rather than using
2134   ;; RelativeOctaveMusic
2135   (define ((make-relative::to-relative-callback variables music-call ref-call)
2136            music pitch)
2137     (let* ((ref-vars (map (lambda (v)
2138                             (if (ly:pitch? v)
2139                                 (make-music 'NoteEvent 'pitch v)
2140                                 (ly:music-deep-copy v)))
2141                           variables))
2142            (after-pitch (ly:make-music-relative! (apply ref-call ref-vars) pitch))
2143            (actual-vars (map (lambda (v r)
2144                                (if (ly:pitch? v)
2145                                    (ly:music-property r 'pitch)
2146                                    r))
2147                              variables ref-vars))
2148            (rel-music (apply music-call actual-vars)))
2149       (set! (ly:music-property music 'element) rel-music)
2150       after-pitch))
2151   `(make-music 'RelativeOctaveMusic
2152                'to-relative-callback
2153                (,make-relative::to-relative-callback
2154                 (list ,@variables)
2155                 (lambda ,variables ,music)
2156                 (lambda ,variables ,reference))
2157                'element ,music))
2158
2159 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2160 ;; The following functions are all associated with the crossStaff
2161 ;;  function
2162
2163 (define (close-enough? x y)
2164   "Values are close enough to ignore the difference"
2165   (< (abs (- x y)) 0.0001))
2166
2167 (define (extent-combine extents)
2168   "Combine a list of extents"
2169   (if (pair? (cdr extents))
2170       (interval-union (car extents) (extent-combine (cdr extents)))
2171       (car extents)))
2172
2173 (define ((stem-connectable? ref root) stem)
2174   "Check if the stem is connectable to the root"
2175   ;; The root is always connectable to itself
2176   (or (eq? root stem)
2177       (and
2178        ;; Horizontal positions of the stems must be almost the same
2179        (close-enough? (car (ly:grob-extent root ref X))
2180                       (car (ly:grob-extent stem ref X)))
2181        ;; The stem must be in the direction away from the root's notehead
2182        (positive? (* (ly:grob-property root 'direction)
2183                      (- (car (ly:grob-extent stem ref Y))
2184                         (car (ly:grob-extent root ref Y))))))))
2185
2186 (define (stem-span-stencil span)
2187   "Connect stems if we have at least one stem connectable to the root"
2188   (let* ((system (ly:grob-system span))
2189          (root (ly:grob-parent span X))
2190          (stems (filter (stem-connectable? system root)
2191                         (ly:grob-object span 'stems))))
2192     (if (<= 2 (length stems))
2193         (let* ((yextents (map (lambda (st)
2194                                 (ly:grob-extent st system Y)) stems))
2195                (yextent (extent-combine yextents))
2196                (layout (ly:grob-layout root))
2197                (blot (ly:output-def-lookup layout 'blot-diameter)))
2198           ;; Hide spanned stems
2199           (for-each (lambda (st)
2200                       (set! (ly:grob-property st 'stencil) #f))
2201                     stems)
2202           ;; Draw a nice looking stem with rounded corners
2203           (ly:round-filled-box (ly:grob-extent root root X) yextent blot))
2204         ;; Nothing to connect, don't draw the span
2205         #f)))
2206
2207 (define ((make-stem-span! stems trans) root)
2208   "Create a stem span as a child of the cross-staff stem (the root)"
2209   (let ((span (ly:engraver-make-grob trans 'Stem '())))
2210     (ly:grob-set-parent! span X root)
2211     (set! (ly:grob-object span 'stems) stems)
2212     ;; Suppress positioning, the stem code is confused by this weird stem
2213     (set! (ly:grob-property span 'X-offset) 0)
2214     (set! (ly:grob-property span 'stencil) stem-span-stencil)))
2215
2216 (define-public (cross-staff-connect stem)
2217   "Set cross-staff property of the stem to this function to connect it to
2218 other stems automatically"
2219   #t)
2220
2221 (define (stem-is-root? stem)
2222   "Check if automatic connecting of the stem was requested.  Stems connected
2223 to cross-staff beams are cross-staff, but they should not be connected to
2224 other stems just because of that."
2225   (eq? cross-staff-connect (ly:grob-property-data stem 'cross-staff)))
2226
2227 (define (make-stem-spans! ctx stems trans)
2228   "Create stem spans for cross-staff stems"
2229   ;; Cannot do extensive checks here, just make sure there are at least
2230   ;; two stems at this musical moment
2231   (if (<= 2 (length stems))
2232       (let ((roots (filter stem-is-root? stems)))
2233         (for-each (make-stem-span! stems trans) roots))))
2234
2235 (define-public (Span_stem_engraver ctx)
2236   "Connect cross-staff stems to the stems above in the system"
2237   (let ((stems '()))
2238     (make-engraver
2239      ;; Record all stems for the given moment
2240      (acknowledgers
2241       ((stem-interface trans grob source)
2242        (set! stems (cons grob stems))))
2243      ;; Process stems and reset the stem list to empty
2244      ((process-acknowledged trans)
2245       (make-stem-spans! ctx stems trans)
2246       (set! stems '())))))
2247
2248 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2249 ;; The following is used by the alterBroken function.
2250
2251 (define ((value-for-spanner-piece arg) grob)
2252   "Associate a piece of broken spanner @var{grob} with an element
2253 of list @var{arg}."
2254   (let* ((orig (ly:grob-original grob))
2255          (siblings (ly:spanner-broken-into orig)))
2256
2257     (define (helper sibs arg)
2258       (if (null? arg)
2259           arg
2260           (if (eq? (car sibs) grob)
2261               (car arg)
2262               (helper (cdr sibs) (cdr arg)))))
2263
2264     (if (>= (length siblings) 2)
2265         (helper siblings arg)
2266         (car arg))))
2267 (export value-for-spanner-piece)
2268
2269 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2270 ;; The following are used by the \offset function
2271
2272 (define (find-value-to-offset prop self alist)
2273   "Return the first value of the property @var{prop} in the property
2274 alist @var{alist} -- after having found @var{self}.  If @var{self} is
2275 not found, return the first value of @var{prop}."
2276   (let ((segment (member (cons prop self) alist)))
2277     (if (not segment)
2278         (assoc-get prop alist)
2279         (assoc-get prop (cdr segment)))))
2280
2281 (define (offset-multiple-types arg offsets)
2282   "Displace @var{arg} by @var{offsets} if @var{arg} is a number, a
2283 number pair, or a list of number pairs.  If @var{offsets} is an empty
2284 list or if there is a type-mismatch, @var{arg} will be returned."
2285   (cond
2286     ((and (number? arg) (number? offsets))
2287      (+ arg offsets))
2288     ((and (number-pair? arg)
2289           (or (number? offsets)
2290               (number-pair? offsets)))
2291      (coord-translate arg offsets))
2292     ((and (number-pair-list? arg) (number-pair-list? offsets))
2293      (map
2294        (lambda (x y) (coord-translate x y))
2295        arg offsets))
2296     (else arg)))
2297
2298 (define-public (offsetter property offsets)
2299   "Apply @var{offsets} to the default values of @var{property} of @var{grob}.
2300 Offsets are restricted to immutable properties and values of type @code{number},
2301 @code{number-pair}, or @code{number-pair-list}."
2302   (define (self grob)
2303     (let* ((immutable (ly:grob-basic-properties grob))
2304            ; We need to search the basic-properties alist for our property to
2305            ; obtain values to offset.  Our search is complicated by the fact that
2306            ; calling the music function `offset' as an override conses a pair to
2307            ; the head of the alist.  This pair must be discounted.  The closure it
2308            ; contains is named `self' so it can be easily recognized.  If `offset'
2309            ; is called as a tweak, the basic-property alist is unaffected.
2310            (target (find-value-to-offset property self immutable))
2311            ; if target is a procedure, we need to apply it to our grob to calculate
2312            ; values to offset.
2313            (vals
2314              (if (procedure? target)
2315                  (target grob)
2316                  target))
2317            (can-type-be-offset?
2318              (or (number? vals)
2319                  (number-pair? vals)
2320                  (number-pair-list? vals))))
2321
2322       (if can-type-be-offset?
2323           ; '(+inf.0 . -inf.0) would offset to itself.  This will be confusing to a
2324           ; user unaware of the default value of the property, so issue a warning.
2325           (if (equal? empty-interval vals)
2326               (ly:warning "default '~a of ~a is ~a and can't be offset"
2327                 property grob vals)
2328               (let* ((orig (ly:grob-original grob))
2329                      (siblings
2330                        (if (ly:spanner? grob)
2331                            (ly:spanner-broken-into orig)
2332                            '()))
2333                      (total-found (length siblings))
2334                      ; Since there is some flexibility in input syntax,
2335                      ; structure of `offsets' is normalized.
2336                      (offsets
2337                        (if (or (not (pair? offsets))
2338                                (number-pair? offsets)
2339                                (and (number-pair-list? offsets)
2340                                     (number-pair-list? vals)))
2341                            (list offsets)
2342                            offsets)))
2343
2344                 (define (helper sibs offs)
2345                   ; apply offsets to the siblings of broken spanners
2346                   (if (pair? offs)
2347                       (if (eq? (car sibs) grob)
2348                           (offset-multiple-types vals (car offs))
2349                           (helper (cdr sibs) (cdr offs)))
2350                       vals))
2351
2352                 (if (>= total-found 2)
2353                     (helper siblings offsets)
2354                     (offset-multiple-types vals (car offsets)))))
2355
2356               (begin
2357                 (ly:warning "the property '~a of ~a cannot be offset" property grob)
2358                 vals))))
2359     ; return the closure named `self'
2360     self)
2361
2362
2363 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2364 ;; \magnifyMusic and \magnifyStaff
2365
2366 ;; defined as a function instead of a list because the
2367 ;; all-grob-descriptions alist is not available yet
2368 (define-public (find-named-props prop-name grob-descriptions)
2369   "Used by @code{\\magnifyMusic} and @code{\\magnifyStaff}.  When
2370 @var{grob-descriptions} is equal to the @code{all-grob-descriptions}
2371 alist (defined in @file{scm/define-grobs.scm}), this will find all grobs
2372 that can have a value for the @var{prop-name} property, and return them
2373 as a list in the following format:
2374 @example
2375 '((grob prop-name)
2376   (grob prop-name)
2377   ...)
2378 @end example"
2379   (define (find-grobs-with-interface interface grob-descriptions)
2380     (define (has-this-interface? grob-desc)
2381       (let* ((meta (ly:assoc-get 'meta (cdr grob-desc)))
2382              (interfaces (ly:assoc-get 'interfaces meta '())))
2383         (memq interface interfaces)))
2384     (let* ((grob-descriptions-with-this-interface
2385              (filter has-this-interface? grob-descriptions))
2386            (grob-names-with-this-interface
2387              (map car grob-descriptions-with-this-interface)))
2388       grob-names-with-this-interface))
2389   (let* ((interface
2390            (case prop-name
2391              ((baseline-skip word-space) 'text-interface)
2392              ((space-alist)              'break-aligned-interface)
2393              (else (ly:programming-error
2394                      "find-named-props: no interface associated with ~s"
2395                      prop-name))))
2396          (grobs-with-this-prop
2397            (find-grobs-with-interface interface grob-descriptions)))
2398     (map (lambda (x) (list x prop-name))
2399          grobs-with-this-prop)))
2400
2401
2402 (define (magnifyStaff-is-set? context mag)
2403   (let* ((Staff (ly:context-find context 'Staff))
2404          (old-mag (ly:context-property Staff 'magnifyStaffValue)))
2405     (not (null? old-mag))))
2406
2407 (define (staff-magnification-is-changing? context mag)
2408   (let* ((Staff (ly:context-find context 'Staff))
2409          (old-mag (ly:context-property Staff 'magnifyStaffValue 1)))
2410     (not (= old-mag mag))))
2411
2412 (define-public (scale-fontSize func-name mag)
2413   "Used by @code{\\magnifyMusic} and @code{\\magnifyStaff}.  Look up the
2414 current @code{fontSize} in the appropriate context and scale it by the
2415 magnification factor @var{mag}.  @var{func-name} is either
2416 @code{'magnifyMusic} or @code{'magnifyStaff}."
2417   (make-apply-context
2418     (lambda (context)
2419       (if (or (eq? func-name 'magnifyMusic)
2420               ;; for \magnifyStaff, only scale the fontSize
2421               ;; if staff magnification is changing
2422               ;; and does not equal 1
2423               (and (staff-magnification-is-changing? context mag)
2424                    (not (= mag 1))))
2425         (let* ((where (case func-name
2426                         ((magnifyMusic) context)
2427                         ((magnifyStaff) (ly:context-find context 'Staff))))
2428                (fontSize (ly:context-property where 'fontSize 0))
2429                (new-fontSize (+ fontSize (magnification->font-size mag))))
2430           (ly:context-set-property! where 'fontSize new-fontSize))))))
2431
2432 (define-public (revert-fontSize func-name mag)
2433   "Used by @code{\\magnifyMusic} and @code{\\magnifyStaff}.  Calculate
2434 the previous @code{fontSize} value (before scaling) by factoring out the
2435 magnification factor @var{mag} (if @var{func-name} is
2436 @code{'magnifyMusic}), or by factoring out the context property
2437 @code{magnifyStaffValue} (if @var{func-name} is @code{'magnifyStaff}).
2438 Revert the @code{fontSize} in the appropriate context accordingly.
2439
2440 With @code{\\magnifyMusic}, the scaling is reverted after the music
2441 block it operates on.  @code{\\magnifyStaff} does not operate on a music
2442 block, so the scaling from a previous call (if there is one) is reverted
2443 before the new scaling takes effect."
2444   (make-apply-context
2445     (lambda (context)
2446       (if (or (eq? func-name 'magnifyMusic)
2447               ;; for \magnifyStaff...
2448               (and
2449                 ;; don't revert the user's fontSize choice
2450                 ;; the first time \magnifyStaff is called
2451                 (magnifyStaff-is-set? context mag)
2452                 ;; only revert the previous fontSize
2453                 ;; if staff magnification is changing
2454                 (staff-magnification-is-changing? context mag)))
2455         (let* ((where
2456                  (case func-name
2457                    ((magnifyMusic) context)
2458                    ((magnifyStaff) (ly:context-find context 'Staff))))
2459                (old-mag
2460                  (case func-name
2461                    ((magnifyMusic) mag)
2462                    ((magnifyStaff)
2463                     (ly:context-property where 'magnifyStaffValue 1))))
2464                (fontSize (ly:context-property where 'fontSize 0))
2465                (old-fontSize (- fontSize (magnification->font-size old-mag))))
2466           (ly:context-set-property! where 'fontSize old-fontSize))))))
2467
2468 (define-public (scale-props func-name mag allowed-to-shrink? props)
2469   "Used by @code{\\magnifyMusic} and @code{\\magnifyStaff}.  For each
2470 prop in @var{props}, find the current value of the requested prop, scale
2471 it by the magnification factor @var{mag}, and do the equivalent of a
2472 @code{\\temporary@tie{}\\override} with the new value in the appropriate
2473 context.  If @var{allowed-to-shrink?} is @code{#f}, don't let the new
2474 value be less than the current value.  @var{func-name} is either
2475 @code{'magnifyMusic} or @code{'magnifyStaff}.  The @var{props} list is
2476 formatted like:
2477 @example
2478 '((Stem thickness)
2479   (Slur line-thickness)
2480   ...)
2481 @end example"
2482   (make-apply-context
2483     (lambda (context)
2484       (define (scale-prop grob-prop-list)
2485         (let* ((grob (car grob-prop-list))
2486                (prop (cadr grob-prop-list))
2487                (where (if (eq? grob 'SpacingSpanner)
2488                         (ly:context-find context 'Score)
2489                         (case func-name
2490                           ((magnifyMusic) context)
2491                           ((magnifyStaff) (ly:context-find context 'Staff)))))
2492                (grob-def (ly:context-grob-definition where grob)))
2493           (if (eq? prop 'space-alist)
2494             (let* ((space-alist (ly:assoc-get prop grob-def))
2495                    (scale-spacing-tuple (lambda (x)
2496                                           (cons (car x)
2497                                                 (cons (cadr x)
2498                                                       (* mag (cddr x))))))
2499                    (scaled-tuples (if space-alist
2500                                       (map scale-spacing-tuple space-alist)
2501                                       '()))
2502                    (new-alist (append scaled-tuples space-alist)))
2503               (ly:context-pushpop-property where grob prop new-alist))
2504             (let* ((val (ly:assoc-get prop grob-def (case prop
2505                                                       ((baseline-skip) 3)
2506                                                       ((word-space)    0.6)
2507                                                       (else            1))))
2508                    (proc (lambda (x)
2509                            (if allowed-to-shrink?
2510                              (* x mag)
2511                              (* x (max 1 mag)))))
2512                    (new-val (if (number-pair? val)
2513                               (cons (proc (car val))
2514                                     (proc (cdr val)))
2515                               (proc val))))
2516               (ly:context-pushpop-property where grob prop new-val)))))
2517       (if (or (eq? func-name 'magnifyMusic)
2518               ;; for \magnifyStaff, only scale the properties
2519               ;; if staff magnification is changing
2520               ;; and does not equal 1
2521               (and (staff-magnification-is-changing? context mag)
2522                    (not (= mag 1))))
2523         (for-each scale-prop props)))))
2524
2525 (define-public (revert-props func-name mag props)
2526   "Used by @code{\\magnifyMusic} and @code{\\magnifyStaff}.  Revert each
2527 prop in @var{props} in the appropriate context.  @var{func-name} is
2528 either @code{'magnifyMusic} or @code{'magnifyStaff}.  The @var{props}
2529 list is formatted like:
2530 @example
2531 '((Stem thickness)
2532   (Slur line-thickness)
2533   ...)
2534 @end example"
2535   (make-apply-context
2536     (lambda (context)
2537       (define (revert-prop grob-prop-list)
2538         (let* ((grob (car grob-prop-list))
2539                (prop (cadr grob-prop-list))
2540                (where (if (eq? grob 'SpacingSpanner)
2541                         (ly:context-find context 'Score)
2542                         (case func-name
2543                           ((magnifyMusic) context)
2544                           ((magnifyStaff) (ly:context-find context 'Staff))))))
2545           (ly:context-pushpop-property where grob prop)))
2546       (if (or (eq? func-name 'magnifyMusic)
2547               ;; for \magnifyStaff...
2548               (and
2549                 ;; don't revert the user's property overrides
2550                 ;; the first time \magnifyStaff is called
2551                 (magnifyStaff-is-set? context mag)
2552                 ;; revert the overrides from the previous \magnifyStaff,
2553                 ;; but only if staff magnification is changing
2554                 (staff-magnification-is-changing? context mag)))
2555         (for-each revert-prop props)))))
2556
2557 ;; \magnifyMusic only
2558 (define-public (scale-beam-thickness mag)
2559   "Used by @code{\\magnifyMusic}.  Scaling @code{Beam.beam-thickness}
2560 exactly to the @var{mag} value will not work.  This uses two reference
2561 values for @code{beam-thickness} to determine an acceptable value when
2562 scaling, then does the equivalent of a
2563 @code{\\temporary@tie{}\\override} with the new value."
2564   (make-apply-context
2565     (lambda (context)
2566       (let* ((grob-def (ly:context-grob-definition context 'Beam))
2567              (val (ly:assoc-get 'beam-thickness grob-def 0.48))
2568              (ratio-to-default (/ val 0.48))
2569              ;; gives beam-thickness=0.48 when mag=1 (like default),
2570              ;; gives beam-thickness=0.35 when mag=0.63 (like CueVoice)
2571              (scaled-default (+ 119/925 (* mag 13/37)))
2572              (new-val (* scaled-default ratio-to-default)))
2573         (ly:context-pushpop-property context 'Beam 'beam-thickness new-val)))))
2574
2575 ;; tag management
2576 ;;
2577
2578 (define tag-groups (make-hash-table))
2579 (call-after-session (lambda () (hash-clear! tag-groups)))
2580
2581 (define-public (define-tag-group tags)
2582   "Define a tag-group consisting of the given @var{tags}, a@tie{}list
2583 of symbols.  Returns @code{#f} if successful, and an error message if
2584 there is a conflicting tag group definition."
2585   (cond ((not (symbol-list? tags)) (format #f (_ "not a symbol list: ~a") tags))
2586         ((any (lambda (tag) (hashq-ref tag-groups tag)) tags)
2587          => (lambda (group) (and (not (lset= eq? group tags))
2588                                  (format #f (_ "conflicting tag group ~a") group))))
2589         (else
2590          (for-each
2591           (lambda (elt) (hashq-set! tag-groups elt tags))
2592           tags)
2593          #f)))
2594
2595 (define-public (tag-group-get tag)
2596   "Return the tag group (as a list of symbols) that the given
2597 @var{tag} symbol belongs to, @code{#f} if none."
2598   (hashq-ref tag-groups tag))
2599
2600 (define-public (tags-remove-predicate tags)
2601   "Returns a predicate that returns @code{#f} for any music that is to
2602 be removed by @{\\removeWithTag} on the given symbol or list of
2603 symbols @var{tags}."
2604   (if (symbol? tags)
2605       (lambda (m)
2606         (not (memq tags (ly:music-property m 'tags))))
2607       (lambda (m)
2608         (not (any (lambda (t) (memq t tags))
2609                   (ly:music-property m 'tags))))))
2610
2611 (define-public (tags-keep-predicate tags)
2612   "Returns a predicate that returns @code{#f} for any music that is to
2613 be removed by @{\\keepWithTag} on the given symbol or list of symbols
2614 @var{tags}."
2615   (if (symbol? tags)
2616       (let ((group (tag-group-get tags)))
2617         (lambda (m)
2618           (let ((music-tags (ly:music-property m 'tags)))
2619             (or
2620              (null? music-tags) ; redundant but very frequent
2621              ;; We know of only one tag to keep.  Either we find it in
2622              ;; the music tags, or all music tags must be from a
2623              ;; different group
2624              (memq tags music-tags)
2625              (not (any (lambda (t) (eq? (tag-group-get t) group)) music-tags))))))
2626       (let ((groups (delete-duplicates (map tag-group-get tags) eq?)))
2627         (lambda (m)
2628           (let ((music-tags (ly:music-property m 'tags)))
2629             (or
2630              (null? music-tags) ; redundant but very frequent
2631              (any (lambda (t) (memq t tags)) music-tags)
2632              ;; if no tag matches, no tag group should match either
2633              (not (any (lambda (t) (memq (tag-group-get t) groups)) music-tags))))))))