1 ;;;; This file is part of LilyPond, the GNU music typesetter.
3 ;;;; Copyright (C) 1998--2015 Jan Nieuwenhuizen <janneke@gnu.org>
4 ;;;; Han-Wen Nienhuys <hanwen@xs4all.nl>
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.
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.
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/>.
19 ;; for define-safe-public when byte-compiling using Guile V2
20 (use-modules (scm safe-utility-defs))
22 (use-modules (ice-9 optargs))
23 (use-modules (srfi srfi-11))
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!))
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)))
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)
43 (any (lambda (t) (music-is-of-type? m t)) types))
44 (lambda (m) (music-is-of-type? m types))))
47 (define-public ly:grob-property
48 (make-procedure-with-setter ly:grob-property
49 ly:grob-set-property!))
51 (define-public ly:grob-object
52 (make-procedure-with-setter ly:grob-object
55 (define-public ly:grob-parent
56 (make-procedure-with-setter ly:grob-parent
59 (define-public ly:prob-property
60 (make-procedure-with-setter ly:prob-property
61 ly:prob-set-property!))
63 (define-public ly:context-property
64 (make-procedure-with-setter ly:context-property
65 ly:context-set-property!))
67 (define-public (music-map function music)
68 "Apply @var{function} to @var{music} and all of the music it contains.
70 First it recurses over the children, then the function is applied to
72 (let ((es (ly:music-property music 'elements))
73 (e (ly:music-property music 'element)))
75 (set! (ly:music-property music 'elements)
76 (map (lambda (y) (music-map function y)) es)))
78 (set! (ly:music-property music 'element)
79 (music-map function e)))
82 (define-public (music-filter pred? music)
83 "Filter out music expressions that do not satisfy @var{pred?}."
85 (define (inner-music-filter pred? music)
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 (lambda (y) (inner-music-filter pred? y)) as)))
91 (filtered-e (if (ly:music? e)
92 (inner-music-filter pred? e)
94 (filtered-es (filter ly:music? (map (lambda (y) (inner-music-filter pred? y)) es))))
96 (set! (ly:music-property music 'element) filtered-e))
98 (set! (ly:music-property music 'elements) filtered-es))
100 (set! (ly:music-property music 'articulations) filtered-as))
101 ;; if filtering emptied the expression, we remove it completely.
102 (if (or (not (pred? music))
103 (and (eq? filtered-es '()) (not (ly:music? e))
104 (or (not (eq? es '()))
109 (set! music (inner-music-filter pred? music))
110 (if (ly:music? music)
112 (make-music 'Music))) ;must return music.
114 (define*-public (display-music music #:optional (port (current-output-port)))
115 "Display music, not done with @code{music-map} for clarity of
118 (display ": { " port)
119 (let ((es (ly:music-property music 'elements))
120 (e (ly:music-property music 'element)))
121 (display (ly:music-mutable-properties music) port)
123 (begin (display "\nElements: {\n" port)
124 (for-each (lambda (m) (display-music m port)) es)
125 (display "}\n" port)))
128 (display "\nChild:" port)
129 (display-music e port))))
130 (display " }\n" port)
134 ;;; A scheme music pretty printer
136 (define (markup-expression->make-markup markup-expression)
137 "Transform `markup-expression' into an equivalent, hopefuly readable, scheme expression.
139 \\markup \\bold \\italic hello
141 (markup #:line (#:bold (#:italic (#:simple \"hello\"))))"
142 (define (proc->command-keyword proc)
143 "Return a keyword, eg. `#:bold', from the `proc' function, eg. #<procedure bold-markup (layout props arg)>"
144 (let ((cmd-markup (symbol->string (procedure-name proc))))
145 (symbol->keyword (string->symbol (substring cmd-markup 0 (- (string-length cmd-markup)
146 (string-length "-markup")))))))
147 (define (transform-arg arg)
148 (cond ((and (pair? arg) (markup? (car arg))) ;; a markup list
149 (append-map inner-markup->make-markup arg))
150 ((and (not (string? arg)) (markup? arg)) ;; a markup
151 (inner-markup->make-markup arg))
153 (music->make-music arg))))
154 (define (inner-markup->make-markup mrkup)
157 (let ((cmd (proc->command-keyword (car mrkup)))
158 (args (map transform-arg (cdr mrkup))))
161 (if (string? markup-expression)
163 `(markup ,@(inner-markup->make-markup markup-expression))))
165 (define-public (music->make-music obj)
166 "Generate an expression that, once evaluated, may return an object
167 equivalent to @var{obj}, that is, for a music expression, a
168 @code{(make-music ...)} form."
169 (define (if-nonzero num)
170 (if (zero? num) '() (list num)))
171 (cond (;; markup expression
173 (markup-expression->make-markup obj))
177 ',(ly:music-property obj 'name)
178 ,@(append-map (lambda (prop)
180 ,(music->make-music (cdr prop))))
181 (remove (lambda (prop)
182 (eqv? (car prop) 'origin))
183 (ly:music-mutable-properties obj)))))
187 ,@(let ((main (ly:moment-main obj))
188 (grace (ly:moment-grace obj)))
189 (cond ((zero? grace) (list main))
190 ((negative? grace) (list main grace))
191 (else ;;positive grace requires 4-arg form
192 (list (numerator main)
195 (denominator grace)))))))
198 `(ly:make-duration ,(ly:duration-log obj)
199 ,@(if (= (ly:duration-scale obj) 1)
200 (if-nonzero (ly:duration-dot-count obj))
201 (list (ly:duration-dot-count obj)
202 (ly:duration-scale obj)))))
205 `(ly:make-pitch ,(ly:pitch-octave obj)
206 ,(ly:pitch-notename obj)
207 ,@(if-nonzero (ly:pitch-alteration obj))))
210 (or (procedure-name obj) obj))
211 (;; a symbol (avoid having an unquoted symbol)
214 (;; an empty list (avoid having an unquoted empty list)
219 `(list ,@(map music->make-music obj)))
222 `(cons ,(music->make-music (car obj))
223 ,(music->make-music (cdr obj))))
227 (use-modules (ice-9 pretty-print))
228 (define*-public (display-scheme-music obj #:optional (port (current-output-port)))
229 "Displays `obj', typically a music expression, in a friendly fashion,
230 which often can be read back in order to generate an equivalent expression."
231 (pretty-print (music->make-music obj) port)
235 ;;; Scheme music expression --> Lily-syntax-using string translator
237 (use-modules (srfi srfi-39)
240 (define*-public (display-lily-music expr #:optional (port (current-output-port))
241 #:key force-duration)
242 "Display the music expression using LilyPond syntax"
243 (memoize-clef-names supported-clefs)
244 (parameterize ((*indent* 0)
245 (*omit-duration* #f))
246 (display (music->lily-string expr) port)
249 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
251 (define-public (shift-one-duration-log music shift dot)
252 "Add @var{shift} to @code{duration-log} of @code{'duration} in
253 @var{music} and optionally @var{dot} to any note encountered.
254 The number of dots in the shifted music may not be less than zero."
255 (let ((d (ly:music-property music 'duration)))
257 (let* ((cp (ly:duration-scale d))
258 (nd (ly:make-duration
259 (+ shift (ly:duration-log d))
260 (max 0 (+ dot (ly:duration-dot-count d)))
262 (set! (ly:music-property music 'duration) nd)))
263 ;clear cached length, since it's no longer valid
264 (set! (ly:music-property music 'length) '())
267 (define-public (shift-duration-log music shift dot)
268 (music-map (lambda (x) (shift-one-duration-log x shift dot))
271 (define-public (tremolo::get-music-list tremolo)
272 "Given a tremolo repeat, return a list of music to engrave for it.
273 This will be a stretched copy of its body, plus a TremoloEvent or
276 This is called only by Chord_tremolo_iterator."
277 (define (first-note-duration music)
278 "Finds the duration of the first NoteEvent by searching
279 depth-first through MUSIC."
280 ;; NoteEvent or a non-expanded chord-repetition
281 ;; We just take anything that actually sports an announced duration.
282 (if (ly:duration? (ly:music-property music 'duration))
283 (ly:music-property music 'duration)
284 (let loop ((elts (if (ly:music? (ly:music-property music 'element))
285 (list (ly:music-property music 'element))
286 (ly:music-property music 'elements))))
288 (let ((dur (first-note-duration (car elts))))
289 (if (ly:duration? dur)
291 (loop (cdr elts))))))))
292 (let* ((times (ly:music-property tremolo 'repeat-count))
293 (body (ly:music-property tremolo 'element))
294 (children (if (music-is-of-type? body 'sequential-music)
295 ;; \repeat tremolo n { ... }
296 (count duration-of-note ; do not count empty <>
297 (extract-named-music body
298 '(EventChord NoteEvent)))
299 ;; \repeat tremolo n c4
301 (tremolo-type (if (positive? children)
302 (let* ((note-duration (first-note-duration body))
303 (duration-log (if (ly:duration? note-duration)
304 (ly:duration-log note-duration)
306 (ash 1 duration-log))
308 (stretched (ly:music-deep-copy body)))
309 (if (positive? children)
310 ;; # of dots is equal to the 1 in bitwise representation (minus 1)!
311 (let* ((dots (1- (logcount (* times children))))
312 ;; The remaining missing multiplier to scale the notes by
314 (mult (/ (* times children (ash 1 dots)) (1- (ash 2 dots))))
315 (shift (- (ly:intlog2 (floor mult)))))
316 (if (not (and (integer? mult) (= (logcount mult) 1)))
319 (ly:format (_ "invalid tremolo repeat count: ~a") times)))
320 ;; Make each note take the full duration
321 (ly:music-compress stretched (ly:make-moment 1 children))
322 ;; Adjust the displayed note durations
323 (shift-duration-log stretched shift dots)))
324 ;; Return the stretched body plus a tremolo event
326 (list (make-music 'TremoloEvent
328 'tremolo-type tremolo-type
329 'origin (ly:music-property tremolo 'origin))
331 (list (make-music 'TremoloSpanEvent
332 'span-direction START
334 'tremolo-type tremolo-type
335 'origin (ly:music-property tremolo 'origin))
337 (make-music 'TremoloSpanEvent
339 'origin (ly:music-property tremolo 'origin))))))
341 (define-public (make-repeat name times main alts)
342 "Create a repeat music expression, with all properties initialized
344 (let ((type (or (assoc-get name '(("volta" . VoltaRepeatedMusic)
345 ("unfold" . UnfoldedRepeatedMusic)
346 ("percent" . PercentRepeatedMusic)
347 ("tremolo" . TremoloRepeatedMusic)))
348 (begin (ly:warning (_ "unknown repeat type `~S': must be volta, unfold, percent, or tremolo") name)
349 'VoltaRepeatedMusic)))
350 (talts (if (< times (length alts))
352 (ly:warning (_ "More alternatives than repeats. Junking excess alternatives"))
357 'repeat-count (max times 1)
360 (define (calc-repeat-slash-count music)
361 "Given the child-list @var{music} in @code{PercentRepeatMusic},
362 calculate the number of slashes based on the durations. Returns @code{0}
363 if durations in @var{music} vary, allowing slash beats and double-percent
364 beats to be distinguished."
365 (let* ((durs (map duration-of-note
366 (extract-named-music music '(EventChord NoteEvent
367 RestEvent SkipEvent))))
368 (first-dur (car durs)))
370 (if (every (lambda (d) (equal? d first-dur)) durs)
371 (max (- (ly:duration-log first-dur) 2) 1)
374 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
377 (define-public (note-to-cluster music)
378 "Replace @code{NoteEvents} by @code{ClusterNoteEvents}."
379 (if (eq? (ly:music-property music 'name) 'NoteEvent)
380 (make-music 'ClusterNoteEvent
381 'pitch (ly:music-property music 'pitch)
382 'duration (ly:music-property music 'duration))
385 (define-public (notes-to-clusters music)
386 (music-map note-to-cluster music))
388 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
391 (define-public (unfold-repeats music)
392 "Replace all repeats with unfolded repeats."
393 (let ((es (ly:music-property music 'elements))
394 (e (ly:music-property music 'element)))
395 (if (music-is-of-type? music 'repeated-music)
396 (set! music (make-music 'UnfoldedRepeatedMusic music)))
398 (set! (ly:music-property music 'elements)
399 (map unfold-repeats es)))
401 (set! (ly:music-property music 'element)
405 (define-public (unfold-repeats-fully music)
406 "Unfolds repeats and expands the resulting @code{unfolded-repeated-music}."
409 (and (music-is-of-type? m 'unfolded-repeated-music)
410 (make-sequential-music
411 (ly:music-deep-copy (make-unfolded-set m)))))
412 (unfold-repeats music)))
414 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
415 ;; property setting music objs.
417 (define-safe-public (check-grob-path path #:optional location
423 "Check a grob path specification @var{path}, a symbol list (or a
424 single symbol), for validity and possibly complete it. Returns the
425 completed specification, or @code{#f} if invalid. If optional
426 @var{parser} is given, a syntax error is raised in that case,
427 optionally using @var{location}. If an optional keyword argument
428 @code{#:start @var{start}} is given, the parsing starts at the given
429 index in the sequence @samp{Context.Grob.property.sub-property...},
430 with the default of @samp{0} implying the full path.
432 If there is no valid first element of @var{path} fitting at the given
433 path location, an optionally given @code{#:default @var{default}} is
434 used as the respective element instead without checking it for
435 validity at this position.
437 The resulting path after possibly prepending @var{default} can be
438 constrained in length by optional arguments @code{#:min @var{min}} and
439 @code{#:max @var{max}}, defaulting to @samp{1} and unlimited,
441 (let ((path (if (symbol? path) (list path) path)))
442 ;; A Guile 1.x bug specific to optargs precludes moving the
443 ;; defines out of the let
444 (define (unspecial? s)
445 (not (or (object-property s 'is-grob?)
446 (object-property s 'backend-type?))))
448 (object-property s 'is-grob?))
449 (define (property? s)
450 (object-property s 'backend-type?))
451 (define (check c p) (c p))
455 (drop (list unspecial? grob? property?) start)))
459 ;; tricky. Should we make use of the default when the
460 ;; list is empty? In most cases, this question should be
461 ;; academical as an empty list can only be generated by
462 ;; Scheme and is likely an error. We consider this a case
463 ;; of "no valid first element, and default given".
464 ;; Usually, invalid use cases should be caught later using
465 ;; the #:min argument, and if the user explicitly does not
466 ;; catch this, we just follow through.
467 (if default (list default) '()))
469 ;; no checkers, so we have a valid first element and just
470 ;; take the path as-is.
473 (if ((car checkers) (car path))
474 (and (every check (cdr checkers) (cdr path))
476 (and (every check (cdr checkers) path)
477 (cons default path))))
479 (and (every check checkers path)
482 (if max (<= min (length res) max)
483 (<= min (length res))))
487 (format #f (_ "bad grob property path ~a")
492 (define-safe-public (check-context-path path #:optional location)
493 "Check a context property path specification @var{path}, a symbol
494 list (or a single symbol), for validity and possibly complete it.
495 Returns the completed specification, or @code{#f} when rising an
496 error (using optionally @code{location})."
497 (let* ((path (if (symbol? path) (list path) path)))
498 ;; A Guile 1.x bug specific to optargs precludes moving the
499 ;; defines out of the let
500 (define (property? s)
501 (object-property s 'translation-type?))
502 (define (unspecial? s)
504 (define (check c p) (c p))
505 (or (case (length path)
506 ((1) (and (property? (car path)) (cons 'Bottom path)))
507 ((2) (and (unspecial? (car path)) (property? (cadr path)) path))
511 (format #f (_ "bad context property ~a")
516 (define-safe-public (check-music-path path #:optional location #:key default)
517 "Check a music property path specification @var{path}, a symbol
518 list (or a single symbol), for validity and possibly complete it.
519 Returns the completed specification, or @code{#f} when rising an
520 error (using optionally @code{location})."
521 (let* ((path (if (symbol? path) (list path) path)))
522 ;; A Guile 1.x bug specific to optargs precludes moving the
523 ;; defines out of the let
524 (define (property? s)
525 (object-property s 'music-type?))
526 (define (unspecial? s)
528 (or (case (length path)
529 ((1) (and (property? (car path)) (cons default path)))
530 ((2) (and (unspecial? (car path)) (property? (cadr path)) path))
534 (format #f (_ "bad music property ~a")
539 (define-public (make-grob-property-set grob gprop val)
540 "Make a @code{Music} expression that sets @var{gprop} to @var{val} in
541 @var{grob}. Does a pop first, i.e., this is not an override."
542 (make-music 'OverrideProperty
548 (define-public (make-grob-property-override grob gprop val)
549 "Make a @code{Music} expression that overrides @var{gprop} to @var{val}
551 (make-music 'OverrideProperty
556 (define-public (make-grob-property-revert grob gprop)
557 "Revert the grob property @var{gprop} for @var{grob}."
558 (make-music 'RevertProperty
560 'grob-property gprop))
562 (define direction-polyphonic-grobs
563 '(AccidentalSuggestion
581 (define general-grace-settings
582 `((Voice Stem font-size -3)
583 (Voice Flag font-size -3)
584 (Voice NoteHead font-size -3)
585 (Voice TabNoteHead font-size -4)
586 (Voice Dots font-size -3)
587 (Voice Stem length-fraction 0.8)
588 (Voice Stem no-stem-extend #t)
589 (Voice Beam beam-thickness 0.384)
590 (Voice Beam length-fraction 0.8)
591 (Voice Accidental font-size -4)
592 (Voice AccidentalCautionary font-size -4)
593 (Voice Script font-size -3)
594 (Voice Fingering font-size -8)
595 (Voice StringNumber font-size -8)))
597 (define-public score-grace-settings
599 `((Voice Stem direction ,UP)
600 (Voice Slur direction ,DOWN))
601 general-grace-settings))
603 ;; Getting a unique context id name
605 (define-session unique-counter -1)
606 (define-safe-public (get-next-unique-voice-name)
607 (set! unique-counter (1+ unique-counter))
608 (format #f "uniqueContext~s" unique-counter))
611 (define-safe-public (make-voice-props-set n)
612 (make-sequential-music
614 (map (lambda (x) (make-grob-property-set x 'direction
616 direction-polyphonic-grobs)
618 (make-property-set 'graceSettings general-grace-settings)
619 (make-grob-property-set 'NoteColumn 'horizontal-shift (quotient n 2))))))
621 (define-safe-public (make-voice-props-override n)
622 (make-sequential-music
624 (map (lambda (x) (make-grob-property-override x 'direction
626 direction-polyphonic-grobs)
628 (make-property-set 'graceSettings general-grace-settings)
629 (make-grob-property-override 'NoteColumn 'horizontal-shift (quotient n 2))))))
631 (define-safe-public (make-voice-props-revert)
632 (make-sequential-music
634 (map (lambda (x) (make-grob-property-revert x 'direction))
635 direction-polyphonic-grobs)
636 (list (make-property-unset 'graceSettings)
637 (make-grob-property-revert 'NoteColumn 'horizontal-shift)))))
640 (define-safe-public (context-spec-music m context #:optional id mods)
641 "Add \\context @var{context} = @var{id} \\with @var{mods} to @var{m}."
642 (let ((cm (make-music 'ContextSpeccedMusic
644 'context-type context)))
646 (set! (ly:music-property cm 'context-id) id))
648 (set! (ly:music-property cm 'property-operations)
649 (if (ly:context-mod? mods)
650 (ly:get-context-mods mods)
654 (define-safe-public (descend-to-context m context #:optional id mods)
655 "Like @code{context-spec-music}, but only descending."
656 (let ((cm (context-spec-music m context id mods)))
657 (ly:music-set-property! cm 'descend-only #t)
660 (define-public (make-non-relative-music mus)
661 (make-music 'UnrelativableMusic
664 (define-public (make-apply-context func)
665 (make-music 'ApplyContext
668 (define-public (make-sequential-music elts)
669 (make-music 'SequentialMusic
672 (define-public (make-simultaneous-music elts)
673 (make-music 'SimultaneousMusic
676 (define-safe-public (make-event-chord elts)
677 (make-music 'EventChord
680 (define-public (make-skip-music dur)
681 (make-music 'SkipMusic
684 (define-public (make-grace-music music)
685 (make-music 'GraceMusic
691 (define-public (make-multi-measure-rest duration location)
692 (make-music 'MultiMeasureRestMusic
696 (define-public (make-property-set sym val)
697 (make-music 'PropertySet
701 (define-public (make-property-unset sym)
702 (make-music 'PropertyUnset
705 (define-safe-public (make-articulation name . properties)
706 (apply make-music 'ArticulationEvent
707 'articulation-type name
710 (define-public (make-lyric-event string duration)
711 (make-music 'LyricEvent
715 (define-safe-public (make-span-event type span-dir)
717 'span-direction span-dir))
719 (define-public (override-head-style heads style)
720 "Override style for @var{heads} to @var{style}."
721 (make-sequential-music
724 (make-grob-property-override h 'style style))
726 (list (make-grob-property-override heads 'style style)))))
728 (define-public (revert-head-style heads)
729 "Revert style for @var{heads}."
730 (make-sequential-music
733 (make-grob-property-revert h 'style))
735 (list (make-grob-property-revert heads 'style)))))
737 (define-public (style-note-heads heads style music)
738 "Set @var{style} for all @var{heads} in @var{music}. Works both
739 inside of and outside of chord construct."
740 ;; are we inside a <...>?
741 (if (eq? (ly:music-property music 'name) 'NoteEvent)
742 ;; yes -> use a tweak
744 (set! (ly:music-property music 'tweaks)
745 (acons 'style style (ly:music-property music 'tweaks)))
747 ;; not in <...>, so use overrides
748 (make-sequential-music
750 (override-head-style heads style)
752 (revert-head-style heads)))))
754 (define-public (set-mus-properties! m alist)
755 "Set all of @var{alist} as properties of @var{m}."
758 (set! (ly:music-property m (caar alist)) (cdar alist))
759 (set-mus-properties! m (cdr alist)))))
761 (define-public (music-separator? m)
762 "Is @var{m} a separator?"
763 (let ((ts (ly:music-property m 'types)))
764 (memq 'separator ts)))
766 ;;; expanding repeat chords
767 (define-public (copy-repeat-chord original-chord repeat-chord duration
769 "Copies all events in @var{event-types} (be sure to include
770 @code{rhythmic-events}) from @var{original-chord} over to
771 @var{repeat-chord} with their articulations filtered as well. Any
772 duration is replaced with the specified @var{duration}."
773 ;; First remove everything from event-types that can already be
774 ;; found in the repeated chord. We don't need to look for
775 ;; articulations on individual events since they can't actually get
776 ;; into a repeat chord given its input syntax.
778 (define keep-element? (music-type-predicate event-types))
782 (for-each (lambda (e)
783 (for-each (lambda (x)
784 (set! event-types (delq x event-types)))
785 (ly:music-property e 'types)))
786 (ly:music-property repeat-chord field)))
787 '(elements articulations))
789 ;; now treat the elements
790 (set! (ly:music-property repeat-chord 'elements)
792 (ly:music-deep-copy (filter keep-element?
793 (ly:music-property original-chord
798 (let ((arts (ly:music-property m 'articulations)))
800 (set! (ly:music-property m 'articulations)
801 (ly:set-origin! (filter! keep-element? arts)
803 (if (ly:duration? (ly:music-property m 'duration))
804 (set! (ly:music-property m 'duration) duration))
805 (if (ly:music-property m 'cautionary #f)
806 (set! (ly:music-property m 'cautionary) #f))
807 (if (ly:music-property m 'force-accidental #f)
808 (set! (ly:music-property m 'force-accidental) #f))))
810 (append! elts (ly:music-property repeat-chord 'elements))))
811 (let ((arts (filter keep-element?
812 (ly:music-property original-chord
815 (set! (ly:music-property repeat-chord 'articulations)
817 (ly:music-deep-copy arts repeat-chord)
818 (ly:music-property repeat-chord 'articulations)))))
822 (define-public (expand-repeat-chords! event-types music)
823 "Walks through @var{music} and fills repeated chords (notable by
824 having a duration in @code{duration}) with the notes from their
825 respective predecessor chord."
826 (let loop ((music music) (last-chord #f))
827 (if (music-is-of-type? music 'event-chord)
828 (let ((chord-repeat (ly:music-property music 'duration)))
830 ((not (ly:duration? chord-repeat))
831 (if (any (lambda (m) (ly:duration?
832 (ly:music-property m 'duration)))
833 (ly:music-property music 'elements))
837 (set! (ly:music-property music 'duration) '())
838 (copy-repeat-chord last-chord music chord-repeat event-types))
840 (ly:music-warning music (_ "Bad chord repetition"))
842 (let ((elt (ly:music-property music 'element)))
843 (fold loop (if (ly:music? elt) (loop elt last-chord) last-chord)
844 (ly:music-property music 'elements)))))
847 ;;; This does _not_ copy any articulations. Rationale: one main
848 ;;; incentive for pitch-repeating durations is after ties, such that
849 ;;; 4~2~8. can stand in for a 15/16 note in \partial 4 position. In
850 ;;; this use case, any repeated articulations will be a nuisance.
852 ;;; String assignments in TabStaff might seem like a worthwhile
853 ;;; exception, but they would be better tackled by the respective
854 ;;; engravers themselves (see issue 3662).
856 ;;; Repeating chords as well seems problematic for things like
859 ;;; \new Staff { c4 c c <c e> }
860 ;;; \new RhythmicStaff { 4 4 4 4 }
864 ;;; However, because of MIDI it is not advisable to use RhythmicStaff
865 ;;; without any initial pitch/drum-type. For music functions taking
866 ;;; pure rhythms as an argument, the running of expand-repeat-notes!
867 ;;; at scorification time is irrelevant: at that point of time, the
868 ;;; music function has already run.
870 (define-public (expand-repeat-notes! music)
871 "Walks through @var{music} and gives pitchless notes (not having a
872 pitch in code{pitch} or a drum type in @code{drum-type}) the pitch(es)
873 from the predecessor note/chord if available."
874 (let ((last-pitch #f))
877 (define (set-and-ret last)
878 (set! last-pitch last)
881 ((music-is-of-type? m 'event-chord)
882 (if (any (lambda (m) (music-is-of-type? m 'rhythmic-event))
883 (ly:music-property m 'elements))
886 ((music-is-of-type? m 'note-event)
888 ((or (ly:music-property m 'pitch #f)
889 (ly:music-property m 'drum-type #f))
891 ;; ok, naked rhythm. Go through the various cases of
893 ;; nothing available: just keep as-is
895 ((ly:pitch? last-pitch)
896 (set! (ly:music-property m 'pitch) last-pitch)
898 ((symbol? last-pitch)
899 (set! (ly:music-property m 'drum-type) last-pitch)
901 ;; Ok, this is the big bad one: the reference is a chord.
902 ;; For now, we use the repeat chord logic. That's not
903 ;; really efficient as cleaning out all articulations is
904 ;; quite simpler than what copy-repeat-chord does.
906 (copy-repeat-chord last-pitch
907 (make-music 'EventChord
909 (ly:music-property m 'articulations)
911 (ly:music-property m 'origin))
912 (ly:music-property m 'duration)
913 '(rhythmic-event)))))
917 ;;; splitting chords into voices.
918 (define (voicify-list lst number)
919 "Make a list of Musics.
921 voicify-list :: [ [Music ] ] -> number -> [Music]
922 LST is a list music-lists.
924 NUMBER is 0-base, i.e., Voice=1 (upstems) has number 0.
928 (cons (context-spec-music
929 (make-sequential-music
930 (list (make-voice-props-set number)
931 (make-simultaneous-music (car lst))))
932 'Bottom (number->string (1+ number)))
933 (voicify-list (cdr lst) (1+ number)))))
935 (define (voicify-chord ch)
936 "Split the parts of a chord into different Voices using separator"
937 (let ((es (ly:music-property ch 'elements)))
938 (set! (ly:music-property ch 'elements)
939 (voicify-list (split-list-by-separator es music-separator?) 0))
942 (define-public (voicify-music m)
943 "Recursively split chords that are separated with @code{\\\\}."
944 (if (not (ly:music? m))
945 (ly:error (_ "music expected: ~S") m))
946 (let ((es (ly:music-property m 'elements))
947 (e (ly:music-property m 'element)))
950 (set! (ly:music-property m 'elements) (map voicify-music es)))
952 (set! (ly:music-property m 'element) (voicify-music e)))
953 (if (and (equal? (ly:music-property m 'name) 'SimultaneousMusic)
954 (any music-separator? es))
955 (set! m (context-spec-music (voicify-chord m) 'Staff)))
958 (define-public (empty-music)
961 ;; Make a function that checks score element for being of a specific type.
962 (define-public (make-type-checker symbol)
964 (grob::has-interface elt symbol)))
966 (define ((outputproperty-compatibility func sym val) grob g-context ao-context)
968 (set! (ly:grob-property grob sym) val)))
969 (export outputproperty-compatibility)
972 (define ((set-output-property grob-name symbol val) grob grob-c context)
974 @code{\\applyoutput #(set-output-property 'Clef 'extra-offset '(0 . 1))}"
975 (let ((meta (ly:grob-property grob 'meta)))
976 (if (equal? (assoc-get 'name meta) grob-name)
977 (set! (ly:grob-property grob symbol) val))))
978 (export set-output-property)
981 (define-public (skip->rest mus)
982 "Replace @var{mus} by @code{RestEvent} of the same duration if it is a
983 @code{SkipEvent}. Useful for extracting parts from crowded scores."
985 (if (memq (ly:music-property mus 'name) '(SkipEvent SkipMusic))
986 (make-music 'RestEvent 'duration (ly:music-property mus 'duration))
990 (define-public (music-clone music . music-properties)
991 "Clone @var{music} and set properties according to
992 @var{music-properties}, a list of alternating property symbols and
994 @example\n(music-clone start-span 'span-direction STOP)
996 Only properties that are not overriden by @var{music-properties} are
997 actually fully cloned."
998 (let ((old-props (list-copy (ly:music-mutable-properties music)))
1000 (m (ly:make-music (ly:prob-immutable-properties music))))
1001 (define (set-props mus-props)
1002 (if (and (not (null? mus-props))
1003 (not (null? (cdr mus-props))))
1005 (set! old-props (assq-remove! old-props (car mus-props)))
1007 (assq-set! new-props
1008 (car mus-props) (cadr mus-props)))
1009 (set-props (cddr mus-props)))))
1010 (set-props music-properties)
1013 (set! (ly:music-property m (car pair))
1014 (ly:music-deep-copy (cdr pair))))
1018 (set! (ly:music-property m (car pair)) (cdr pair)))
1022 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1023 ;; warn for bare chords at start.
1025 (define-public (ly:music-message music msg . rest)
1026 (let ((ip (ly:music-property music 'origin)))
1027 (if (ly:input-location? ip)
1028 (apply ly:input-message ip msg rest)
1029 (apply ly:message msg rest))))
1031 (define-public (ly:music-warning music msg . rest)
1032 (let ((ip (ly:music-property music 'origin)))
1033 (if (ly:input-location? ip)
1034 (apply ly:input-warning ip msg rest)
1035 (apply ly:warning msg rest))))
1037 (define-public (ly:event-warning event msg . rest)
1038 (let ((ip (ly:event-property event 'origin)))
1039 (if (ly:input-location? ip)
1040 (apply ly:input-warning ip msg rest)
1041 (apply ly:warning msg rest))))
1043 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1045 ;; setting stuff for grace context.
1048 (define (vector-extend v x)
1049 "Make a new vector consisting of V, with X added to the end."
1050 (let* ((n (vector-length v))
1051 (nv (make-vector (+ n 1) '())))
1052 (vector-move-left! v 0 n nv 0)
1053 (vector-set! nv n x)
1056 (define (vector-map f v)
1057 "Map F over V. This function returns nothing."
1058 (do ((n (vector-length v))
1061 (f (vector-ref v i))))
1063 (define (vector-reverse-map f v)
1064 "Map F over V, N to 0 order. This function returns nothing."
1065 (do ((i (- (vector-length v) 1) (- i 1)))
1067 (f (vector-ref v i))))
1069 (define-public (add-grace-property context-name grob sym val)
1070 "Set @var{sym}=@var{val} for @var{grob} in @var{context-name}."
1071 (define (set-prop context)
1072 (let* ((where (or (ly:context-find context context-name) context))
1073 (current (ly:context-property where 'graceSettings))
1074 (new-settings (append current
1075 (list (list context-name grob sym val)))))
1076 (ly:context-set-property! where 'graceSettings new-settings)))
1077 (make-apply-context set-prop))
1079 (define-public (remove-grace-property context-name grob sym)
1080 "Remove all @var{sym} for @var{grob} in @var{context-name}."
1081 (define (sym-grob-context? property sym grob context-name)
1082 (and (eq? (car property) context-name)
1083 (eq? (cadr property) grob)
1084 (eq? (caddr property) sym)))
1085 (define (delete-prop context)
1086 (let* ((where (or (ly:context-find context context-name) context))
1087 (current (ly:context-property where 'graceSettings))
1088 (prop-settings (filter
1089 (lambda(x) (sym-grob-context? x sym grob context-name))
1091 (new-settings current))
1092 (for-each (lambda(x)
1093 (set! new-settings (delete x new-settings)))
1095 (ly:context-set-property! where 'graceSettings new-settings)))
1096 (make-apply-context delete-prop))
1099 (defmacro-public def-grace-function (start stop . docstring)
1100 "Helper macro for defining grace music"
1101 `(define-music-function (music) (ly:music?)
1103 (make-music 'GraceMusic
1104 'element (make-music 'SequentialMusic
1105 'elements (list (ly:music-deep-copy ,start)
1107 (ly:music-deep-copy ,stop))))))
1109 (defmacro-public define-syntax-function (type args signature . body)
1110 "Helper macro for `ly:make-music-function'.
1112 (define-syntax-function result-type? (arg1 arg2 ...) (arg1-type arg2-type ...)
1113 ...function body...)
1115 argX-type can take one of the forms @code{predicate?} for mandatory
1116 arguments satisfying the predicate, @code{(predicate?)} for optional
1117 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
1118 value)}} for optional parameters with a specified default
1119 value (evaluated at definition time). An optional parameter can be
1120 omitted in a call only when it can't get confused with a following
1121 parameter of different type.
1123 @code{result-type?} can specify a default in the same manner as
1124 predicates, to be used in case of a type error in arguments or
1127 (define (has-parser/location? arg where)
1128 (let loop ((arg arg))
1132 (define (currying-lambda args doc-string? body)
1133 (if (and (pair? args)
1135 (currying-lambda (car args) doc-string?
1136 `((lambda ,(cdr args) ,@body)))
1137 (let* ((compatibility? (if (list? args)
1138 (= (length args) (+ 2 (length signature)))
1139 (and (pair? args) (pair? (cdr args))
1140 (eq? (car args) 'parser))))
1141 (realargs (if compatibility? (cddr args) args)))
1143 ,(format #f "~a\n~a" realargs (or doc-string? ""))
1144 ,@(if (and compatibility?
1145 (has-parser/location? body (take args 2)))
1146 `((let ((,(car args) (*parser*)) (,(cadr args) (*location*)))
1151 (and (pair? body) (pair? (cdr body))
1152 (if (string? (car body))
1154 (and (pair? (car body))
1155 (eq? '_i (caar body))
1157 (string? (cadar body))
1158 (null? (cddar body))
1160 ;; When the music function definition contains an i10n doc string,
1161 ;; (_i "doc string"), keep the literal string only
1162 `(ly:make-music-function
1163 (list ,@(map (lambda (pred)
1166 ,(and (pair? (cdr pred)) (cadr pred)))
1168 (cons type signature)))
1169 ,(currying-lambda args docstring (if docstring (cdr body) body)))))
1171 (defmacro-public define-music-function rest
1172 "Defining macro returning music functions.
1174 (define-music-function (arg1 arg2 ...) (arg1-type? arg2-type? ...)
1175 ...function body...)
1177 argX-type can take one of the forms @code{predicate?} for mandatory
1178 arguments satisfying the predicate, @code{(predicate?)} for optional
1179 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
1180 value)}} for optional parameters with a specified default
1181 value (evaluated at definition time). An optional parameter can be
1182 omitted in a call only when it can't get confused with a following
1183 parameter of different type.
1185 Must return a music expression. The @code{origin} is automatically
1186 set to the @code{location} parameter."
1188 `(define-syntax-function (ly:music? (make-music 'Music 'void #t)) ,@rest))
1191 (defmacro-public define-scheme-function rest
1192 "Defining macro returning Scheme functions.
1194 (define-scheme-function (arg1 arg2 ...) (arg1-type? arg2-type? ...)
1195 ...function body...)
1197 argX-type can take one of the forms @code{predicate?} for mandatory
1198 arguments satisfying the predicate, @code{(predicate?)} for optional
1199 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
1200 value)}} for optional parameters with a specified default
1201 value (evaluated at definition time). An optional parameter can be
1202 omitted in a call only when it can't get confused with a following
1203 parameter of different type.
1205 Can return arbitrary expressions. If a music expression is returned,
1206 its @code{origin} is automatically set to the @code{location}
1209 `(define-syntax-function scheme? ,@rest))
1211 (defmacro-public define-void-function rest
1212 "This defines a Scheme function like @code{define-scheme-function} with
1213 void return value (i.e., what most Guile functions with `unspecified'
1214 value return). Use this when defining functions for executing actions
1215 rather than returning values, to keep Lilypond from trying to interpret
1217 `(define-syntax-function (void? *unspecified*) ,@rest *unspecified*))
1219 (defmacro-public define-event-function rest
1220 "Defining macro returning event functions.
1222 (define-event-function (arg1 arg2 ...) (arg1-type? arg2-type? ...)
1223 ...function body...)
1225 argX-type can take one of the forms @code{predicate?} for mandatory
1226 arguments satisfying the predicate, @code{(predicate?)} for optional
1227 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
1228 value)}} for optional parameters with a specified default
1229 value (evaluated at definition time). An optional parameter can be
1230 omitted in a call only when it can't get confused with a following
1231 parameter of different type.
1233 Must return an event expression. The @code{origin} is automatically
1234 set to the @code{location} parameter."
1236 `(define-syntax-function (ly:event? (make-music 'Event 'void #t)) ,@rest))
1238 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1240 (define-public (cue-substitute quote-music)
1241 "Must happen after @code{quote-substitute}."
1243 (if (vector? (ly:music-property quote-music 'quoted-events))
1244 (let* ((dir (ly:music-property quote-music 'quoted-voice-direction))
1245 (clef (ly:music-property quote-music 'quoted-music-clef #f))
1246 (main-voice (case dir ((1) 1) ((-1) 0) (else #f)))
1247 (cue-voice (and main-voice (- 1 main-voice)))
1248 (cue-type (ly:music-property quote-music 'quoted-context-type #f))
1249 (cue-id (ly:music-property quote-music 'quoted-context-id))
1250 (main-music (ly:music-property quote-music 'element))
1251 (return-value quote-music))
1254 (set! (ly:music-property quote-music 'element)
1255 (make-sequential-music
1257 (make-voice-props-override main-voice)
1259 (make-voice-props-revert)))))
1261 ;; if we have stem dirs, change both quoted and main music
1262 ;; to have opposite stems.
1264 ;; cannot context-spec Quote-music, since context
1265 ;; for the quotes is determined in the iterator.
1267 (make-sequential-music
1270 (and clef (make-cue-clef-set clef))
1271 (and cue-type cue-voice
1273 (make-voice-props-override cue-voice)
1276 (and cue-type cue-voice
1278 (make-voice-props-revert)
1280 (and clef (make-cue-clef-unset))))))
1283 (define ((quote-substitute quote-tab) music)
1284 (let* ((quoted-name (ly:music-property music 'quoted-music-name))
1285 (quoted-vector (and (string? quoted-name)
1286 (hash-ref quote-tab quoted-name #f))))
1289 (if (string? quoted-name)
1290 (if (vector? quoted-vector)
1292 (set! (ly:music-property music 'quoted-events) quoted-vector)
1293 (set! (ly:music-property music 'iterator-ctor)
1294 ly:quote-iterator::constructor))
1295 (ly:music-warning music (ly:format (_ "cannot find quoted music: `~S'") quoted-name))))
1297 (export quote-substitute)
1300 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1301 ;; switch it on here, so parsing and init isn't checked (too slow!)
1303 ;; automatic music transformations.
1305 (define (switch-on-debugging m)
1306 (if (defined? 'set-debug-cell-accesses!)
1307 (set-debug-cell-accesses! 15000))
1310 (define (music-check-error music)
1313 (if (and (ly:music? m)
1314 (eq? (ly:music-property m 'error-found) #t))
1317 (for-each signal (ly:music-property music 'elements))
1318 (signal (ly:music-property music 'element))
1321 (set! (ly:music-property music 'error-found) #t))
1324 (define (precompute-music-length music)
1325 (set! (ly:music-property music 'length)
1326 (ly:music-length music))
1329 (define-public (make-duration-of-length moment)
1330 "Make duration of the given @code{moment} length."
1331 (ly:make-duration 0 0
1332 (ly:moment-main-numerator moment)
1333 (ly:moment-main-denominator moment)))
1335 (define (make-skipped moment bool)
1336 "Depending on BOOL, set or unset skipTypesetting,
1337 then make SkipMusic of the given MOMENT length, and
1338 then revert skipTypesetting."
1339 (make-sequential-music
1341 (context-spec-music (make-property-set 'skipTypesetting bool)
1343 (make-music 'SkipMusic 'duration
1344 (make-duration-of-length moment))
1345 (context-spec-music (make-property-set 'skipTypesetting (not bool))
1348 (define (skip-as-needed music)
1350 << { \\set skipTypesetting = ##f
1351 LENGTHOF(\\showFirstLength)
1352 \\set skipTypesetting = ##t
1353 LENGTHOF(\\showLastLength) }
1357 When only showFirstLength is set,
1358 the 'length property of the music is
1359 overridden to speed up compiling."
1361 ((show-last (ly:parser-lookup 'showLastLength))
1362 (show-first (ly:parser-lookup 'showFirstLength))
1363 (show-last-length (and (ly:music? show-last)
1364 (ly:music-length show-last)))
1365 (show-first-length (and (ly:music? show-first)
1366 (ly:music-length show-first)))
1367 (orig-length (ly:music-length music)))
1369 ;;FIXME: if using either showFirst- or showLastLength,
1370 ;; make sure that skipBars is not set.
1374 ;; both properties may be set.
1375 ((and show-first-length show-last-length)
1377 ((skip-length (ly:moment-sub orig-length show-last-length)))
1378 (make-simultaneous-music
1380 (make-sequential-music
1382 (make-skipped skip-length #t)
1383 ;; let's draw a separator between the beginning and the end
1384 (context-spec-music (make-property-set 'whichBar "||")
1386 (make-skipped show-first-length #f)
1389 ;; we may only want to print the last length
1392 ((skip-length (ly:moment-sub orig-length show-last-length)))
1393 (make-simultaneous-music
1395 (make-skipped skip-length #t)
1398 ;; we may only want to print the beginning; in this case
1399 ;; only the first length will be processed (much faster).
1401 ;; the first length must not exceed the original length.
1402 (if (ly:moment<? show-first-length orig-length)
1403 (set! (ly:music-property music 'length)
1410 (define-session-public toplevel-music-functions
1412 (lambda (music) (expand-repeat-chords!
1413 (cons 'rhythmic-event
1414 (ly:parser-lookup '$chord-repeat-events))
1416 expand-repeat-notes!
1418 (lambda (x) (music-map music-check-error x))
1419 (lambda (x) (music-map precompute-music-length x))
1421 (music-map (quote-substitute (ly:parser-lookup 'musicQuotes)) music))
1423 ;; switch-on-debugging
1424 (lambda (x) (music-map cue-substitute x))
1429 ;;; general purpose music functions
1431 (define (shift-octave pitch octave-shift)
1432 (_i "Add @var{octave-shift} to the octave of @var{pitch}.")
1434 (+ (ly:pitch-octave pitch) octave-shift)
1435 (ly:pitch-notename pitch)
1436 (ly:pitch-alteration pitch)))
1442 (define (apply-durations lyric-music durations)
1443 (define (apply-duration music)
1444 (if (and (not (equal? (ly:music-length music) ZERO-MOMENT))
1445 (ly:duration? (ly:music-property music 'duration)))
1447 (set! (ly:music-property music 'duration) (car durations))
1448 (set! durations (cdr durations)))))
1450 (music-map apply-duration lyric-music))
1453 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1456 (define (recent-enough? bar-number alteration-def laziness)
1457 (or (number? alteration-def)
1458 (equal? laziness #t)
1459 (<= bar-number (+ (cadr alteration-def) laziness))))
1461 (define (accidental-invalid? alteration-def)
1462 "Checks an alteration entry for being invalid.
1464 Non-key alterations are invalidated when tying into the next bar or
1465 when there is a clef change, since neither repetition nor cancellation
1466 can be omitted when the same note occurs again.
1468 Returns @code{#f} or the reason for the invalidation, a symbol."
1469 (let* ((def (if (pair? alteration-def)
1470 (car alteration-def)
1472 (and (symbol? def) def)))
1474 (define (extract-alteration alteration-def)
1475 (cond ((number? alteration-def)
1477 ((pair? alteration-def)
1478 (car alteration-def))
1481 (define (check-pitch-against-signature context pitch barnum laziness octaveness all-naturals)
1482 "Checks the need for an accidental and a @q{restore} accidental against
1483 @code{localAlterations} and @code{keyAlterations}.
1484 The @var{laziness} is the number of measures
1485 for which reminder accidentals are used (i.e., if @var{laziness} is zero,
1486 only cancel accidentals in the same measure; if @var{laziness} is three,
1487 we cancel accidentals up to three measures after they first appear.
1488 @var{octaveness} is either @code{'same-octave} or @code{'any-octave} and
1489 specifies whether accidentals should be canceled in different octaves.
1490 If @var{all-naturals} is ##t, notes that do not occur in @code{keyAlterations}
1491 also get an accidental."
1492 (let* ((ignore-octave (cond ((equal? octaveness 'any-octave) #t)
1493 ((equal? octaveness 'same-octave) #f)
1495 (ly:warning (_ "Unknown octaveness type: ~S ") octaveness)
1496 (ly:warning (_ "Defaulting to 'any-octave."))
1498 (key (ly:context-property context 'keyAlterations))
1499 (local (ly:context-property context 'localAlterations))
1500 (notename (ly:pitch-notename pitch))
1501 (octave (ly:pitch-octave pitch))
1502 (pitch-handle (cons octave notename))
1504 (need-accidental #f)
1505 (previous-alteration #f)
1506 (from-other-octaves #f)
1507 (from-same-octave (assoc-get pitch-handle local))
1508 (from-key-sig (or (assoc-get notename local)
1510 ;; If no notename match is found from localAlterations, we may have a custom
1511 ;; type with octave-specific entries of the form ((octave . pitch) alteration)
1512 ;; instead of (pitch . alteration). Since this type cannot coexist with entries in
1513 ;; localAlterations, try extracting from keyAlterations instead.
1514 (assoc-get pitch-handle key))))
1516 ;; loop through localAlterations to search for a notename match from other octaves
1517 (let loop ((l local))
1519 (let ((entry (car l)))
1520 (if (and (pair? (car entry))
1521 (= (cdar entry) notename))
1522 (set! from-other-octaves (cdr entry))
1525 ;; find previous alteration-def for comparison with pitch
1527 ;; from same octave?
1528 ((and (not ignore-octave)
1530 (recent-enough? barnum from-same-octave laziness))
1531 (set! previous-alteration from-same-octave))
1536 (recent-enough? barnum from-other-octaves laziness))
1537 (set! previous-alteration from-other-octaves))
1539 ;; not recent enough, extract from key signature/local key signature
1541 (set! previous-alteration from-key-sig)))
1543 (if (accidental-invalid? previous-alteration)
1544 (set! need-accidental #t)
1546 (let* ((prev-alt (extract-alteration previous-alteration))
1547 (this-alt (ly:pitch-alteration pitch)))
1549 (if (or (and all-naturals (eq? #f previous-alteration)) (not (= this-alt prev-alt)))
1551 (set! need-accidental #t)
1552 (if (and (not (= this-alt 0))
1553 (and (< (abs this-alt) (abs prev-alt))
1554 (> (* prev-alt this-alt) 0)))
1555 (set! need-restore #t))))))
1557 (cons need-restore need-accidental)))
1559 (define ((make-accidental-rule octaveness laziness) context pitch barnum measurepos)
1560 "Create an accidental rule that makes its decision based on the octave of
1561 the note and a laziness value.
1563 @var{octaveness} is either @code{'same-octave} or @code{'any-octave} and
1564 defines whether the rule should respond to accidental changes in other
1565 octaves than the current. @code{'same-octave} is the normal way to typeset
1566 accidentals -- an accidental is made if the alteration is different from the
1567 last active pitch in the same octave. @code{'any-octave} looks at the last
1568 active pitch in any octave.
1570 @var{laziness} states over how many bars an accidental should be remembered.
1571 @code{0}@tie{}is the default -- accidental lasts over 0@tie{}bar lines, that
1572 is, to the end of current measure. A positive integer means that the
1573 accidental lasts over that many bar lines. @w{@code{-1}} is `forget
1574 immediately', that is, only look at key signature. @code{#t} is `forever'."
1576 (check-pitch-against-signature context pitch barnum laziness octaveness #f))
1577 (export make-accidental-rule)
1579 (define ((make-accidental-dodecaphonic-rule octaveness laziness) context pitch barnum measurepos)
1580 "Variation on function make-accidental-rule that creates an dodecaphonic
1583 (check-pitch-against-signature context pitch barnum laziness octaveness #t))
1584 (export make-accidental-dodecaphonic-rule)
1586 (define (key-entry-notename entry)
1587 "Return the pitch of an @var{entry} in @code{localAlterations}.
1588 The @samp{car} of the entry is either of the form @code{notename} or
1589 of the form @code{(octave . notename)}. The latter form is used for special
1590 key signatures or to indicate an explicit accidental.
1592 The @samp{cdr} of the entry is either a rational @code{alter} indicating
1593 a key signature alteration, or of the form
1594 @code{(alter . (barnum . measurepos))} indicating an alteration caused by
1595 an accidental in music."
1596 (if (pair? (car entry))
1600 (define (key-entry-octave entry)
1601 "Return the octave of an entry in @code{localAlterations}
1602 or @code{#f} if the entry does not have an octave.
1603 See @code{key-entry-notename} for details."
1604 (and (pair? (car entry)) (caar entry)))
1606 (define (key-entry-bar-number entry)
1607 "Return the bar number of an entry in @code{localAlterations}
1608 or @code {#f} if the entry does not have a bar number.
1609 See @code{key-entry-notename} for details."
1610 (and (pair? (cdr entry)) (caddr entry)))
1612 (define (key-entry-measure-position entry)
1613 "Return the measure position of an entry in @code{localAlterations}
1614 or @code {#f} if the entry does not have a measure position.
1615 See @code{key-entry-notename} for details."
1616 (and (pair? (cdr entry)) (cdddr entry)))
1618 (define (key-entry-alteration entry)
1619 "Return the alteration of an entry in localAlterations
1621 For convenience, returns @code{0} if entry is @code{#f}."
1623 (if (number? (cdr entry))
1628 (define-public (find-pitch-entry keysig pitch accept-global accept-local)
1629 "Return the first entry in @var{keysig} that matches @var{pitch}
1630 by notename and octave. Alteration is not considered.
1631 @var{accept-global} states whether key signature entries should be included.
1632 @var{accept-local} states whether local accidentals should be included.
1633 If no matching entry is found, @var{#f} is returned."
1635 (let* ((entry (car keysig))
1636 (entryoct (key-entry-octave entry))
1637 (entrynn (key-entry-notename entry))
1638 (nn (ly:pitch-notename pitch)))
1639 (if (and (equal? nn entrynn)
1641 (= entryoct (ly:pitch-octave pitch)))
1642 (if (key-entry-bar-number entry)
1646 (find-pitch-entry (cdr keysig) pitch accept-global accept-local)))))
1648 (define-public (neo-modern-accidental-rule context pitch barnum measurepos)
1649 "An accidental rule that typesets an accidental if it differs from the
1650 key signature @emph{and} does not directly follow a note on the same
1651 staff line. This rule should not be used alone because it does neither
1652 look at bar lines nor different accidentals at the same note name."
1653 (let* ((keysig (ly:context-property context 'localAlterations))
1654 (entry (find-pitch-entry keysig pitch #t #t)))
1657 (let* ((global-entry (find-pitch-entry keysig pitch #t #f))
1658 (key-acc (key-entry-alteration global-entry))
1659 (acc (ly:pitch-alteration pitch))
1660 (entrymp (key-entry-measure-position entry))
1661 (entrybn (key-entry-bar-number entry)))
1662 (cons #f (not (or (equal? acc key-acc)
1663 (and (equal? entrybn barnum) (equal? entrymp measurepos)))))))))
1665 (define-public (dodecaphonic-no-repeat-rule context pitch barnum measurepos)
1666 "An accidental rule that typesets an accidental before every
1667 note (just as in the dodecaphonic accidental style) @emph{except} if
1668 the note is immediately preceded by a note with the same pitch. This
1669 is a common accidental style in contemporary notation."
1670 (let* ((keysig (ly:context-property context 'localAlterations))
1671 (entry (find-pitch-entry keysig pitch #f #t)))
1674 (let ((entrymp (key-entry-measure-position entry))
1675 (entrybn (key-entry-bar-number entry))
1676 (entryalt (key-entry-alteration entry))
1677 (alt (ly:pitch-alteration pitch)))
1679 (not (and (equal? entrybn barnum)
1680 (or (equal? measurepos entrymp)
1681 (ly:moment<? measurepos entrymp))
1682 (equal? entryalt alt))))))))
1684 (define-public (teaching-accidental-rule context pitch barnum measurepos)
1685 "An accidental rule that typesets a cautionary accidental if it is
1686 included in the key signature @emph{and} does not directly follow a note
1687 on the same staff line."
1688 (let* ((keysig (ly:context-property context 'localAlterations))
1689 (entry (find-pitch-entry keysig pitch #t #t)))
1692 (let* ((global-entry (find-pitch-entry keysig pitch #f #f))
1693 (key-acc (key-entry-alteration global-entry))
1694 (acc (ly:pitch-alteration pitch))
1695 (entrymp (key-entry-measure-position entry))
1696 (entrybn (key-entry-bar-number entry)))
1697 (cons #f (not (or (equal? acc key-acc)
1698 (and (equal? entrybn barnum) (equal? entrymp measurepos)))))))))
1700 (define-public (set-accidentals-properties extra-natural
1701 auto-accs auto-cauts
1704 (make-sequential-music
1705 (append (if (boolean? extra-natural)
1706 (list (make-property-set 'extraNatural extra-natural))
1708 (list (make-property-set 'autoAccidentals auto-accs)
1709 (make-property-set 'autoCautionaries auto-cauts))))
1712 (define-public (set-accidental-style style . rest)
1713 "Set accidental style to @var{style}. Optionally take a context
1714 argument, e.g. @code{'Staff} or @code{'Voice}. The context defaults
1715 to @code{Staff}, except for piano styles, which use @code{GrandStaff}
1717 (let ((context (if (pair? rest)
1719 (pcontext (if (pair? rest)
1720 (car rest) 'GrandStaff)))
1722 ;; accidentals as they were common in the 18th century.
1723 ((equal? style 'default)
1724 (set-accidentals-properties #t
1725 `(Staff ,(make-accidental-rule 'same-octave 0))
1728 ;; accidentals from one voice do NOT get canceled in other voices
1729 ((equal? style 'voice)
1730 (set-accidentals-properties #t
1731 `(Voice ,(make-accidental-rule 'same-octave 0))
1734 ;; accidentals as suggested by Kurt Stone, Music Notation in the 20th century.
1735 ;; This includes all the default accidentals, but accidentals also needs canceling
1736 ;; in other octaves and in the next measure.
1737 ((equal? style 'modern)
1738 (set-accidentals-properties #f
1739 `(Staff ,(make-accidental-rule 'same-octave 0)
1740 ,(make-accidental-rule 'any-octave 0)
1741 ,(make-accidental-rule 'same-octave 1))
1744 ;; the accidentals that Stone adds to the old standard as cautionaries
1745 ((equal? style 'modern-cautionary)
1746 (set-accidentals-properties #f
1747 `(Staff ,(make-accidental-rule 'same-octave 0))
1748 `(Staff ,(make-accidental-rule 'any-octave 0)
1749 ,(make-accidental-rule 'same-octave 1))
1751 ;; same as modern, but accidentals different from the key signature are always
1752 ;; typeset - unless they directly follow a note of the same pitch.
1753 ((equal? style 'neo-modern)
1754 (set-accidentals-properties #f
1755 `(Staff ,(make-accidental-rule 'same-octave 0)
1756 ,(make-accidental-rule 'any-octave 0)
1757 ,(make-accidental-rule 'same-octave 1)
1758 ,neo-modern-accidental-rule)
1761 ((equal? style 'neo-modern-cautionary)
1762 (set-accidentals-properties #f
1763 `(Staff ,(make-accidental-rule 'same-octave 0))
1764 `(Staff ,(make-accidental-rule 'any-octave 0)
1765 ,(make-accidental-rule 'same-octave 1)
1766 ,neo-modern-accidental-rule)
1768 ((equal? style 'neo-modern-voice)
1769 (set-accidentals-properties #f
1770 `(Voice ,(make-accidental-rule 'same-octave 0)
1771 ,(make-accidental-rule 'any-octave 0)
1772 ,(make-accidental-rule 'same-octave 1)
1773 ,neo-modern-accidental-rule
1774 Staff ,(make-accidental-rule 'same-octave 0)
1775 ,(make-accidental-rule 'any-octave 0)
1776 ,(make-accidental-rule 'same-octave 1)
1777 ,neo-modern-accidental-rule)
1780 ((equal? style 'neo-modern-voice-cautionary)
1781 (set-accidentals-properties #f
1782 `(Voice ,(make-accidental-rule 'same-octave 0))
1783 `(Voice ,(make-accidental-rule 'any-octave 0)
1784 ,(make-accidental-rule 'same-octave 1)
1785 ,neo-modern-accidental-rule
1786 Staff ,(make-accidental-rule 'same-octave 0)
1787 ,(make-accidental-rule 'any-octave 0)
1788 ,(make-accidental-rule 'same-octave 1)
1789 ,neo-modern-accidental-rule)
1791 ;; Accidentals as they were common in dodecaphonic music with no tonality.
1792 ;; Each note gets one accidental.
1793 ((equal? style 'dodecaphonic)
1794 (set-accidentals-properties #f
1795 `(Staff ,(lambda (c p bn mp) '(#f . #t)))
1798 ;; As in dodecaphonic style with the exception that immediately
1799 ;; repeated notes (in the same voice) don't get an accidental
1800 ((equal? style 'dodecaphonic-no-repeat)
1801 (set-accidentals-properties #f
1802 `(Staff ,dodecaphonic-no-repeat-rule)
1805 ;; Variety of the dodecaphonic style. Each note gets an accidental,
1806 ;; except notes that were already handled in the same measure.
1807 ((equal? style 'dodecaphonic-first)
1808 (set-accidentals-properties #f
1809 `(Staff ,(make-accidental-dodecaphonic-rule 'same-octave 0))
1813 ;; Multivoice accidentals to be read both by musicians playing one voice
1814 ;; and musicians playing all voices.
1815 ;; Accidentals are typeset for each voice, but they ARE canceled across voices.
1816 ((equal? style 'modern-voice)
1817 (set-accidentals-properties #f
1818 `(Voice ,(make-accidental-rule 'same-octave 0)
1819 ,(make-accidental-rule 'any-octave 0)
1820 ,(make-accidental-rule 'same-octave 1)
1821 Staff ,(make-accidental-rule 'same-octave 0)
1822 ,(make-accidental-rule 'any-octave 0)
1823 ,(make-accidental-rule 'same-octave 1))
1826 ;; same as modernVoiceAccidental eccept that all special accidentals are typeset
1828 ((equal? style 'modern-voice-cautionary)
1829 (set-accidentals-properties #f
1830 `(Voice ,(make-accidental-rule 'same-octave 0))
1831 `(Voice ,(make-accidental-rule 'any-octave 0)
1832 ,(make-accidental-rule 'same-octave 1)
1833 Staff ,(make-accidental-rule 'same-octave 0)
1834 ,(make-accidental-rule 'any-octave 0)
1835 ,(make-accidental-rule 'same-octave 1))
1837 ;; stone's suggestions for accidentals on grand staff.
1838 ;; Accidentals are canceled across the staves in the same grand staff as well
1839 ((equal? style 'piano)
1840 (set-accidentals-properties #f
1841 `(Staff ,(make-accidental-rule 'same-octave 0)
1842 ,(make-accidental-rule 'any-octave 0)
1843 ,(make-accidental-rule 'same-octave 1)
1845 ,(make-accidental-rule 'any-octave 0)
1846 ,(make-accidental-rule 'same-octave 1))
1849 ((equal? style 'piano-cautionary)
1850 (set-accidentals-properties #f
1851 `(Staff ,(make-accidental-rule 'same-octave 0))
1852 `(Staff ,(make-accidental-rule 'any-octave 0)
1853 ,(make-accidental-rule 'same-octave 1)
1855 ,(make-accidental-rule 'any-octave 0)
1856 ,(make-accidental-rule 'same-octave 1))
1859 ;; same as modern, but cautionary accidentals are printed for all sharp or flat
1860 ;; tones specified by the key signature.
1861 ((equal? style 'teaching)
1862 (set-accidentals-properties #f
1863 `(Staff ,(make-accidental-rule 'same-octave 0))
1864 `(Staff ,(make-accidental-rule 'same-octave 1)
1865 ,teaching-accidental-rule)
1868 ;; do not set localAlterations when a note alterated differently from
1869 ;; localAlterations is found.
1870 ;; Causes accidentals to be printed at every note instead of
1871 ;; remembered for the duration of a measure.
1872 ;; accidentals not being remembered, causing accidentals always to
1873 ;; be typeset relative to the time signature
1874 ((equal? style 'forget)
1875 (set-accidentals-properties '()
1876 `(Staff ,(make-accidental-rule 'same-octave -1))
1879 ;; Do not reset the key at the start of a measure. Accidentals will be
1880 ;; printed only once and are in effect until overridden, possibly many
1882 ((equal? style 'no-reset)
1883 (set-accidentals-properties '()
1884 `(Staff ,(make-accidental-rule 'same-octave #t))
1888 (ly:warning (_ "unknown accidental style: ~S") style)
1889 (make-sequential-music '())))))
1891 (define-public (invalidate-alterations context)
1892 "Invalidate alterations in @var{context}.
1894 Elements of @code{'localAlterations} corresponding to local
1895 alterations of the key signature have the form
1896 @code{'((octave . notename) . (alter barnum . measurepos))}.
1897 Replace them with a version where @code{alter} is set to @code{'clef}
1898 to force a repetition of accidentals.
1900 Entries that conform with the current key signature are not invalidated."
1901 (let* ((keysig (ly:context-property context 'keyAlterations)))
1902 (set! (ly:context-property context 'localAlterations)
1905 (let* ((localalt (key-entry-alteration entry)))
1906 (if (or (accidental-invalid? localalt)
1907 (not (key-entry-bar-number entry))
1909 (key-entry-alteration
1912 (ly:make-pitch (key-entry-octave entry)
1913 (key-entry-notename entry)
1917 (cons (car entry) (cons 'clef (cddr entry))))))
1918 (ly:context-property context 'localAlterations)))))
1920 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1922 (define-public (skip-of-length mus)
1923 "Create a skip of exactly the same length as @var{mus}."
1927 'duration (ly:make-duration 0 0))))
1929 (make-event-chord (list (ly:music-compress skip (ly:music-length mus))))))
1931 (define-public (mmrest-of-length mus)
1932 "Create a multi-measure rest of exactly the same length as @var{mus}."
1935 (make-multi-measure-rest
1936 (ly:make-duration 0 0) '())))
1937 (ly:music-compress skip (ly:music-length mus))
1940 (define-public (pitch-of-note event-chord)
1941 (let ((evs (filter (lambda (x)
1942 (music-is-of-type? x 'note-event))
1943 (ly:music-property event-chord 'elements))))
1946 (ly:music-property (car evs) 'pitch))))
1948 (define-public (duration-of-note event-chord)
1950 ((pair? event-chord)
1951 (or (duration-of-note (car event-chord))
1952 (duration-of-note (cdr event-chord))))
1953 ((ly:music? event-chord)
1954 (let ((dur (ly:music-property event-chord 'duration)))
1955 (if (ly:duration? dur)
1957 (duration-of-note (ly:music-property event-chord 'elements)))))
1960 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1962 (define-public (map-some-music map? music)
1963 "Walk through @var{music}, transform all elements calling @var{map?}
1964 and only recurse if this returns @code{#f}. @code{elements} or
1965 @code{articulations} that are not music expressions are discarded:
1966 this allows some amount of filtering.
1968 @code{map-some-music} may overwrite the original @var{music}."
1969 (let loop ((music music))
1971 (let ((elt (ly:music-property music 'element))
1972 (elts (ly:music-property music 'elements))
1973 (arts (ly:music-property music 'articulations)))
1975 (set! (ly:music-property music 'element)
1978 (set! (ly:music-property music 'elements)
1979 (filter! ly:music? (map! loop elts))))
1981 (set! (ly:music-property music 'articulations)
1982 (filter! ly:music? (map! loop arts))))
1985 (define-public (for-some-music stop? music)
1986 "Walk through @var{music}, process all elements calling @var{stop?}
1987 and only recurse if this returns @code{#f}."
1988 (let loop ((music music))
1989 (if (not (stop? music))
1990 (let ((elt (ly:music-property music 'element)))
1993 (for-each loop (ly:music-property music 'elements))
1994 (for-each loop (ly:music-property music 'articulations))))))
1996 (define-public (fold-some-music pred? proc init music)
1997 "This works recursively on music like @code{fold} does on a list,
1998 calling @samp{(@var{pred?} music)} on every music element. If
1999 @code{#f} is returned for an element, it is processed recursively
2000 with the same initial value of @samp{previous}, otherwise
2001 @samp{(@var{proc} music previous)} replaces @samp{previous}
2002 and no recursion happens.
2003 The top @var{music} is processed using @var{init} for @samp{previous}."
2004 (let loop ((music music) (previous init))
2006 (proc music previous)
2009 (let ((elt (ly:music-property music 'element)))
2012 (loop elt previous)))
2013 (ly:music-property music 'elements))
2014 (ly:music-property music 'articulations)))))
2016 (define-public (extract-music music pred?)
2017 "Return a flat list of all music matching @var{pred?} inside of
2018 @var{music}, not recursing into matches themselves."
2019 (reverse! (fold-some-music pred? cons '() music)))
2021 (define-public (extract-named-music music music-name)
2022 "Return a flat list of all music named @var{music-name} (either a
2023 single event symbol or a list of alternatives) inside of @var{music},
2024 not recursing into matches themselves."
2027 (if (cheap-list? music-name)
2028 (lambda (m) (memq (ly:music-property m 'name) music-name))
2029 (lambda (m) (eq? (ly:music-property m 'name) music-name)))))
2031 (define-public (extract-typed-music music type)
2032 "Return a flat list of all music with @var{type} (either a single
2033 type symbol or a list of alternatives) inside of @var{music}, not
2034 recursing into matches themselves."
2035 (extract-music music (music-type-predicate type)))
2037 (define-public (event-chord-wrap! music)
2038 "Wrap isolated rhythmic events and non-postevent events in
2039 @var{music} inside of an @code{EventChord}. Chord repeats @samp{q}
2040 are expanded using the default settings of the parser."
2043 (cond ((music-is-of-type? m 'event-chord)
2044 (if (pair? (ly:music-property m 'articulations))
2046 (set! (ly:music-property m 'elements)
2047 (append (ly:music-property m 'elements)
2048 (ly:music-property m 'articulations)))
2049 (set! (ly:music-property m 'articulations) '())))
2051 ((music-is-of-type? m 'rhythmic-event)
2052 (let ((arts (ly:music-property m 'articulations)))
2054 (set! (ly:music-property m 'articulations) '()))
2055 (make-event-chord (cons m arts))))
2057 (expand-repeat-notes!
2058 (expand-repeat-chords!
2059 (cons 'rhythmic-event
2060 (ly:parser-lookup '$chord-repeat-events))
2063 (define-public (event-chord-notes event-chord)
2064 "Return a list of all notes from @var{event-chord}."
2066 (lambda (m) (eq? 'NoteEvent (ly:music-property m 'name)))
2067 (ly:music-property event-chord 'elements)))
2069 (define-public (event-chord-pitches event-chord)
2070 "Return a list of all pitches from @var{event-chord}."
2071 (map (lambda (x) (ly:music-property x 'pitch))
2072 (event-chord-notes event-chord)))
2074 (define-public (event-chord-reduce music)
2075 "Reduces event chords in @var{music} to their first note event,
2076 retaining only the chord articulations. Returns the modified music."
2079 (and (music-is-of-type? m 'event-chord)
2080 (let*-values (((notes arts) (partition
2082 (music-is-of-type? mus 'rhythmic-event))
2083 (ly:music-property m 'elements)))
2084 ((dur) (ly:music-property m 'duration))
2085 ((full-arts) (append arts
2086 (ly:music-property m 'articulations)))
2087 ((first-note) (and (pair? notes) (car notes))))
2089 (set! (ly:music-property first-note 'articulations)
2093 ;; A repeat chord. Produce an unpitched note.
2094 (make-music 'NoteEvent
2096 'articulations full-arts))
2098 (ly:music-error m (_ "Missing duration"))
2099 (make-music 'NoteEvent
2100 'duration (ly:make-duration 2 0 0)
2101 'articulations full-arts))))))
2105 (defmacro-public make-relative (variables reference music)
2106 "The list of pitch or music variables in @var{variables} is used as
2107 a sequence for creating relativable music from @var{music}.
2109 When the constructed music is used outside of @code{\\relative}, it
2110 just reflects plugging in the @var{variables} into @var{music}.
2112 The action inside of @code{\\relative}, however, is determined by
2113 first relativizing the surrogate @var{reference} with the variables
2114 plugged in and then using the variables relativized as a side effect
2115 of relativizing @var{reference} for evaluating @var{music}.
2117 Since pitches don't have the object identity required for tracing the
2118 effect of the reference call, they are replaced @emph{only} for the
2119 purpose of evaluating @var{reference} with simple pitched note events.
2121 The surrogate @var{reference} expression has to be written with that
2122 in mind. In addition, it must @emph{not} contain @emph{copies} of
2123 music that is supposed to be relativized but rather the
2124 @emph{originals}. This @emph{includes} the pitch expressions. As a
2125 rule, inside of @code{#@{@dots{}#@}} variables must @emph{only} be
2126 introduced using @code{#}, never via the copying construct @code{$}.
2127 The reference expression will usually just be a sequential or chord
2128 expression naming all variables in sequence, implying that following
2129 music will be relativized according to the resulting pitch of the last
2130 or first variable, respectively.
2132 Since the usual purpose is to create more complex music from general
2133 arguments and since music expression parts must not occur more than
2134 once, one @emph{does} generally need to use copying operators in the
2135 @emph{replacement} expression @var{music} when using an argument more
2136 than once there. Using an argument more than once in @var{reference},
2137 in contrast, does not make sense.
2139 There is another fine point to mind: @var{music} must @emph{only}
2140 contain freshly constructed elements or copied constructs. This will
2141 be the case anyway for regular LilyPond code inside of
2142 @code{#@{@dots{}#@}}, but any other elements (apart from the
2143 @var{variables} themselves which are already copied) must be created
2146 The reason is that it is usually permitted to change music in-place as
2147 long as one does a @var{ly:music-deep-copy} on it, and such a copy of
2148 the whole resulting expression will @emph{not} be able to copy
2149 variables/values inside of closures where the information for
2150 relativization is being stored.
2153 ;; pitch and music generator might be stored instead in music
2154 ;; properties, and it might make sense to create a music type of its
2155 ;; own for this kind of construct rather than using
2156 ;; RelativeOctaveMusic
2157 (define ((make-relative::to-relative-callback variables music-call ref-call)
2159 (let* ((ref-vars (map (lambda (v)
2161 (make-music 'NoteEvent 'pitch v)
2162 (ly:music-deep-copy v)))
2164 (after-pitch (ly:make-music-relative! (apply ref-call ref-vars) pitch))
2165 (actual-vars (map (lambda (v r)
2167 (ly:music-property r 'pitch)
2169 variables ref-vars))
2170 (rel-music (apply music-call actual-vars)))
2171 (set! (ly:music-property music 'element) rel-music)
2173 `(make-music 'RelativeOctaveMusic
2174 'to-relative-callback
2175 (,make-relative::to-relative-callback
2177 (lambda ,variables ,music)
2178 (lambda ,variables ,reference))
2181 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2182 ;; The following functions are all associated with the crossStaff
2185 (define (close-enough? x y)
2186 "Values are close enough to ignore the difference"
2187 (< (abs (- x y)) 0.0001))
2189 (define (extent-combine extents)
2190 "Combine a list of extents"
2191 (if (pair? (cdr extents))
2192 (interval-union (car extents) (extent-combine (cdr extents)))
2195 (define ((stem-connectable? ref root) stem)
2196 "Check if the stem is connectable to the root"
2197 ;; The root is always connectable to itself
2200 ;; Horizontal positions of the stems must be almost the same
2201 (close-enough? (car (ly:grob-extent root ref X))
2202 (car (ly:grob-extent stem ref X)))
2203 ;; The stem must be in the direction away from the root's notehead
2204 (positive? (* (ly:grob-property root 'direction)
2205 (- (car (ly:grob-extent stem ref Y))
2206 (car (ly:grob-extent root ref Y))))))))
2208 (define (stem-span-stencil span)
2209 "Connect stems if we have at least one stem connectable to the root"
2210 (let* ((system (ly:grob-system span))
2211 (root (ly:grob-parent span X))
2212 (stems (filter (stem-connectable? system root)
2213 (ly:grob-object span 'stems))))
2214 (if (<= 2 (length stems))
2215 (let* ((yextents (map (lambda (st)
2216 (ly:grob-extent st system Y)) stems))
2217 (yextent (extent-combine yextents))
2218 (layout (ly:grob-layout root))
2219 (blot (ly:output-def-lookup layout 'blot-diameter)))
2220 ;; Hide spanned stems
2221 (for-each (lambda (st)
2222 (set! (ly:grob-property st 'stencil) #f))
2224 ;; Draw a nice looking stem with rounded corners
2225 (ly:round-filled-box (ly:grob-extent root root X) yextent blot))
2226 ;; Nothing to connect, don't draw the span
2229 (define ((make-stem-span! stems trans) root)
2230 "Create a stem span as a child of the cross-staff stem (the root)"
2231 (let ((span (ly:engraver-make-grob trans 'Stem '())))
2232 (ly:grob-set-parent! span X root)
2233 (set! (ly:grob-object span 'stems) stems)
2234 ;; Suppress positioning, the stem code is confused by this weird stem
2235 (set! (ly:grob-property span 'X-offset) 0)
2236 (set! (ly:grob-property span 'stencil) stem-span-stencil)))
2238 (define-public (cross-staff-connect stem)
2239 "Set cross-staff property of the stem to this function to connect it to
2240 other stems automatically"
2243 (define (stem-is-root? stem)
2244 "Check if automatic connecting of the stem was requested. Stems connected
2245 to cross-staff beams are cross-staff, but they should not be connected to
2246 other stems just because of that."
2247 (eq? cross-staff-connect (ly:grob-property-data stem 'cross-staff)))
2249 (define (make-stem-spans! ctx stems trans)
2250 "Create stem spans for cross-staff stems"
2251 ;; Cannot do extensive checks here, just make sure there are at least
2252 ;; two stems at this musical moment
2253 (if (<= 2 (length stems))
2254 (let ((roots (filter stem-is-root? stems)))
2255 (for-each (make-stem-span! stems trans) roots))))
2257 (define-public (Span_stem_engraver ctx)
2258 "Connect cross-staff stems to the stems above in the system"
2261 ;; Record all stems for the given moment
2263 ((stem-interface trans grob source)
2264 (set! stems (cons grob stems))))
2265 ;; Process stems and reset the stem list to empty
2266 ((process-acknowledged trans)
2267 (make-stem-spans! ctx stems trans)
2268 (set! stems '())))))
2270 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2271 ;; The following is used by the alterBroken function.
2273 (define ((value-for-spanner-piece arg) grob)
2274 "Associate a piece of broken spanner @var{grob} with an element
2276 (let* ((orig (ly:grob-original grob))
2277 (siblings (ly:spanner-broken-into orig)))
2279 (define (helper sibs arg)
2282 (if (eq? (car sibs) grob)
2284 (helper (cdr sibs) (cdr arg)))))
2286 (if (>= (length siblings) 2)
2287 (helper siblings arg)
2289 (export value-for-spanner-piece)
2291 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2292 ;; The following are used by the \offset function
2294 (define (find-value-to-offset prop self alist)
2295 "Return the first value of the property @var{prop} in the property
2296 alist @var{alist} -- after having found @var{self}. If @var{self} is
2297 not found, return the first value of @var{prop}."
2298 (let ((segment (member (cons prop self) alist)))
2300 (assoc-get prop alist)
2301 (assoc-get prop (cdr segment)))))
2303 (define (offset-multiple-types arg offsets)
2304 "Displace @var{arg} by @var{offsets} if @var{arg} is a number, a
2305 number pair, or a list of number pairs. If @var{offsets} is an empty
2306 list or if there is a type-mismatch, @var{arg} will be returned."
2308 ((and (number? arg) (number? offsets))
2310 ((and (number-pair? arg)
2311 (or (number? offsets)
2312 (number-pair? offsets)))
2313 (coord-translate arg offsets))
2314 ((and (number-pair-list? arg) (number-pair-list? offsets))
2316 (lambda (x y) (coord-translate x y))
2320 (define-public (grob-transformer property func)
2321 "Create an override value good for applying @var{func} to either
2322 pure or unpure values. @var{func} is called with the respective grob
2323 as first argument and the default value (after resolving all callbacks)
2325 (define (worker self container-part grob . rest)
2326 (let* ((immutable (ly:grob-basic-properties grob))
2327 ;; We need to search the basic-properties alist for our
2328 ;; property to obtain values to offset. Our search is
2329 ;; complicated by the fact that calling the music function
2330 ;; `offset' as an override conses a pair to the head of the
2331 ;; alist. This pair must be discounted. The closure it
2332 ;; contains is named `self' so it can be easily recognized.
2333 ;; If `offset' is called as a tweak, the basic-property
2334 ;; alist is unaffected.
2335 (target (find-value-to-offset property self immutable))
2336 ;; if target is a procedure, we need to apply it to our
2337 ;; grob to calculate values to offset.
2338 (vals (cond ((procedure? target) (target grob))
2339 ;; Argument lists for a pure procedure pulled
2340 ;; from an unpure-pure-container may be
2341 ;; different from a normal procedure, so we
2342 ;; need a different code path and calling
2343 ;; convention for procedures pulled from an
2344 ;; container as opposed to from the property
2345 ((ly:unpure-pure-container? target)
2346 (let ((part (container-part target)))
2347 (if (procedure? part)
2348 (apply part grob rest)
2352 ;; return the container named `self'. The container self-reference
2353 ;; seems like chasing its own tail but gets dissolved by
2354 ;; define/lambda separating binding and referencing of "self".
2355 (define self (ly:make-unpure-pure-container
2357 (worker self ly:unpure-pure-container-unpure-part grob))
2358 (lambda (grob . rest)
2359 (apply worker self ly:unpure-pure-container-pure-part
2363 (define-public (offsetter property offsets)
2364 "Apply @var{offsets} to the default values of @var{property} of @var{grob}.
2365 Offsets are restricted to immutable properties and values of type @code{number},
2366 @code{number-pair}, or @code{number-pair-list}."
2367 (define (offset-fun grob vals)
2368 (let ((can-type-be-offset?
2371 (number-pair-list? vals))))
2372 (if can-type-be-offset?
2373 ;; '(+inf.0 . -inf.0) would offset to itself. This will be
2374 ;; confusing to a user unaware of the default value of the
2375 ;; property, so issue a warning.
2376 (if (equal? empty-interval vals)
2377 (ly:warning "default '~a of ~a is ~a and can't be offset"
2379 (let* ((orig (ly:grob-original grob))
2381 (if (ly:spanner? grob)
2382 (ly:spanner-broken-into orig)
2384 (total-found (length siblings))
2385 ;; Since there is some flexibility in input
2386 ;; syntax, structure of `offsets' is normalized.
2388 (if (or (not (pair? offsets))
2389 (number-pair? offsets)
2390 (and (number-pair-list? offsets)
2391 (number-pair-list? vals)))
2395 (define (helper sibs offs)
2396 ;; apply offsets to the siblings of broken spanners
2398 (if (eq? (car sibs) grob)
2399 (offset-multiple-types vals (car offs))
2400 (helper (cdr sibs) (cdr offs)))
2403 (if (>= total-found 2)
2404 (helper siblings offsets)
2405 (offset-multiple-types vals (car offsets)))))
2408 (ly:warning "the property '~a of ~a cannot be offset" property grob)
2410 (grob-transformer property offset-fun))
2412 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2413 ;; \magnifyMusic and \magnifyStaff
2415 ;; defined as a function instead of a list because the
2416 ;; all-grob-descriptions alist is not available yet
2417 (define-public (find-named-props prop-name grob-descriptions)
2418 "Used by @code{\\magnifyMusic} and @code{\\magnifyStaff}. When
2419 @var{grob-descriptions} is equal to the @code{all-grob-descriptions}
2420 alist (defined in @file{scm/define-grobs.scm}), this will find all grobs
2421 that can have a value for the @var{prop-name} property, and return them
2422 as a list in the following format:
2428 (define (find-grobs-with-interface interface grob-descriptions)
2429 (define (has-this-interface? grob-desc)
2430 (let* ((meta (ly:assoc-get 'meta (cdr grob-desc)))
2431 (interfaces (ly:assoc-get 'interfaces meta '())))
2432 (memq interface interfaces)))
2433 (let* ((grob-descriptions-with-this-interface
2434 (filter has-this-interface? grob-descriptions))
2435 (grob-names-with-this-interface
2436 (map car grob-descriptions-with-this-interface)))
2437 grob-names-with-this-interface))
2440 ((baseline-skip word-space) 'text-interface)
2441 ((space-alist) 'break-aligned-interface)
2442 (else (ly:programming-error
2443 "find-named-props: no interface associated with ~s"
2445 (grobs-with-this-prop
2446 (find-grobs-with-interface interface grob-descriptions)))
2447 (map (lambda (x) (list x prop-name))
2448 grobs-with-this-prop)))
2451 (define (magnifyStaff-is-set? context mag)
2452 (let* ((Staff (ly:context-find context 'Staff))
2453 (old-mag (ly:context-property Staff 'magnifyStaffValue)))
2454 (not (null? old-mag))))
2456 (define (staff-magnification-is-changing? context mag)
2457 (let* ((Staff (ly:context-find context 'Staff))
2458 (old-mag (ly:context-property Staff 'magnifyStaffValue 1)))
2459 (not (= old-mag mag))))
2461 (define-public (scale-fontSize func-name mag)
2462 "Used by @code{\\magnifyMusic} and @code{\\magnifyStaff}. Look up the
2463 current @code{fontSize} in the appropriate context and scale it by the
2464 magnification factor @var{mag}. @var{func-name} is either
2465 @code{'magnifyMusic} or @code{'magnifyStaff}."
2468 (if (or (eq? func-name 'magnifyMusic)
2469 ;; for \magnifyStaff, only scale the fontSize
2470 ;; if staff magnification is changing
2471 ;; and does not equal 1
2472 (and (staff-magnification-is-changing? context mag)
2474 (let* ((where (case func-name
2475 ((magnifyMusic) context)
2476 ((magnifyStaff) (ly:context-find context 'Staff))))
2477 (fontSize (ly:context-property where 'fontSize 0))
2478 (new-fontSize (+ fontSize (magnification->font-size mag))))
2479 (ly:context-set-property! where 'fontSize new-fontSize))))))
2481 (define-public (revert-fontSize func-name mag)
2482 "Used by @code{\\magnifyMusic} and @code{\\magnifyStaff}. Calculate
2483 the previous @code{fontSize} value (before scaling) by factoring out the
2484 magnification factor @var{mag} (if @var{func-name} is
2485 @code{'magnifyMusic}), or by factoring out the context property
2486 @code{magnifyStaffValue} (if @var{func-name} is @code{'magnifyStaff}).
2487 Revert the @code{fontSize} in the appropriate context accordingly.
2489 With @code{\\magnifyMusic}, the scaling is reverted after the music
2490 block it operates on. @code{\\magnifyStaff} does not operate on a music
2491 block, so the scaling from a previous call (if there is one) is reverted
2492 before the new scaling takes effect."
2495 (if (or (eq? func-name 'magnifyMusic)
2496 ;; for \magnifyStaff...
2498 ;; don't revert the user's fontSize choice
2499 ;; the first time \magnifyStaff is called
2500 (magnifyStaff-is-set? context mag)
2501 ;; only revert the previous fontSize
2502 ;; if staff magnification is changing
2503 (staff-magnification-is-changing? context mag)))
2506 ((magnifyMusic) context)
2507 ((magnifyStaff) (ly:context-find context 'Staff))))
2510 ((magnifyMusic) mag)
2512 (ly:context-property where 'magnifyStaffValue 1))))
2513 (fontSize (ly:context-property where 'fontSize 0))
2514 (old-fontSize (- fontSize (magnification->font-size old-mag))))
2515 (ly:context-set-property! where 'fontSize old-fontSize))))))
2517 (define-public (scale-props func-name mag allowed-to-shrink? props)
2518 "Used by @code{\\magnifyMusic} and @code{\\magnifyStaff}. For each
2519 prop in @var{props}, find the current value of the requested prop, scale
2520 it by the magnification factor @var{mag}, and do the equivalent of a
2521 @code{\\temporary@tie{}\\override} with the new value in the appropriate
2522 context. If @var{allowed-to-shrink?} is @code{#f}, don't let the new
2523 value be less than the current value. @var{func-name} is either
2524 @code{'magnifyMusic} or @code{'magnifyStaff}. The @var{props} list is
2528 (Slur line-thickness)
2533 (define (scale-prop grob-prop-list)
2534 (let* ((grob (car grob-prop-list))
2535 (prop (cadr grob-prop-list))
2536 (where (if (eq? grob 'SpacingSpanner)
2537 (ly:context-find context 'Score)
2539 ((magnifyMusic) context)
2540 ((magnifyStaff) (ly:context-find context 'Staff)))))
2541 (grob-def (ly:context-grob-definition where grob)))
2542 (if (eq? prop 'space-alist)
2543 (let* ((space-alist (ly:assoc-get prop grob-def))
2544 (scale-spacing-tuple (lambda (x)
2547 (* mag (cddr x))))))
2548 (scaled-tuples (if space-alist
2549 (map scale-spacing-tuple space-alist)
2551 (new-alist (append scaled-tuples space-alist)))
2552 (ly:context-pushpop-property where grob prop new-alist))
2553 (let* ((val (ly:assoc-get prop grob-def (case prop
2558 (if allowed-to-shrink?
2560 (* x (max 1 mag)))))
2561 (new-val (if (number-pair? val)
2562 (cons (proc (car val))
2565 (ly:context-pushpop-property where grob prop new-val)))))
2566 (if (or (eq? func-name 'magnifyMusic)
2567 ;; for \magnifyStaff, only scale the properties
2568 ;; if staff magnification is changing
2569 ;; and does not equal 1
2570 (and (staff-magnification-is-changing? context mag)
2572 (for-each scale-prop props)))))
2574 (define-public (revert-props func-name mag props)
2575 "Used by @code{\\magnifyMusic} and @code{\\magnifyStaff}. Revert each
2576 prop in @var{props} in the appropriate context. @var{func-name} is
2577 either @code{'magnifyMusic} or @code{'magnifyStaff}. The @var{props}
2578 list is formatted like:
2581 (Slur line-thickness)
2586 (define (revert-prop grob-prop-list)
2587 (let* ((grob (car grob-prop-list))
2588 (prop (cadr grob-prop-list))
2589 (where (if (eq? grob 'SpacingSpanner)
2590 (ly:context-find context 'Score)
2592 ((magnifyMusic) context)
2593 ((magnifyStaff) (ly:context-find context 'Staff))))))
2594 (ly:context-pushpop-property where grob prop)))
2595 (if (or (eq? func-name 'magnifyMusic)
2596 ;; for \magnifyStaff...
2598 ;; don't revert the user's property overrides
2599 ;; the first time \magnifyStaff is called
2600 (magnifyStaff-is-set? context mag)
2601 ;; revert the overrides from the previous \magnifyStaff,
2602 ;; but only if staff magnification is changing
2603 (staff-magnification-is-changing? context mag)))
2604 (for-each revert-prop props)))))
2606 ;; \magnifyMusic only
2607 (define-public (scale-beam-thickness mag)
2608 "Used by @code{\\magnifyMusic}. Scaling @code{Beam.beam-thickness}
2609 exactly to the @var{mag} value will not work. This uses two reference
2610 values for @code{beam-thickness} to determine an acceptable value when
2611 scaling, then does the equivalent of a
2612 @code{\\temporary@tie{}\\override} with the new value."
2615 (let* ((grob-def (ly:context-grob-definition context 'Beam))
2616 (val (ly:assoc-get 'beam-thickness grob-def 0.48))
2617 (ratio-to-default (/ val 0.48))
2618 ;; gives beam-thickness=0.48 when mag=1 (like default),
2619 ;; gives beam-thickness=0.35 when mag=0.63 (like CueVoice)
2620 (scaled-default (+ 119/925 (* mag 13/37)))
2621 (new-val (* scaled-default ratio-to-default)))
2622 (ly:context-pushpop-property context 'Beam 'beam-thickness new-val)))))
2627 (define tag-groups (make-hash-table))
2628 (call-after-session (lambda () (hash-clear! tag-groups)))
2630 (define-public (define-tag-group tags)
2631 "Define a tag-group consisting of the given @var{tags}, a@tie{}list
2632 of symbols. Returns @code{#f} if successful, and an error message if
2633 there is a conflicting tag group definition."
2634 (cond ((not (symbol-list? tags)) (format #f (_ "not a symbol list: ~a") tags))
2635 ((any (lambda (tag) (hashq-ref tag-groups tag)) tags)
2636 => (lambda (group) (and (not (lset= eq? group tags))
2637 (format #f (_ "conflicting tag group ~a") group))))
2640 (lambda (elt) (hashq-set! tag-groups elt tags))
2644 (define-public (tag-group-get tag)
2645 "Return the tag group (as a list of symbols) that the given
2646 @var{tag} symbol belongs to, @code{#f} if none."
2647 (hashq-ref tag-groups tag))
2649 (define-public (tags-remove-predicate tags)
2650 "Returns a predicate that returns @code{#f} for any music that is to
2651 be removed by @{\\removeWithTag} on the given symbol or list of
2652 symbols @var{tags}."
2655 (not (memq tags (ly:music-property m 'tags))))
2657 (not (any (lambda (t) (memq t tags))
2658 (ly:music-property m 'tags))))))
2660 (define-public (tags-keep-predicate tags)
2661 "Returns a predicate that returns @code{#f} for any music that is to
2662 be removed by @{\\keepWithTag} on the given symbol or list of symbols
2665 (let ((group (tag-group-get tags)))
2667 (let ((music-tags (ly:music-property m 'tags)))
2669 (null? music-tags) ; redundant but very frequent
2670 ;; We know of only one tag to keep. Either we find it in
2671 ;; the music tags, or all music tags must be from a
2673 (memq tags music-tags)
2674 (not (any (lambda (t) (eq? (tag-group-get t) group)) music-tags))))))
2675 (let ((groups (delete-duplicates (map tag-group-get tags) eq?)))
2677 (let ((music-tags (ly:music-property m 'tags)))
2679 (null? music-tags) ; redundant but very frequent
2680 (any (lambda (t) (memq t tags)) music-tags)
2681 ;; if no tag matches, no tag group should match either
2682 (not (any (lambda (t) (memq (tag-group-get t) groups)) music-tags))))))))