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