]> git.donarmstrong.com Git - lilypond.git/blob - scm/music-functions.scm
New upstream version 2.19.80
[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:music-error music msg . rest)
1091   (ly:parser-error (apply format #f msg rest)
1092                    (ly:music-property music 'origin)))
1093
1094 (define-public (ly:event-warning event msg . rest)
1095   (let ((ip (ly:event-property event 'origin)))
1096     (if (ly:input-location? ip)
1097         (apply ly:input-warning ip msg rest)
1098         (apply ly:warning msg rest))))
1099
1100 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1101 ;;
1102 ;; setting stuff for grace context.
1103 ;;
1104
1105 (define (vector-extend v x)
1106   "Make a new vector consisting of V, with X added to the end."
1107   (let* ((n (vector-length v))
1108          (nv (make-vector (+ n 1) '())))
1109     (vector-move-left! v 0 n nv 0)
1110     (vector-set! nv n x)
1111     nv))
1112
1113 (define (vector-map f v)
1114   "Map F over V.  This function returns nothing."
1115   (do ((n (vector-length v))
1116        (i 0 (+ i 1)))
1117       ((>= i n))
1118     (f (vector-ref v i))))
1119
1120 (define (vector-reverse-map f v)
1121   "Map F over V, N to 0 order.  This function returns nothing."
1122   (do ((i (- (vector-length v) 1) (- i 1)))
1123       ((< i 0))
1124     (f (vector-ref v i))))
1125
1126 (define-public (add-grace-property context-name grob sym val)
1127   "Set @var{sym}=@var{val} for @var{grob} in @var{context-name}."
1128   (define (set-prop context)
1129     (let* ((where (or (ly:context-find context context-name) context))
1130            (current (ly:context-property where 'graceSettings))
1131            (new-settings (append current
1132                                  (list (list context-name grob sym val)))))
1133       (ly:context-set-property! where 'graceSettings new-settings)))
1134   (make-apply-context set-prop))
1135
1136 (define-public (remove-grace-property context-name grob sym)
1137   "Remove all @var{sym} for @var{grob} in @var{context-name}."
1138   (define (sym-grob-context? property sym grob context-name)
1139     (and (eq? (car property) context-name)
1140          (eq? (cadr property) grob)
1141          (eq? (caddr property) sym)))
1142   (define (delete-prop context)
1143     (let* ((where (or (ly:context-find context context-name) context))
1144            (current (ly:context-property where 'graceSettings))
1145            (prop-settings (filter
1146                            (lambda(x) (sym-grob-context? x sym grob context-name))
1147                            current))
1148            (new-settings current))
1149       (for-each (lambda(x)
1150                   (set! new-settings (delete x new-settings)))
1151                 prop-settings)
1152       (ly:context-set-property! where 'graceSettings new-settings)))
1153   (make-apply-context delete-prop))
1154
1155
1156 (defmacro-public def-grace-function (start stop . docstring)
1157   "Helper macro for defining grace music"
1158   `(define-music-function (music) (ly:music?)
1159      ,@docstring
1160      (make-music 'GraceMusic
1161                  'element (make-music 'SequentialMusic
1162                                       'elements (list (ly:music-deep-copy ,start)
1163                                                       music
1164                                                       (ly:music-deep-copy ,stop))))))
1165
1166 (defmacro-public define-syntax-function (type args signature . body)
1167   "Helper macro for `ly:make-music-function'.
1168 Syntax:
1169   (define-syntax-function result-type? (arg1 arg2 ...) (arg1-type arg2-type ...)
1170     ...function body...)
1171
1172 argX-type can take one of the forms @code{predicate?} for mandatory
1173 arguments satisfying the predicate, @code{(predicate?)} for optional
1174 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
1175 value)}} for optional parameters with a specified default
1176 value (evaluated at definition time).  An optional parameter can be
1177 omitted in a call only when it can't get confused with a following
1178 parameter of different type.
1179
1180 @code{result-type?} can specify a default in the same manner as
1181 predicates, to be used in case of a type error in arguments or
1182 result."
1183
1184   (define (has-parser/location? arg where)
1185     (let loop ((arg arg))
1186       (if (list? arg)
1187           (any loop arg)
1188           (memq arg where))))
1189   (define (currying-lambda args doc-string? body)
1190     (if (and (pair? args)
1191              (pair? (car args)))
1192         (currying-lambda (car args) doc-string?
1193                          `((lambda ,(cdr args) ,@body)))
1194         (let* ((compatibility? (if (list? args)
1195                                    (= (length args) (+ 2 (length signature)))
1196                                    (and (pair? args) (pair? (cdr args))
1197                                         (eq? (car args) 'parser))))
1198                (realargs (if compatibility? (cddr args) args)))
1199           `(lambda ,realargs
1200              ,(format #f "~a\n~a" realargs (or doc-string? ""))
1201              ,@(if (and compatibility?
1202                         (has-parser/location? body (take args 2)))
1203                    `((let ((,(car args) (*parser*)) (,(cadr args) (*location*)))
1204                        ,@body))
1205                    body)))))
1206
1207   (let ((docstring
1208          (and (pair? body) (pair? (cdr body))
1209               (if (string? (car body))
1210                   (car body)
1211                   (and (pair? (car body))
1212                        (eq? '_i (caar body))
1213                        (pair? (cdar body))
1214                        (string? (cadar body))
1215                        (null? (cddar body))
1216                        (cadar body))))))
1217     ;; When the music function definition contains an i10n doc string,
1218     ;; (_i "doc string"), keep the literal string only
1219     `(ly:make-music-function
1220       (list ,@(map (lambda (pred)
1221                      (if (pair? pred)
1222                          `(cons ,(car pred)
1223                                 ,(and (pair? (cdr pred)) (cadr pred)))
1224                          pred))
1225                    (cons type signature)))
1226       ,(currying-lambda args docstring (if docstring (cdr body) body)))))
1227
1228 (defmacro-public define-music-function rest
1229   "Defining macro returning music functions.
1230 Syntax:
1231   (define-music-function (arg1 arg2 ...) (arg1-type? arg2-type? ...)
1232     ...function body...)
1233
1234 argX-type can take one of the forms @code{predicate?} for mandatory
1235 arguments satisfying the predicate, @code{(predicate?)} for optional
1236 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
1237 value)}} for optional parameters with a specified default
1238 value (evaluated at definition time).  An optional parameter can be
1239 omitted in a call only when it can't get confused with a following
1240 parameter of different type.
1241
1242 Must return a music expression.  The @code{origin} is automatically
1243 set to the @code{location} parameter."
1244
1245   `(define-syntax-function (ly:music? (make-music 'Music 'void #t)) ,@rest))
1246
1247
1248 (defmacro-public define-scheme-function rest
1249   "Defining macro returning Scheme functions.
1250 Syntax:
1251   (define-scheme-function (arg1 arg2 ...) (arg1-type? arg2-type? ...)
1252     ...function body...)
1253
1254 argX-type can take one of the forms @code{predicate?} for mandatory
1255 arguments satisfying the predicate, @code{(predicate?)} for optional
1256 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
1257 value)}} for optional parameters with a specified default
1258 value (evaluated at definition time).  An optional parameter can be
1259 omitted in a call only when it can't get confused with a following
1260 parameter of different type.
1261
1262 Can return arbitrary expressions.  If a music expression is returned,
1263 its @code{origin} is automatically set to the @code{location}
1264 parameter."
1265
1266   `(define-syntax-function scheme? ,@rest))
1267
1268 (defmacro-public define-void-function rest
1269   "This defines a Scheme function like @code{define-scheme-function} with
1270 void return value (i.e., what most Guile functions with `unspecified'
1271 value return).  Use this when defining functions for executing actions
1272 rather than returning values, to keep Lilypond from trying to interpret
1273 the return value."
1274   `(define-syntax-function (void? *unspecified*) ,@rest *unspecified*))
1275
1276 (defmacro-public define-event-function rest
1277   "Defining macro returning event functions.
1278 Syntax:
1279   (define-event-function (arg1 arg2 ...) (arg1-type? arg2-type? ...)
1280     ...function body...)
1281
1282 argX-type can take one of the forms @code{predicate?} for mandatory
1283 arguments satisfying the predicate, @code{(predicate?)} for optional
1284 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
1285 value)}} for optional parameters with a specified default
1286 value (evaluated at definition time).  An optional parameter can be
1287 omitted in a call only when it can't get confused with a following
1288 parameter of different type.
1289
1290 Must return an event expression.  The @code{origin} is automatically
1291 set to the @code{location} parameter."
1292
1293   `(define-syntax-function (ly:event? (make-music 'Event 'void #t)) ,@rest))
1294
1295 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1296
1297 (define-public (cue-substitute quote-music)
1298   "Must happen after @code{quote-substitute}."
1299
1300   (if (vector? (ly:music-property quote-music 'quoted-events))
1301       (let* ((dir (ly:music-property quote-music 'quoted-voice-direction))
1302              (clef (ly:music-property quote-music 'quoted-music-clef #f))
1303              (main-voice (case dir ((1) 1) ((-1) 0) (else #f)))
1304              (cue-voice (and main-voice (- 1 main-voice)))
1305              (cue-type (ly:music-property quote-music 'quoted-context-type #f))
1306              (cue-id (ly:music-property quote-music 'quoted-context-id))
1307              (main-music (ly:music-property quote-music 'element))
1308              (return-value quote-music))
1309
1310         (if main-voice
1311             (set! (ly:music-property quote-music 'element)
1312                   (make-sequential-music
1313                    (list
1314                     (make-voice-props-override main-voice)
1315                     main-music
1316                     (make-voice-props-revert)))))
1317
1318         ;; if we have stem dirs, change both quoted and main music
1319         ;; to have opposite stems.
1320
1321         ;; cannot context-spec Quote-music, since context
1322         ;; for the quotes is determined in the iterator.
1323
1324         (make-sequential-music
1325          (delq! #f
1326                 (list
1327                  (and clef (make-cue-clef-set clef))
1328                  (and cue-type cue-voice
1329                       (context-spec-music
1330                        (make-voice-props-override cue-voice)
1331                        cue-type cue-id))
1332                  quote-music
1333                  (and cue-type cue-voice
1334                       (context-spec-music
1335                        (make-voice-props-revert)
1336                        cue-type cue-id))
1337                  (and clef (make-cue-clef-unset))))))
1338       quote-music))
1339
1340 (define ((quote-substitute quote-tab) music)
1341   (let* ((quoted-name (ly:music-property music 'quoted-music-name))
1342          (quoted-vector (and (string? quoted-name)
1343                              (hash-ref quote-tab quoted-name #f))))
1344
1345
1346     (if (string? quoted-name)
1347         (if (vector? quoted-vector)
1348             (begin
1349               (set! (ly:music-property music 'quoted-events) quoted-vector)
1350               (set! (ly:music-property music 'iterator-ctor)
1351                     ly:quote-iterator::constructor))
1352             (ly:music-warning music (ly:format (_ "cannot find quoted music: `~S'") quoted-name))))
1353     music))
1354 (export quote-substitute)
1355
1356
1357 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1358 ;; switch it on here, so parsing and init isn't checked (too slow!)
1359 ;;
1360 ;; automatic music transformations.
1361
1362 (define (switch-on-debugging m)
1363   (if (defined? 'set-debug-cell-accesses!)
1364       (set-debug-cell-accesses! 15000))
1365   m)
1366
1367 (define (music-check-error music)
1368   (define found #f)
1369   (define (signal m)
1370     (if (and (ly:music? m)
1371              (eq? (ly:music-property m 'error-found) #t))
1372         (set! found #t)))
1373
1374   (for-each signal (ly:music-property music 'elements))
1375   (signal (ly:music-property music 'element))
1376
1377   (if found
1378       (set! (ly:music-property music 'error-found) #t))
1379   music)
1380
1381 (define (precompute-music-length music)
1382   (set! (ly:music-property music 'length)
1383         (ly:music-length music))
1384   music)
1385
1386 (define-public (make-duration-of-length moment)
1387   "Make duration of the given @code{moment} length."
1388   (ly:make-duration 0 0
1389                     (ly:moment-main-numerator moment)
1390                     (ly:moment-main-denominator moment)))
1391
1392 (define (make-skipped moment bool)
1393   "Depending on BOOL, set or unset skipTypesetting,
1394 then make SkipMusic of the given MOMENT length, and
1395 then revert skipTypesetting."
1396   (make-sequential-music
1397    (list
1398     (context-spec-music (make-property-set 'skipTypesetting bool)
1399                         'Score)
1400     (make-music 'SkipMusic 'duration
1401                 (make-duration-of-length moment))
1402     (context-spec-music (make-property-set 'skipTypesetting (not bool))
1403                         'Score))))
1404
1405 (define (skip-as-needed music)
1406   "Replace MUSIC by
1407  << {  \\set skipTypesetting = ##f
1408  LENGTHOF(\\showFirstLength)
1409  \\set skipTypesetting = ##t
1410  LENGTHOF(\\showLastLength) }
1411  MUSIC >>
1412  if appropriate.
1413
1414  When only showFirstLength is set,
1415  the 'length property of the music is
1416  overridden to speed up compiling."
1417   (let*
1418       ((show-last (ly:parser-lookup 'showLastLength))
1419        (show-first (ly:parser-lookup 'showFirstLength))
1420        (show-last-length (and (ly:music? show-last)
1421                               (ly:music-length show-last)))
1422        (show-first-length (and (ly:music? show-first)
1423                                (ly:music-length show-first)))
1424        (orig-length (ly:music-length music)))
1425
1426     ;;FIXME: if using either showFirst- or showLastLength,
1427     ;; make sure that skipBars is not set.
1428
1429     (cond
1430
1431      ;; both properties may be set.
1432      ((and show-first-length show-last-length)
1433       (let
1434           ((skip-length (ly:moment-sub orig-length show-last-length)))
1435         (make-simultaneous-music
1436          (list
1437           (make-sequential-music
1438            (list
1439             (make-skipped skip-length #t)
1440             ;; let's draw a separator between the beginning and the end
1441             (context-spec-music (make-property-set 'whichBar "||")
1442                                 'Timing)))
1443           (make-skipped show-first-length #f)
1444           music))))
1445
1446      ;; we may only want to print the last length
1447      (show-last-length
1448       (let
1449           ((skip-length (ly:moment-sub orig-length show-last-length)))
1450         (make-simultaneous-music
1451          (list
1452           (make-skipped skip-length #t)
1453           music))))
1454
1455      ;; we may only want to print the beginning; in this case
1456      ;; only the first length will be processed (much faster).
1457      (show-first-length
1458       ;; the first length must not exceed the original length.
1459       (if (ly:moment<? show-first-length orig-length)
1460           (set! (ly:music-property music 'length)
1461                 show-first-length))
1462       music)
1463
1464      (else music))))
1465
1466
1467 (define-session-public toplevel-music-functions
1468   (list
1469    (lambda (music) (expand-repeat-chords!
1470                     (cons 'rhythmic-event
1471                           (ly:parser-lookup '$chord-repeat-events))
1472                     music))
1473    expand-repeat-notes!
1474    voicify-music
1475    (lambda (x) (music-map music-check-error x))
1476    (lambda (x) (music-map precompute-music-length x))
1477    (lambda (music)
1478      (music-map (quote-substitute (ly:parser-lookup 'musicQuotes))  music))
1479
1480    ;; switch-on-debugging
1481    (lambda (x) (music-map cue-substitute x))
1482
1483    skip-as-needed))
1484
1485 ;;;;;;;;;;
1486 ;;; general purpose music functions
1487
1488 (define (shift-octave pitch octave-shift)
1489   (_i "Add @var{octave-shift} to the octave of @var{pitch}.")
1490   (ly:make-pitch
1491    (+ (ly:pitch-octave pitch) octave-shift)
1492    (ly:pitch-notename pitch)
1493    (ly:pitch-alteration pitch)))
1494
1495
1496 ;;;;;;;;;;;;;;;;;
1497 ;; lyrics
1498
1499 (define (apply-durations lyric-music durations)
1500   (define (apply-duration music)
1501     (if (and (not (equal? (ly:music-length music) ZERO-MOMENT))
1502              (ly:duration?  (ly:music-property music 'duration)))
1503         (begin
1504           (set! (ly:music-property music 'duration) (car durations))
1505           (set! durations (cdr durations)))))
1506
1507   (music-map apply-duration lyric-music))
1508
1509
1510 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1511 ;; accidentals
1512
1513 (define (recent-enough? bar-number alteration-def laziness)
1514   (or (number? alteration-def)
1515       (equal? laziness #t)
1516       (<= bar-number (+ (cadr alteration-def) laziness))))
1517
1518 (define (accidental-invalid? alteration-def)
1519   "Checks an alteration entry for being invalid.
1520
1521 Non-key alterations are invalidated when tying into the next bar or
1522 when there is a clef change, since neither repetition nor cancellation
1523 can be omitted when the same note occurs again.
1524
1525 Returns @code{#f} or the reason for the invalidation, a symbol."
1526   (let* ((def (if (pair? alteration-def)
1527                   (car alteration-def)
1528                   alteration-def)))
1529     (and (symbol? def) def)))
1530
1531 (define (extract-alteration alteration-def)
1532   (cond ((number? alteration-def)
1533          alteration-def)
1534         ((pair? alteration-def)
1535          (car alteration-def))
1536         (else 0)))
1537
1538 (define (check-pitch-against-signature context pitch barnum laziness octaveness all-naturals)
1539   "Checks the need for an accidental and a @q{restore} accidental against
1540 @code{localAlterations} and @code{keyAlterations}.
1541 The @var{laziness} is the number of measures
1542 for which reminder accidentals are used (i.e., if @var{laziness} is zero,
1543 only cancel accidentals in the same measure; if @var{laziness} is three,
1544 we cancel accidentals up to three measures after they first appear.
1545 @var{octaveness} is either @code{'same-octave} or @code{'any-octave} and
1546 specifies whether accidentals should be canceled in different octaves.
1547 If @var{all-naturals} is ##t, notes that do not occur in @code{keyAlterations}
1548 also get an accidental."
1549   (let* ((ignore-octave (cond ((equal? octaveness 'any-octave) #t)
1550                               ((equal? octaveness 'same-octave) #f)
1551                               (else
1552                                (ly:warning (_ "Unknown octaveness type: ~S ") octaveness)
1553                                (ly:warning (_ "Defaulting to 'any-octave."))
1554                                #t)))
1555          (key (ly:context-property context 'keyAlterations))
1556          (local (ly:context-property context 'localAlterations))
1557          (notename (ly:pitch-notename pitch))
1558          (octave (ly:pitch-octave pitch))
1559          (pitch-handle (cons octave notename))
1560          (need-restore #f)
1561          (need-accidental #f)
1562          (previous-alteration #f)
1563          (from-other-octaves #f)
1564          (from-same-octave (assoc-get pitch-handle local))
1565          (from-key-sig (or (assoc-get notename local)
1566
1567                            ;; If no notename match is found from localAlterations, we may have a custom
1568                            ;; type with octave-specific entries of the form ((octave . pitch) alteration)
1569                            ;; instead of (pitch . alteration).  Since this type cannot coexist with entries in
1570                            ;; localAlterations, try extracting from keyAlterations instead.
1571                            (assoc-get pitch-handle key))))
1572
1573     ;; loop through localAlterations to search for a notename match from other octaves
1574     (let loop ((l local))
1575       (if (pair? l)
1576           (let ((entry (car l)))
1577             (if (and (pair? (car entry))
1578                      (= (cdar entry) notename))
1579                 (set! from-other-octaves (cdr entry))
1580                 (loop (cdr l))))))
1581
1582     ;; find previous alteration-def for comparison with pitch
1583     (cond
1584      ;; from same octave?
1585      ((and (not ignore-octave)
1586            from-same-octave
1587            (recent-enough? barnum from-same-octave laziness))
1588       (set! previous-alteration from-same-octave))
1589
1590      ;; from any octave?
1591      ((and ignore-octave
1592            from-other-octaves
1593            (recent-enough? barnum from-other-octaves laziness))
1594       (set! previous-alteration from-other-octaves))
1595
1596      ;; not recent enough, extract from key signature/local key signature
1597      (from-key-sig
1598       (set! previous-alteration from-key-sig)))
1599
1600     (if (accidental-invalid? previous-alteration)
1601         (set! need-accidental #t)
1602
1603         (let* ((prev-alt (extract-alteration previous-alteration))
1604                (this-alt (ly:pitch-alteration pitch)))
1605
1606           (if (or (and all-naturals (eq? #f previous-alteration)) (not (= this-alt prev-alt)))
1607               (begin
1608                 (set! need-accidental #t)
1609                 (if (and (not (= this-alt 0))
1610                          (and (< (abs this-alt) (abs prev-alt))
1611                               (> (* prev-alt this-alt) 0)))
1612                     (set! need-restore #t))))))
1613
1614     (cons need-restore need-accidental)))
1615
1616 (define ((make-accidental-rule octaveness laziness) context pitch barnum measurepos)
1617   "Create an accidental rule that makes its decision based on the octave of
1618 the note and a laziness value.
1619
1620 @var{octaveness} is either @code{'same-octave} or @code{'any-octave} and
1621 defines whether the rule should respond to accidental changes in other
1622 octaves than the current.  @code{'same-octave} is the normal way to typeset
1623 accidentals -- an accidental is made if the alteration is different from the
1624 last active pitch in the same octave.  @code{'any-octave} looks at the last
1625 active pitch in any octave.
1626
1627 @var{laziness} states over how many bars an accidental should be remembered.
1628 @code{0}@tie{}is the default -- accidental lasts over 0@tie{}bar lines, that
1629 is, to the end of current measure.  A positive integer means that the
1630 accidental lasts over that many bar lines.  @w{@code{-1}} is `forget
1631 immediately', that is, only look at key signature.  @code{#t} is `forever'."
1632
1633   (check-pitch-against-signature context pitch barnum laziness octaveness #f))
1634 (export make-accidental-rule)
1635
1636 (define ((make-accidental-dodecaphonic-rule octaveness laziness) context pitch barnum measurepos)
1637   "Variation on function make-accidental-rule that creates an dodecaphonic
1638 accidental rule."
1639
1640   (check-pitch-against-signature context pitch barnum laziness octaveness #t))
1641 (export make-accidental-dodecaphonic-rule)
1642
1643 (define (key-entry-notename entry)
1644   "Return the pitch of an @var{entry} in @code{localAlterations}.
1645 The @samp{car} of the entry is either of the form @code{notename} or
1646 of the form @code{(octave . notename)}.  The latter form is used for special
1647 key signatures or to indicate an explicit accidental.
1648
1649 The @samp{cdr} of the entry is either a rational @code{alter} indicating
1650 a key signature alteration, or of the form
1651 @code{(alter . (barnum . measurepos))} indicating an alteration caused by
1652 an accidental in music."
1653   (if (pair? (car entry))
1654       (cdar entry)
1655       (car entry)))
1656
1657 (define (key-entry-octave entry)
1658   "Return the octave of an entry in @code{localAlterations}
1659 or @code{#f} if the entry does not have an octave.
1660 See @code{key-entry-notename} for details."
1661   (and (pair? (car entry)) (caar entry)))
1662
1663 (define (key-entry-bar-number entry)
1664   "Return the bar number of an entry in @code{localAlterations}
1665 or @code {#f} if the entry does not have a bar number.
1666 See @code{key-entry-notename} for details."
1667   (and (pair? (cdr entry)) (caddr entry)))
1668
1669 (define (key-entry-measure-position entry)
1670   "Return the measure position of an entry in @code{localAlterations}
1671 or @code {#f} if the entry does not have a measure position.
1672 See @code{key-entry-notename} for details."
1673   (and (pair? (cdr entry)) (cdddr entry)))
1674
1675 (define (key-entry-alteration entry)
1676   "Return the alteration of an entry in localAlterations
1677
1678 For convenience, returns @code{0} if entry is @code{#f}."
1679   (if entry
1680       (if (number? (cdr entry))
1681           (cdr entry)
1682           (cadr entry))
1683       0))
1684
1685 (define-public (find-pitch-entry keysig pitch accept-global accept-local)
1686   "Return the first entry in @var{keysig} that matches @var{pitch}
1687 by notename and octave.  Alteration is not considered.
1688 @var{accept-global} states whether key signature entries should be included.
1689 @var{accept-local} states whether local accidentals should be included.
1690 If no matching entry is found, @var{#f} is returned."
1691   (and (pair? keysig)
1692        (let* ((entry (car keysig))
1693               (entryoct (key-entry-octave entry))
1694               (entrynn (key-entry-notename entry))
1695               (nn (ly:pitch-notename pitch)))
1696          (if (and (equal? nn entrynn)
1697                   (or (not entryoct)
1698                       (= entryoct (ly:pitch-octave pitch)))
1699                   (if (key-entry-bar-number entry)
1700                       accept-local
1701                       accept-global))
1702              entry
1703              (find-pitch-entry (cdr keysig) pitch accept-global accept-local)))))
1704
1705 (define-public (neo-modern-accidental-rule context pitch barnum measurepos)
1706   "An accidental rule that typesets an accidental if it differs from the
1707 key signature @emph{and} does not directly follow a note on the same
1708 staff line.  This rule should not be used alone because it does neither
1709 look at bar lines nor different accidentals at the same note name."
1710   (let* ((keysig (ly:context-property context 'localAlterations))
1711          (entry (find-pitch-entry keysig pitch #t #t)))
1712     (if (not entry)
1713         (cons #f #f)
1714         (let* ((global-entry (find-pitch-entry keysig pitch #t #f))
1715                (key-acc (key-entry-alteration global-entry))
1716                (acc (ly:pitch-alteration pitch))
1717                (entrymp (key-entry-measure-position entry))
1718                (entrybn (key-entry-bar-number entry)))
1719           (cons #f (not (or (equal? acc key-acc)
1720                             (and (equal? entrybn barnum) (equal? entrymp measurepos)))))))))
1721
1722 (define-public (dodecaphonic-no-repeat-rule context pitch barnum measurepos)
1723   "An accidental rule that typesets an accidental before every
1724 note (just as in the dodecaphonic accidental style) @emph{except} if
1725 the note is immediately preceded by a note with the same pitch. This
1726 is a common accidental style in contemporary notation."
1727    (let* ((keysig (ly:context-property context 'localAlterations))
1728           (entry (find-pitch-entry keysig pitch #f #t)))
1729      (if (not entry)
1730          (cons #f #t)
1731          (let ((entrymp (key-entry-measure-position entry))
1732                (entrybn (key-entry-bar-number entry))
1733                (entryalt (key-entry-alteration entry))
1734                (alt (ly:pitch-alteration pitch)))
1735            (cons #t
1736                  (not (and (equal? entrybn barnum)
1737                            (or (equal? measurepos entrymp)
1738                                (ly:moment<? measurepos entrymp))
1739                            (equal? entryalt alt))))))))
1740
1741 (define-public (teaching-accidental-rule context pitch barnum measurepos)
1742   "An accidental rule that typesets a cautionary accidental if it is
1743 included in the key signature @emph{and} does not directly follow a note
1744 on the same staff line."
1745   (let* ((keysig (ly:context-property context 'localAlterations))
1746          (entry (find-pitch-entry keysig pitch #t #t)))
1747     (if (not entry)
1748         (cons #f #f)
1749         (let* ((global-entry (find-pitch-entry keysig pitch #f #f))
1750                (key-acc (key-entry-alteration global-entry))
1751                (acc (ly:pitch-alteration pitch))
1752                (entrymp (key-entry-measure-position entry))
1753                (entrybn (key-entry-bar-number entry)))
1754           (cons #f (not (or (equal? acc key-acc)
1755                             (and (equal? entrybn barnum) (equal? entrymp measurepos)))))))))
1756
1757 (define-session-public accidental-styles
1758   ;; An alist containing specification for all accidental styles.
1759   ;; Each accidental style needs three entries for the context properties
1760   ;; extraNatural, autoAccidentals and autoCautionaries.
1761   ;; An optional fourth entry may specify a default context for the accidental
1762   ;; style, for use with the piano styles.
1763   `(
1764      ;; accidentals as they were common in the 18th century.
1765      (default #t
1766               (Staff ,(make-accidental-rule 'same-octave 0))
1767               ())
1768      ;; accidentals from one voice do NOT get canceled in other voices
1769      (voice #t
1770             (Voice ,(make-accidental-rule 'same-octave 0))
1771             ())
1772      ;; accidentals as suggested by Kurt Stone in
1773      ;; â€˜Music Notation in the 20th century’.
1774      ;; This includes all the default accidentals, but accidentals also need
1775      ;; canceling in other octaves and in the next measure.
1776      (modern #f
1777              (Staff ,(make-accidental-rule 'same-octave 0)
1778                     ,(make-accidental-rule 'any-octave 0)
1779                     ,(make-accidental-rule 'same-octave 1))
1780              ())
1781      ;; the accidentals that Stone adds to the old standard as cautionaries
1782      (modern-cautionary #f
1783                         (Staff ,(make-accidental-rule 'same-octave 0))
1784                         (Staff ,(make-accidental-rule 'any-octave 0)
1785                                ,(make-accidental-rule 'same-octave 1)))
1786      ;; same as modern, but accidentals different from the key signature are
1787      ;; always typeset - unless they directly follow a note of the same pitch.
1788      (neo-modern #f
1789                  (Staff ,(make-accidental-rule 'same-octave 0)
1790                         ,(make-accidental-rule 'any-octave 0)
1791                         ,(make-accidental-rule 'same-octave 1)
1792                         ,neo-modern-accidental-rule)
1793                  ())
1794      (neo-modern-cautionary #f
1795                             (Staff ,(make-accidental-rule 'same-octave 0))
1796                             (Staff ,(make-accidental-rule 'any-octave 0)
1797                                    ,(make-accidental-rule 'same-octave 1)
1798                                    ,neo-modern-accidental-rule))
1799      (neo-modern-voice #f
1800                        (Voice ,(make-accidental-rule 'same-octave 0)
1801                               ,(make-accidental-rule 'any-octave 0)
1802                               ,(make-accidental-rule 'same-octave 1)
1803                               ,neo-modern-accidental-rule
1804                               Staff
1805                               ,(make-accidental-rule 'same-octave 0)
1806                               ,(make-accidental-rule 'any-octave 0)
1807                               ,(make-accidental-rule 'same-octave 1)
1808                               ,neo-modern-accidental-rule)
1809                        ())
1810      (neo-modern-voice-cautionary #f
1811                                   (Voice ,(make-accidental-rule 'same-octave 0))
1812                                   (Voice ,(make-accidental-rule 'any-octave 0)
1813                                          ,(make-accidental-rule 'same-octave 1)
1814                                          ,neo-modern-accidental-rule
1815                                          Staff
1816                                          ,(make-accidental-rule 'same-octave 0)
1817                                          ,(make-accidental-rule 'any-octave 0)
1818                                          ,(make-accidental-rule 'same-octave 1)
1819                                          ,neo-modern-accidental-rule))
1820
1821      ;; Accidentals as they were common in dodecaphonic music with no tonality.
1822      ;; Each note gets one accidental.
1823      (dodecaphonic #f
1824                    (Staff ,(lambda (c p bn mp) '(#f . #t)))
1825                    ())
1826      ;; As in dodecaphonic style with the exception that immediately
1827      ;; repeated notes (in the same voice) don't get an accidental
1828      (dodecaphonic-no-repeat #f
1829                              (Staff ,dodecaphonic-no-repeat-rule)
1830                              ())
1831      ;; Variety of the dodecaphonic style. Each note gets an accidental,
1832      ;; except notes that were already handled in the same measure.
1833      (dodecaphonic-first #f
1834                          (Staff ,(make-accidental-dodecaphonic-rule 'same-octave 0))
1835                          ())
1836
1837      ;; Multivoice accidentals to be read both by musicians playing one voice
1838      ;; and musicians playing all voices. Accidentals are typeset for each
1839      ;; voice, but they ARE canceled across voices.
1840      (modern-voice #f
1841                    (Voice ,(make-accidental-rule 'same-octave 0)
1842                           ,(make-accidental-rule 'any-octave 0)
1843                           ,(make-accidental-rule 'same-octave 1)
1844                           Staff
1845                           ,(make-accidental-rule 'same-octave 0)
1846                           ,(make-accidental-rule 'any-octave 0)
1847                           ,(make-accidental-rule 'same-octave 1))
1848                    ())
1849      ;; same as modernVoiceAccidental except that all special accidentals
1850      ;; are typeset as cautionaries
1851      (modern-voice-cautionary #f
1852                               (Voice ,(make-accidental-rule 'same-octave 0))
1853                               (Voice ,(make-accidental-rule 'any-octave 0)
1854                                      ,(make-accidental-rule 'same-octave 1)
1855                                      Staff
1856                                      ,(make-accidental-rule 'same-octave 0)
1857                                      ,(make-accidental-rule 'any-octave 0)
1858                                      ,(make-accidental-rule 'same-octave 1)))
1859
1860      ;; Stone's suggestions for accidentals on grand staff.
1861      ;; Accidentals are canceled across the staves
1862      ;; in the same grand staff as well
1863      (piano #f
1864             (Staff ,(make-accidental-rule 'same-octave 0)
1865                    ,(make-accidental-rule 'any-octave 0)
1866                    ,(make-accidental-rule 'same-octave 1)
1867                    GrandStaff
1868                    ,(make-accidental-rule 'any-octave 0)
1869                    ,(make-accidental-rule 'same-octave 1))
1870             ()
1871             GrandStaff)
1872      (piano-cautionary #f
1873                        (Staff ,(make-accidental-rule 'same-octave 0))
1874                        (Staff ,(make-accidental-rule 'any-octave 0)
1875                               ,(make-accidental-rule 'same-octave 1)
1876                               GrandStaff
1877                               ,(make-accidental-rule 'any-octave 0)
1878                               ,(make-accidental-rule 'same-octave 1))
1879                        GrandStaff)
1880
1881      ;; Accidentals on a choir staff for simultaneous reading of the
1882      ;; own voice and the surrounding choir. Similar to piano, except
1883      ;; that the first alteration within a voice is always printed.
1884      (choral #f
1885              (Voice ,(make-accidental-rule 'same-octave 0)
1886                     Staff
1887                     ,(make-accidental-rule 'same-octave 1)
1888                     ,(make-accidental-rule 'any-octave 0)
1889                     ,(make-accidental-rule 'same-octave 1)
1890                     ChoirStaff
1891                     ,(make-accidental-rule 'any-octave 0)
1892                     ,(make-accidental-rule 'same-octave 1))
1893              ()
1894              ChoirStaff)
1895      (choral-cautionary #f
1896                         (Voice ,(make-accidental-rule 'same-octave 0)
1897                                Staff
1898                                ,(make-accidental-rule 'same-octave 0))
1899                         (Staff ,(make-accidental-rule 'any-octave 0)
1900                                ,(make-accidental-rule 'same-octave 1)
1901                                ChoirStaff
1902                                ,(make-accidental-rule 'any-octave 0)
1903                                ,(make-accidental-rule 'same-octave 1))
1904                         ChoirStaff)
1905
1906      ;; same as modern, but cautionary accidentals are printed for all
1907      ;; non-natural tones specified by the key signature.
1908      (teaching #f
1909                (Staff ,(make-accidental-rule 'same-octave 0))
1910                (Staff ,(make-accidental-rule 'same-octave 1)
1911                       ,teaching-accidental-rule))
1912
1913      ;; do not set localAlterations when a note alterated differently from
1914      ;; localAlterations is found.
1915      ;; Causes accidentals to be printed at every note instead of
1916      ;; remembered for the duration of a measure.
1917      ;; accidentals not being remembered, causing accidentals always to
1918      ;; be typeset relative to the time signature
1919      (forget ()
1920              (Staff ,(make-accidental-rule 'same-octave -1))
1921              ())
1922      ;; Do not reset the key at the start of a measure.  Accidentals will be
1923      ;; printed only once and are in effect until overridden, possibly many
1924      ;; measures later.
1925      (no-reset ()
1926                (Staff ,(make-accidental-rule 'same-octave #t))
1927                ())
1928      ))
1929
1930 (define-public (set-accidental-style style . rest)
1931   "Set accidental style to @var{style}.  Optionally take a context
1932 argument, e.g. @code{'Staff} or @code{'Voice}.  The context defaults
1933 to @code{Staff}, except for piano styles, which use @code{GrandStaff}
1934 as a context."
1935   (let ((spec (assoc-get style accidental-styles)))
1936     (if spec
1937         (let ((extra-natural (first spec))
1938               (auto-accs (second spec))
1939               (auto-cauts (third spec))
1940               (context (cond ((pair? rest) (car rest))
1941                              ((= 4 (length spec)) (fourth spec))
1942                              (else 'Staff))))
1943           (context-spec-music
1944            (make-sequential-music
1945             (append (if (boolean? extra-natural)
1946                         (list (make-property-set 'extraNatural extra-natural))
1947                         '())
1948                     (list (make-property-set 'autoAccidentals auto-accs)
1949                           (make-property-set 'autoCautionaries auto-cauts))))
1950            context))
1951         (begin
1952          (ly:warning (_ "unknown accidental style: ~S") style)
1953          (make-sequential-music '())))))
1954
1955 (define-public (invalidate-alterations context)
1956   "Invalidate alterations in @var{context}.
1957
1958 Elements of @code{'localAlterations} corresponding to local
1959 alterations of the key signature have the form
1960 @code{'((octave . notename) . (alter barnum . measurepos))}.
1961 Replace them with a version where @code{alter} is set to @code{'clef}
1962 to force a repetition of accidentals.
1963
1964 Entries that conform with the current key signature are not invalidated."
1965   (let* ((keysig (ly:context-property context 'keyAlterations)))
1966     (set! (ly:context-property context 'localAlterations)
1967           (map-in-order
1968            (lambda (entry)
1969              (let* ((localalt (key-entry-alteration entry)))
1970                (if (or (accidental-invalid? localalt)
1971                        (not (key-entry-bar-number entry))
1972                        (= localalt
1973                           (key-entry-alteration
1974                            (find-pitch-entry
1975                             keysig
1976                             (ly:make-pitch (key-entry-octave entry)
1977                                            (key-entry-notename entry)
1978                                            0)
1979                             #t #t))))
1980                    entry
1981                    (cons (car entry) (cons 'clef (cddr entry))))))
1982            (ly:context-property context 'localAlterations)))))
1983
1984 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1985
1986 (define-public (skip-of-length mus)
1987   "Create a skip of exactly the same length as @var{mus}."
1988   (let* ((skip
1989           (make-music
1990            'SkipEvent
1991            'duration (ly:make-duration 0 0))))
1992
1993     (make-event-chord (list (ly:music-compress skip (ly:music-length mus))))))
1994
1995 (define-public (mmrest-of-length mus)
1996   "Create a multi-measure rest of exactly the same length as @var{mus}."
1997
1998   (let* ((skip
1999           (make-multi-measure-rest
2000            (ly:make-duration 0 0) '())))
2001     (ly:music-compress skip (ly:music-length mus))
2002     skip))
2003
2004 (define-public (pitch-of-note event-chord)
2005   (let ((evs (filter (lambda (x)
2006                        (music-is-of-type? x 'note-event))
2007                      (ly:music-property event-chord 'elements))))
2008
2009     (and (pair? evs)
2010          (ly:music-property (car evs) 'pitch))))
2011
2012 (define-public (duration-of-note event-chord)
2013   (cond
2014    ((pair? event-chord)
2015     (or (duration-of-note (car event-chord))
2016         (duration-of-note (cdr event-chord))))
2017    ((ly:music? event-chord)
2018     (let ((dur (ly:music-property event-chord 'duration)))
2019       (if (ly:duration? dur)
2020           dur
2021           (duration-of-note (ly:music-property event-chord 'elements)))))
2022    (else #f)))
2023
2024 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2025
2026 (define-public (map-some-music map? music)
2027   "Walk through @var{music}, transform all elements calling @var{map?}
2028 and only recurse if this returns @code{#f}.  @code{elements} or
2029 @code{articulations} that are not music expressions are discarded:
2030 this allows some amount of filtering.
2031
2032 @code{map-some-music} may overwrite the original @var{music}."
2033   (let loop ((music music))
2034     (or (map? music)
2035         (let ((elt (ly:music-property music 'element))
2036               (elts (ly:music-property music 'elements))
2037               (arts (ly:music-property music 'articulations)))
2038           (if (ly:music? elt)
2039               (set! (ly:music-property music 'element)
2040                     (loop elt)))
2041           (if (pair? elts)
2042               (set! (ly:music-property music 'elements)
2043                     (filter! ly:music? (map! loop elts))))
2044           (if (pair? arts)
2045               (set! (ly:music-property music 'articulations)
2046                     (filter! ly:music? (map! loop arts))))
2047           music))))
2048
2049 (define-public (for-some-music stop? music)
2050   "Walk through @var{music}, process all elements calling @var{stop?}
2051 and only recurse if this returns @code{#f}."
2052   (let loop ((music music))
2053     (if (not (stop? music))
2054         (let ((elt (ly:music-property music 'element)))
2055           (if (ly:music? elt)
2056               (loop elt))
2057           (for-each loop (ly:music-property music 'elements))
2058           (for-each loop (ly:music-property music 'articulations))))))
2059
2060 (define-public (fold-some-music pred? proc init music)
2061   "This works recursively on music like @code{fold} does on a list,
2062 calling @samp{(@var{pred?} music)} on every music element.  If
2063 @code{#f} is returned for an element, it is processed recursively
2064 with the same initial value of @samp{previous}, otherwise
2065 @samp{(@var{proc} music previous)} replaces @samp{previous}
2066 and no recursion happens.
2067 The top @var{music} is processed using @var{init} for @samp{previous}."
2068   (let loop ((music music) (previous init))
2069     (if (pred? music)
2070         (proc music previous)
2071         (fold loop
2072               (fold loop
2073                     (let ((elt (ly:music-property music 'element)))
2074                       (if (null? elt)
2075                           previous
2076                           (loop elt previous)))
2077                     (ly:music-property music 'elements))
2078               (ly:music-property music 'articulations)))))
2079
2080 (define-public (extract-music music pred?)
2081   "Return a flat list of all music matching @var{pred?} inside of
2082 @var{music}, not recursing into matches themselves."
2083   (reverse! (fold-some-music pred? cons '() music)))
2084
2085 (define-public (extract-named-music music music-name)
2086   "Return a flat list of all music named @var{music-name} (either a
2087 single event symbol or a list of alternatives) inside of @var{music},
2088 not recursing into matches themselves."
2089   (extract-music
2090    music
2091    (if (cheap-list? music-name)
2092        (lambda (m) (memq (ly:music-property m 'name) music-name))
2093        (lambda (m) (eq? (ly:music-property m 'name) music-name)))))
2094
2095 (define-public (extract-typed-music music type)
2096   "Return a flat list of all music with @var{type} (either a single
2097 type symbol or a list of alternatives) inside of @var{music}, not
2098 recursing into matches themselves."
2099   (extract-music music (music-type-predicate type)))
2100
2101 (define-public (event-chord-wrap! music)
2102   "Wrap isolated rhythmic events and non-postevent events in
2103 @var{music} inside of an @code{EventChord}.  Chord repeats @samp{q}
2104 are expanded using the default settings of the parser."
2105   (map-some-music
2106    (lambda (m)
2107      (cond ((music-is-of-type? m 'event-chord)
2108             (if (pair? (ly:music-property m 'articulations))
2109                 (begin
2110                   (set! (ly:music-property m 'elements)
2111                         (append (ly:music-property m 'elements)
2112                                 (ly:music-property m 'articulations)))
2113                   (set! (ly:music-property m 'articulations) '())))
2114             m)
2115            ((music-is-of-type? m 'rhythmic-event)
2116             (let ((arts (ly:music-property m 'articulations)))
2117               (if (pair? arts)
2118                   (set! (ly:music-property m 'articulations) '()))
2119               (make-event-chord (cons m arts))))
2120            (else #f)))
2121    (expand-repeat-notes!
2122     (expand-repeat-chords!
2123      (cons 'rhythmic-event
2124            (ly:parser-lookup '$chord-repeat-events))
2125      music))))
2126
2127 (define-public (event-chord-notes event-chord)
2128   "Return a list of all notes from @var{event-chord}."
2129   (filter
2130    (lambda (m) (eq? 'NoteEvent (ly:music-property m 'name)))
2131    (ly:music-property event-chord 'elements)))
2132
2133 (define-public (event-chord-pitches event-chord)
2134   "Return a list of all pitches from @var{event-chord}."
2135   (map (lambda (x) (ly:music-property x 'pitch))
2136        (event-chord-notes event-chord)))
2137
2138 (define-public (music-pitches music)
2139   "Return a list of all pitches from @var{music}."
2140   ;; Opencoded for efficiency.
2141   (reverse!
2142    (let loop ((music music) (pitches '()))
2143      (let ((p (ly:music-property music 'pitch)))
2144        (if (ly:pitch? p)
2145            (cons p pitches)
2146            (let ((elt (ly:music-property music 'element)))
2147              (fold loop
2148                    (if (ly:music? elt)
2149                        (loop elt pitches)
2150                        pitches)
2151                    (ly:music-property music 'elements))))))))
2152
2153 (define-public (event-chord-reduce music)
2154   "Reduces event chords in @var{music} to their first note event,
2155 retaining only the chord articulations.  Returns the modified music."
2156   (map-some-music
2157    (lambda (m)
2158      (and (music-is-of-type? m 'event-chord)
2159           (let*-values (((notes arts) (partition
2160                                        (lambda (mus)
2161                                          (music-is-of-type? mus 'rhythmic-event))
2162                                        (ly:music-property m 'elements)))
2163                         ((dur) (ly:music-property m 'duration))
2164                         ((full-arts) (append arts
2165                                              (ly:music-property m 'articulations)))
2166                         ((first-note) (and (pair? notes) (car notes))))
2167             (cond (first-note
2168                    (set! (ly:music-property first-note 'articulations)
2169                          full-arts)
2170                    first-note)
2171                   ((ly:duration? dur)
2172                    ;; A repeat chord. Produce an unpitched note.
2173                    (make-music 'NoteEvent
2174                                'duration dur
2175                                'articulations full-arts))
2176                   (else
2177                    ;; This is an empty chord.  Ugh.  We cannot really
2178                    ;; reduce this in any manner, so we just keep it.
2179                    m)))))
2180    music))
2181
2182 (defmacro-public make-relative (variables reference music)
2183   "The list of pitch or music variables in @var{variables} is used as
2184 a sequence for creating relativable music from @var{music}.
2185
2186 When the constructed music is used outside of @code{\\relative}, it
2187 just reflects plugging in the @var{variables} into @var{music}.
2188
2189 The action inside of @code{\\relative}, however, is determined by
2190 first relativizing the surrogate @var{reference} with the variables
2191 plugged in and then using the variables relativized as a side effect
2192 of relativizing @var{reference} for evaluating @var{music}.
2193
2194 Since pitches don't have the object identity required for tracing the
2195 effect of the reference call, they are replaced @emph{only} for the
2196 purpose of evaluating @var{reference} with simple pitched note events.
2197
2198 The surrogate @var{reference} expression has to be written with that
2199 in mind.  In addition, it must @emph{not} contain @emph{copies} of
2200 music that is supposed to be relativized but rather the
2201 @emph{originals}.  This @emph{includes} the pitch expressions.  As a
2202 rule, inside of @code{#@{@dots{}#@}} variables must @emph{only} be
2203 introduced using @code{#}, never via the copying construct @code{$}.
2204 The reference expression will usually just be a sequential or chord
2205 expression naming all variables in sequence, implying that following
2206 music will be relativized according to the resulting pitch of the last
2207 or first variable, respectively.
2208
2209 Since the usual purpose is to create more complex music from general
2210 arguments and since music expression parts must not occur more than
2211 once, one @emph{does} generally need to use copying operators in the
2212 @emph{replacement} expression @var{music} when using an argument more
2213 than once there.  Using an argument more than once in @var{reference},
2214 in contrast, does not make sense.
2215
2216 There is another fine point to mind: @var{music} must @emph{only}
2217 contain freshly constructed elements or copied constructs.  This will
2218 be the case anyway for regular LilyPond code inside of
2219 @code{#@{@dots{}#@}}, but any other elements (apart from the
2220 @var{variables} themselves which are already copied) must be created
2221 or copied as well.
2222
2223 The reason is that it is usually permitted to change music in-place as
2224 long as one does a @var{ly:music-deep-copy} on it, and such a copy of
2225 the whole resulting expression will @emph{not} be able to copy
2226 variables/values inside of closures where the information for
2227 relativization is being stored.
2228 "
2229
2230   ;; pitch and music generator might be stored instead in music
2231   ;; properties, and it might make sense to create a music type of its
2232   ;; own for this kind of construct rather than using
2233   ;; RelativeOctaveMusic
2234   (define ((make-relative::to-relative-callback variables music-call ref-call)
2235            music pitch)
2236     (let* ((ref-vars (map (lambda (v)
2237                             (if (ly:pitch? v)
2238                                 (make-music 'NoteEvent 'pitch v)
2239                                 (ly:music-deep-copy v)))
2240                           variables))
2241            (after-pitch (ly:make-music-relative! (apply ref-call ref-vars) pitch))
2242            (actual-vars (map (lambda (v r)
2243                                (if (ly:pitch? v)
2244                                    (ly:music-property r 'pitch)
2245                                    r))
2246                              variables ref-vars))
2247            (rel-music (apply music-call actual-vars)))
2248       (set! (ly:music-property music 'element) rel-music)
2249       after-pitch))
2250   `(make-music 'RelativeOctaveMusic
2251                'to-relative-callback
2252                (,make-relative::to-relative-callback
2253                 (list ,@variables)
2254                 (lambda ,variables ,music)
2255                 (lambda ,variables ,reference))
2256                'element ,music))
2257
2258 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2259 ;; The following functions are all associated with the crossStaff
2260 ;;  function
2261
2262 (define (close-enough? x y)
2263   "Values are close enough to ignore the difference"
2264   (< (abs (- x y)) 0.0001))
2265
2266 (define (extent-combine extents)
2267   "Combine a list of extents"
2268   (if (pair? (cdr extents))
2269       (interval-union (car extents) (extent-combine (cdr extents)))
2270       (car extents)))
2271
2272 (define ((stem-connectable? ref root) stem)
2273   "Check if the stem is connectable to the root"
2274   ;; The root is always connectable to itself
2275   (or (eq? root stem)
2276       (and
2277        ;; Horizontal positions of the stems must be almost the same
2278        (close-enough? (car (ly:grob-extent root ref X))
2279                       (car (ly:grob-extent stem ref X)))
2280        ;; The stem must be in the direction away from the root's notehead
2281        (positive? (* (ly:grob-property root 'direction)
2282                      (- (car (ly:grob-extent stem ref Y))
2283                         (car (ly:grob-extent root ref Y))))))))
2284
2285 (define (stem-span-stencil span)
2286   "Connect stems if we have at least one stem connectable to the root"
2287   (let* ((system (ly:grob-system span))
2288          (root (ly:grob-parent span X))
2289          (stems (filter (stem-connectable? system root)
2290                         (ly:grob-object span 'stems))))
2291     (if (<= 2 (length stems))
2292         (let* ((yextents (map (lambda (st)
2293                                 (ly:grob-extent st system Y)) stems))
2294                (yextent (extent-combine yextents))
2295                (layout (ly:grob-layout root))
2296                (blot (ly:output-def-lookup layout 'blot-diameter)))
2297           ;; Hide spanned stems
2298           (for-each (lambda (st)
2299                       (set! (ly:grob-property st 'stencil) #f))
2300                     stems)
2301           ;; Draw a nice looking stem with rounded corners
2302           (ly:round-filled-box (ly:grob-extent root root X) yextent blot))
2303         ;; Nothing to connect, don't draw the span
2304         #f)))
2305
2306 (define ((make-stem-span! stems trans) root)
2307   "Create a stem span as a child of the cross-staff stem (the root)"
2308   (let ((span (ly:engraver-make-grob trans 'Stem '())))
2309     (ly:grob-set-parent! span X root)
2310     (set! (ly:grob-object span 'stems) stems)
2311     ;; Suppress positioning, the stem code is confused by this weird stem
2312     (set! (ly:grob-property span 'X-offset) 0)
2313     (set! (ly:grob-property span 'stencil) stem-span-stencil)))
2314
2315 (define-public (cross-staff-connect stem)
2316   "Set cross-staff property of the stem to this function to connect it to
2317 other stems automatically"
2318   #t)
2319
2320 (define (stem-is-root? stem)
2321   "Check if automatic connecting of the stem was requested.  Stems connected
2322 to cross-staff beams are cross-staff, but they should not be connected to
2323 other stems just because of that."
2324   (eq? cross-staff-connect (ly:grob-property-data stem 'cross-staff)))
2325
2326 (define (make-stem-spans! ctx stems trans)
2327   "Create stem spans for cross-staff stems"
2328   ;; Cannot do extensive checks here, just make sure there are at least
2329   ;; two stems at this musical moment
2330   (if (<= 2 (length stems))
2331       (let ((roots (filter stem-is-root? stems)))
2332         (for-each (make-stem-span! stems trans) roots))))
2333
2334 (define-public (Span_stem_engraver ctx)
2335   "Connect cross-staff stems to the stems above in the system"
2336   (let ((stems '()))
2337     (make-engraver
2338      ;; Record all stems for the given moment
2339      (acknowledgers
2340       ((stem-interface trans grob source)
2341        (set! stems (cons grob stems))))
2342      ;; Process stems and reset the stem list to empty
2343      ((process-acknowledged trans)
2344       (make-stem-spans! ctx stems trans)
2345       (set! stems '())))))
2346
2347 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2348 ;; The following is used by the alterBroken function.
2349
2350 (define ((value-for-spanner-piece arg) grob)
2351   "Associate a piece of broken spanner @var{grob} with an element
2352 of list @var{arg}."
2353   (let* ((orig (ly:grob-original grob))
2354          (siblings (ly:spanner-broken-into orig)))
2355
2356     (define (helper sibs arg)
2357       (if (null? arg)
2358           arg
2359           (if (eq? (car sibs) grob)
2360               (car arg)
2361               (helper (cdr sibs) (cdr arg)))))
2362
2363     (if (>= (length siblings) 2)
2364         (helper siblings arg)
2365         (car arg))))
2366 (export value-for-spanner-piece)
2367
2368 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2369 ;; The following are used by the \offset function
2370
2371 (define (find-value-to-offset prop self alist)
2372   "Return the first value of the property @var{prop} in the property
2373 alist @var{alist} -- after having found @var{self}.  If @var{self} is
2374 not found, return the first value of @var{prop}."
2375   (let ((segment (member (cons prop self) alist)))
2376     (if (not segment)
2377         (assoc-get prop alist)
2378         (assoc-get prop (cdr segment)))))
2379
2380 (define (offset-multiple-types arg offsets)
2381   "Displace @var{arg} by @var{offsets} if @var{arg} is a number, a
2382 number pair, or a list of number pairs.  If @var{offsets} is an empty
2383 list or if there is a type-mismatch, @var{arg} will be returned."
2384   (cond
2385     ((and (number? arg) (number? offsets))
2386      (+ arg offsets))
2387     ((and (number-pair? arg)
2388           (or (number? offsets)
2389               (number-pair? offsets)))
2390      (coord-translate arg offsets))
2391     ((and (number-pair-list? arg) (number-pair-list? offsets))
2392      (map coord-translate arg offsets))
2393     (else arg)))
2394
2395 (define-public (grob-transformer property func)
2396   "Create an override value good for applying @var{func} to either
2397 pure or unpure values.  @var{func} is called with the respective grob
2398 as first argument and the default value (after resolving all callbacks)
2399 as the second."
2400   (define (worker self caller grob . rest)
2401     (let* ((immutable (ly:grob-basic-properties grob))
2402            ;; We need to search the basic-properties alist for our
2403            ;; property to obtain values to offset.  Our search is
2404            ;; complicated by the fact that calling the music function
2405            ;; `offset' as an override conses a pair to the head of the
2406            ;; alist.  This pair must be discounted.  The closure it
2407            ;; contains is named `self' so it can be easily recognized.
2408            ;; If `offset' is called as a tweak, the basic-property
2409            ;; alist is unaffected.
2410            (target (find-value-to-offset property self immutable))
2411            ;; if target is a procedure, we need to apply it to our
2412            ;; grob to calculate values to offset.
2413            (vals (apply caller target grob rest)))
2414       (func grob vals)))
2415   ;; return the container named `self'.  The container self-reference
2416   ;; seems like chasing its own tail but gets dissolved by
2417   ;; define/lambda separating binding and referencing of "self".
2418   (define self (ly:make-unpure-pure-container
2419                 (lambda (grob)
2420                   (worker self ly:unpure-call grob))
2421                 (lambda (grob . rest)
2422                   (apply worker self ly:pure-call grob rest))))
2423   self)
2424
2425 (define-public (offsetter property offsets)
2426   "Apply @var{offsets} to the default values of @var{property} of @var{grob}.
2427 Offsets are restricted to immutable properties and values of type @code{number},
2428 @code{number-pair}, or @code{number-pair-list}."
2429   (define (offset-fun grob vals)
2430     (let ((can-type-be-offset?
2431            (or (number? vals)
2432                (number-pair? vals)
2433                (number-pair-list? vals))))
2434       (if can-type-be-offset?
2435           ;; '(+inf.0 . -inf.0) would offset to itself.  This will be
2436           ;; confusing to a user unaware of the default value of the
2437           ;; property, so issue a warning.
2438           (if (equal? empty-interval vals)
2439               (ly:warning "default '~a of ~a is ~a and can't be offset"
2440                 property grob vals)
2441               (let* ((orig (ly:grob-original grob))
2442                      (siblings
2443                        (if (ly:spanner? grob)
2444                            (ly:spanner-broken-into orig)
2445                            '()))
2446                      (total-found (length siblings))
2447                      ;; Since there is some flexibility in input
2448                      ;; syntax, structure of `offsets' is normalized.
2449                      (offsets
2450                        (if (or (not (pair? offsets))
2451                                (number-pair? offsets)
2452                                (and (number-pair-list? offsets)
2453                                     (number-pair-list? vals)))
2454                            (list offsets)
2455                            offsets)))
2456
2457                 (define (helper sibs offs)
2458                   ;; apply offsets to the siblings of broken spanners
2459                   (if (pair? offs)
2460                       (if (eq? (car sibs) grob)
2461                           (offset-multiple-types vals (car offs))
2462                           (helper (cdr sibs) (cdr offs)))
2463                       vals))
2464
2465                 (if (>= total-found 2)
2466                     (helper siblings offsets)
2467                     (offset-multiple-types vals (car offsets)))))
2468
2469           (begin
2470             (ly:warning "the property '~a of ~a cannot be offset" property grob)
2471             vals))))
2472   (grob-transformer property offset-fun))
2473
2474 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2475 ;; \magnifyMusic and \magnifyStaff
2476
2477 ;; defined as a function instead of a list because the
2478 ;; all-grob-descriptions alist is not available yet
2479 (define-public (find-named-props prop-name grob-descriptions)
2480   "Used by @code{\\magnifyMusic} and @code{\\magnifyStaff}.  When
2481 @var{grob-descriptions} is equal to the @code{all-grob-descriptions}
2482 alist (defined in @file{scm/define-grobs.scm}), this will find all grobs
2483 that can have a value for the @var{prop-name} property, and return them
2484 as a list in the following format:
2485 @example
2486 '((grob prop-name)
2487   (grob prop-name)
2488   ...)
2489 @end example"
2490   (define (find-grobs-with-interface interface grob-descriptions)
2491     (define (has-this-interface? grob-desc)
2492       (let* ((meta (ly:assoc-get 'meta (cdr grob-desc)))
2493              (interfaces (ly:assoc-get 'interfaces meta '())))
2494         (memq interface interfaces)))
2495     (let* ((grob-descriptions-with-this-interface
2496              (filter has-this-interface? grob-descriptions))
2497            (grob-names-with-this-interface
2498              (map car grob-descriptions-with-this-interface)))
2499       grob-names-with-this-interface))
2500   (let* ((interface
2501            (case prop-name
2502              ((baseline-skip word-space) 'text-interface)
2503              ((space-alist)              'break-aligned-interface)
2504              (else (ly:programming-error
2505                      "find-named-props: no interface associated with ~s"
2506                      prop-name))))
2507          (grobs-with-this-prop
2508            (find-grobs-with-interface interface grob-descriptions)))
2509     (map (lambda (x) (list x prop-name))
2510          grobs-with-this-prop)))
2511
2512
2513 (define (magnifyStaff-is-set? context mag)
2514   (let* ((Staff (ly:context-find context 'Staff))
2515          (old-mag (ly:context-property Staff 'magnifyStaffValue)))
2516     (not (null? old-mag))))
2517
2518 (define (staff-magnification-is-changing? context mag)
2519   (let* ((Staff (ly:context-find context 'Staff))
2520          (old-mag (ly:context-property Staff 'magnifyStaffValue 1)))
2521     (not (= old-mag mag))))
2522
2523 (define-public (scale-fontSize func-name mag)
2524   "Used by @code{\\magnifyMusic} and @code{\\magnifyStaff}.  Look up the
2525 current @code{fontSize} in the appropriate context and scale it by the
2526 magnification factor @var{mag}.  @var{func-name} is either
2527 @code{'magnifyMusic} or @code{'magnifyStaff}."
2528   (make-apply-context
2529     (lambda (context)
2530       (if (or (eq? func-name 'magnifyMusic)
2531               ;; for \magnifyStaff, only scale the fontSize
2532               ;; if staff magnification is changing
2533               ;; and does not equal 1
2534               (and (staff-magnification-is-changing? context mag)
2535                    (not (= mag 1))))
2536         (let* ((where (case func-name
2537                         ((magnifyMusic) context)
2538                         ((magnifyStaff) (ly:context-find context 'Staff))))
2539                (fontSize (ly:context-property where 'fontSize 0))
2540                (new-fontSize (+ fontSize (magnification->font-size mag))))
2541           (ly:context-set-property! where 'fontSize new-fontSize))))))
2542
2543 (define-public (revert-fontSize func-name mag)
2544   "Used by @code{\\magnifyMusic} and @code{\\magnifyStaff}.  Calculate
2545 the previous @code{fontSize} value (before scaling) by factoring out the
2546 magnification factor @var{mag} (if @var{func-name} is
2547 @code{'magnifyMusic}), or by factoring out the context property
2548 @code{magnifyStaffValue} (if @var{func-name} is @code{'magnifyStaff}).
2549 Revert the @code{fontSize} in the appropriate context accordingly.
2550
2551 With @code{\\magnifyMusic}, the scaling is reverted after the music
2552 block it operates on.  @code{\\magnifyStaff} does not operate on a music
2553 block, so the scaling from a previous call (if there is one) is reverted
2554 before the new scaling takes effect."
2555   (make-apply-context
2556     (lambda (context)
2557       (if (or (eq? func-name 'magnifyMusic)
2558               ;; for \magnifyStaff...
2559               (and
2560                 ;; don't revert the user's fontSize choice
2561                 ;; the first time \magnifyStaff is called
2562                 (magnifyStaff-is-set? context mag)
2563                 ;; only revert the previous fontSize
2564                 ;; if staff magnification is changing
2565                 (staff-magnification-is-changing? context mag)))
2566         (let* ((where
2567                  (case func-name
2568                    ((magnifyMusic) context)
2569                    ((magnifyStaff) (ly:context-find context 'Staff))))
2570                (old-mag
2571                  (case func-name
2572                    ((magnifyMusic) mag)
2573                    ((magnifyStaff)
2574                     (ly:context-property where 'magnifyStaffValue 1))))
2575                (fontSize (ly:context-property where 'fontSize 0))
2576                (old-fontSize (- fontSize (magnification->font-size old-mag))))
2577           (ly:context-set-property! where 'fontSize old-fontSize))))))
2578
2579 (define-public (scale-props func-name mag allowed-to-shrink? props)
2580   "Used by @code{\\magnifyMusic} and @code{\\magnifyStaff}.  For each
2581 prop in @var{props}, find the current value of the requested prop, scale
2582 it by the magnification factor @var{mag}, and do the equivalent of a
2583 @code{\\temporary@tie{}\\override} with the new value in the appropriate
2584 context.  If @var{allowed-to-shrink?} is @code{#f}, don't let the new
2585 value be less than the current value.  @var{func-name} is either
2586 @code{'magnifyMusic} or @code{'magnifyStaff}.  The @var{props} list is
2587 formatted like:
2588 @example
2589 '((Stem thickness)
2590   (Slur line-thickness)
2591   ...)
2592 @end example"
2593   (make-apply-context
2594     (lambda (context)
2595       (define (scale-prop grob-prop-list)
2596         (let* ((grob (car grob-prop-list))
2597                (prop (cadr grob-prop-list))
2598                (where (if (eq? grob 'SpacingSpanner)
2599                         (ly:context-find context 'Score)
2600                         (case func-name
2601                           ((magnifyMusic) context)
2602                           ((magnifyStaff) (ly:context-find context 'Staff)))))
2603                (grob-def (ly:context-grob-definition where grob)))
2604           (if (eq? prop 'space-alist)
2605             (let* ((space-alist (ly:assoc-get prop grob-def))
2606                    (scale-spacing-tuple (lambda (x)
2607                                           (cons (car x)
2608                                                 (cons (cadr x)
2609                                                       (* mag (cddr x))))))
2610                    (scaled-tuples (if space-alist
2611                                       (map scale-spacing-tuple space-alist)
2612                                       '()))
2613                    (new-alist (append scaled-tuples space-alist)))
2614               (ly:context-pushpop-property where grob prop new-alist))
2615             (let* ((val (ly:assoc-get prop grob-def (case prop
2616                                                       ((baseline-skip) 3)
2617                                                       ((word-space)    0.6)
2618                                                       (else            1))))
2619                    (proc (lambda (x)
2620                            (if allowed-to-shrink?
2621                              (* x mag)
2622                              (* x (max 1 mag)))))
2623                    (new-val (if (number-pair? val)
2624                               (cons (proc (car val))
2625                                     (proc (cdr val)))
2626                               (proc val))))
2627               (ly:context-pushpop-property where grob prop new-val)))))
2628       (if (or (eq? func-name 'magnifyMusic)
2629               ;; for \magnifyStaff, only scale the properties
2630               ;; if staff magnification is changing
2631               ;; and does not equal 1
2632               (and (staff-magnification-is-changing? context mag)
2633                    (not (= mag 1))))
2634         (for-each scale-prop props)))))
2635
2636 (define-public (revert-props func-name mag props)
2637   "Used by @code{\\magnifyMusic} and @code{\\magnifyStaff}.  Revert each
2638 prop in @var{props} in the appropriate context.  @var{func-name} is
2639 either @code{'magnifyMusic} or @code{'magnifyStaff}.  The @var{props}
2640 list is formatted like:
2641 @example
2642 '((Stem thickness)
2643   (Slur line-thickness)
2644   ...)
2645 @end example"
2646   (make-apply-context
2647     (lambda (context)
2648       (define (revert-prop grob-prop-list)
2649         (let* ((grob (car grob-prop-list))
2650                (prop (cadr grob-prop-list))
2651                (where (if (eq? grob 'SpacingSpanner)
2652                         (ly:context-find context 'Score)
2653                         (case func-name
2654                           ((magnifyMusic) context)
2655                           ((magnifyStaff) (ly:context-find context 'Staff))))))
2656           (ly:context-pushpop-property where grob prop)))
2657       (if (or (eq? func-name 'magnifyMusic)
2658               ;; for \magnifyStaff...
2659               (and
2660                 ;; don't revert the user's property overrides
2661                 ;; the first time \magnifyStaff is called
2662                 (magnifyStaff-is-set? context mag)
2663                 ;; revert the overrides from the previous \magnifyStaff,
2664                 ;; but only if staff magnification is changing
2665                 (staff-magnification-is-changing? context mag)))
2666         (for-each revert-prop props)))))
2667
2668 ;; \magnifyMusic only
2669 (define-public (scale-beam-thickness mag)
2670   "Used by @code{\\magnifyMusic}.  Scaling @code{Beam.beam-thickness}
2671 exactly to the @var{mag} value will not work.  This uses two reference
2672 values for @code{beam-thickness} to determine an acceptable value when
2673 scaling, then does the equivalent of a
2674 @code{\\temporary@tie{}\\override} with the new value."
2675   (make-apply-context
2676     (lambda (context)
2677       (let* ((grob-def (ly:context-grob-definition context 'Beam))
2678              (val (ly:assoc-get 'beam-thickness grob-def 0.48))
2679              (ratio-to-default (/ val 0.48))
2680              ;; gives beam-thickness=0.48 when mag=1 (like default),
2681              ;; gives beam-thickness=0.35 when mag=0.63 (like CueVoice)
2682              (scaled-default (+ 119/925 (* mag 13/37)))
2683              (new-val (* scaled-default ratio-to-default)))
2684         (ly:context-pushpop-property context 'Beam 'beam-thickness new-val)))))
2685
2686 ;; tag management
2687 ;;
2688
2689 (define tag-groups (make-hash-table))
2690 (call-after-session (lambda () (hash-clear! tag-groups)))
2691
2692 (define-public (define-tag-group tags)
2693   "Define a tag-group consisting of the given @var{tags}, a@tie{}list
2694 of symbols.  Returns @code{#f} if successful, and an error message if
2695 there is a conflicting tag group definition."
2696   (cond ((not (symbol-list? tags)) (format #f (_ "not a symbol list: ~a") tags))
2697         ((any (lambda (tag) (hashq-ref tag-groups tag)) tags)
2698          => (lambda (group) (and (not (lset= eq? group tags))
2699                                  (format #f (_ "conflicting tag group ~a") group))))
2700         (else
2701          (for-each
2702           (lambda (elt) (hashq-set! tag-groups elt tags))
2703           tags)
2704          #f)))
2705
2706 (define-public (tag-group-get tag)
2707   "Return the tag group (as a list of symbols) that the given
2708 @var{tag} symbol belongs to, @code{#f} if none."
2709   (hashq-ref tag-groups tag))
2710
2711 (define-public (tags-remove-predicate tags)
2712   "Returns a predicate that returns @code{#f} for any music that is to
2713 be removed by @{\\removeWithTag} on the given symbol or list of
2714 symbols @var{tags}."
2715   (if (symbol? tags)
2716       (lambda (m)
2717         (not (memq tags (ly:music-property m 'tags))))
2718       (lambda (m)
2719         (not (any (lambda (t) (memq t tags))
2720                   (ly:music-property m 'tags))))))
2721
2722 (define-public (tags-keep-predicate tags)
2723   "Returns a predicate that returns @code{#f} for any music that is to
2724 be removed by @{\\keepWithTag} on the given symbol or list of symbols
2725 @var{tags}."
2726   (if (symbol? tags)
2727       (let ((group (tag-group-get tags)))
2728         (lambda (m)
2729           (let ((music-tags (ly:music-property m 'tags)))
2730             (or
2731              (null? music-tags) ; redundant but very frequent
2732              ;; We know of only one tag to keep.  Either we find it in
2733              ;; the music tags, or all music tags must be from a
2734              ;; different group
2735              (memq tags music-tags)
2736              (not (any (lambda (t) (eq? (tag-group-get t) group)) music-tags))))))
2737       (let ((groups (delete-duplicates (map tag-group-get tags) eq?)))
2738         (lambda (m)
2739           (let ((music-tags (ly:music-property m 'tags)))
2740             (or
2741              (null? music-tags) ; redundant but very frequent
2742              (any (lambda (t) (memq t tags)) music-tags)
2743              ;; if no tag matches, no tag group should match either
2744              (not (any (lambda (t) (memq (tag-group-get t) groups)) music-tags))))))))