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