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