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