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