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