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