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 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 inner-music-filter as)))
91 (filtered-e (if (ly:music? e)
92 (inner-music-filter e)
94 (filtered-es (filter ly:music? (map inner-music-filter 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 invalidated 'element, we remove the music unless
102 ;; there are remaining 'elements in which case we just hope and
104 (if (or (not (pred? music))
105 (and (null? filtered-es)
106 (not (ly:music? filtered-e))
111 (set! music (inner-music-filter music))
112 (if (ly:music? music)
114 (make-music 'Music))) ;must return music.
116 (define*-public (display-music music #:optional (port (current-output-port)))
117 "Display music, not done with @code{music-map} for clarity of
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)
125 (begin (display "\nElements: {\n" port)
126 (for-each (lambda (m) (display-music m port)) es)
127 (display "}\n" port)))
130 (display "\nChild:" port)
131 (display-music e port))))
132 (display " }\n" port)
136 ;;; A scheme music pretty printer
138 (define (markup-expression->make-markup markup-expression)
139 "Transform `markup-expression' into an equivalent, hopefuly readable, scheme expression.
141 \\markup \\bold \\italic hello
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))
155 (music->make-music arg))))
156 (define (inner-markup->make-markup mrkup)
159 (let ((cmd (proc->command-keyword (car mrkup)))
160 (args (map transform-arg (cdr mrkup))))
163 (if (string? markup-expression)
165 `(markup ,@(inner-markup->make-markup markup-expression))))
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
175 (markup-expression->make-markup obj))
179 ',(ly:music-property obj 'name)
180 ,@(append-map (lambda (prop)
182 ,(music->make-music (cdr prop))))
183 (remove (lambda (prop)
184 (eqv? (car prop) 'origin))
185 (ly:music-mutable-properties obj)))))
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)
197 (denominator grace)))))))
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)))))
207 `(ly:make-pitch ,(ly:pitch-octave obj)
208 ,(ly:pitch-notename obj)
209 ,@(if-nonzero (ly:pitch-alteration obj))))
212 (or (procedure-name obj) obj))
213 (;; a symbol (avoid having an unquoted symbol)
216 (;; an empty list (avoid having an unquoted empty list)
221 `(list ,@(map music->make-music obj)))
224 `(cons ,(music->make-music (car obj))
225 ,(music->make-music (cdr obj))))
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)
237 ;;; Scheme music expression --> Lily-syntax-using string translator
239 (use-modules (srfi srfi-39)
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)
251 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
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)))
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)))
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) '())
269 (define-public (shift-duration-log music shift dot)
270 (music-map (lambda (x) (shift-one-duration-log x shift dot))
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
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))))
290 (let ((dur (first-note-duration (car elts))))
291 (if (ly:duration? 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
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)
308 (ash 1 duration-log))
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
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)))
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
328 (list (make-music 'TremoloEvent
330 'tremolo-type tremolo-type
331 'origin (ly:music-property tremolo 'origin))
333 (list (make-music 'TremoloSpanEvent
334 'span-direction START
336 'tremolo-type tremolo-type
337 'origin (ly:music-property tremolo 'origin))
339 (make-music 'TremoloSpanEvent
341 'origin (ly:music-property tremolo 'origin))))))
343 (define-public (make-repeat name times main alts)
344 "Create a repeat music expression, with all properties initialized
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))
354 (ly:warning (_ "More alternatives than repeats. Junking excess alternatives"))
359 'repeat-count (max times 1)
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)))
372 (if (every (lambda (d) (equal? d first-dur)) durs)
373 (max (- (ly:duration-log first-dur) 2) 1)
376 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
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))
387 (define-public (notes-to-clusters music)
388 (music-map note-to-cluster music))
390 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
393 (define-public (unfold-repeats music)
394 "Replace all repeats with unfolded repeats."
395 (let ((es (ly:music-property music 'elements))
396 (e (ly:music-property music 'element)))
397 (if (music-is-of-type? music 'repeated-music)
398 (set! music (make-music 'UnfoldedRepeatedMusic music)))
400 (set! (ly:music-property music 'elements)
401 (map unfold-repeats es)))
403 (set! (ly:music-property music 'element)
407 (define-public (unfold-repeats-fully music)
408 "Unfolds repeats and expands the resulting @code{unfolded-repeated-music}."
411 (and (music-is-of-type? m 'unfolded-repeated-music)
412 (make-sequential-music
413 (ly:music-deep-copy (make-unfolded-set m)))))
414 (unfold-repeats music)))
416 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
417 ;; property setting music objs.
419 (define-safe-public (check-grob-path path #:optional location
425 "Check a grob path specification @var{path}, a symbol list (or a
426 single symbol), for validity and possibly complete it. Returns the
427 completed specification, or @code{#f} if invalid. If optional
428 @var{parser} is given, a syntax error is raised in that case,
429 optionally using @var{location}. If an optional keyword argument
430 @code{#:start @var{start}} is given, the parsing starts at the given
431 index in the sequence @samp{Context.Grob.property.sub-property...},
432 with the default of @samp{0} implying the full path.
434 If there is no valid first element of @var{path} fitting at the given
435 path location, an optionally given @code{#:default @var{default}} is
436 used as the respective element instead without checking it for
437 validity at this position.
439 The resulting path after possibly prepending @var{default} can be
440 constrained in length by optional arguments @code{#:min @var{min}} and
441 @code{#:max @var{max}}, defaulting to @samp{1} and unlimited,
443 (let ((path (if (symbol? path) (list path) path)))
444 ;; A Guile 1.x bug specific to optargs precludes moving the
445 ;; defines out of the let
446 (define (unspecial? s)
447 (not (or (object-property s 'is-grob?)
448 (object-property s 'backend-type?))))
450 (object-property s 'is-grob?))
451 (define (property? s)
452 (object-property s 'backend-type?))
453 (define (check c p) (c p))
457 (drop (list unspecial? grob? property?) start)))
461 ;; tricky. Should we make use of the default when the
462 ;; list is empty? In most cases, this question should be
463 ;; academical as an empty list can only be generated by
464 ;; Scheme and is likely an error. We consider this a case
465 ;; of "no valid first element, and default given".
466 ;; Usually, invalid use cases should be caught later using
467 ;; the #:min argument, and if the user explicitly does not
468 ;; catch this, we just follow through.
469 (if default (list default) '()))
471 ;; no checkers, so we have a valid first element and just
472 ;; take the path as-is.
475 (if ((car checkers) (car path))
476 (and (every check (cdr checkers) (cdr path))
478 (and (every check (cdr checkers) path)
479 (cons default path))))
481 (and (every check checkers path)
484 (if max (<= min (length res) max)
485 (<= min (length res))))
489 (format #f (_ "bad grob property path ~a")
494 (define-safe-public (check-context-path path #:optional location)
495 "Check a context property path specification @var{path}, a symbol
496 list (or a single symbol), for validity and possibly complete it.
497 Returns the completed specification, or @code{#f} when rising an
498 error (using optionally @code{location})."
499 (let* ((path (if (symbol? path) (list path) path)))
500 ;; A Guile 1.x bug specific to optargs precludes moving the
501 ;; defines out of the let
502 (define (property? s)
503 (object-property s 'translation-type?))
504 (define (unspecial? s)
506 (define (check c p) (c p))
507 (or (case (length path)
508 ((1) (and (property? (car path)) (cons 'Bottom path)))
509 ((2) (and (unspecial? (car path)) (property? (cadr path)) path))
513 (format #f (_ "bad context property ~a")
518 (define-safe-public (check-music-path path #:optional location #:key default)
519 "Check a music property path specification @var{path}, a symbol
520 list (or a single symbol), for validity and possibly complete it.
521 Returns the completed specification, or @code{#f} when rising an
522 error (using optionally @code{location})."
523 (let* ((path (if (symbol? path) (list path) path)))
524 ;; A Guile 1.x bug specific to optargs precludes moving the
525 ;; defines out of the let
526 (define (property? s)
527 (object-property s 'music-type?))
528 (define (unspecial? s)
530 (or (case (length path)
531 ((1) (and (property? (car path)) (cons default path)))
532 ((2) (and (unspecial? (car path)) (property? (cadr path)) path))
536 (format #f (_ "bad music property ~a")
541 (define-public (make-grob-property-set grob gprop val)
542 "Make a @code{Music} expression that overrides a @var{gprop} to
543 @var{val} in @var{grob}. Does a pop first, i.e. this is not a
544 @code{\\temporary \\override}."
545 (make-music 'OverrideProperty
551 (define-public (make-grob-property-override grob gprop val)
552 "Make a @code{Music} expression that overrides @var{gprop} to
553 @var{val} in @var{grob}. This is a @code{\\temporary \\override},
554 making it possible to @code{\\revert} to any previous value afterwards."
555 (make-music 'OverrideProperty
560 (define-public (make-grob-property-revert grob gprop)
561 "Revert the grob property @var{gprop} for @var{grob}."
562 (make-music 'RevertProperty
564 'grob-property gprop))
566 (define direction-polyphonic-grobs
567 '(AccidentalSuggestion
585 (define general-grace-settings
586 `((Voice Stem font-size -3)
587 (Voice Flag font-size -3)
588 (Voice NoteHead font-size -3)
589 (Voice TabNoteHead font-size -4)
590 (Voice Dots font-size -3)
591 (Voice Stem length-fraction 0.8)
592 (Voice Stem no-stem-extend #t)
593 (Voice Beam beam-thickness 0.384)
594 (Voice Beam length-fraction 0.8)
595 (Voice Accidental font-size -4)
596 (Voice AccidentalCautionary font-size -4)
597 (Voice Script font-size -3)
598 (Voice Fingering font-size -8)
599 (Voice StringNumber font-size -8)))
601 (define-public score-grace-settings
603 `((Voice Stem direction ,UP)
604 (Voice Slur direction ,DOWN))
605 general-grace-settings))
607 ;; Getting a unique context id name
609 (define-session unique-counter -1)
610 (define-safe-public (get-next-unique-voice-name)
611 (set! unique-counter (1+ unique-counter))
612 (format #f "uniqueContext~s" unique-counter))
615 (define-safe-public (make-voice-props-set n)
616 (make-sequential-music
618 (map (lambda (x) (make-grob-property-set x 'direction
620 direction-polyphonic-grobs)
622 (make-property-set 'graceSettings general-grace-settings)
623 (make-grob-property-set 'NoteColumn 'horizontal-shift (quotient n 2))))))
625 (define-safe-public (make-voice-props-override n)
626 (make-sequential-music
628 (map (lambda (x) (make-grob-property-override x 'direction
630 direction-polyphonic-grobs)
632 (make-property-set 'graceSettings general-grace-settings)
633 (make-grob-property-override 'NoteColumn 'horizontal-shift (quotient n 2))))))
635 (define-safe-public (make-voice-props-revert)
636 (make-sequential-music
638 (map (lambda (x) (make-grob-property-revert x 'direction))
639 direction-polyphonic-grobs)
640 (list (make-property-unset 'graceSettings)
641 (make-grob-property-revert 'NoteColumn 'horizontal-shift)))))
644 (define-safe-public (context-spec-music m context #:optional id mods)
645 "Add \\context @var{context} = @var{id} \\with @var{mods} to @var{m}."
646 (let ((cm (make-music 'ContextSpeccedMusic
648 'context-type context)))
650 (set! (ly:music-property cm 'context-id) id))
652 (set! (ly:music-property cm 'property-operations)
653 (if (ly:context-mod? mods)
654 (ly:get-context-mods mods)
658 (define-safe-public (descend-to-context m context #:optional id mods)
659 "Like @code{context-spec-music}, but only descending."
660 (let ((cm (context-spec-music m context id mods)))
661 (ly:music-set-property! cm 'descend-only #t)
664 (define-public (make-non-relative-music mus)
665 (make-music 'UnrelativableMusic
668 (define-public (make-apply-context func)
669 (make-music 'ApplyContext
672 (define-public (make-sequential-music elts)
673 (make-music 'SequentialMusic
676 (define-public (make-simultaneous-music elts)
677 (make-music 'SimultaneousMusic
680 (define-safe-public (make-event-chord elts)
681 (make-music 'EventChord
684 (define-public (make-skip-music dur)
685 (make-music 'SkipMusic
688 (define-public (make-grace-music music)
689 (make-music 'GraceMusic
695 (define-public (make-multi-measure-rest duration location)
696 (make-music 'MultiMeasureRestMusic
700 (define-public (make-property-set sym val)
701 (make-music 'PropertySet
705 (define-public (make-property-unset sym)
706 (make-music 'PropertyUnset
709 (define-safe-public (make-articulation name . properties)
710 (apply make-music 'ArticulationEvent
711 'articulation-type name
714 (define-public (make-lyric-event string duration)
715 (make-music 'LyricEvent
719 (define-safe-public (make-span-event type span-dir)
721 'span-direction span-dir))
723 (define-public (override-head-style heads style)
724 "Override style for @var{heads} to @var{style}."
725 (make-sequential-music
728 (make-grob-property-override h 'style style))
730 (list (make-grob-property-override heads 'style style)))))
732 (define-public (revert-head-style heads)
733 "Revert style for @var{heads}."
734 (make-sequential-music
737 (make-grob-property-revert h 'style))
739 (list (make-grob-property-revert heads 'style)))))
741 (define-public (style-note-heads heads style music)
742 "Set @var{style} for all @var{heads} in @var{music}. Works both
743 inside of and outside of chord construct."
744 ;; are we inside a <...>?
745 (if (eq? (ly:music-property music 'name) 'NoteEvent)
746 ;; yes -> use a tweak
748 (set! (ly:music-property music 'tweaks)
749 (acons 'style style (ly:music-property music 'tweaks)))
751 ;; not in <...>, so use overrides
752 (make-sequential-music
754 (override-head-style heads style)
756 (revert-head-style heads)))))
758 (define-public (set-mus-properties! m alist)
759 "Set all of @var{alist} as properties of @var{m}."
762 (set! (ly:music-property m (caar alist)) (cdar alist))
763 (set-mus-properties! m (cdr alist)))))
765 (define-public (music-separator? m)
766 "Is @var{m} a separator?"
767 (let ((ts (ly:music-property m 'types)))
768 (memq 'separator ts)))
770 ;;; expanding repeat chords
771 (define-public (copy-repeat-chord original-chord repeat-chord duration
773 "Copies all events in @var{event-types} (be sure to include
774 @code{rhythmic-events}) from @var{original-chord} over to
775 @var{repeat-chord} with their articulations filtered as well. Any
776 duration is replaced with the specified @var{duration}."
777 ;; First remove everything from event-types that can already be
778 ;; found in the repeated chord. We don't need to look for
779 ;; articulations on individual events since they can't actually get
780 ;; into a repeat chord given its input syntax.
782 (define keep-element? (music-type-predicate event-types))
786 (for-each (lambda (e)
787 (for-each (lambda (x)
788 (set! event-types (delq x event-types)))
789 (ly:music-property e 'types)))
790 (ly:music-property repeat-chord field)))
791 '(elements articulations))
793 ;; now treat the elements
794 (set! (ly:music-property repeat-chord 'elements)
796 (ly:music-deep-copy (filter keep-element?
797 (ly:music-property original-chord
802 (let ((arts (ly:music-property m 'articulations)))
804 (set! (ly:music-property m 'articulations)
805 (ly:set-origin! (filter! keep-element? arts)
807 (if (ly:duration? (ly:music-property m 'duration))
808 (set! (ly:music-property m 'duration) duration))
809 (if (ly:music-property m 'cautionary #f)
810 (set! (ly:music-property m 'cautionary) #f))
811 (if (ly:music-property m 'force-accidental #f)
812 (set! (ly:music-property m 'force-accidental) #f))))
814 (append! elts (ly:music-property repeat-chord 'elements))))
815 (let ((arts (filter keep-element?
816 (ly:music-property original-chord
819 (set! (ly:music-property repeat-chord 'articulations)
821 (ly:music-deep-copy arts repeat-chord)
822 (ly:music-property repeat-chord 'articulations)))))
826 (define-public (expand-repeat-chords! event-types music)
827 "Walks through @var{music} and fills repeated chords (notable by
828 having a duration in @code{duration}) with the notes from their
829 respective predecessor chord."
830 (let loop ((music music) (last-chord #f))
831 (if (music-is-of-type? music 'event-chord)
832 (let ((chord-repeat (ly:music-property music 'duration)))
834 ((not (ly:duration? chord-repeat))
835 (if (any (lambda (m) (ly:duration?
836 (ly:music-property m 'duration)))
837 (ly:music-property music 'elements))
841 (set! (ly:music-property music 'duration) '())
842 (copy-repeat-chord last-chord music chord-repeat event-types))
844 (ly:music-warning music (_ "Bad chord repetition"))
846 (let ((elt (ly:music-property music 'element)))
847 (fold loop (if (ly:music? elt) (loop elt last-chord) last-chord)
848 (ly:music-property music 'elements)))))
851 ;;; This does _not_ copy any articulations. Rationale: one main
852 ;;; incentive for pitch-repeating durations is after ties, such that
853 ;;; 4~2~8. can stand in for a 15/16 note in \partial 4 position. In
854 ;;; this use case, any repeated articulations will be a nuisance.
856 ;;; String assignments in TabStaff might seem like a worthwhile
857 ;;; exception, but they would be better tackled by the respective
858 ;;; engravers themselves (see issue 3662).
860 ;;; Repeating chords as well seems problematic for things like
863 ;;; \new Staff { c4 c c <c e> }
864 ;;; \new RhythmicStaff { 4 4 4 4 }
868 ;;; However, because of MIDI it is not advisable to use RhythmicStaff
869 ;;; without any initial pitch/drum-type. For music functions taking
870 ;;; pure rhythms as an argument, the running of expand-repeat-notes!
871 ;;; at scorification time is irrelevant: at that point of time, the
872 ;;; music function has already run.
874 (define-public (expand-repeat-notes! music)
875 "Walks through @var{music} and gives pitchless notes (not having a
876 pitch in code{pitch} or a drum type in @code{drum-type}) the pitch(es)
877 from the predecessor note/chord if available."
878 (let ((last-pitch #f))
881 (define (set-and-ret last)
882 (set! last-pitch last)
885 ((music-is-of-type? m 'event-chord)
886 (if (any (lambda (m) (music-is-of-type? m 'rhythmic-event))
887 (ly:music-property m 'elements))
890 ((music-is-of-type? m 'note-event)
892 ((or (ly:music-property m 'pitch #f)
893 (ly:music-property m 'drum-type #f))
895 ;; ok, naked rhythm. Go through the various cases of
897 ;; nothing available: just keep as-is
899 ((ly:pitch? last-pitch)
900 (set! (ly:music-property m 'pitch) last-pitch)
902 ((symbol? last-pitch)
903 (set! (ly:music-property m 'drum-type) last-pitch)
905 ;; Ok, this is the big bad one: the reference is a chord.
906 ;; For now, we use the repeat chord logic. That's not
907 ;; really efficient as cleaning out all articulations is
908 ;; quite simpler than what copy-repeat-chord does.
910 (copy-repeat-chord last-pitch
911 (make-music 'EventChord
913 (ly:music-property m 'articulations)
915 (ly:music-property m 'origin))
916 (ly:music-property m 'duration)
917 '(rhythmic-event)))))
921 ;;; splitting chords into voices.
922 (define (voicify-list lst number)
923 "Make a list of Musics.
925 voicify-list :: [ [Music ] ] -> number -> [Music]
926 LST is a list music-lists.
928 NUMBER is 0-base, i.e., Voice=1 (upstems) has number 0.
932 (cons (context-spec-music
933 (make-sequential-music
934 (list (make-voice-props-set number)
935 (make-simultaneous-music (car lst))))
936 'Bottom (number->string (1+ number)))
937 (voicify-list (cdr lst) (1+ number)))))
939 (define (voicify-chord ch)
940 "Split the parts of a chord into different Voices using separator"
941 (let ((es (ly:music-property ch 'elements)))
942 (set! (ly:music-property ch 'elements)
943 (voicify-list (split-list-by-separator es music-separator?) 0))
946 (define-public (voicify-music m)
947 "Recursively split chords that are separated with @code{\\\\}."
948 (if (not (ly:music? m))
949 (ly:error (_ "music expected: ~S") m))
950 (let ((es (ly:music-property m 'elements))
951 (e (ly:music-property m 'element)))
954 (set! (ly:music-property m 'elements) (map voicify-music es)))
956 (set! (ly:music-property m 'element) (voicify-music e)))
957 (if (and (equal? (ly:music-property m 'name) 'SimultaneousMusic)
958 (any music-separator? es))
959 (set! m (context-spec-music (voicify-chord m) 'Staff)))
962 (define-public (empty-music)
965 ;; Make a function that checks score element for being of a specific type.
966 (define-public (make-type-checker symbol)
968 (grob::has-interface elt symbol)))
970 (define ((outputproperty-compatibility func sym val) grob g-context ao-context)
972 (set! (ly:grob-property grob sym) val)))
973 (export outputproperty-compatibility)
976 (define ((set-output-property grob-name symbol val) grob grob-c context)
978 @code{\\applyoutput #(set-output-property 'Clef 'extra-offset '(0 . 1))}"
979 (let ((meta (ly:grob-property grob 'meta)))
980 (if (equal? (assoc-get 'name meta) grob-name)
981 (set! (ly:grob-property grob symbol) val))))
982 (export set-output-property)
985 (define-public (skip->rest mus)
986 "Replace @var{mus} by @code{RestEvent} of the same duration if it is a
987 @code{SkipEvent}. Useful for extracting parts from crowded scores."
989 (if (memq (ly:music-property mus 'name) '(SkipEvent SkipMusic))
990 (make-music 'RestEvent 'duration (ly:music-property mus 'duration))
994 (define-public (music-clone music . music-properties)
995 "Clone @var{music} and set properties according to
996 @var{music-properties}, a list of alternating property symbols and
998 @example\n(music-clone start-span 'span-direction STOP)
1000 Only properties that are not overriden by @var{music-properties} are
1001 actually fully cloned."
1002 (let ((old-props (list-copy (ly:music-mutable-properties music)))
1004 (m (ly:make-music (ly:prob-immutable-properties music))))
1005 (define (set-props mus-props)
1006 (if (and (not (null? mus-props))
1007 (not (null? (cdr mus-props))))
1009 (set! old-props (assq-remove! old-props (car mus-props)))
1011 (assq-set! new-props
1012 (car mus-props) (cadr mus-props)))
1013 (set-props (cddr mus-props)))))
1014 (set-props music-properties)
1017 (set! (ly:music-property m (car pair))
1018 (ly:music-deep-copy (cdr pair))))
1022 (set! (ly:music-property m (car pair)) (cdr pair)))
1026 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1027 ;; warn for bare chords at start.
1029 (define-public (ly:music-message music msg . rest)
1030 (let ((ip (ly:music-property music 'origin)))
1031 (if (ly:input-location? ip)
1032 (apply ly:input-message ip msg rest)
1033 (apply ly:message msg rest))))
1035 (define-public (ly:music-warning music msg . rest)
1036 (let ((ip (ly:music-property music 'origin)))
1037 (if (ly:input-location? ip)
1038 (apply ly:input-warning ip msg rest)
1039 (apply ly:warning msg rest))))
1041 (define-public (ly:event-warning event msg . rest)
1042 (let ((ip (ly:event-property event 'origin)))
1043 (if (ly:input-location? ip)
1044 (apply ly:input-warning ip msg rest)
1045 (apply ly:warning msg rest))))
1047 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1049 ;; setting stuff for grace context.
1052 (define (vector-extend v x)
1053 "Make a new vector consisting of V, with X added to the end."
1054 (let* ((n (vector-length v))
1055 (nv (make-vector (+ n 1) '())))
1056 (vector-move-left! v 0 n nv 0)
1057 (vector-set! nv n x)
1060 (define (vector-map f v)
1061 "Map F over V. This function returns nothing."
1062 (do ((n (vector-length v))
1065 (f (vector-ref v i))))
1067 (define (vector-reverse-map f v)
1068 "Map F over V, N to 0 order. This function returns nothing."
1069 (do ((i (- (vector-length v) 1) (- i 1)))
1071 (f (vector-ref v i))))
1073 (define-public (add-grace-property context-name grob sym val)
1074 "Set @var{sym}=@var{val} for @var{grob} in @var{context-name}."
1075 (define (set-prop context)
1076 (let* ((where (or (ly:context-find context context-name) context))
1077 (current (ly:context-property where 'graceSettings))
1078 (new-settings (append current
1079 (list (list context-name grob sym val)))))
1080 (ly:context-set-property! where 'graceSettings new-settings)))
1081 (make-apply-context set-prop))
1083 (define-public (remove-grace-property context-name grob sym)
1084 "Remove all @var{sym} for @var{grob} in @var{context-name}."
1085 (define (sym-grob-context? property sym grob context-name)
1086 (and (eq? (car property) context-name)
1087 (eq? (cadr property) grob)
1088 (eq? (caddr property) sym)))
1089 (define (delete-prop context)
1090 (let* ((where (or (ly:context-find context context-name) context))
1091 (current (ly:context-property where 'graceSettings))
1092 (prop-settings (filter
1093 (lambda(x) (sym-grob-context? x sym grob context-name))
1095 (new-settings current))
1096 (for-each (lambda(x)
1097 (set! new-settings (delete x new-settings)))
1099 (ly:context-set-property! where 'graceSettings new-settings)))
1100 (make-apply-context delete-prop))
1103 (defmacro-public def-grace-function (start stop . docstring)
1104 "Helper macro for defining grace music"
1105 `(define-music-function (music) (ly:music?)
1107 (make-music 'GraceMusic
1108 'element (make-music 'SequentialMusic
1109 'elements (list (ly:music-deep-copy ,start)
1111 (ly:music-deep-copy ,stop))))))
1113 (defmacro-public define-syntax-function (type args signature . body)
1114 "Helper macro for `ly:make-music-function'.
1116 (define-syntax-function result-type? (arg1 arg2 ...) (arg1-type arg2-type ...)
1117 ...function body...)
1119 argX-type can take one of the forms @code{predicate?} for mandatory
1120 arguments satisfying the predicate, @code{(predicate?)} for optional
1121 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
1122 value)}} for optional parameters with a specified default
1123 value (evaluated at definition time). An optional parameter can be
1124 omitted in a call only when it can't get confused with a following
1125 parameter of different type.
1127 @code{result-type?} can specify a default in the same manner as
1128 predicates, to be used in case of a type error in arguments or
1131 (define (has-parser/location? arg where)
1132 (let loop ((arg arg))
1136 (define (currying-lambda args doc-string? body)
1137 (if (and (pair? args)
1139 (currying-lambda (car args) doc-string?
1140 `((lambda ,(cdr args) ,@body)))
1141 (let* ((compatibility? (if (list? args)
1142 (= (length args) (+ 2 (length signature)))
1143 (and (pair? args) (pair? (cdr args))
1144 (eq? (car args) 'parser))))
1145 (realargs (if compatibility? (cddr args) args)))
1147 ,(format #f "~a\n~a" realargs (or doc-string? ""))
1148 ,@(if (and compatibility?
1149 (has-parser/location? body (take args 2)))
1150 `((let ((,(car args) (*parser*)) (,(cadr args) (*location*)))
1155 (and (pair? body) (pair? (cdr body))
1156 (if (string? (car body))
1158 (and (pair? (car body))
1159 (eq? '_i (caar body))
1161 (string? (cadar body))
1162 (null? (cddar body))
1164 ;; When the music function definition contains an i10n doc string,
1165 ;; (_i "doc string"), keep the literal string only
1166 `(ly:make-music-function
1167 (list ,@(map (lambda (pred)
1170 ,(and (pair? (cdr pred)) (cadr pred)))
1172 (cons type signature)))
1173 ,(currying-lambda args docstring (if docstring (cdr body) body)))))
1175 (defmacro-public define-music-function rest
1176 "Defining macro returning music functions.
1178 (define-music-function (arg1 arg2 ...) (arg1-type? arg2-type? ...)
1179 ...function body...)
1181 argX-type can take one of the forms @code{predicate?} for mandatory
1182 arguments satisfying the predicate, @code{(predicate?)} for optional
1183 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
1184 value)}} for optional parameters with a specified default
1185 value (evaluated at definition time). An optional parameter can be
1186 omitted in a call only when it can't get confused with a following
1187 parameter of different type.
1189 Must return a music expression. The @code{origin} is automatically
1190 set to the @code{location} parameter."
1192 `(define-syntax-function (ly:music? (make-music 'Music 'void #t)) ,@rest))
1195 (defmacro-public define-scheme-function rest
1196 "Defining macro returning Scheme functions.
1198 (define-scheme-function (arg1 arg2 ...) (arg1-type? arg2-type? ...)
1199 ...function body...)
1201 argX-type can take one of the forms @code{predicate?} for mandatory
1202 arguments satisfying the predicate, @code{(predicate?)} for optional
1203 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
1204 value)}} for optional parameters with a specified default
1205 value (evaluated at definition time). An optional parameter can be
1206 omitted in a call only when it can't get confused with a following
1207 parameter of different type.
1209 Can return arbitrary expressions. If a music expression is returned,
1210 its @code{origin} is automatically set to the @code{location}
1213 `(define-syntax-function scheme? ,@rest))
1215 (defmacro-public define-void-function rest
1216 "This defines a Scheme function like @code{define-scheme-function} with
1217 void return value (i.e., what most Guile functions with `unspecified'
1218 value return). Use this when defining functions for executing actions
1219 rather than returning values, to keep Lilypond from trying to interpret
1221 `(define-syntax-function (void? *unspecified*) ,@rest *unspecified*))
1223 (defmacro-public define-event-function rest
1224 "Defining macro returning event functions.
1226 (define-event-function (arg1 arg2 ...) (arg1-type? arg2-type? ...)
1227 ...function body...)
1229 argX-type can take one of the forms @code{predicate?} for mandatory
1230 arguments satisfying the predicate, @code{(predicate?)} for optional
1231 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
1232 value)}} for optional parameters with a specified default
1233 value (evaluated at definition time). An optional parameter can be
1234 omitted in a call only when it can't get confused with a following
1235 parameter of different type.
1237 Must return an event expression. The @code{origin} is automatically
1238 set to the @code{location} parameter."
1240 `(define-syntax-function (ly:event? (make-music 'Event 'void #t)) ,@rest))
1242 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1244 (define-public (cue-substitute quote-music)
1245 "Must happen after @code{quote-substitute}."
1247 (if (vector? (ly:music-property quote-music 'quoted-events))
1248 (let* ((dir (ly:music-property quote-music 'quoted-voice-direction))
1249 (clef (ly:music-property quote-music 'quoted-music-clef #f))
1250 (main-voice (case dir ((1) 1) ((-1) 0) (else #f)))
1251 (cue-voice (and main-voice (- 1 main-voice)))
1252 (cue-type (ly:music-property quote-music 'quoted-context-type #f))
1253 (cue-id (ly:music-property quote-music 'quoted-context-id))
1254 (main-music (ly:music-property quote-music 'element))
1255 (return-value quote-music))
1258 (set! (ly:music-property quote-music 'element)
1259 (make-sequential-music
1261 (make-voice-props-override main-voice)
1263 (make-voice-props-revert)))))
1265 ;; if we have stem dirs, change both quoted and main music
1266 ;; to have opposite stems.
1268 ;; cannot context-spec Quote-music, since context
1269 ;; for the quotes is determined in the iterator.
1271 (make-sequential-music
1274 (and clef (make-cue-clef-set clef))
1275 (and cue-type cue-voice
1277 (make-voice-props-override cue-voice)
1280 (and cue-type cue-voice
1282 (make-voice-props-revert)
1284 (and clef (make-cue-clef-unset))))))
1287 (define ((quote-substitute quote-tab) music)
1288 (let* ((quoted-name (ly:music-property music 'quoted-music-name))
1289 (quoted-vector (and (string? quoted-name)
1290 (hash-ref quote-tab quoted-name #f))))
1293 (if (string? quoted-name)
1294 (if (vector? quoted-vector)
1296 (set! (ly:music-property music 'quoted-events) quoted-vector)
1297 (set! (ly:music-property music 'iterator-ctor)
1298 ly:quote-iterator::constructor))
1299 (ly:music-warning music (ly:format (_ "cannot find quoted music: `~S'") quoted-name))))
1301 (export quote-substitute)
1304 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1305 ;; switch it on here, so parsing and init isn't checked (too slow!)
1307 ;; automatic music transformations.
1309 (define (switch-on-debugging m)
1310 (if (defined? 'set-debug-cell-accesses!)
1311 (set-debug-cell-accesses! 15000))
1314 (define (music-check-error music)
1317 (if (and (ly:music? m)
1318 (eq? (ly:music-property m 'error-found) #t))
1321 (for-each signal (ly:music-property music 'elements))
1322 (signal (ly:music-property music 'element))
1325 (set! (ly:music-property music 'error-found) #t))
1328 (define (precompute-music-length music)
1329 (set! (ly:music-property music 'length)
1330 (ly:music-length music))
1333 (define-public (make-duration-of-length moment)
1334 "Make duration of the given @code{moment} length."
1335 (ly:make-duration 0 0
1336 (ly:moment-main-numerator moment)
1337 (ly:moment-main-denominator moment)))
1339 (define (make-skipped moment bool)
1340 "Depending on BOOL, set or unset skipTypesetting,
1341 then make SkipMusic of the given MOMENT length, and
1342 then revert skipTypesetting."
1343 (make-sequential-music
1345 (context-spec-music (make-property-set 'skipTypesetting bool)
1347 (make-music 'SkipMusic 'duration
1348 (make-duration-of-length moment))
1349 (context-spec-music (make-property-set 'skipTypesetting (not bool))
1352 (define (skip-as-needed music)
1354 << { \\set skipTypesetting = ##f
1355 LENGTHOF(\\showFirstLength)
1356 \\set skipTypesetting = ##t
1357 LENGTHOF(\\showLastLength) }
1361 When only showFirstLength is set,
1362 the 'length property of the music is
1363 overridden to speed up compiling."
1365 ((show-last (ly:parser-lookup 'showLastLength))
1366 (show-first (ly:parser-lookup 'showFirstLength))
1367 (show-last-length (and (ly:music? show-last)
1368 (ly:music-length show-last)))
1369 (show-first-length (and (ly:music? show-first)
1370 (ly:music-length show-first)))
1371 (orig-length (ly:music-length music)))
1373 ;;FIXME: if using either showFirst- or showLastLength,
1374 ;; make sure that skipBars is not set.
1378 ;; both properties may be set.
1379 ((and show-first-length show-last-length)
1381 ((skip-length (ly:moment-sub orig-length show-last-length)))
1382 (make-simultaneous-music
1384 (make-sequential-music
1386 (make-skipped skip-length #t)
1387 ;; let's draw a separator between the beginning and the end
1388 (context-spec-music (make-property-set 'whichBar "||")
1390 (make-skipped show-first-length #f)
1393 ;; we may only want to print the last length
1396 ((skip-length (ly:moment-sub orig-length show-last-length)))
1397 (make-simultaneous-music
1399 (make-skipped skip-length #t)
1402 ;; we may only want to print the beginning; in this case
1403 ;; only the first length will be processed (much faster).
1405 ;; the first length must not exceed the original length.
1406 (if (ly:moment<? show-first-length orig-length)
1407 (set! (ly:music-property music 'length)
1414 (define-session-public toplevel-music-functions
1416 (lambda (music) (expand-repeat-chords!
1417 (cons 'rhythmic-event
1418 (ly:parser-lookup '$chord-repeat-events))
1420 expand-repeat-notes!
1422 (lambda (x) (music-map music-check-error x))
1423 (lambda (x) (music-map precompute-music-length x))
1425 (music-map (quote-substitute (ly:parser-lookup 'musicQuotes)) music))
1427 ;; switch-on-debugging
1428 (lambda (x) (music-map cue-substitute x))
1433 ;;; general purpose music functions
1435 (define (shift-octave pitch octave-shift)
1436 (_i "Add @var{octave-shift} to the octave of @var{pitch}.")
1438 (+ (ly:pitch-octave pitch) octave-shift)
1439 (ly:pitch-notename pitch)
1440 (ly:pitch-alteration pitch)))
1446 (define (apply-durations lyric-music durations)
1447 (define (apply-duration music)
1448 (if (and (not (equal? (ly:music-length music) ZERO-MOMENT))
1449 (ly:duration? (ly:music-property music 'duration)))
1451 (set! (ly:music-property music 'duration) (car durations))
1452 (set! durations (cdr durations)))))
1454 (music-map apply-duration lyric-music))
1457 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1460 (define (recent-enough? bar-number alteration-def laziness)
1461 (or (number? alteration-def)
1462 (equal? laziness #t)
1463 (<= bar-number (+ (cadr alteration-def) laziness))))
1465 (define (accidental-invalid? alteration-def)
1466 "Checks an alteration entry for being invalid.
1468 Non-key alterations are invalidated when tying into the next bar or
1469 when there is a clef change, since neither repetition nor cancellation
1470 can be omitted when the same note occurs again.
1472 Returns @code{#f} or the reason for the invalidation, a symbol."
1473 (let* ((def (if (pair? alteration-def)
1474 (car alteration-def)
1476 (and (symbol? def) def)))
1478 (define (extract-alteration alteration-def)
1479 (cond ((number? alteration-def)
1481 ((pair? alteration-def)
1482 (car alteration-def))
1485 (define (check-pitch-against-signature context pitch barnum laziness octaveness all-naturals)
1486 "Checks the need for an accidental and a @q{restore} accidental against
1487 @code{localAlterations} and @code{keyAlterations}.
1488 The @var{laziness} is the number of measures
1489 for which reminder accidentals are used (i.e., if @var{laziness} is zero,
1490 only cancel accidentals in the same measure; if @var{laziness} is three,
1491 we cancel accidentals up to three measures after they first appear.
1492 @var{octaveness} is either @code{'same-octave} or @code{'any-octave} and
1493 specifies whether accidentals should be canceled in different octaves.
1494 If @var{all-naturals} is ##t, notes that do not occur in @code{keyAlterations}
1495 also get an accidental."
1496 (let* ((ignore-octave (cond ((equal? octaveness 'any-octave) #t)
1497 ((equal? octaveness 'same-octave) #f)
1499 (ly:warning (_ "Unknown octaveness type: ~S ") octaveness)
1500 (ly:warning (_ "Defaulting to 'any-octave."))
1502 (key (ly:context-property context 'keyAlterations))
1503 (local (ly:context-property context 'localAlterations))
1504 (notename (ly:pitch-notename pitch))
1505 (octave (ly:pitch-octave pitch))
1506 (pitch-handle (cons octave notename))
1508 (need-accidental #f)
1509 (previous-alteration #f)
1510 (from-other-octaves #f)
1511 (from-same-octave (assoc-get pitch-handle local))
1512 (from-key-sig (or (assoc-get notename local)
1514 ;; If no notename match is found from localAlterations, we may have a custom
1515 ;; type with octave-specific entries of the form ((octave . pitch) alteration)
1516 ;; instead of (pitch . alteration). Since this type cannot coexist with entries in
1517 ;; localAlterations, try extracting from keyAlterations instead.
1518 (assoc-get pitch-handle key))))
1520 ;; loop through localAlterations to search for a notename match from other octaves
1521 (let loop ((l local))
1523 (let ((entry (car l)))
1524 (if (and (pair? (car entry))
1525 (= (cdar entry) notename))
1526 (set! from-other-octaves (cdr entry))
1529 ;; find previous alteration-def for comparison with pitch
1531 ;; from same octave?
1532 ((and (not ignore-octave)
1534 (recent-enough? barnum from-same-octave laziness))
1535 (set! previous-alteration from-same-octave))
1540 (recent-enough? barnum from-other-octaves laziness))
1541 (set! previous-alteration from-other-octaves))
1543 ;; not recent enough, extract from key signature/local key signature
1545 (set! previous-alteration from-key-sig)))
1547 (if (accidental-invalid? previous-alteration)
1548 (set! need-accidental #t)
1550 (let* ((prev-alt (extract-alteration previous-alteration))
1551 (this-alt (ly:pitch-alteration pitch)))
1553 (if (or (and all-naturals (eq? #f previous-alteration)) (not (= this-alt prev-alt)))
1555 (set! need-accidental #t)
1556 (if (and (not (= this-alt 0))
1557 (and (< (abs this-alt) (abs prev-alt))
1558 (> (* prev-alt this-alt) 0)))
1559 (set! need-restore #t))))))
1561 (cons need-restore need-accidental)))
1563 (define ((make-accidental-rule octaveness laziness) context pitch barnum measurepos)
1564 "Create an accidental rule that makes its decision based on the octave of
1565 the note and a laziness value.
1567 @var{octaveness} is either @code{'same-octave} or @code{'any-octave} and
1568 defines whether the rule should respond to accidental changes in other
1569 octaves than the current. @code{'same-octave} is the normal way to typeset
1570 accidentals -- an accidental is made if the alteration is different from the
1571 last active pitch in the same octave. @code{'any-octave} looks at the last
1572 active pitch in any octave.
1574 @var{laziness} states over how many bars an accidental should be remembered.
1575 @code{0}@tie{}is the default -- accidental lasts over 0@tie{}bar lines, that
1576 is, to the end of current measure. A positive integer means that the
1577 accidental lasts over that many bar lines. @w{@code{-1}} is `forget
1578 immediately', that is, only look at key signature. @code{#t} is `forever'."
1580 (check-pitch-against-signature context pitch barnum laziness octaveness #f))
1581 (export make-accidental-rule)
1583 (define ((make-accidental-dodecaphonic-rule octaveness laziness) context pitch barnum measurepos)
1584 "Variation on function make-accidental-rule that creates an dodecaphonic
1587 (check-pitch-against-signature context pitch barnum laziness octaveness #t))
1588 (export make-accidental-dodecaphonic-rule)
1590 (define (key-entry-notename entry)
1591 "Return the pitch of an @var{entry} in @code{localAlterations}.
1592 The @samp{car} of the entry is either of the form @code{notename} or
1593 of the form @code{(octave . notename)}. The latter form is used for special
1594 key signatures or to indicate an explicit accidental.
1596 The @samp{cdr} of the entry is either a rational @code{alter} indicating
1597 a key signature alteration, or of the form
1598 @code{(alter . (barnum . measurepos))} indicating an alteration caused by
1599 an accidental in music."
1600 (if (pair? (car entry))
1604 (define (key-entry-octave entry)
1605 "Return the octave of an entry in @code{localAlterations}
1606 or @code{#f} if the entry does not have an octave.
1607 See @code{key-entry-notename} for details."
1608 (and (pair? (car entry)) (caar entry)))
1610 (define (key-entry-bar-number entry)
1611 "Return the bar number of an entry in @code{localAlterations}
1612 or @code {#f} if the entry does not have a bar number.
1613 See @code{key-entry-notename} for details."
1614 (and (pair? (cdr entry)) (caddr entry)))
1616 (define (key-entry-measure-position entry)
1617 "Return the measure position of an entry in @code{localAlterations}
1618 or @code {#f} if the entry does not have a measure position.
1619 See @code{key-entry-notename} for details."
1620 (and (pair? (cdr entry)) (cdddr entry)))
1622 (define (key-entry-alteration entry)
1623 "Return the alteration of an entry in localAlterations
1625 For convenience, returns @code{0} if entry is @code{#f}."
1627 (if (number? (cdr entry))
1632 (define-public (find-pitch-entry keysig pitch accept-global accept-local)
1633 "Return the first entry in @var{keysig} that matches @var{pitch}
1634 by notename and octave. Alteration is not considered.
1635 @var{accept-global} states whether key signature entries should be included.
1636 @var{accept-local} states whether local accidentals should be included.
1637 If no matching entry is found, @var{#f} is returned."
1639 (let* ((entry (car keysig))
1640 (entryoct (key-entry-octave entry))
1641 (entrynn (key-entry-notename entry))
1642 (nn (ly:pitch-notename pitch)))
1643 (if (and (equal? nn entrynn)
1645 (= entryoct (ly:pitch-octave pitch)))
1646 (if (key-entry-bar-number entry)
1650 (find-pitch-entry (cdr keysig) pitch accept-global accept-local)))))
1652 (define-public (neo-modern-accidental-rule context pitch barnum measurepos)
1653 "An accidental rule that typesets an accidental if it differs from the
1654 key signature @emph{and} does not directly follow a note on the same
1655 staff line. This rule should not be used alone because it does neither
1656 look at bar lines nor different accidentals at the same note name."
1657 (let* ((keysig (ly:context-property context 'localAlterations))
1658 (entry (find-pitch-entry keysig pitch #t #t)))
1661 (let* ((global-entry (find-pitch-entry keysig pitch #t #f))
1662 (key-acc (key-entry-alteration global-entry))
1663 (acc (ly:pitch-alteration pitch))
1664 (entrymp (key-entry-measure-position entry))
1665 (entrybn (key-entry-bar-number entry)))
1666 (cons #f (not (or (equal? acc key-acc)
1667 (and (equal? entrybn barnum) (equal? entrymp measurepos)))))))))
1669 (define-public (dodecaphonic-no-repeat-rule context pitch barnum measurepos)
1670 "An accidental rule that typesets an accidental before every
1671 note (just as in the dodecaphonic accidental style) @emph{except} if
1672 the note is immediately preceded by a note with the same pitch. This
1673 is a common accidental style in contemporary notation."
1674 (let* ((keysig (ly:context-property context 'localAlterations))
1675 (entry (find-pitch-entry keysig pitch #f #t)))
1678 (let ((entrymp (key-entry-measure-position entry))
1679 (entrybn (key-entry-bar-number entry))
1680 (entryalt (key-entry-alteration entry))
1681 (alt (ly:pitch-alteration pitch)))
1683 (not (and (equal? entrybn barnum)
1684 (or (equal? measurepos entrymp)
1685 (ly:moment<? measurepos entrymp))
1686 (equal? entryalt alt))))))))
1688 (define-public (teaching-accidental-rule context pitch barnum measurepos)
1689 "An accidental rule that typesets a cautionary accidental if it is
1690 included in the key signature @emph{and} does not directly follow a note
1691 on the same staff line."
1692 (let* ((keysig (ly:context-property context 'localAlterations))
1693 (entry (find-pitch-entry keysig pitch #t #t)))
1696 (let* ((global-entry (find-pitch-entry keysig pitch #f #f))
1697 (key-acc (key-entry-alteration global-entry))
1698 (acc (ly:pitch-alteration pitch))
1699 (entrymp (key-entry-measure-position entry))
1700 (entrybn (key-entry-bar-number entry)))
1701 (cons #f (not (or (equal? acc key-acc)
1702 (and (equal? entrybn barnum) (equal? entrymp measurepos)))))))))
1704 (define-session-public accidental-styles
1705 ;; An alist containing specification for all accidental styles.
1706 ;; Each accidental style needs three entries for the context properties
1707 ;; extraNatural, autoAccidentals and autoCautionaries.
1708 ;; An optional fourth entry may specify a default context for the accidental
1709 ;; style, for use with the piano styles.
1711 ;; accidentals as they were common in the 18th century.
1713 (Staff ,(make-accidental-rule 'same-octave 0))
1715 ;; accidentals from one voice do NOT get canceled in other voices
1717 (Voice ,(make-accidental-rule 'same-octave 0))
1719 ;; accidentals as suggested by Kurt Stone in
1720 ;; ‘Music Notation in the 20th century’.
1721 ;; This includes all the default accidentals, but accidentals also need
1722 ;; canceling in other octaves and in the next measure.
1724 (Staff ,(make-accidental-rule 'same-octave 0)
1725 ,(make-accidental-rule 'any-octave 0)
1726 ,(make-accidental-rule 'same-octave 1))
1728 ;; the accidentals that Stone adds to the old standard as cautionaries
1729 (modern-cautionary #f
1730 (Staff ,(make-accidental-rule 'same-octave 0))
1731 (Staff ,(make-accidental-rule 'any-octave 0)
1732 ,(make-accidental-rule 'same-octave 1)))
1733 ;; same as modern, but accidentals different from the key signature are
1734 ;; always typeset - unless they directly follow a note of the same pitch.
1736 (Staff ,(make-accidental-rule 'same-octave 0)
1737 ,(make-accidental-rule 'any-octave 0)
1738 ,(make-accidental-rule 'same-octave 1)
1739 ,neo-modern-accidental-rule)
1741 (neo-modern-cautionary #f
1742 (Staff ,(make-accidental-rule 'same-octave 0))
1743 (Staff ,(make-accidental-rule 'any-octave 0)
1744 ,(make-accidental-rule 'same-octave 1)
1745 ,neo-modern-accidental-rule))
1746 (neo-modern-voice #f
1747 (Voice ,(make-accidental-rule 'same-octave 0)
1748 ,(make-accidental-rule 'any-octave 0)
1749 ,(make-accidental-rule 'same-octave 1)
1750 ,neo-modern-accidental-rule
1752 ,(make-accidental-rule 'same-octave 0)
1753 ,(make-accidental-rule 'any-octave 0)
1754 ,(make-accidental-rule 'same-octave 1)
1755 ,neo-modern-accidental-rule)
1757 (neo-modern-voice-cautionary #f
1758 (Voice ,(make-accidental-rule 'same-octave 0))
1759 (Voice ,(make-accidental-rule 'any-octave 0)
1760 ,(make-accidental-rule 'same-octave 1)
1761 ,neo-modern-accidental-rule
1763 ,(make-accidental-rule 'same-octave 0)
1764 ,(make-accidental-rule 'any-octave 0)
1765 ,(make-accidental-rule 'same-octave 1)
1766 ,neo-modern-accidental-rule))
1768 ;; Accidentals as they were common in dodecaphonic music with no tonality.
1769 ;; Each note gets one accidental.
1771 (Staff ,(lambda (c p bn mp) '(#f . #t)))
1773 ;; As in dodecaphonic style with the exception that immediately
1774 ;; repeated notes (in the same voice) don't get an accidental
1775 (dodecaphonic-no-repeat #f
1776 (Staff ,dodecaphonic-no-repeat-rule)
1778 ;; Variety of the dodecaphonic style. Each note gets an accidental,
1779 ;; except notes that were already handled in the same measure.
1780 (dodecaphonic-first #f
1781 (Staff ,(make-accidental-dodecaphonic-rule 'same-octave 0))
1784 ;; Multivoice accidentals to be read both by musicians playing one voice
1785 ;; and musicians playing all voices. Accidentals are typeset for each
1786 ;; voice, but they ARE canceled across voices.
1788 (Voice ,(make-accidental-rule 'same-octave 0)
1789 ,(make-accidental-rule 'any-octave 0)
1790 ,(make-accidental-rule 'same-octave 1)
1792 ,(make-accidental-rule 'same-octave 0)
1793 ,(make-accidental-rule 'any-octave 0)
1794 ,(make-accidental-rule 'same-octave 1))
1796 ;; same as modernVoiceAccidental except that all special accidentals
1797 ;; are typeset as cautionaries
1798 (modern-voice-cautionary #f
1799 (Voice ,(make-accidental-rule 'same-octave 0))
1800 (Voice ,(make-accidental-rule 'any-octave 0)
1801 ,(make-accidental-rule 'same-octave 1)
1803 ,(make-accidental-rule 'same-octave 0)
1804 ,(make-accidental-rule 'any-octave 0)
1805 ,(make-accidental-rule 'same-octave 1)))
1807 ;; Stone's suggestions for accidentals on grand staff.
1808 ;; Accidentals are canceled across the staves
1809 ;; in the same grand staff as well
1811 (Staff ,(make-accidental-rule 'same-octave 0)
1812 ,(make-accidental-rule 'any-octave 0)
1813 ,(make-accidental-rule 'same-octave 1)
1815 ,(make-accidental-rule 'any-octave 0)
1816 ,(make-accidental-rule 'same-octave 1))
1819 (piano-cautionary #f
1820 (Staff ,(make-accidental-rule 'same-octave 0))
1821 (Staff ,(make-accidental-rule 'any-octave 0)
1822 ,(make-accidental-rule 'same-octave 1)
1824 ,(make-accidental-rule 'any-octave 0)
1825 ,(make-accidental-rule 'same-octave 1))
1828 ;; same as modern, but cautionary accidentals are printed for all
1829 ;; non-natural tones specified by the key signature.
1831 (Staff ,(make-accidental-rule 'same-octave 0))
1832 (Staff ,(make-accidental-rule 'same-octave 1)
1833 ,teaching-accidental-rule))
1835 ;; do not set localAlterations when a note alterated differently from
1836 ;; localAlterations is found.
1837 ;; Causes accidentals to be printed at every note instead of
1838 ;; remembered for the duration of a measure.
1839 ;; accidentals not being remembered, causing accidentals always to
1840 ;; be typeset relative to the time signature
1842 (Staff ,(make-accidental-rule 'same-octave -1))
1844 ;; Do not reset the key at the start of a measure. Accidentals will be
1845 ;; printed only once and are in effect until overridden, possibly many
1848 (Staff ,(make-accidental-rule 'same-octave #t))
1852 (define-public (set-accidental-style style . rest)
1853 "Set accidental style to @var{style}. Optionally take a context
1854 argument, e.g. @code{'Staff} or @code{'Voice}. The context defaults
1855 to @code{Staff}, except for piano styles, which use @code{GrandStaff}
1857 (let ((spec (assoc-get style accidental-styles)))
1859 (let ((extra-natural (first spec))
1860 (auto-accs (second spec))
1861 (auto-cauts (third spec))
1862 (context (cond ((pair? rest) (car rest))
1863 ((= 4 (length spec)) (fourth spec))
1866 (make-sequential-music
1867 (append (if (boolean? extra-natural)
1868 (list (make-property-set 'extraNatural extra-natural))
1870 (list (make-property-set 'autoAccidentals auto-accs)
1871 (make-property-set 'autoCautionaries auto-cauts))))
1874 (ly:warning (_ "unknown accidental style: ~S") style)
1875 (make-sequential-music '())))))
1877 (define-public (invalidate-alterations context)
1878 "Invalidate alterations in @var{context}.
1880 Elements of @code{'localAlterations} corresponding to local
1881 alterations of the key signature have the form
1882 @code{'((octave . notename) . (alter barnum . measurepos))}.
1883 Replace them with a version where @code{alter} is set to @code{'clef}
1884 to force a repetition of accidentals.
1886 Entries that conform with the current key signature are not invalidated."
1887 (let* ((keysig (ly:context-property context 'keyAlterations)))
1888 (set! (ly:context-property context 'localAlterations)
1891 (let* ((localalt (key-entry-alteration entry)))
1892 (if (or (accidental-invalid? localalt)
1893 (not (key-entry-bar-number entry))
1895 (key-entry-alteration
1898 (ly:make-pitch (key-entry-octave entry)
1899 (key-entry-notename entry)
1903 (cons (car entry) (cons 'clef (cddr entry))))))
1904 (ly:context-property context 'localAlterations)))))
1906 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1908 (define-public (skip-of-length mus)
1909 "Create a skip of exactly the same length as @var{mus}."
1913 'duration (ly:make-duration 0 0))))
1915 (make-event-chord (list (ly:music-compress skip (ly:music-length mus))))))
1917 (define-public (mmrest-of-length mus)
1918 "Create a multi-measure rest of exactly the same length as @var{mus}."
1921 (make-multi-measure-rest
1922 (ly:make-duration 0 0) '())))
1923 (ly:music-compress skip (ly:music-length mus))
1926 (define-public (pitch-of-note event-chord)
1927 (let ((evs (filter (lambda (x)
1928 (music-is-of-type? x 'note-event))
1929 (ly:music-property event-chord 'elements))))
1932 (ly:music-property (car evs) 'pitch))))
1934 (define-public (duration-of-note event-chord)
1936 ((pair? event-chord)
1937 (or (duration-of-note (car event-chord))
1938 (duration-of-note (cdr event-chord))))
1939 ((ly:music? event-chord)
1940 (let ((dur (ly:music-property event-chord 'duration)))
1941 (if (ly:duration? dur)
1943 (duration-of-note (ly:music-property event-chord 'elements)))))
1946 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1948 (define-public (map-some-music map? music)
1949 "Walk through @var{music}, transform all elements calling @var{map?}
1950 and only recurse if this returns @code{#f}. @code{elements} or
1951 @code{articulations} that are not music expressions are discarded:
1952 this allows some amount of filtering.
1954 @code{map-some-music} may overwrite the original @var{music}."
1955 (let loop ((music music))
1957 (let ((elt (ly:music-property music 'element))
1958 (elts (ly:music-property music 'elements))
1959 (arts (ly:music-property music 'articulations)))
1961 (set! (ly:music-property music 'element)
1964 (set! (ly:music-property music 'elements)
1965 (filter! ly:music? (map! loop elts))))
1967 (set! (ly:music-property music 'articulations)
1968 (filter! ly:music? (map! loop arts))))
1971 (define-public (for-some-music stop? music)
1972 "Walk through @var{music}, process all elements calling @var{stop?}
1973 and only recurse if this returns @code{#f}."
1974 (let loop ((music music))
1975 (if (not (stop? music))
1976 (let ((elt (ly:music-property music 'element)))
1979 (for-each loop (ly:music-property music 'elements))
1980 (for-each loop (ly:music-property music 'articulations))))))
1982 (define-public (fold-some-music pred? proc init music)
1983 "This works recursively on music like @code{fold} does on a list,
1984 calling @samp{(@var{pred?} music)} on every music element. If
1985 @code{#f} is returned for an element, it is processed recursively
1986 with the same initial value of @samp{previous}, otherwise
1987 @samp{(@var{proc} music previous)} replaces @samp{previous}
1988 and no recursion happens.
1989 The top @var{music} is processed using @var{init} for @samp{previous}."
1990 (let loop ((music music) (previous init))
1992 (proc music previous)
1995 (let ((elt (ly:music-property music 'element)))
1998 (loop elt previous)))
1999 (ly:music-property music 'elements))
2000 (ly:music-property music 'articulations)))))
2002 (define-public (extract-music music pred?)
2003 "Return a flat list of all music matching @var{pred?} inside of
2004 @var{music}, not recursing into matches themselves."
2005 (reverse! (fold-some-music pred? cons '() music)))
2007 (define-public (extract-named-music music music-name)
2008 "Return a flat list of all music named @var{music-name} (either a
2009 single event symbol or a list of alternatives) inside of @var{music},
2010 not recursing into matches themselves."
2013 (if (cheap-list? music-name)
2014 (lambda (m) (memq (ly:music-property m 'name) music-name))
2015 (lambda (m) (eq? (ly:music-property m 'name) music-name)))))
2017 (define-public (extract-typed-music music type)
2018 "Return a flat list of all music with @var{type} (either a single
2019 type symbol or a list of alternatives) inside of @var{music}, not
2020 recursing into matches themselves."
2021 (extract-music music (music-type-predicate type)))
2023 (define-public (event-chord-wrap! music)
2024 "Wrap isolated rhythmic events and non-postevent events in
2025 @var{music} inside of an @code{EventChord}. Chord repeats @samp{q}
2026 are expanded using the default settings of the parser."
2029 (cond ((music-is-of-type? m 'event-chord)
2030 (if (pair? (ly:music-property m 'articulations))
2032 (set! (ly:music-property m 'elements)
2033 (append (ly:music-property m 'elements)
2034 (ly:music-property m 'articulations)))
2035 (set! (ly:music-property m 'articulations) '())))
2037 ((music-is-of-type? m 'rhythmic-event)
2038 (let ((arts (ly:music-property m 'articulations)))
2040 (set! (ly:music-property m 'articulations) '()))
2041 (make-event-chord (cons m arts))))
2043 (expand-repeat-notes!
2044 (expand-repeat-chords!
2045 (cons 'rhythmic-event
2046 (ly:parser-lookup '$chord-repeat-events))
2049 (define-public (event-chord-notes event-chord)
2050 "Return a list of all notes from @var{event-chord}."
2052 (lambda (m) (eq? 'NoteEvent (ly:music-property m 'name)))
2053 (ly:music-property event-chord 'elements)))
2055 (define-public (event-chord-pitches event-chord)
2056 "Return a list of all pitches from @var{event-chord}."
2057 (map (lambda (x) (ly:music-property x 'pitch))
2058 (event-chord-notes event-chord)))
2060 (define-public (music-pitches music)
2061 "Return a list of all pitches from @var{music}."
2062 ;; Opencoded for efficiency.
2064 (let loop ((music music) (pitches '()))
2065 (let ((p (ly:music-property music 'pitch)))
2068 (let ((elt (ly:music-property music 'element)))
2073 (ly:music-property music 'elements))))))))
2075 (define-public (event-chord-reduce music)
2076 "Reduces event chords in @var{music} to their first note event,
2077 retaining only the chord articulations. Returns the modified music."
2080 (and (music-is-of-type? m 'event-chord)
2081 (let*-values (((notes arts) (partition
2083 (music-is-of-type? mus 'rhythmic-event))
2084 (ly:music-property m 'elements)))
2085 ((dur) (ly:music-property m 'duration))
2086 ((full-arts) (append arts
2087 (ly:music-property m 'articulations)))
2088 ((first-note) (and (pair? notes) (car notes))))
2090 (set! (ly:music-property first-note 'articulations)
2094 ;; A repeat chord. Produce an unpitched note.
2095 (make-music 'NoteEvent
2097 'articulations full-arts))
2099 (ly:music-error m (_ "Missing duration"))
2100 (make-music 'NoteEvent
2101 'duration (ly:make-duration 2 0 0)
2102 'articulations full-arts))))))
2106 (defmacro-public make-relative (variables reference music)
2107 "The list of pitch or music variables in @var{variables} is used as
2108 a sequence for creating relativable music from @var{music}.
2110 When the constructed music is used outside of @code{\\relative}, it
2111 just reflects plugging in the @var{variables} into @var{music}.
2113 The action inside of @code{\\relative}, however, is determined by
2114 first relativizing the surrogate @var{reference} with the variables
2115 plugged in and then using the variables relativized as a side effect
2116 of relativizing @var{reference} for evaluating @var{music}.
2118 Since pitches don't have the object identity required for tracing the
2119 effect of the reference call, they are replaced @emph{only} for the
2120 purpose of evaluating @var{reference} with simple pitched note events.
2122 The surrogate @var{reference} expression has to be written with that
2123 in mind. In addition, it must @emph{not} contain @emph{copies} of
2124 music that is supposed to be relativized but rather the
2125 @emph{originals}. This @emph{includes} the pitch expressions. As a
2126 rule, inside of @code{#@{@dots{}#@}} variables must @emph{only} be
2127 introduced using @code{#}, never via the copying construct @code{$}.
2128 The reference expression will usually just be a sequential or chord
2129 expression naming all variables in sequence, implying that following
2130 music will be relativized according to the resulting pitch of the last
2131 or first variable, respectively.
2133 Since the usual purpose is to create more complex music from general
2134 arguments and since music expression parts must not occur more than
2135 once, one @emph{does} generally need to use copying operators in the
2136 @emph{replacement} expression @var{music} when using an argument more
2137 than once there. Using an argument more than once in @var{reference},
2138 in contrast, does not make sense.
2140 There is another fine point to mind: @var{music} must @emph{only}
2141 contain freshly constructed elements or copied constructs. This will
2142 be the case anyway for regular LilyPond code inside of
2143 @code{#@{@dots{}#@}}, but any other elements (apart from the
2144 @var{variables} themselves which are already copied) must be created
2147 The reason is that it is usually permitted to change music in-place as
2148 long as one does a @var{ly:music-deep-copy} on it, and such a copy of
2149 the whole resulting expression will @emph{not} be able to copy
2150 variables/values inside of closures where the information for
2151 relativization is being stored.
2154 ;; pitch and music generator might be stored instead in music
2155 ;; properties, and it might make sense to create a music type of its
2156 ;; own for this kind of construct rather than using
2157 ;; RelativeOctaveMusic
2158 (define ((make-relative::to-relative-callback variables music-call ref-call)
2160 (let* ((ref-vars (map (lambda (v)
2162 (make-music 'NoteEvent 'pitch v)
2163 (ly:music-deep-copy v)))
2165 (after-pitch (ly:make-music-relative! (apply ref-call ref-vars) pitch))
2166 (actual-vars (map (lambda (v r)
2168 (ly:music-property r 'pitch)
2170 variables ref-vars))
2171 (rel-music (apply music-call actual-vars)))
2172 (set! (ly:music-property music 'element) rel-music)
2174 `(make-music 'RelativeOctaveMusic
2175 'to-relative-callback
2176 (,make-relative::to-relative-callback
2178 (lambda ,variables ,music)
2179 (lambda ,variables ,reference))
2182 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2183 ;; The following functions are all associated with the crossStaff
2186 (define (close-enough? x y)
2187 "Values are close enough to ignore the difference"
2188 (< (abs (- x y)) 0.0001))
2190 (define (extent-combine extents)
2191 "Combine a list of extents"
2192 (if (pair? (cdr extents))
2193 (interval-union (car extents) (extent-combine (cdr extents)))
2196 (define ((stem-connectable? ref root) stem)
2197 "Check if the stem is connectable to the root"
2198 ;; The root is always connectable to itself
2201 ;; Horizontal positions of the stems must be almost the same
2202 (close-enough? (car (ly:grob-extent root ref X))
2203 (car (ly:grob-extent stem ref X)))
2204 ;; The stem must be in the direction away from the root's notehead
2205 (positive? (* (ly:grob-property root 'direction)
2206 (- (car (ly:grob-extent stem ref Y))
2207 (car (ly:grob-extent root ref Y))))))))
2209 (define (stem-span-stencil span)
2210 "Connect stems if we have at least one stem connectable to the root"
2211 (let* ((system (ly:grob-system span))
2212 (root (ly:grob-parent span X))
2213 (stems (filter (stem-connectable? system root)
2214 (ly:grob-object span 'stems))))
2215 (if (<= 2 (length stems))
2216 (let* ((yextents (map (lambda (st)
2217 (ly:grob-extent st system Y)) stems))
2218 (yextent (extent-combine yextents))
2219 (layout (ly:grob-layout root))
2220 (blot (ly:output-def-lookup layout 'blot-diameter)))
2221 ;; Hide spanned stems
2222 (for-each (lambda (st)
2223 (set! (ly:grob-property st 'stencil) #f))
2225 ;; Draw a nice looking stem with rounded corners
2226 (ly:round-filled-box (ly:grob-extent root root X) yextent blot))
2227 ;; Nothing to connect, don't draw the span
2230 (define ((make-stem-span! stems trans) root)
2231 "Create a stem span as a child of the cross-staff stem (the root)"
2232 (let ((span (ly:engraver-make-grob trans 'Stem '())))
2233 (ly:grob-set-parent! span X root)
2234 (set! (ly:grob-object span 'stems) stems)
2235 ;; Suppress positioning, the stem code is confused by this weird stem
2236 (set! (ly:grob-property span 'X-offset) 0)
2237 (set! (ly:grob-property span 'stencil) stem-span-stencil)))
2239 (define-public (cross-staff-connect stem)
2240 "Set cross-staff property of the stem to this function to connect it to
2241 other stems automatically"
2244 (define (stem-is-root? stem)
2245 "Check if automatic connecting of the stem was requested. Stems connected
2246 to cross-staff beams are cross-staff, but they should not be connected to
2247 other stems just because of that."
2248 (eq? cross-staff-connect (ly:grob-property-data stem 'cross-staff)))
2250 (define (make-stem-spans! ctx stems trans)
2251 "Create stem spans for cross-staff stems"
2252 ;; Cannot do extensive checks here, just make sure there are at least
2253 ;; two stems at this musical moment
2254 (if (<= 2 (length stems))
2255 (let ((roots (filter stem-is-root? stems)))
2256 (for-each (make-stem-span! stems trans) roots))))
2258 (define-public (Span_stem_engraver ctx)
2259 "Connect cross-staff stems to the stems above in the system"
2262 ;; Record all stems for the given moment
2264 ((stem-interface trans grob source)
2265 (set! stems (cons grob stems))))
2266 ;; Process stems and reset the stem list to empty
2267 ((process-acknowledged trans)
2268 (make-stem-spans! ctx stems trans)
2269 (set! stems '())))))
2271 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2272 ;; The following is used by the alterBroken function.
2274 (define ((value-for-spanner-piece arg) grob)
2275 "Associate a piece of broken spanner @var{grob} with an element
2277 (let* ((orig (ly:grob-original grob))
2278 (siblings (ly:spanner-broken-into orig)))
2280 (define (helper sibs arg)
2283 (if (eq? (car sibs) grob)
2285 (helper (cdr sibs) (cdr arg)))))
2287 (if (>= (length siblings) 2)
2288 (helper siblings arg)
2290 (export value-for-spanner-piece)
2292 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2293 ;; The following are used by the \offset function
2295 (define (find-value-to-offset prop self alist)
2296 "Return the first value of the property @var{prop} in the property
2297 alist @var{alist} -- after having found @var{self}. If @var{self} is
2298 not found, return the first value of @var{prop}."
2299 (let ((segment (member (cons prop self) alist)))
2301 (assoc-get prop alist)
2302 (assoc-get prop (cdr segment)))))
2304 (define (offset-multiple-types arg offsets)
2305 "Displace @var{arg} by @var{offsets} if @var{arg} is a number, a
2306 number pair, or a list of number pairs. If @var{offsets} is an empty
2307 list or if there is a type-mismatch, @var{arg} will be returned."
2309 ((and (number? arg) (number? offsets))
2311 ((and (number-pair? arg)
2312 (or (number? offsets)
2313 (number-pair? offsets)))
2314 (coord-translate arg offsets))
2315 ((and (number-pair-list? arg) (number-pair-list? offsets))
2316 (map coord-translate arg offsets))
2319 (define-public (grob-transformer property func)
2320 "Create an override value good for applying @var{func} to either
2321 pure or unpure values. @var{func} is called with the respective grob
2322 as first argument and the default value (after resolving all callbacks)
2324 (define (worker self caller grob . rest)
2325 (let* ((immutable (ly:grob-basic-properties grob))
2326 ;; We need to search the basic-properties alist for our
2327 ;; property to obtain values to offset. Our search is
2328 ;; complicated by the fact that calling the music function
2329 ;; `offset' as an override conses a pair to the head of the
2330 ;; alist. This pair must be discounted. The closure it
2331 ;; contains is named `self' so it can be easily recognized.
2332 ;; If `offset' is called as a tweak, the basic-property
2333 ;; alist is unaffected.
2334 (target (find-value-to-offset property self immutable))
2335 ;; if target is a procedure, we need to apply it to our
2336 ;; grob to calculate values to offset.
2337 (vals (apply caller target grob rest)))
2339 ;; return the container named `self'. The container self-reference
2340 ;; seems like chasing its own tail but gets dissolved by
2341 ;; define/lambda separating binding and referencing of "self".
2342 (define self (ly:make-unpure-pure-container
2344 (worker self ly:unpure-call grob))
2345 (lambda (grob . rest)
2346 (apply worker self ly:pure-call grob rest))))
2349 (define-public (offsetter property offsets)
2350 "Apply @var{offsets} to the default values of @var{property} of @var{grob}.
2351 Offsets are restricted to immutable properties and values of type @code{number},
2352 @code{number-pair}, or @code{number-pair-list}."
2353 (define (offset-fun grob vals)
2354 (let ((can-type-be-offset?
2357 (number-pair-list? vals))))
2358 (if can-type-be-offset?
2359 ;; '(+inf.0 . -inf.0) would offset to itself. This will be
2360 ;; confusing to a user unaware of the default value of the
2361 ;; property, so issue a warning.
2362 (if (equal? empty-interval vals)
2363 (ly:warning "default '~a of ~a is ~a and can't be offset"
2365 (let* ((orig (ly:grob-original grob))
2367 (if (ly:spanner? grob)
2368 (ly:spanner-broken-into orig)
2370 (total-found (length siblings))
2371 ;; Since there is some flexibility in input
2372 ;; syntax, structure of `offsets' is normalized.
2374 (if (or (not (pair? offsets))
2375 (number-pair? offsets)
2376 (and (number-pair-list? offsets)
2377 (number-pair-list? vals)))
2381 (define (helper sibs offs)
2382 ;; apply offsets to the siblings of broken spanners
2384 (if (eq? (car sibs) grob)
2385 (offset-multiple-types vals (car offs))
2386 (helper (cdr sibs) (cdr offs)))
2389 (if (>= total-found 2)
2390 (helper siblings offsets)
2391 (offset-multiple-types vals (car offsets)))))
2394 (ly:warning "the property '~a of ~a cannot be offset" property grob)
2396 (grob-transformer property offset-fun))
2398 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2399 ;; \magnifyMusic and \magnifyStaff
2401 ;; defined as a function instead of a list because the
2402 ;; all-grob-descriptions alist is not available yet
2403 (define-public (find-named-props prop-name grob-descriptions)
2404 "Used by @code{\\magnifyMusic} and @code{\\magnifyStaff}. When
2405 @var{grob-descriptions} is equal to the @code{all-grob-descriptions}
2406 alist (defined in @file{scm/define-grobs.scm}), this will find all grobs
2407 that can have a value for the @var{prop-name} property, and return them
2408 as a list in the following format:
2414 (define (find-grobs-with-interface interface grob-descriptions)
2415 (define (has-this-interface? grob-desc)
2416 (let* ((meta (ly:assoc-get 'meta (cdr grob-desc)))
2417 (interfaces (ly:assoc-get 'interfaces meta '())))
2418 (memq interface interfaces)))
2419 (let* ((grob-descriptions-with-this-interface
2420 (filter has-this-interface? grob-descriptions))
2421 (grob-names-with-this-interface
2422 (map car grob-descriptions-with-this-interface)))
2423 grob-names-with-this-interface))
2426 ((baseline-skip word-space) 'text-interface)
2427 ((space-alist) 'break-aligned-interface)
2428 (else (ly:programming-error
2429 "find-named-props: no interface associated with ~s"
2431 (grobs-with-this-prop
2432 (find-grobs-with-interface interface grob-descriptions)))
2433 (map (lambda (x) (list x prop-name))
2434 grobs-with-this-prop)))
2437 (define (magnifyStaff-is-set? context mag)
2438 (let* ((Staff (ly:context-find context 'Staff))
2439 (old-mag (ly:context-property Staff 'magnifyStaffValue)))
2440 (not (null? old-mag))))
2442 (define (staff-magnification-is-changing? context mag)
2443 (let* ((Staff (ly:context-find context 'Staff))
2444 (old-mag (ly:context-property Staff 'magnifyStaffValue 1)))
2445 (not (= old-mag mag))))
2447 (define-public (scale-fontSize func-name mag)
2448 "Used by @code{\\magnifyMusic} and @code{\\magnifyStaff}. Look up the
2449 current @code{fontSize} in the appropriate context and scale it by the
2450 magnification factor @var{mag}. @var{func-name} is either
2451 @code{'magnifyMusic} or @code{'magnifyStaff}."
2454 (if (or (eq? func-name 'magnifyMusic)
2455 ;; for \magnifyStaff, only scale the fontSize
2456 ;; if staff magnification is changing
2457 ;; and does not equal 1
2458 (and (staff-magnification-is-changing? context mag)
2460 (let* ((where (case func-name
2461 ((magnifyMusic) context)
2462 ((magnifyStaff) (ly:context-find context 'Staff))))
2463 (fontSize (ly:context-property where 'fontSize 0))
2464 (new-fontSize (+ fontSize (magnification->font-size mag))))
2465 (ly:context-set-property! where 'fontSize new-fontSize))))))
2467 (define-public (revert-fontSize func-name mag)
2468 "Used by @code{\\magnifyMusic} and @code{\\magnifyStaff}. Calculate
2469 the previous @code{fontSize} value (before scaling) by factoring out the
2470 magnification factor @var{mag} (if @var{func-name} is
2471 @code{'magnifyMusic}), or by factoring out the context property
2472 @code{magnifyStaffValue} (if @var{func-name} is @code{'magnifyStaff}).
2473 Revert the @code{fontSize} in the appropriate context accordingly.
2475 With @code{\\magnifyMusic}, the scaling is reverted after the music
2476 block it operates on. @code{\\magnifyStaff} does not operate on a music
2477 block, so the scaling from a previous call (if there is one) is reverted
2478 before the new scaling takes effect."
2481 (if (or (eq? func-name 'magnifyMusic)
2482 ;; for \magnifyStaff...
2484 ;; don't revert the user's fontSize choice
2485 ;; the first time \magnifyStaff is called
2486 (magnifyStaff-is-set? context mag)
2487 ;; only revert the previous fontSize
2488 ;; if staff magnification is changing
2489 (staff-magnification-is-changing? context mag)))
2492 ((magnifyMusic) context)
2493 ((magnifyStaff) (ly:context-find context 'Staff))))
2496 ((magnifyMusic) mag)
2498 (ly:context-property where 'magnifyStaffValue 1))))
2499 (fontSize (ly:context-property where 'fontSize 0))
2500 (old-fontSize (- fontSize (magnification->font-size old-mag))))
2501 (ly:context-set-property! where 'fontSize old-fontSize))))))
2503 (define-public (scale-props func-name mag allowed-to-shrink? props)
2504 "Used by @code{\\magnifyMusic} and @code{\\magnifyStaff}. For each
2505 prop in @var{props}, find the current value of the requested prop, scale
2506 it by the magnification factor @var{mag}, and do the equivalent of a
2507 @code{\\temporary@tie{}\\override} with the new value in the appropriate
2508 context. If @var{allowed-to-shrink?} is @code{#f}, don't let the new
2509 value be less than the current value. @var{func-name} is either
2510 @code{'magnifyMusic} or @code{'magnifyStaff}. The @var{props} list is
2514 (Slur line-thickness)
2519 (define (scale-prop grob-prop-list)
2520 (let* ((grob (car grob-prop-list))
2521 (prop (cadr grob-prop-list))
2522 (where (if (eq? grob 'SpacingSpanner)
2523 (ly:context-find context 'Score)
2525 ((magnifyMusic) context)
2526 ((magnifyStaff) (ly:context-find context 'Staff)))))
2527 (grob-def (ly:context-grob-definition where grob)))
2528 (if (eq? prop 'space-alist)
2529 (let* ((space-alist (ly:assoc-get prop grob-def))
2530 (scale-spacing-tuple (lambda (x)
2533 (* mag (cddr x))))))
2534 (scaled-tuples (if space-alist
2535 (map scale-spacing-tuple space-alist)
2537 (new-alist (append scaled-tuples space-alist)))
2538 (ly:context-pushpop-property where grob prop new-alist))
2539 (let* ((val (ly:assoc-get prop grob-def (case prop
2544 (if allowed-to-shrink?
2546 (* x (max 1 mag)))))
2547 (new-val (if (number-pair? val)
2548 (cons (proc (car val))
2551 (ly:context-pushpop-property where grob prop new-val)))))
2552 (if (or (eq? func-name 'magnifyMusic)
2553 ;; for \magnifyStaff, only scale the properties
2554 ;; if staff magnification is changing
2555 ;; and does not equal 1
2556 (and (staff-magnification-is-changing? context mag)
2558 (for-each scale-prop props)))))
2560 (define-public (revert-props func-name mag props)
2561 "Used by @code{\\magnifyMusic} and @code{\\magnifyStaff}. Revert each
2562 prop in @var{props} in the appropriate context. @var{func-name} is
2563 either @code{'magnifyMusic} or @code{'magnifyStaff}. The @var{props}
2564 list is formatted like:
2567 (Slur line-thickness)
2572 (define (revert-prop grob-prop-list)
2573 (let* ((grob (car grob-prop-list))
2574 (prop (cadr grob-prop-list))
2575 (where (if (eq? grob 'SpacingSpanner)
2576 (ly:context-find context 'Score)
2578 ((magnifyMusic) context)
2579 ((magnifyStaff) (ly:context-find context 'Staff))))))
2580 (ly:context-pushpop-property where grob prop)))
2581 (if (or (eq? func-name 'magnifyMusic)
2582 ;; for \magnifyStaff...
2584 ;; don't revert the user's property overrides
2585 ;; the first time \magnifyStaff is called
2586 (magnifyStaff-is-set? context mag)
2587 ;; revert the overrides from the previous \magnifyStaff,
2588 ;; but only if staff magnification is changing
2589 (staff-magnification-is-changing? context mag)))
2590 (for-each revert-prop props)))))
2592 ;; \magnifyMusic only
2593 (define-public (scale-beam-thickness mag)
2594 "Used by @code{\\magnifyMusic}. Scaling @code{Beam.beam-thickness}
2595 exactly to the @var{mag} value will not work. This uses two reference
2596 values for @code{beam-thickness} to determine an acceptable value when
2597 scaling, then does the equivalent of a
2598 @code{\\temporary@tie{}\\override} with the new value."
2601 (let* ((grob-def (ly:context-grob-definition context 'Beam))
2602 (val (ly:assoc-get 'beam-thickness grob-def 0.48))
2603 (ratio-to-default (/ val 0.48))
2604 ;; gives beam-thickness=0.48 when mag=1 (like default),
2605 ;; gives beam-thickness=0.35 when mag=0.63 (like CueVoice)
2606 (scaled-default (+ 119/925 (* mag 13/37)))
2607 (new-val (* scaled-default ratio-to-default)))
2608 (ly:context-pushpop-property context 'Beam 'beam-thickness new-val)))))
2613 (define tag-groups (make-hash-table))
2614 (call-after-session (lambda () (hash-clear! tag-groups)))
2616 (define-public (define-tag-group tags)
2617 "Define a tag-group consisting of the given @var{tags}, a@tie{}list
2618 of symbols. Returns @code{#f} if successful, and an error message if
2619 there is a conflicting tag group definition."
2620 (cond ((not (symbol-list? tags)) (format #f (_ "not a symbol list: ~a") tags))
2621 ((any (lambda (tag) (hashq-ref tag-groups tag)) tags)
2622 => (lambda (group) (and (not (lset= eq? group tags))
2623 (format #f (_ "conflicting tag group ~a") group))))
2626 (lambda (elt) (hashq-set! tag-groups elt tags))
2630 (define-public (tag-group-get tag)
2631 "Return the tag group (as a list of symbols) that the given
2632 @var{tag} symbol belongs to, @code{#f} if none."
2633 (hashq-ref tag-groups tag))
2635 (define-public (tags-remove-predicate tags)
2636 "Returns a predicate that returns @code{#f} for any music that is to
2637 be removed by @{\\removeWithTag} on the given symbol or list of
2638 symbols @var{tags}."
2641 (not (memq tags (ly:music-property m 'tags))))
2643 (not (any (lambda (t) (memq t tags))
2644 (ly:music-property m 'tags))))))
2646 (define-public (tags-keep-predicate tags)
2647 "Returns a predicate that returns @code{#f} for any music that is to
2648 be removed by @{\\keepWithTag} on the given symbol or list of symbols
2651 (let ((group (tag-group-get tags)))
2653 (let ((music-tags (ly:music-property m 'tags)))
2655 (null? music-tags) ; redundant but very frequent
2656 ;; We know of only one tag to keep. Either we find it in
2657 ;; the music tags, or all music tags must be from a
2659 (memq tags music-tags)
2660 (not (any (lambda (t) (eq? (tag-group-get t) group)) music-tags))))))
2661 (let ((groups (delete-duplicates (map tag-group-get tags) eq?)))
2663 (let ((music-tags (ly:music-property m 'tags)))
2665 (null? music-tags) ; redundant but very frequent
2666 (any (lambda (t) (memq t tags)) music-tags)
2667 ;; if no tag matches, no tag group should match either
2668 (not (any (lambda (t) (memq (tag-group-get t) groups)) music-tags))))))))