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