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