1 ;;;; This file is part of LilyPond, the GNU music typesetter.
3 ;;;; Copyright (C) 1998--2014 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)))
39 (define-public ly:grob-property
40 (make-procedure-with-setter ly:grob-property
41 ly:grob-set-property!))
43 (define-public ly:grob-object
44 (make-procedure-with-setter ly:grob-object
47 (define-public ly:grob-parent
48 (make-procedure-with-setter ly:grob-parent
51 (define-public ly:prob-property
52 (make-procedure-with-setter ly:prob-property
53 ly:prob-set-property!))
55 (define-public ly:context-property
56 (make-procedure-with-setter ly:context-property
57 ly:context-set-property!))
59 (define-public (music-map function music)
60 "Apply @var{function} to @var{music} and all of the music it contains.
62 First it recurses over the children, then the function is applied to
64 (let ((es (ly:music-property music 'elements))
65 (e (ly:music-property music 'element)))
67 (set! (ly:music-property music 'elements)
68 (map (lambda (y) (music-map function y)) es)))
70 (set! (ly:music-property music 'element)
71 (music-map function e)))
74 (define-public (music-filter pred? music)
75 "Filter out music expressions that do not satisfy @var{pred?}."
77 (define (inner-music-filter pred? music)
79 (let* ((es (ly:music-property music 'elements))
80 (e (ly:music-property music 'element))
81 (as (ly:music-property music 'articulations))
82 (filtered-as (filter ly:music? (map (lambda (y) (inner-music-filter pred? y)) as)))
83 (filtered-e (if (ly:music? e)
84 (inner-music-filter pred? e)
86 (filtered-es (filter ly:music? (map (lambda (y) (inner-music-filter pred? y)) es))))
88 (set! (ly:music-property music 'element) filtered-e))
90 (set! (ly:music-property music 'elements) filtered-es))
92 (set! (ly:music-property music 'articulations) filtered-as))
93 ;; if filtering emptied the expression, we remove it completely.
94 (if (or (not (pred? music))
95 (and (eq? filtered-es '()) (not (ly:music? e))
96 (or (not (eq? es '()))
101 (set! music (inner-music-filter pred? music))
102 (if (ly:music? music)
104 (make-music 'Music))) ;must return music.
106 (define*-public (display-music music #:optional (port (current-output-port)))
107 "Display music, not done with @code{music-map} for clarity of
110 (display ": { " port)
111 (let ((es (ly:music-property music 'elements))
112 (e (ly:music-property music 'element)))
113 (display (ly:music-mutable-properties music) port)
115 (begin (display "\nElements: {\n" port)
116 (for-each (lambda (m) (display-music m port)) es)
117 (display "}\n" port)))
120 (display "\nChild:" port)
121 (display-music e port))))
122 (display " }\n" port)
126 ;;; A scheme music pretty printer
128 (define (markup-expression->make-markup markup-expression)
129 "Transform `markup-expression' into an equivalent, hopefuly readable, scheme expression.
131 \\markup \\bold \\italic hello
133 (markup #:line (#:bold (#:italic (#:simple \"hello\"))))"
134 (define (proc->command-keyword proc)
135 "Return a keyword, eg. `#:bold', from the `proc' function, eg. #<procedure bold-markup (layout props arg)>"
136 (let ((cmd-markup (symbol->string (procedure-name proc))))
137 (symbol->keyword (string->symbol (substring cmd-markup 0 (- (string-length cmd-markup)
138 (string-length "-markup")))))))
139 (define (transform-arg arg)
140 (cond ((and (pair? arg) (markup? (car arg))) ;; a markup list
141 (append-map inner-markup->make-markup arg))
142 ((and (not (string? arg)) (markup? arg)) ;; a markup
143 (inner-markup->make-markup arg))
145 (music->make-music arg))))
146 (define (inner-markup->make-markup mrkup)
149 (let ((cmd (proc->command-keyword (car mrkup)))
150 (args (map transform-arg (cdr mrkup))))
153 (if (string? markup-expression)
155 `(markup ,@(inner-markup->make-markup markup-expression))))
157 (define-public (music->make-music obj)
158 "Generate an expression that, once evaluated, may return an object
159 equivalent to @var{obj}, that is, for a music expression, a
160 @code{(make-music ...)} form."
161 (define (if-nonzero num)
162 (if (zero? num) '() (list num)))
163 (cond (;; markup expression
165 (markup-expression->make-markup obj))
169 ',(ly:music-property obj 'name)
170 ,@(append-map (lambda (prop)
172 ,(music->make-music (cdr prop))))
173 (remove (lambda (prop)
174 (eqv? (car prop) 'origin))
175 (ly:music-mutable-properties obj)))))
179 ,@(let ((main (ly:moment-main obj))
180 (grace (ly:moment-grace obj)))
181 (cond ((zero? grace) (list main))
182 ((negative? grace) (list main grace))
183 (else ;;positive grace requires 4-arg form
184 (list (numerator main)
187 (denominator grace)))))))
190 `(ly:make-duration ,(ly:duration-log obj)
191 ,@(if (= (ly:duration-scale obj) 1)
192 (if-nonzero (ly:duration-dot-count obj))
193 (list (ly:duration-dot-count obj)
194 (ly:duration-scale obj)))))
197 `(ly:make-pitch ,(ly:pitch-octave obj)
198 ,(ly:pitch-notename obj)
199 ,@(if-nonzero (ly:pitch-alteration obj))))
202 (or (procedure-name obj) obj))
203 (;; a symbol (avoid having an unquoted symbol)
206 (;; an empty list (avoid having an unquoted empty list)
211 `(list ,@(map music->make-music obj)))
214 `(cons ,(music->make-music (car obj))
215 ,(music->make-music (cdr obj))))
219 (use-modules (ice-9 pretty-print))
220 (define*-public (display-scheme-music obj #:optional (port (current-output-port)))
221 "Displays `obj', typically a music expression, in a friendly fashion,
222 which often can be read back in order to generate an equivalent expression."
223 (pretty-print (music->make-music obj) port)
227 ;;; Scheme music expression --> Lily-syntax-using string translator
229 (use-modules (srfi srfi-39)
232 (define*-public (display-lily-music expr parser #:optional (port (current-output-port))
233 #:key force-duration)
234 "Display the music expression using LilyPond syntax"
235 (memoize-clef-names supported-clefs)
236 (parameterize ((*indent* 0)
237 (*previous-duration* (ly:make-duration 2))
238 (*force-duration* force-duration))
239 (display (music->lily-string expr parser) port)
242 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
244 (define-public (shift-one-duration-log music shift dot)
245 "Add @var{shift} to @code{duration-log} of @code{'duration} in
246 @var{music} and optionally @var{dot} to any note encountered.
247 The number of dots in the shifted music may not be less than zero."
248 (let ((d (ly:music-property music 'duration)))
250 (let* ((cp (ly:duration-scale d))
251 (nd (ly:make-duration
252 (+ shift (ly:duration-log d))
253 (max 0 (+ dot (ly:duration-dot-count d)))
255 (set! (ly:music-property music 'duration) nd)))
256 ;clear cached length, since it's no longer valid
257 (set! (ly:music-property music 'length) '())
260 (define-public (shift-duration-log music shift dot)
261 (music-map (lambda (x) (shift-one-duration-log x shift dot))
264 (define-public (tremolo::get-music-list tremolo)
265 "Given a tremolo repeat, return a list of music to engrave for it.
266 This will be a stretched copy of its body, plus a TremoloEvent or
269 This is called only by Chord_tremolo_iterator."
270 (define (first-note-duration music)
271 "Finds the duration of the first NoteEvent by searching
272 depth-first through MUSIC."
273 ;; NoteEvent or a non-expanded chord-repetition
274 ;; We just take anything that actually sports an announced duration.
275 (if (ly:duration? (ly:music-property music 'duration))
276 (ly:music-property music 'duration)
277 (let loop ((elts (if (ly:music? (ly:music-property music 'element))
278 (list (ly:music-property music 'element))
279 (ly:music-property music 'elements))))
281 (let ((dur (first-note-duration (car elts))))
282 (if (ly:duration? dur)
284 (loop (cdr elts))))))))
285 (let* ((times (ly:music-property tremolo 'repeat-count))
286 (body (ly:music-property tremolo 'element))
287 (children (if (music-is-of-type? body 'sequential-music)
288 ;; \repeat tremolo n { ... }
289 (length (extract-named-music body '(EventChord
291 ;; \repeat tremolo n c4
293 (tremolo-type (if (positive? children)
294 (let* ((note-duration (first-note-duration body))
295 (duration-log (if (ly:duration? note-duration)
296 (ly:duration-log note-duration)
298 (ash 1 duration-log))
300 (stretched (ly:music-deep-copy body)))
301 (if (positive? children)
302 ;; # of dots is equal to the 1 in bitwise representation (minus 1)!
303 (let* ((dots (1- (logcount (* times children))))
304 ;; The remaining missing multiplier to scale the notes by
306 (mult (/ (* times children (ash 1 dots)) (1- (ash 2 dots))))
307 (shift (- (ly:intlog2 (floor mult)))))
308 (if (not (and (integer? mult) (= (logcount mult) 1)))
311 (ly:format (_ "invalid tremolo repeat count: ~a") times)))
312 ;; Make each note take the full duration
313 (ly:music-compress stretched (ly:make-moment 1 children))
314 ;; Adjust the displayed note durations
315 (shift-duration-log stretched shift dots)))
316 ;; Return the stretched body plus a tremolo event
318 (list (make-music 'TremoloEvent
320 'tremolo-type tremolo-type
321 'origin (ly:music-property tremolo 'origin))
323 (list (make-music 'TremoloSpanEvent
324 'span-direction START
326 'tremolo-type tremolo-type
327 'origin (ly:music-property tremolo 'origin))
329 (make-music 'TremoloSpanEvent
331 'origin (ly:music-property tremolo 'origin))))))
333 (define-public (make-repeat name times main alts)
334 "Create a repeat music expression, with all properties initialized
336 (let ((type (or (assoc-get name '(("volta" . VoltaRepeatedMusic)
337 ("unfold" . UnfoldedRepeatedMusic)
338 ("percent" . PercentRepeatedMusic)
339 ("tremolo" . TremoloRepeatedMusic)))
340 (begin (ly:warning (_ "unknown repeat type `~S': must be volta, unfold, percent, or tremolo") name)
341 'VoltaRepeatedMusic)))
342 (talts (if (< times (length alts))
344 (ly:warning (_ "More alternatives than repeats. Junking excess alternatives"))
349 'repeat-count (max times 1)
352 (define (calc-repeat-slash-count music)
353 "Given the child-list @var{music} in @code{PercentRepeatMusic},
354 calculate the number of slashes based on the durations. Returns @code{0}
355 if durations in @var{music} vary, allowing slash beats and double-percent
356 beats to be distinguished."
357 (let* ((durs (map duration-of-note
358 (extract-named-music music '(EventChord NoteEvent
359 RestEvent SkipEvent))))
360 (first-dur (car durs)))
362 (if (every (lambda (d) (equal? d first-dur)) durs)
363 (max (- (ly:duration-log first-dur) 2) 1)
366 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
369 (define-public (note-to-cluster music)
370 "Replace @code{NoteEvents} by @code{ClusterNoteEvents}."
371 (if (eq? (ly:music-property music 'name) 'NoteEvent)
372 (make-music 'ClusterNoteEvent
373 'pitch (ly:music-property music 'pitch)
374 'duration (ly:music-property music 'duration))
377 (define-public (notes-to-clusters music)
378 (music-map note-to-cluster music))
380 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
383 (define-public (unfold-repeats music)
384 "Replace all repeats with unfolded repeats."
385 (let ((es (ly:music-property music 'elements))
386 (e (ly:music-property music 'element)))
387 (if (music-is-of-type? music 'repeated-music)
388 (set! music (make-music 'UnfoldedRepeatedMusic music)))
390 (set! (ly:music-property music 'elements)
391 (map unfold-repeats es)))
393 (set! (ly:music-property music 'element)
397 (define-public (unfold-repeats-fully music)
398 "Unfolds repeats and expands the resulting @code{unfolded-repeated-music}."
401 (and (music-is-of-type? m 'unfolded-repeated-music)
402 (make-sequential-music
404 (let ((n (ly:music-property m 'repeat-count))
405 (alts (ly:music-property m 'elements))
406 (body (ly:music-property m 'element)))
408 ((null? alts) (make-list n body))
411 (zip (make-list n body)
412 (append! (make-list (max 0 (- n (length alts)))
415 (unfold-repeats music)))
417 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
418 ;; property setting music objs.
420 (define-safe-public (check-grob-path path #:optional parser location
426 "Check a grob path specification @var{path}, a symbol list (or a
427 single symbol), for validity and possibly complete it. Returns the
428 completed specification, or @code{#f} if invalid. If optional
429 @var{parser} is given, a syntax error is raised in that case,
430 optionally using @var{location}. If an optional keyword argument
431 @code{#:start @var{start}} is given, the parsing starts at the given
432 index in the sequence @samp{Context.Grob.property.sub-property...},
433 with the default of @samp{0} implying the full path.
435 If there is no valid first element of @var{path} fitting at the given
436 path location, an optionally given @code{#:default @var{default}} is
437 used as the respective element instead without checking it for
438 validity at this position.
440 The resulting path after possibly prepending @var{default} can be
441 constrained in length by optional arguments @code{#:min @var{min}} and
442 @code{#:max @var{max}}, defaulting to @samp{1} and unlimited,
444 (let ((path (if (symbol? path) (list path) path)))
445 ;; A Guile 1.x bug specific to optargs precludes moving the
446 ;; defines out of the let
447 (define (unspecial? s)
448 (not (or (object-property s 'is-grob?)
449 (object-property s 'backend-type?))))
451 (object-property s 'is-grob?))
452 (define (property? s)
453 (object-property s 'backend-type?))
454 (define (check c p) (c p))
458 (drop (list unspecial? grob? property?) start)))
462 ;; tricky. Should we make use of the default when the
463 ;; list is empty? In most cases, this question should be
464 ;; academical as an empty list can only be generated by
465 ;; Scheme and is likely an error. We consider this a case
466 ;; of "no valid first element, and default given".
467 ;; Usually, invalid use cases should be caught later using
468 ;; the #:min argument, and if the user explicitly does not
469 ;; catch this, we just follow through.
470 (if default (list default) '()))
472 ;; no checkers, so we have a valid first element and just
473 ;; take the path as-is.
476 (if ((car checkers) (car path))
477 (and (every check (cdr checkers) (cdr path))
479 (and (every check (cdr checkers) path)
480 (cons default path))))
482 (and (every check checkers path)
485 (if max (<= min (length res) max)
486 (<= min (length res))))
490 (ly:parser-error parser
491 (format #f (_ "bad grob property path ~a")
496 (define-public (make-grob-property-set grob gprop val)
497 "Make a @code{Music} expression that sets @var{gprop} to @var{val} in
498 @var{grob}. Does a pop first, i.e., this is not an override."
499 (make-music 'OverrideProperty
505 (define-public (make-grob-property-override grob gprop val)
506 "Make a @code{Music} expression that overrides @var{gprop} to @var{val}
508 (make-music 'OverrideProperty
513 (define-public (make-grob-property-revert grob gprop)
514 "Revert the grob property @var{gprop} for @var{grob}."
515 (make-music 'RevertProperty
517 'grob-property gprop))
519 (define direction-polyphonic-grobs
520 '(AccidentalSuggestion
538 (define general-grace-settings
539 `((Voice Stem font-size -3)
540 (Voice Flag font-size -3)
541 (Voice NoteHead font-size -3)
542 (Voice TabNoteHead font-size -4)
543 (Voice Dots font-size -3)
544 (Voice Stem length-fraction 0.8)
545 (Voice Stem no-stem-extend #t)
546 (Voice Beam beam-thickness 0.384)
547 (Voice Beam length-fraction 0.8)
548 (Voice Accidental font-size -4)
549 (Voice AccidentalCautionary font-size -4)
550 (Voice Script font-size -3)
551 (Voice Fingering font-size -8)
552 (Voice StringNumber font-size -8)))
554 (define-public score-grace-settings
556 `((Voice Stem direction ,UP)
557 (Voice Slur direction ,DOWN))
558 general-grace-settings))
560 (define-safe-public (make-voice-props-set n)
561 (make-sequential-music
563 (map (lambda (x) (make-grob-property-set x 'direction
565 direction-polyphonic-grobs)
567 (make-property-set 'graceSettings general-grace-settings)
568 (make-grob-property-set 'NoteColumn 'horizontal-shift (quotient n 2))))))
570 (define-safe-public (make-voice-props-override n)
571 (make-sequential-music
573 (map (lambda (x) (make-grob-property-override x 'direction
575 direction-polyphonic-grobs)
577 (make-property-set 'graceSettings general-grace-settings)
578 (make-grob-property-override 'NoteColumn 'horizontal-shift (quotient n 2))))))
580 (define-safe-public (make-voice-props-revert)
581 (make-sequential-music
583 (map (lambda (x) (make-grob-property-revert x 'direction))
584 direction-polyphonic-grobs)
585 (list (make-property-unset 'graceSettings)
586 (make-grob-property-revert 'NoteColumn 'horizontal-shift)))))
589 (define-safe-public (context-spec-music m context #:optional id)
590 "Add \\context CONTEXT = ID to M."
591 (let ((cm (make-music 'ContextSpeccedMusic
593 'context-type context)))
595 (set! (ly:music-property cm 'context-id) id))
598 (define-public (descend-to-context m context)
599 "Like @code{context-spec-music}, but only descending."
600 (let ((cm (context-spec-music m context)))
601 (ly:music-set-property! cm 'descend-only #t)
604 (define-public (make-non-relative-music mus)
605 (make-music 'UnrelativableMusic
608 (define-public (make-apply-context func)
609 (make-music 'ApplyContext
612 (define-public (make-sequential-music elts)
613 (make-music 'SequentialMusic
616 (define-public (make-simultaneous-music elts)
617 (make-music 'SimultaneousMusic
620 (define-safe-public (make-event-chord elts)
621 (make-music 'EventChord
624 (define-public (make-skip-music dur)
625 (make-music 'SkipMusic
628 (define-public (make-grace-music music)
629 (make-music 'GraceMusic
635 (define-public (make-multi-measure-rest duration location)
636 (make-music 'MultiMeasureRestMusic
640 (define-public (make-property-set sym val)
641 (make-music 'PropertySet
645 (define-public (make-property-unset sym)
646 (make-music 'PropertyUnset
649 (define-safe-public (make-articulation name . properties)
650 (apply make-music 'ArticulationEvent
651 'articulation-type name
654 (define-public (make-lyric-event string duration)
655 (make-music 'LyricEvent
659 (define-safe-public (make-span-event type span-dir)
661 'span-direction span-dir))
663 (define-public (override-head-style heads style)
664 "Override style for @var{heads} to @var{style}."
665 (make-sequential-music
668 (make-grob-property-override h 'style style))
670 (list (make-grob-property-override heads 'style style)))))
672 (define-public (revert-head-style heads)
673 "Revert style for @var{heads}."
674 (make-sequential-music
677 (make-grob-property-revert h 'style))
679 (list (make-grob-property-revert heads 'style)))))
681 (define-public (style-note-heads heads style music)
682 "Set @var{style} for all @var{heads} in @var{music}. Works both
683 inside of and outside of chord construct."
684 ;; are we inside a <...>?
685 (if (eq? (ly:music-property music 'name) 'NoteEvent)
686 ;; yes -> use a tweak
688 (set! (ly:music-property music 'tweaks)
689 (acons 'style style (ly:music-property music 'tweaks)))
691 ;; not in <...>, so use overrides
692 (make-sequential-music
694 (override-head-style heads style)
696 (revert-head-style heads)))))
698 (define-public (set-mus-properties! m alist)
699 "Set all of @var{alist} as properties of @var{m}."
702 (set! (ly:music-property m (caar alist)) (cdar alist))
703 (set-mus-properties! m (cdr alist)))))
705 (define-public (music-separator? m)
706 "Is @var{m} a separator?"
707 (let ((ts (ly:music-property m 'types)))
708 (memq 'separator ts)))
710 ;;; expanding repeat chords
711 (define-public (copy-repeat-chord original-chord repeat-chord duration
713 "Copies all events in @var{event-types} (be sure to include
714 @code{rhythmic-events}) from @var{original-chord} over to
715 @var{repeat-chord} with their articulations filtered as well. Any
716 duration is replaced with the specified @var{duration}."
717 ;; First remove everything from event-types that can already be
718 ;; found in the repeated chord. We don't need to look for
719 ;; articulations on individual events since they can't actually get
720 ;; into a repeat chord given its input syntax.
722 (define (keep-element? m)
723 (any (lambda (t) (music-is-of-type? m t))
725 (define origin (ly:music-property repeat-chord 'origin #f))
726 (define (set-origin! l)
728 (for-each (lambda (m) (set! (ly:music-property m 'origin) origin)) l))
733 (for-each (lambda (e)
734 (for-each (lambda (x)
735 (set! event-types (delq x event-types)))
736 (ly:music-property e 'types)))
737 (ly:music-property repeat-chord field)))
738 '(elements articulations))
740 ;; now treat the elements
741 (set! (ly:music-property repeat-chord 'elements)
743 (set-origin! (ly:music-deep-copy
744 (filter keep-element?
745 (ly:music-property original-chord
749 (let ((arts (ly:music-property m 'articulations)))
751 (set! (ly:music-property m 'articulations)
752 (set-origin! (filter! keep-element? arts))))
753 (if (ly:duration? (ly:music-property m 'duration))
754 (set! (ly:music-property m 'duration) duration))))
756 (append! elts (ly:music-property repeat-chord 'elements))))
757 (let ((arts (filter keep-element?
758 (ly:music-property original-chord
761 (set! (ly:music-property repeat-chord 'articulations)
763 (set-origin! (ly:music-deep-copy arts))
764 (ly:music-property repeat-chord 'articulations)))))
768 (define-public (expand-repeat-chords! event-types music)
769 "Walks through @var{music} and fills repeated chords (notable by
770 having a duration in @code{duration}) with the notes from their
771 respective predecessor chord."
772 (let loop ((music music) (last-chord #f))
773 (if (music-is-of-type? music 'event-chord)
774 (let ((chord-repeat (ly:music-property music 'duration)))
776 ((not (ly:duration? chord-repeat))
777 (if (any (lambda (m) (ly:duration?
778 (ly:music-property m 'duration)))
779 (ly:music-property music 'elements))
783 (set! (ly:music-property music 'duration) '())
784 (copy-repeat-chord last-chord music chord-repeat event-types))
786 (ly:music-warning music (_ "Bad chord repetition"))
788 (let ((elt (ly:music-property music 'element)))
789 (fold loop (if (ly:music? elt) (loop elt last-chord) last-chord)
790 (ly:music-property music 'elements)))))
793 ;;; This does _not_ copy any articulations. Rationale: one main
794 ;;; incentive for pitch-repeating durations is after ties, such that
795 ;;; 4~2~8. can stand in for a 15/16 note in \partial 4 position. In
796 ;;; this use case, any repeated articulations will be a nuisance.
798 ;;; String assignments in TabStaff might seem like a worthwhile
799 ;;; exception, but they would be better tackled by the respective
800 ;;; engravers themselves (see issue 3662).
802 ;;; Repeating chords as well seems problematic for things like
805 ;;; \new Staff { c4 c c <c e> }
806 ;;; \new RhythmicStaff { 4 4 4 4 }
810 ;;; However, because of MIDI it is not advisable to use RhythmicStaff
811 ;;; without any initial pitch/drum-type. For music functions taking
812 ;;; pure rhythms as an argument, the running of expand-repeat-notes!
813 ;;; at scorification time is irrelevant: at that point of time, the
814 ;;; music function has already run.
816 (define-public (expand-repeat-notes! music)
817 "Walks through @var{music} and gives pitchless notes (not having a
818 pitch in code{pitch} or a drum type in @code{drum-type}) the pitch(es)
819 from the predecessor note/chord if available."
820 (let ((last-pitch #f))
823 (define (set-and-ret last)
824 (set! last-pitch last)
827 ((music-is-of-type? m 'event-chord)
829 ((music-is-of-type? m 'note-event)
831 ((or (ly:music-property m 'pitch #f)
832 (ly:music-property m 'drum-type #f))
834 ;; ok, naked rhythm. Go through the various cases of
836 ;; nothing available: just keep as-is
838 ((ly:pitch? last-pitch)
839 (set! (ly:music-property m 'pitch) last-pitch)
841 ((symbol? last-pitch)
842 (set! (ly:music-property m 'drum-type) last-pitch)
844 ;; Ok, this is the big bad one: the reference is a chord.
845 ;; For now, we use the repeat chord logic. That's not
846 ;; really efficient as cleaning out all articulations is
847 ;; quite simpler than what copy-repeat-chord does.
849 (copy-repeat-chord last-pitch
850 (make-music 'EventChord
852 (ly:music-property m 'articulations)
854 (ly:music-property m 'origin))
855 (ly:music-property m 'duration)
856 '(rhythmic-event)))))
860 ;;; splitting chords into voices.
861 (define (voicify-list lst number)
862 "Make a list of Musics.
864 voicify-list :: [ [Music ] ] -> number -> [Music]
865 LST is a list music-lists.
867 NUMBER is 0-base, i.e., Voice=1 (upstems) has number 0.
871 (cons (context-spec-music
872 (make-sequential-music
873 (list (make-voice-props-set number)
874 (make-simultaneous-music (car lst))))
875 'Bottom (number->string (1+ number)))
876 (voicify-list (cdr lst) (1+ number)))))
878 (define (voicify-chord ch)
879 "Split the parts of a chord into different Voices using separator"
880 (let ((es (ly:music-property ch 'elements)))
881 (set! (ly:music-property ch 'elements)
882 (voicify-list (split-list-by-separator es music-separator?) 0))
885 (define-public (voicify-music m)
886 "Recursively split chords that are separated with @code{\\\\}."
887 (if (not (ly:music? m))
888 (ly:error (_ "music expected: ~S") m))
889 (let ((es (ly:music-property m 'elements))
890 (e (ly:music-property m 'element)))
893 (set! (ly:music-property m 'elements) (map voicify-music es)))
895 (set! (ly:music-property m 'element) (voicify-music e)))
896 (if (and (equal? (ly:music-property m 'name) 'SimultaneousMusic)
897 (any music-separator? es))
898 (set! m (context-spec-music (voicify-chord m) 'Staff)))
901 (define-public (empty-music)
904 ;; Make a function that checks score element for being of a specific type.
905 (define-public (make-type-checker symbol)
907 (grob::has-interface elt symbol)))
909 (define ((outputproperty-compatibility func sym val) grob g-context ao-context)
911 (set! (ly:grob-property grob sym) val)))
912 (export outputproperty-compatibility)
915 (define ((set-output-property grob-name symbol val) grob grob-c context)
917 @code{\\applyoutput #(set-output-property 'Clef 'extra-offset '(0 . 1))}"
918 (let ((meta (ly:grob-property grob 'meta)))
919 (if (equal? (assoc-get 'name meta) grob-name)
920 (set! (ly:grob-property grob symbol) val))))
921 (export set-output-property)
924 (define-public (skip->rest mus)
925 "Replace @var{mus} by @code{RestEvent} of the same duration if it is a
926 @code{SkipEvent}. Useful for extracting parts from crowded scores."
928 (if (memq (ly:music-property mus 'name) '(SkipEvent SkipMusic))
929 (make-music 'RestEvent 'duration (ly:music-property mus 'duration))
933 (define-public (music-has-type music type)
934 (memq type (ly:music-property music 'types)))
936 (define-public (music-clone music . music-properties)
937 "Clone @var{music} and set properties according to
938 @var{music-properties}, a list of alternating property symbols and
940 @example\n(music-clone start-span 'span-direction STOP)
942 Only properties that are not overriden by @var{music-properties} are
943 actually fully cloned."
944 (let ((old-props (list-copy (ly:music-mutable-properties music)))
946 (m (ly:make-music (ly:prob-immutable-properties music))))
947 (define (set-props mus-props)
948 (if (and (not (null? mus-props))
949 (not (null? (cdr mus-props))))
951 (set! old-props (assq-remove! old-props (car mus-props)))
954 (car mus-props) (cadr mus-props)))
955 (set-props (cddr mus-props)))))
956 (set-props music-properties)
959 (set! (ly:music-property m (car pair))
960 (ly:music-deep-copy (cdr pair))))
964 (set! (ly:music-property m (car pair)) (cdr pair)))
968 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
969 ;; warn for bare chords at start.
971 (define-public (ly:music-message music msg . rest)
972 (let ((ip (ly:music-property music 'origin)))
973 (if (ly:input-location? ip)
974 (apply ly:input-message ip msg rest)
975 (apply ly:message msg rest))))
977 (define-public (ly:music-warning music msg . rest)
978 (let ((ip (ly:music-property music 'origin)))
979 (if (ly:input-location? ip)
980 (apply ly:input-warning ip msg rest)
981 (apply ly:warning msg rest))))
983 (define-public (ly:event-warning event msg . rest)
984 (let ((ip (ly:event-property event 'origin)))
985 (if (ly:input-location? ip)
986 (apply ly:input-warning ip msg rest)
987 (apply ly:warning msg rest))))
989 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
991 ;; setting stuff for grace context.
994 (define (vector-extend v x)
995 "Make a new vector consisting of V, with X added to the end."
996 (let* ((n (vector-length v))
997 (nv (make-vector (+ n 1) '())))
998 (vector-move-left! v 0 n nv 0)
1002 (define (vector-map f v)
1003 "Map F over V. This function returns nothing."
1004 (do ((n (vector-length v))
1007 (f (vector-ref v i))))
1009 (define (vector-reverse-map f v)
1010 "Map F over V, N to 0 order. This function returns nothing."
1011 (do ((i (- (vector-length v) 1) (- i 1)))
1013 (f (vector-ref v i))))
1015 (define-public (add-grace-property context-name grob sym val)
1016 "Set @var{sym}=@var{val} for @var{grob} in @var{context-name}."
1017 (define (set-prop context)
1018 (let* ((where (or (ly:context-find context context-name) context))
1019 (current (ly:context-property where 'graceSettings))
1020 (new-settings (append current
1021 (list (list context-name grob sym val)))))
1022 (ly:context-set-property! where 'graceSettings new-settings)))
1023 (make-apply-context set-prop))
1025 (define-public (remove-grace-property context-name grob sym)
1026 "Remove all @var{sym} for @var{grob} in @var{context-name}."
1027 (define (sym-grob-context? property sym grob context-name)
1028 (and (eq? (car property) context-name)
1029 (eq? (cadr property) grob)
1030 (eq? (caddr property) sym)))
1031 (define (delete-prop context)
1032 (let* ((where (or (ly:context-find context context-name) context))
1033 (current (ly:context-property where 'graceSettings))
1034 (prop-settings (filter
1035 (lambda(x) (sym-grob-context? x sym grob context-name))
1037 (new-settings current))
1038 (for-each (lambda(x)
1039 (set! new-settings (delete x new-settings)))
1041 (ly:context-set-property! where 'graceSettings new-settings)))
1042 (make-apply-context delete-prop))
1045 (defmacro-public def-grace-function (start stop . docstring)
1046 "Helper macro for defining grace music"
1047 `(define-music-function (parser location music) (ly:music?)
1049 (make-music 'GraceMusic
1051 'element (make-music 'SequentialMusic
1052 'elements (list (ly:music-deep-copy ,start)
1054 (ly:music-deep-copy ,stop))))))
1056 (defmacro-public define-syntax-function (type args signature . body)
1057 "Helper macro for `ly:make-music-function'.
1059 (define-syntax-function result-type? (parser location arg1 arg2 ...) (arg1-type arg2-type ...)
1060 ...function body...)
1062 argX-type can take one of the forms @code{predicate?} for mandatory
1063 arguments satisfying the predicate, @code{(predicate?)} for optional
1064 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
1065 value)}} for optional parameters with a specified default
1066 value (evaluated at definition time). An optional parameter can be
1067 omitted in a call only when it can't get confused with a following
1068 parameter of different type.
1070 @code{result-type?} can specify a default in the same manner as
1071 predicates, to be used in case of a type error in arguments or
1074 (define (currying-lambda args doc-string? body)
1075 (if (and (pair? args)
1077 (currying-lambda (car args) doc-string?
1078 `((lambda ,(cdr args) ,@body)))
1080 `(lambda ,args ,doc-string? ,@body)
1081 `(lambda ,args ,@body))))
1083 (set! signature (map (lambda (pred)
1086 ,(and (pair? (cdr pred)) (cadr pred)))
1088 (cons type signature)))
1091 (and (pair? body) (pair? (cdr body))
1092 (if (string? (car body))
1094 (and (pair? (car body))
1095 (eq? '_i (caar body))
1097 (string? (cadar body))
1098 (null? (cddar body))
1100 ;; When the music function definition contains an i10n doc string,
1101 ;; (_i "doc string"), keep the literal string only
1102 `(ly:make-music-function
1104 ,(currying-lambda args docstring (if docstring (cdr body) body)))))
1106 (defmacro-public define-music-function rest
1107 "Defining macro returning music functions.
1109 (define-music-function (parser location arg1 arg2 ...) (arg1-type? arg2-type? ...)
1110 ...function body...)
1112 argX-type can take one of the forms @code{predicate?} for mandatory
1113 arguments satisfying the predicate, @code{(predicate?)} for optional
1114 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
1115 value)}} for optional parameters with a specified default
1116 value (evaluated at definition time). An optional parameter can be
1117 omitted in a call only when it can't get confused with a following
1118 parameter of different type.
1120 Must return a music expression. The @code{origin} is automatically
1121 set to the @code{location} parameter."
1123 `(define-syntax-function (ly:music? (make-music 'Music 'void #t)) ,@rest))
1126 (defmacro-public define-scheme-function rest
1127 "Defining macro returning Scheme functions.
1129 (define-scheme-function (parser location arg1 arg2 ...) (arg1-type? arg2-type? ...)
1130 ...function body...)
1132 argX-type can take one of the forms @code{predicate?} for mandatory
1133 arguments satisfying the predicate, @code{(predicate?)} for optional
1134 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
1135 value)}} for optional parameters with a specified default
1136 value (evaluated at definition time). An optional parameter can be
1137 omitted in a call only when it can't get confused with a following
1138 parameter of different type.
1140 Can return arbitrary expressions. If a music expression is returned,
1141 its @code{origin} is automatically set to the @code{location}
1144 `(define-syntax-function scheme? ,@rest))
1146 (defmacro-public define-void-function rest
1147 "This defines a Scheme function like @code{define-scheme-function} with
1148 void return value (i.e., what most Guile functions with `unspecified'
1149 value return). Use this when defining functions for executing actions
1150 rather than returning values, to keep Lilypond from trying to interpret
1152 `(define-syntax-function (void? *unspecified*) ,@rest *unspecified*))
1154 (defmacro-public define-event-function rest
1155 "Defining macro returning event functions.
1157 (define-event-function (parser location arg1 arg2 ...) (arg1-type? arg2-type? ...)
1158 ...function body...)
1160 argX-type can take one of the forms @code{predicate?} for mandatory
1161 arguments satisfying the predicate, @code{(predicate?)} for optional
1162 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
1163 value)}} for optional parameters with a specified default
1164 value (evaluated at definition time). An optional parameter can be
1165 omitted in a call only when it can't get confused with a following
1166 parameter of different type.
1168 Must return an event expression. The @code{origin} is automatically
1169 set to the @code{location} parameter."
1171 `(define-syntax-function (ly:event? (make-music 'Event 'void #t)) ,@rest))
1173 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1175 (define-public (cue-substitute quote-music)
1176 "Must happen after @code{quote-substitute}."
1178 (if (vector? (ly:music-property quote-music 'quoted-events))
1179 (let* ((dir (ly:music-property quote-music 'quoted-voice-direction))
1180 (clef (ly:music-property quote-music 'quoted-music-clef #f))
1181 (main-voice (case dir ((1) 1) ((-1) 0) (else #f)))
1182 (cue-voice (and main-voice (- 1 main-voice)))
1183 (cue-type (ly:music-property quote-music 'quoted-context-type #f))
1184 (cue-id (ly:music-property quote-music 'quoted-context-id))
1185 (main-music (ly:music-property quote-music 'element))
1186 (return-value quote-music))
1189 (set! (ly:music-property quote-music 'element)
1190 (make-sequential-music
1192 (make-voice-props-override main-voice)
1194 (make-voice-props-revert)))))
1196 ;; if we have stem dirs, change both quoted and main music
1197 ;; to have opposite stems.
1199 ;; cannot context-spec Quote-music, since context
1200 ;; for the quotes is determined in the iterator.
1202 (make-sequential-music
1205 (and clef (make-cue-clef-set clef))
1206 (and cue-type cue-voice
1208 (make-voice-props-override cue-voice)
1211 (and cue-type cue-voice
1213 (make-voice-props-revert)
1215 (and clef (make-cue-clef-unset))))))
1218 (define ((quote-substitute quote-tab) music)
1219 (let* ((quoted-name (ly:music-property music 'quoted-music-name))
1220 (quoted-vector (and (string? quoted-name)
1221 (hash-ref quote-tab quoted-name #f))))
1224 (if (string? quoted-name)
1225 (if (vector? quoted-vector)
1227 (set! (ly:music-property music 'quoted-events) quoted-vector)
1228 (set! (ly:music-property music 'iterator-ctor)
1229 ly:quote-iterator::constructor))
1230 (ly:music-warning music (ly:format (_ "cannot find quoted music: `~S'") quoted-name))))
1232 (export quote-substitute)
1235 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1236 ;; switch it on here, so parsing and init isn't checked (too slow!)
1238 ;; automatic music transformations.
1240 (define (switch-on-debugging m)
1241 (if (defined? 'set-debug-cell-accesses!)
1242 (set-debug-cell-accesses! 15000))
1245 (define (music-check-error music)
1248 (if (and (ly:music? m)
1249 (eq? (ly:music-property m 'error-found) #t))
1252 (for-each signal (ly:music-property music 'elements))
1253 (signal (ly:music-property music 'element))
1256 (set! (ly:music-property music 'error-found) #t))
1259 (define (precompute-music-length music)
1260 (set! (ly:music-property music 'length)
1261 (ly:music-length music))
1264 (define-public (make-duration-of-length moment)
1265 "Make duration of the given @code{moment} length."
1266 (ly:make-duration 0 0
1267 (ly:moment-main-numerator moment)
1268 (ly:moment-main-denominator moment)))
1270 (define (make-skipped moment bool)
1271 "Depending on BOOL, set or unset skipTypesetting,
1272 then make SkipMusic of the given MOMENT length, and
1273 then revert skipTypesetting."
1274 (make-sequential-music
1276 (context-spec-music (make-property-set 'skipTypesetting bool)
1278 (make-music 'SkipMusic 'duration
1279 (make-duration-of-length moment))
1280 (context-spec-music (make-property-set 'skipTypesetting (not bool))
1283 (define (skip-as-needed music parser)
1285 << { \\set skipTypesetting = ##f
1286 LENGTHOF(\\showFirstLength)
1287 \\set skipTypesetting = ##t
1288 LENGTHOF(\\showLastLength) }
1292 When only showFirstLength is set,
1293 the 'length property of the music is
1294 overridden to speed up compiling."
1296 ((show-last (ly:parser-lookup parser 'showLastLength))
1297 (show-first (ly:parser-lookup parser 'showFirstLength))
1298 (show-last-length (and (ly:music? show-last)
1299 (ly:music-length show-last)))
1300 (show-first-length (and (ly:music? show-first)
1301 (ly:music-length show-first)))
1302 (orig-length (ly:music-length music)))
1304 ;;FIXME: if using either showFirst- or showLastLength,
1305 ;; make sure that skipBars is not set.
1309 ;; both properties may be set.
1310 ((and show-first-length show-last-length)
1312 ((skip-length (ly:moment-sub orig-length show-last-length)))
1313 (make-simultaneous-music
1315 (make-sequential-music
1317 (make-skipped skip-length #t)
1318 ;; let's draw a separator between the beginning and the end
1319 (context-spec-music (make-property-set 'whichBar "||")
1321 (make-skipped show-first-length #f)
1324 ;; we may only want to print the last length
1327 ((skip-length (ly:moment-sub orig-length show-last-length)))
1328 (make-simultaneous-music
1330 (make-skipped skip-length #t)
1333 ;; we may only want to print the beginning; in this case
1334 ;; only the first length will be processed (much faster).
1336 ;; the first length must not exceed the original length.
1337 (if (ly:moment<? show-first-length orig-length)
1338 (set! (ly:music-property music 'length)
1345 (define-session-public toplevel-music-functions
1347 (lambda (music parser) (expand-repeat-chords!
1348 (cons 'rhythmic-event
1349 (ly:parser-lookup parser '$chord-repeat-events))
1351 (lambda (music parser) (expand-repeat-notes! music))
1352 (lambda (music parser) (voicify-music music))
1353 (lambda (x parser) (music-map music-check-error x))
1354 (lambda (x parser) (music-map precompute-music-length x))
1355 (lambda (music parser)
1357 (music-map (quote-substitute (ly:parser-lookup parser 'musicQuotes)) music))
1359 ;; switch-on-debugging
1360 (lambda (x parser) (music-map cue-substitute x))
1363 (skip-as-needed x parser)
1367 ;;; general purpose music functions
1369 (define (shift-octave pitch octave-shift)
1370 (_i "Add @var{octave-shift} to the octave of @var{pitch}.")
1372 (+ (ly:pitch-octave pitch) octave-shift)
1373 (ly:pitch-notename pitch)
1374 (ly:pitch-alteration pitch)))
1380 (define (apply-durations lyric-music durations)
1381 (define (apply-duration music)
1382 (if (and (not (equal? (ly:music-length music) ZERO-MOMENT))
1383 (ly:duration? (ly:music-property music 'duration)))
1385 (set! (ly:music-property music 'duration) (car durations))
1386 (set! durations (cdr durations)))))
1388 (music-map apply-duration lyric-music))
1391 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1394 (define (recent-enough? bar-number alteration-def laziness)
1395 (or (number? alteration-def)
1396 (equal? laziness #t)
1397 (<= bar-number (+ (cadr alteration-def) laziness))))
1399 (define (accidental-invalid? alteration-def)
1400 "Checks an alteration entry for being invalid.
1402 Non-key alterations are invalidated when tying into the next bar or
1403 when there is a clef change, since neither repetition nor cancellation
1404 can be omitted when the same note occurs again.
1406 Returns @code{#f} or the reason for the invalidation, a symbol."
1407 (let* ((def (if (pair? alteration-def)
1408 (car alteration-def)
1410 (and (symbol? def) def)))
1412 (define (extract-alteration alteration-def)
1413 (cond ((number? alteration-def)
1415 ((pair? alteration-def)
1416 (car alteration-def))
1419 (define (check-pitch-against-signature context pitch barnum laziness octaveness all-naturals)
1420 "Checks the need for an accidental and a @q{restore} accidental against
1421 @code{localAlterations} and @code{keyAlterations}.
1422 The @var{laziness} is the number of measures
1423 for which reminder accidentals are used (i.e., if @var{laziness} is zero,
1424 only cancel accidentals in the same measure; if @var{laziness} is three,
1425 we cancel accidentals up to three measures after they first appear.
1426 @var{octaveness} is either @code{'same-octave} or @code{'any-octave} and
1427 specifies whether accidentals should be canceled in different octaves.
1428 If @var{all-naturals} is ##t, notes that do not occur in @code{keyAlterations}
1429 also get an accidental."
1430 (let* ((ignore-octave (cond ((equal? octaveness 'any-octave) #t)
1431 ((equal? octaveness 'same-octave) #f)
1433 (ly:warning (_ "Unknown octaveness type: ~S ") octaveness)
1434 (ly:warning (_ "Defaulting to 'any-octave."))
1436 (key (ly:context-property context 'keyAlterations))
1437 (local (ly:context-property context 'localAlterations))
1438 (notename (ly:pitch-notename pitch))
1439 (octave (ly:pitch-octave pitch))
1440 (pitch-handle (cons octave notename))
1442 (need-accidental #f)
1443 (previous-alteration #f)
1444 (from-other-octaves #f)
1445 (from-same-octave (assoc-get pitch-handle local))
1446 (from-key-sig (or (assoc-get notename local)
1448 ;; If no notename match is found from localAlterations, we may have a custom
1449 ;; type with octave-specific entries of the form ((octave . pitch) alteration)
1450 ;; instead of (pitch . alteration). Since this type cannot coexist with entries in
1451 ;; localAlterations, try extracting from keyAlterations instead.
1452 (assoc-get pitch-handle key))))
1454 ;; loop through localAlterations to search for a notename match from other octaves
1455 (let loop ((l local))
1457 (let ((entry (car l)))
1458 (if (and (pair? (car entry))
1459 (= (cdar entry) notename))
1460 (set! from-other-octaves (cdr entry))
1463 ;; find previous alteration-def for comparison with pitch
1465 ;; from same octave?
1466 ((and (not ignore-octave)
1468 (recent-enough? barnum from-same-octave laziness))
1469 (set! previous-alteration from-same-octave))
1474 (recent-enough? barnum from-other-octaves laziness))
1475 (set! previous-alteration from-other-octaves))
1477 ;; not recent enough, extract from key signature/local key signature
1479 (set! previous-alteration from-key-sig)))
1481 (if (accidental-invalid? previous-alteration)
1482 (set! need-accidental #t)
1484 (let* ((prev-alt (extract-alteration previous-alteration))
1485 (this-alt (ly:pitch-alteration pitch)))
1487 (if (or (and all-naturals (eq? #f previous-alteration)) (not (= this-alt prev-alt)))
1489 (set! need-accidental #t)
1490 (if (and (not (= this-alt 0))
1491 (and (< (abs this-alt) (abs prev-alt))
1492 (> (* prev-alt this-alt) 0)))
1493 (set! need-restore #t))))))
1495 (cons need-restore need-accidental)))
1497 (define ((make-accidental-rule octaveness laziness) context pitch barnum measurepos)
1498 "Create an accidental rule that makes its decision based on the octave of
1499 the note and a laziness value.
1501 @var{octaveness} is either @code{'same-octave} or @code{'any-octave} and
1502 defines whether the rule should respond to accidental changes in other
1503 octaves than the current. @code{'same-octave} is the normal way to typeset
1504 accidentals -- an accidental is made if the alteration is different from the
1505 last active pitch in the same octave. @code{'any-octave} looks at the last
1506 active pitch in any octave.
1508 @var{laziness} states over how many bars an accidental should be remembered.
1509 @code{0}@tie{}is the default -- accidental lasts over 0@tie{}bar lines, that
1510 is, to the end of current measure. A positive integer means that the
1511 accidental lasts over that many bar lines. @w{@code{-1}} is `forget
1512 immediately', that is, only look at key signature. @code{#t} is `forever'."
1514 (check-pitch-against-signature context pitch barnum laziness octaveness #f))
1515 (export make-accidental-rule)
1517 (define ((make-accidental-dodecaphonic-rule octaveness laziness) context pitch barnum measurepos)
1518 "Variation on function make-accidental-rule that creates an dodecaphonic
1521 (check-pitch-against-signature context pitch barnum laziness octaveness #t))
1522 (export make-accidental-dodecaphonic-rule)
1524 (define (key-entry-notename entry)
1525 "Return the pitch of an @var{entry} in @code{localAlterations}.
1526 The @samp{car} of the entry is either of the form @code{notename} or
1527 of the form @code{(octave . notename)}. The latter form is used for special
1528 key signatures or to indicate an explicit accidental.
1530 The @samp{cdr} of the entry is either a rational @code{alter} indicating
1531 a key signature alteration, or of the form
1532 @code{(alter . (barnum . measurepos))} indicating an alteration caused by
1533 an accidental in music."
1534 (if (pair? (car entry))
1538 (define (key-entry-octave entry)
1539 "Return the octave of an entry in @code{localAlterations}
1540 or @code{#f} if the entry does not have an octave.
1541 See @code{key-entry-notename} for details."
1542 (and (pair? (car entry)) (caar entry)))
1544 (define (key-entry-bar-number entry)
1545 "Return the bar number of an entry in @code{localAlterations}
1546 or @code {#f} if the entry does not have a bar number.
1547 See @code{key-entry-notename} for details."
1548 (and (pair? (cdr entry)) (caddr entry)))
1550 (define (key-entry-measure-position entry)
1551 "Return the measure position of an entry in @code{localAlterations}
1552 or @code {#f} if the entry does not have a measure position.
1553 See @code{key-entry-notename} for details."
1554 (and (pair? (cdr entry)) (cdddr entry)))
1556 (define (key-entry-alteration entry)
1557 "Return the alteration of an entry in localAlterations
1559 For convenience, returns @code{0} if entry is @code{#f}."
1561 (if (number? (cdr entry))
1566 (define-public (find-pitch-entry keysig pitch accept-global accept-local)
1567 "Return the first entry in @var{keysig} that matches @var{pitch}
1568 by notename and octave. Alteration is not considered.
1569 @var{accept-global} states whether key signature entries should be included.
1570 @var{accept-local} states whether local accidentals should be included.
1571 If no matching entry is found, @var{#f} is returned."
1573 (let* ((entry (car keysig))
1574 (entryoct (key-entry-octave entry))
1575 (entrynn (key-entry-notename entry))
1576 (nn (ly:pitch-notename pitch)))
1577 (if (and (equal? nn entrynn)
1579 (= entryoct (ly:pitch-octave pitch)))
1580 (if (key-entry-bar-number entry)
1584 (find-pitch-entry (cdr keysig) pitch accept-global accept-local)))))
1586 (define-public (neo-modern-accidental-rule context pitch barnum measurepos)
1587 "An accidental rule that typesets an accidental if it differs from the
1588 key signature @emph{and} does not directly follow a note on the same
1589 staff line. This rule should not be used alone because it does neither
1590 look at bar lines nor different accidentals at the same note name."
1591 (let* ((keysig (ly:context-property context 'localAlterations))
1592 (entry (find-pitch-entry keysig pitch #t #t)))
1595 (let* ((global-entry (find-pitch-entry keysig pitch #t #f))
1596 (key-acc (key-entry-alteration global-entry))
1597 (acc (ly:pitch-alteration pitch))
1598 (entrymp (key-entry-measure-position entry))
1599 (entrybn (key-entry-bar-number entry)))
1600 (cons #f (not (or (equal? acc key-acc)
1601 (and (equal? entrybn barnum) (equal? entrymp measurepos)))))))))
1603 (define-public (dodecaphonic-no-repeat-rule context pitch barnum measurepos)
1604 "An accidental rule that typesets an accidental before every
1605 note (just as in the dodecaphonic accidental style) @emph{except} if
1606 the note is immediately preceded by a note with the same pitch. This
1607 is a common accidental style in contemporary notation."
1608 (let* ((keysig (ly:context-property context 'localAlterations))
1609 (entry (find-pitch-entry keysig pitch #f #t)))
1612 (let ((entrymp (key-entry-measure-position entry))
1613 (entrybn (key-entry-bar-number entry))
1614 (entryalt (key-entry-alteration entry))
1615 (alt (ly:pitch-alteration pitch)))
1617 (not (and (equal? entrybn barnum)
1618 (or (equal? measurepos entrymp)
1619 (ly:moment<? measurepos entrymp))
1620 (equal? entryalt alt))))))))
1622 (define-public (teaching-accidental-rule context pitch barnum measurepos)
1623 "An accidental rule that typesets a cautionary accidental if it is
1624 included in the key signature @emph{and} does not directly follow a note
1625 on the same staff line."
1626 (let* ((keysig (ly:context-property context 'localAlterations))
1627 (entry (find-pitch-entry keysig pitch #t #t)))
1630 (let* ((global-entry (find-pitch-entry keysig pitch #f #f))
1631 (key-acc (key-entry-alteration global-entry))
1632 (acc (ly:pitch-alteration pitch))
1633 (entrymp (key-entry-measure-position entry))
1634 (entrybn (key-entry-bar-number entry)))
1635 (cons #f (not (or (equal? acc key-acc)
1636 (and (equal? entrybn barnum) (equal? entrymp measurepos)))))))))
1638 (define-public (set-accidentals-properties extra-natural
1639 auto-accs auto-cauts
1642 (make-sequential-music
1643 (append (if (boolean? extra-natural)
1644 (list (make-property-set 'extraNatural extra-natural))
1646 (list (make-property-set 'autoAccidentals auto-accs)
1647 (make-property-set 'autoCautionaries auto-cauts))))
1650 (define-public (set-accidental-style style . rest)
1651 "Set accidental style to @var{style}. Optionally take a context
1652 argument, e.g. @code{'Staff} or @code{'Voice}. The context defaults
1653 to @code{Staff}, except for piano styles, which use @code{GrandStaff}
1655 (let ((context (if (pair? rest)
1657 (pcontext (if (pair? rest)
1658 (car rest) 'GrandStaff)))
1660 ;; accidentals as they were common in the 18th century.
1661 ((equal? style 'default)
1662 (set-accidentals-properties #t
1663 `(Staff ,(make-accidental-rule 'same-octave 0))
1666 ;; accidentals from one voice do NOT get canceled in other voices
1667 ((equal? style 'voice)
1668 (set-accidentals-properties #t
1669 `(Voice ,(make-accidental-rule 'same-octave 0))
1672 ;; accidentals as suggested by Kurt Stone, Music Notation in the 20th century.
1673 ;; This includes all the default accidentals, but accidentals also needs canceling
1674 ;; in other octaves and in the next measure.
1675 ((equal? style 'modern)
1676 (set-accidentals-properties #f
1677 `(Staff ,(make-accidental-rule 'same-octave 0)
1678 ,(make-accidental-rule 'any-octave 0)
1679 ,(make-accidental-rule 'same-octave 1))
1682 ;; the accidentals that Stone adds to the old standard as cautionaries
1683 ((equal? style 'modern-cautionary)
1684 (set-accidentals-properties #f
1685 `(Staff ,(make-accidental-rule 'same-octave 0))
1686 `(Staff ,(make-accidental-rule 'any-octave 0)
1687 ,(make-accidental-rule 'same-octave 1))
1689 ;; same as modern, but accidentals different from the key signature are always
1690 ;; typeset - unless they directly follow a note of the same pitch.
1691 ((equal? style 'neo-modern)
1692 (set-accidentals-properties #f
1693 `(Staff ,(make-accidental-rule 'same-octave 0)
1694 ,(make-accidental-rule 'any-octave 0)
1695 ,(make-accidental-rule 'same-octave 1)
1696 ,neo-modern-accidental-rule)
1699 ((equal? style 'neo-modern-cautionary)
1700 (set-accidentals-properties #f
1701 `(Staff ,(make-accidental-rule 'same-octave 0))
1702 `(Staff ,(make-accidental-rule 'any-octave 0)
1703 ,(make-accidental-rule 'same-octave 1)
1704 ,neo-modern-accidental-rule)
1706 ((equal? style 'neo-modern-voice)
1707 (set-accidentals-properties #f
1708 `(Voice ,(make-accidental-rule 'same-octave 0)
1709 ,(make-accidental-rule 'any-octave 0)
1710 ,(make-accidental-rule 'same-octave 1)
1711 ,neo-modern-accidental-rule
1712 Staff ,(make-accidental-rule 'same-octave 0)
1713 ,(make-accidental-rule 'any-octave 0)
1714 ,(make-accidental-rule 'same-octave 1)
1715 ,neo-modern-accidental-rule)
1718 ((equal? style 'neo-modern-voice-cautionary)
1719 (set-accidentals-properties #f
1720 `(Voice ,(make-accidental-rule 'same-octave 0))
1721 `(Voice ,(make-accidental-rule 'any-octave 0)
1722 ,(make-accidental-rule 'same-octave 1)
1723 ,neo-modern-accidental-rule
1724 Staff ,(make-accidental-rule 'same-octave 0)
1725 ,(make-accidental-rule 'any-octave 0)
1726 ,(make-accidental-rule 'same-octave 1)
1727 ,neo-modern-accidental-rule)
1729 ;; Accidentals as they were common in dodecaphonic music with no tonality.
1730 ;; Each note gets one accidental.
1731 ((equal? style 'dodecaphonic)
1732 (set-accidentals-properties #f
1733 `(Staff ,(lambda (c p bn mp) '(#f . #t)))
1736 ;; As in dodecaphonic style with the exception that immediately
1737 ;; repeated notes (in the same voice) don't get an accidental
1738 ((equal? style 'dodecaphonic-no-repeat)
1739 (set-accidentals-properties #f
1740 `(Staff ,dodecaphonic-no-repeat-rule)
1743 ;; Variety of the dodecaphonic style. Each note gets an accidental,
1744 ;; except notes that were already handled in the same measure.
1745 ((equal? style 'dodecaphonic-first)
1746 (set-accidentals-properties #f
1747 `(Staff ,(make-accidental-dodecaphonic-rule 'same-octave 0))
1751 ;; Multivoice accidentals to be read both by musicians playing one voice
1752 ;; and musicians playing all voices.
1753 ;; Accidentals are typeset for each voice, but they ARE canceled across voices.
1754 ((equal? style 'modern-voice)
1755 (set-accidentals-properties #f
1756 `(Voice ,(make-accidental-rule 'same-octave 0)
1757 ,(make-accidental-rule 'any-octave 0)
1758 ,(make-accidental-rule 'same-octave 1)
1759 Staff ,(make-accidental-rule 'same-octave 0)
1760 ,(make-accidental-rule 'any-octave 0)
1761 ,(make-accidental-rule 'same-octave 1))
1764 ;; same as modernVoiceAccidental eccept that all special accidentals are typeset
1766 ((equal? style 'modern-voice-cautionary)
1767 (set-accidentals-properties #f
1768 `(Voice ,(make-accidental-rule 'same-octave 0))
1769 `(Voice ,(make-accidental-rule 'any-octave 0)
1770 ,(make-accidental-rule 'same-octave 1)
1771 Staff ,(make-accidental-rule 'same-octave 0)
1772 ,(make-accidental-rule 'any-octave 0)
1773 ,(make-accidental-rule 'same-octave 1))
1775 ;; stone's suggestions for accidentals on grand staff.
1776 ;; Accidentals are canceled across the staves in the same grand staff as well
1777 ((equal? style 'piano)
1778 (set-accidentals-properties #f
1779 `(Staff ,(make-accidental-rule 'same-octave 0)
1780 ,(make-accidental-rule 'any-octave 0)
1781 ,(make-accidental-rule 'same-octave 1)
1783 ,(make-accidental-rule 'any-octave 0)
1784 ,(make-accidental-rule 'same-octave 1))
1787 ((equal? style 'piano-cautionary)
1788 (set-accidentals-properties #f
1789 `(Staff ,(make-accidental-rule 'same-octave 0))
1790 `(Staff ,(make-accidental-rule 'any-octave 0)
1791 ,(make-accidental-rule 'same-octave 1)
1793 ,(make-accidental-rule 'any-octave 0)
1794 ,(make-accidental-rule 'same-octave 1))
1797 ;; same as modern, but cautionary accidentals are printed for all sharp or flat
1798 ;; tones specified by the key signature.
1799 ((equal? style 'teaching)
1800 (set-accidentals-properties #f
1801 `(Staff ,(make-accidental-rule 'same-octave 0))
1802 `(Staff ,(make-accidental-rule 'same-octave 1)
1803 ,teaching-accidental-rule)
1806 ;; do not set localAlterations when a note alterated differently from
1807 ;; localAlterations is found.
1808 ;; Causes accidentals to be printed at every note instead of
1809 ;; remembered for the duration of a measure.
1810 ;; accidentals not being remembered, causing accidentals always to
1811 ;; be typeset relative to the time signature
1812 ((equal? style 'forget)
1813 (set-accidentals-properties '()
1814 `(Staff ,(make-accidental-rule 'same-octave -1))
1817 ;; Do not reset the key at the start of a measure. Accidentals will be
1818 ;; printed only once and are in effect until overridden, possibly many
1820 ((equal? style 'no-reset)
1821 (set-accidentals-properties '()
1822 `(Staff ,(make-accidental-rule 'same-octave #t))
1826 (ly:warning (_ "unknown accidental style: ~S") style)
1827 (make-sequential-music '())))))
1829 (define-public (invalidate-alterations context)
1830 "Invalidate alterations in @var{context}.
1832 Elements of @code{'localAlterations} corresponding to local
1833 alterations of the key signature have the form
1834 @code{'((octave . notename) . (alter barnum . measurepos))}.
1835 Replace them with a version where @code{alter} is set to @code{'clef}
1836 to force a repetition of accidentals.
1838 Entries that conform with the current key signature are not invalidated."
1839 (let* ((keysig (ly:context-property context 'keyAlterations)))
1840 (set! (ly:context-property context 'localAlterations)
1843 (let* ((localalt (key-entry-alteration entry)))
1844 (if (or (accidental-invalid? localalt)
1845 (not (key-entry-bar-number entry))
1847 (key-entry-alteration
1850 (ly:make-pitch (key-entry-octave entry)
1851 (key-entry-notename entry)
1855 (cons (car entry) (cons 'clef (cddr entry))))))
1856 (ly:context-property context 'localAlterations)))))
1858 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1860 (define-public (skip-of-length mus)
1861 "Create a skip of exactly the same length as @var{mus}."
1865 'duration (ly:make-duration 0 0))))
1867 (make-event-chord (list (ly:music-compress skip (ly:music-length mus))))))
1869 (define-public (mmrest-of-length mus)
1870 "Create a multi-measure rest of exactly the same length as @var{mus}."
1873 (make-multi-measure-rest
1874 (ly:make-duration 0 0) '())))
1875 (ly:music-compress skip (ly:music-length mus))
1878 (define-public (pitch-of-note event-chord)
1879 (let ((evs (filter (lambda (x)
1880 (music-has-type x 'note-event))
1881 (ly:music-property event-chord 'elements))))
1884 (ly:music-property (car evs) 'pitch))))
1886 (define-public (duration-of-note event-chord)
1888 ((pair? event-chord)
1889 (or (duration-of-note (car event-chord))
1890 (duration-of-note (cdr event-chord))))
1891 ((ly:music? event-chord)
1892 (let ((dur (ly:music-property event-chord 'duration)))
1893 (if (ly:duration? dur)
1895 (duration-of-note (ly:music-property event-chord 'elements)))))
1898 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1900 (define-public (map-some-music map? music)
1901 "Walk through @var{music}, transform all elements calling @var{map?}
1902 and only recurse if this returns @code{#f}. @code{elements} or
1903 @code{articulations} that are not music expressions are discarded:
1904 this allows some amount of filtering.
1906 @code{map-some-music} may overwrite the original @var{music}."
1907 (let loop ((music music))
1909 (let ((elt (ly:music-property music 'element))
1910 (elts (ly:music-property music 'elements))
1911 (arts (ly:music-property music 'articulations)))
1913 (set! (ly:music-property music 'element)
1916 (set! (ly:music-property music 'elements)
1917 (filter! ly:music? (map! loop elts))))
1919 (set! (ly:music-property music 'articulations)
1920 (filter! ly:music? (map! loop arts))))
1923 (define-public (for-some-music stop? music)
1924 "Walk through @var{music}, process all elements calling @var{stop?}
1925 and only recurse if this returns @code{#f}."
1926 (let loop ((music music))
1927 (if (not (stop? music))
1928 (let ((elt (ly:music-property music 'element)))
1931 (for-each loop (ly:music-property music 'elements))
1932 (for-each loop (ly:music-property music 'articulations))))))
1934 (define-public (fold-some-music pred? proc init music)
1935 "This works recursively on music like @code{fold} does on a list,
1936 calling @samp{(@var{pred?} music)} on every music element. If
1937 @code{#f} is returned for an element, it is processed recursively
1938 with the same initial value of @samp{previous}, otherwise
1939 @samp{(@var{proc} music previous)} replaces @samp{previous}
1940 and no recursion happens.
1941 The top @var{music} is processed using @var{init} for @samp{previous}."
1942 (let loop ((music music) (previous init))
1944 (proc music previous)
1947 (let ((elt (ly:music-property music 'element)))
1950 (loop elt previous)))
1951 (ly:music-property music 'elements))
1952 (ly:music-property music 'articulations)))))
1954 (define-public (extract-music music pred?)
1955 "Return a flat list of all music matching @var{pred?} inside of
1956 @var{music}, not recursing into matches themselves."
1957 (reverse! (fold-some-music pred? cons '() music)))
1959 (define-public (extract-named-music music music-name)
1960 "Return a flat list of all music named @var{music-name} (either a
1961 single event symbol or a list of alternatives) inside of @var{music},
1962 not recursing into matches themselves."
1965 (if (cheap-list? music-name)
1966 (lambda (m) (memq (ly:music-property m 'name) music-name))
1967 (lambda (m) (eq? (ly:music-property m 'name) music-name)))))
1969 (define-public (extract-typed-music music type)
1970 "Return a flat list of all music with @var{type} (either a single
1971 type symbol or a list of alternatives) inside of @var{music}, not
1972 recursing into matches themselves."
1975 (if (cheap-list? type)
1977 (any (lambda (t) (music-is-of-type? m t)) type))
1978 (lambda (m) (music-is-of-type? m type)))))
1980 (define*-public (event-chord-wrap! music #:optional parser)
1981 "Wrap isolated rhythmic events and non-postevent events in
1982 @var{music} inside of an @code{EventChord}. If the optional
1983 @var{parser} argument is given, chord repeats @samp{q} are expanded
1984 using the default settings. Otherwise, you need to cater for them
1988 (cond ((music-is-of-type? m 'event-chord)
1989 (if (pair? (ly:music-property m 'articulations))
1991 (set! (ly:music-property m 'elements)
1992 (append (ly:music-property m 'elements)
1993 (ly:music-property m 'articulations)))
1994 (set! (ly:music-property m 'articulations) '())))
1996 ((music-is-of-type? m 'rhythmic-event)
1997 (let ((arts (ly:music-property m 'articulations)))
1999 (set! (ly:music-property m 'articulations) '()))
2000 (make-event-chord (cons m arts))))
2003 (expand-repeat-chords!
2004 (cons 'rhythmic-event
2005 (ly:parser-lookup parser '$chord-repeat-events))
2009 (define-public (event-chord-notes event-chord)
2010 "Return a list of all notes from @var{event-chord}."
2012 (lambda (m) (eq? 'NoteEvent (ly:music-property m 'name)))
2013 (ly:music-property event-chord 'elements)))
2015 (define-public (event-chord-pitches event-chord)
2016 "Return a list of all pitches from @var{event-chord}."
2017 (map (lambda (x) (ly:music-property x 'pitch))
2018 (event-chord-notes event-chord)))
2020 (define-public (event-chord-reduce music)
2021 "Reduces event chords in @var{music} to their first note event,
2022 retaining only the chord articulations. Returns the modified music."
2025 (and (music-is-of-type? m 'event-chord)
2026 (let*-values (((notes arts) (partition
2028 (music-is-of-type? mus 'rhythmic-event))
2029 (ly:music-property m 'elements)))
2030 ((dur) (ly:music-property m 'duration))
2031 ((full-arts) (append arts
2032 (ly:music-property m 'articulations)))
2033 ((first-note) (and (pair? notes) (car notes))))
2035 (set! (ly:music-property first-note 'articulations)
2039 ;; A repeat chord. Produce an unpitched note.
2040 (make-music 'NoteEvent
2042 'articulations full-arts))
2044 (ly:music-error m (_ "Missing duration"))
2045 (make-music 'NoteEvent
2046 'duration (ly:make-duration 2 0 0)
2047 'articulations full-arts))))))
2051 (defmacro-public make-relative (variables reference music)
2052 "The list of pitch or music variables in @var{variables} is used as
2053 a sequence for creating relativable music from @var{music}.
2055 When the constructed music is used outside of @code{\\relative}, it
2056 just reflects plugging in the @var{variables} into @var{music}.
2058 The action inside of @code{\\relative}, however, is determined by
2059 first relativizing the surrogate @var{reference} with the variables
2060 plugged in and then using the variables relativized as a side effect
2061 of relativizing @var{reference} for evaluating @var{music}.
2063 Since pitches don't have the object identity required for tracing the
2064 effect of the reference call, they are replaced @emph{only} for the
2065 purpose of evaluating @var{reference} with simple pitched note events.
2067 The surrogate @var{reference} expression has to be written with that
2068 in mind. In addition, it must @emph{not} contain @emph{copies} of
2069 music that is supposed to be relativized but rather the
2070 @emph{originals}. This @emph{includes} the pitch expressions. As a
2071 rule, inside of @code{#@{@dots{}#@}} variables must @emph{only} be
2072 introduced using @code{#}, never via the copying construct @code{$}.
2073 The reference expression will usually just be a sequential or chord
2074 expression naming all variables in sequence, implying that following
2075 music will be relativized according to the resulting pitch of the last
2076 or first variable, respectively.
2078 Since the usual purpose is to create more complex music from general
2079 arguments and since music expression parts must not occur more than
2080 once, one @emph{does} generally need to use copying operators in the
2081 @emph{replacement} expression @var{music} when using an argument more
2082 than once there. Using an argument more than once in @var{reference},
2083 in contrast, does not make sense.
2085 There is another fine point to mind: @var{music} must @emph{only}
2086 contain freshly constructed elements or copied constructs. This will
2087 be the case anyway for regular LilyPond code inside of
2088 @code{#@{@dots{}#@}}, but any other elements (apart from the
2089 @var{variables} themselves which are already copied) must be created
2092 The reason is that it is usually permitted to change music in-place as
2093 long as one does a @var{ly:music-deep-copy} on it, and such a copy of
2094 the whole resulting expression will @emph{not} be able to copy
2095 variables/values inside of closures where the information for
2096 relativization is being stored.
2099 ;; pitch and music generator might be stored instead in music
2100 ;; properties, and it might make sense to create a music type of its
2101 ;; own for this kind of construct rather than using
2102 ;; RelativeOctaveMusic
2103 (define ((make-relative::to-relative-callback variables music-call ref-call)
2105 (let* ((ref-vars (map (lambda (v)
2107 (make-music 'NoteEvent 'pitch v)
2108 (ly:music-deep-copy v)))
2110 (after-pitch (ly:make-music-relative! (apply ref-call ref-vars) pitch))
2111 (actual-vars (map (lambda (v r)
2113 (ly:music-property r 'pitch)
2115 variables ref-vars))
2116 (rel-music (apply music-call actual-vars)))
2117 (set! (ly:music-property music 'element) rel-music)
2119 `(make-music 'RelativeOctaveMusic
2120 'to-relative-callback
2121 (,make-relative::to-relative-callback
2123 (lambda ,variables ,music)
2124 (lambda ,variables ,reference))
2127 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2128 ;; The following functions are all associated with the crossStaff
2131 (define (close-enough? x y)
2132 "Values are close enough to ignore the difference"
2133 (< (abs (- x y)) 0.0001))
2135 (define (extent-combine extents)
2136 "Combine a list of extents"
2137 (if (pair? (cdr extents))
2138 (interval-union (car extents) (extent-combine (cdr extents)))
2141 (define ((stem-connectable? ref root) stem)
2142 "Check if the stem is connectable to the root"
2143 ;; The root is always connectable to itself
2146 ;; Horizontal positions of the stems must be almost the same
2147 (close-enough? (car (ly:grob-extent root ref X))
2148 (car (ly:grob-extent stem ref X)))
2149 ;; The stem must be in the direction away from the root's notehead
2150 (positive? (* (ly:grob-property root 'direction)
2151 (- (car (ly:grob-extent stem ref Y))
2152 (car (ly:grob-extent root ref Y))))))))
2154 (define (stem-span-stencil span)
2155 "Connect stems if we have at least one stem connectable to the root"
2156 (let* ((system (ly:grob-system span))
2157 (root (ly:grob-parent span X))
2158 (stems (filter (stem-connectable? system root)
2159 (ly:grob-object span 'stems))))
2160 (if (<= 2 (length stems))
2161 (let* ((yextents (map (lambda (st)
2162 (ly:grob-extent st system Y)) stems))
2163 (yextent (extent-combine yextents))
2164 (layout (ly:grob-layout root))
2165 (blot (ly:output-def-lookup layout 'blot-diameter)))
2166 ;; Hide spanned stems
2167 (for-each (lambda (st)
2168 (set! (ly:grob-property st 'stencil) #f))
2170 ;; Draw a nice looking stem with rounded corners
2171 (ly:round-filled-box (ly:grob-extent root root X) yextent blot))
2172 ;; Nothing to connect, don't draw the span
2175 (define ((make-stem-span! stems trans) root)
2176 "Create a stem span as a child of the cross-staff stem (the root)"
2177 (let ((span (ly:engraver-make-grob trans 'Stem '())))
2178 (ly:grob-set-parent! span X root)
2179 (set! (ly:grob-object span 'stems) stems)
2180 ;; Suppress positioning, the stem code is confused by this weird stem
2181 (set! (ly:grob-property span 'X-offset) 0)
2182 (set! (ly:grob-property span 'stencil) stem-span-stencil)))
2184 (define-public (cross-staff-connect stem)
2185 "Set cross-staff property of the stem to this function to connect it to
2186 other stems automatically"
2189 (define (stem-is-root? stem)
2190 "Check if automatic connecting of the stem was requested. Stems connected
2191 to cross-staff beams are cross-staff, but they should not be connected to
2192 other stems just because of that."
2193 (eq? cross-staff-connect (ly:grob-property-data stem 'cross-staff)))
2195 (define (make-stem-spans! ctx stems trans)
2196 "Create stem spans for cross-staff stems"
2197 ;; Cannot do extensive checks here, just make sure there are at least
2198 ;; two stems at this musical moment
2199 (if (<= 2 (length stems))
2200 (let ((roots (filter stem-is-root? stems)))
2201 (for-each (make-stem-span! stems trans) roots))))
2203 (define-public (Span_stem_engraver ctx)
2204 "Connect cross-staff stems to the stems above in the system"
2207 ;; Record all stems for the given moment
2209 ((stem-interface trans grob source)
2210 (set! stems (cons grob stems))))
2211 ;; Process stems and reset the stem list to empty
2212 ((process-acknowledged trans)
2213 (make-stem-spans! ctx stems trans)
2214 (set! stems '())))))
2216 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2217 ;; The following is used by the alterBroken function.
2219 (define ((value-for-spanner-piece arg) grob)
2220 "Associate a piece of broken spanner @var{grob} with an element
2222 (let* ((orig (ly:grob-original grob))
2223 (siblings (ly:spanner-broken-into orig)))
2225 (define (helper sibs arg)
2228 (if (eq? (car sibs) grob)
2230 (helper (cdr sibs) (cdr arg)))))
2232 (if (>= (length siblings) 2)
2233 (helper siblings arg)
2235 (export value-for-spanner-piece)
2237 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2240 (define (measure-counter-stencil grob)
2241 "Print a number for a measure count. The number is centered using
2242 the extents of @code{BreakAlignment} grobs associated with
2243 @code{NonMusicalPaperColumn} grobs. In the case of an unbroken measure, these
2244 columns are the left and right bounds of a @code{MeasureCounter} spanner.
2245 Broken measures are numbered in parentheses."
2246 (let* ((orig (ly:grob-original grob))
2247 (siblings (ly:spanner-broken-into orig)) ; have we been split?
2248 (bounds (ly:grob-array->list (ly:grob-object grob 'columns)))
2249 (refp (ly:grob-system grob))
2250 ;; we use the first and/or last NonMusicalPaperColumn grob(s) of
2251 ;; a system in the event that a MeasureCounter spanner is broken
2252 (all-cols (ly:grob-array->list (ly:grob-object refp 'columns)))
2255 (lambda (col) (eq? #t (ly:grob-property col 'non-musical)))
2258 (if (or (null? siblings) ; spanner is unbroken
2259 (eq? grob (car siblings))) ; or the first piece
2263 (if (or (null? siblings)
2264 (eq? grob (car (reverse siblings))))
2265 (car (reverse bounds))
2266 (car (reverse all-cols))))
2267 (elts-L (ly:grob-array->list (ly:grob-object left-bound 'elements)))
2268 (elts-R (ly:grob-array->list (ly:grob-object right-bound 'elements)))
2271 (lambda (elt) (grob::has-interface elt 'break-alignment-interface))
2275 (lambda (elt) (grob::has-interface elt 'break-alignment-interface))
2277 (break-alignment-L-ext (ly:grob-extent (car break-alignment-L) refp X))
2278 (break-alignment-R-ext (ly:grob-extent (car break-alignment-R) refp X))
2279 (num (markup (number->string (ly:grob-property grob 'count-from))))
2281 (if (or (null? siblings)
2282 (eq? grob (car siblings)))
2284 (make-parenthesize-markup num)))
2285 (num (grob-interpret-markup grob num))
2286 (num (ly:stencil-aligned-to num X (ly:grob-property grob 'self-alignment-X)))
2288 (ly:stencil-translate-axis
2290 (+ (interval-length break-alignment-L-ext)
2292 (- (car break-alignment-R-ext)
2293 (cdr break-alignment-L-ext))))
2297 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2298 ;; The following are used by the \offset function
2300 (define (find-value-to-offset prop self alist)
2301 "Return the first value of the property @var{prop} in the property
2302 alist @var{alist} -- after having found @var{self}. If @var{self} is
2303 not found, return the first value of @var{prop}."
2304 (let ((segment (member (cons prop self) alist)))
2306 (assoc-get prop alist)
2307 (assoc-get prop (cdr segment)))))
2309 (define (offset-multiple-types arg offsets)
2310 "Displace @var{arg} by @var{offsets} if @var{arg} is a number, a
2311 number pair, or a list of number pairs. If @var{offsets} is an empty
2312 list or if there is a type-mismatch, @var{arg} will be returned."
2314 ((and (number? arg) (number? offsets))
2316 ((and (number-pair? arg)
2317 (or (number? offsets)
2318 (number-pair? offsets)))
2319 (coord-translate arg offsets))
2320 ((and (number-pair-list? arg) (number-pair-list? offsets))
2322 (lambda (x y) (coord-translate x y))
2326 (define-public (offsetter property offsets)
2327 "Apply @var{offsets} to the default values of @var{property} of @var{grob}.
2328 Offsets are restricted to immutable properties and values of type @code{number},
2329 @code{number-pair}, or @code{number-pair-list}."
2331 (let* ((immutable (ly:grob-basic-properties grob))
2332 ; We need to search the basic-properties alist for our property to
2333 ; obtain values to offset. Our search is complicated by the fact that
2334 ; calling the music function `offset' as an override conses a pair to
2335 ; the head of the alist. This pair must be discounted. The closure it
2336 ; contains is named `self' so it can be easily recognized. If `offset'
2337 ; is called as a tweak, the basic-property alist is unaffected.
2338 (target (find-value-to-offset property self immutable))
2339 ; if target is a procedure, we need to apply it to our grob to calculate
2342 (if (procedure? target)
2345 (can-type-be-offset?
2348 (number-pair-list? vals))))
2350 (if can-type-be-offset?
2351 ; '(+inf.0 . -inf.0) would offset to itself. This will be confusing to a
2352 ; user unaware of the default value of the property, so issue a warning.
2353 (if (equal? empty-interval vals)
2354 (ly:warning "default '~a of ~a is ~a and can't be offset"
2356 (let* ((orig (ly:grob-original grob))
2358 (if (ly:spanner? grob)
2359 (ly:spanner-broken-into orig)
2361 (total-found (length siblings))
2362 ; Since there is some flexibility in input syntax,
2363 ; structure of `offsets' is normalized.
2365 (if (or (not (pair? offsets))
2366 (number-pair? offsets)
2367 (and (number-pair-list? offsets)
2368 (number-pair-list? vals)))
2372 (define (helper sibs offs)
2373 ; apply offsets to the siblings of broken spanners
2375 (if (eq? (car sibs) grob)
2376 (offset-multiple-types vals (car offs))
2377 (helper (cdr sibs) (cdr offs)))
2380 (if (>= total-found 2)
2381 (helper siblings offsets)
2382 (offset-multiple-types vals (car offsets)))))
2385 (ly:warning "the property '~a of ~a cannot be offset" property grob)
2387 ; return the closure named `self'
2391 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2392 ;; \magnifyMusic and \magnifyStaff
2394 ;; defined as a function instead of a list because the
2395 ;; all-grob-descriptions alist is not available yet
2396 (define-public (find-named-props prop-name grob-descriptions)
2397 "Used by @code{\\magnifyMusic} and @code{\\magnifyStaff}. When
2398 @var{grob-descriptions} is equal to the @code{all-grob-descriptions}
2399 alist (defined in @file{scm/define-grobs.scm}), this will find all grobs
2400 that can have a value for the @var{prop-name} property, and return them
2401 as a list in the following format:
2407 (define (find-grobs-with-interface interface grob-descriptions)
2408 (define (has-this-interface? grob-desc)
2409 (let* ((meta (ly:assoc-get 'meta (cdr grob-desc)))
2410 (interfaces (ly:assoc-get 'interfaces meta '())))
2411 (memq interface interfaces)))
2412 (let* ((grob-descriptions-with-this-interface
2413 (filter has-this-interface? grob-descriptions))
2414 (grob-names-with-this-interface
2415 (map car grob-descriptions-with-this-interface)))
2416 grob-names-with-this-interface))
2419 ((baseline-skip word-space) 'text-interface)
2420 ((space-alist) 'break-aligned-interface)
2421 (else (ly:programming-error
2422 "find-named-props: no interface associated with ~s"
2424 (grobs-with-this-prop
2425 (find-grobs-with-interface interface grob-descriptions)))
2426 (map (lambda (x) (list x prop-name))
2427 grobs-with-this-prop)))
2430 (define (magnifyStaff-is-set? context mag)
2431 (let* ((Staff (ly:context-find context 'Staff))
2432 (old-mag (ly:context-property Staff 'magnifyStaffValue)))
2433 (not (null? old-mag))))
2435 (define (staff-magnification-is-changing? context mag)
2436 (let* ((Staff (ly:context-find context 'Staff))
2437 (old-mag (ly:context-property Staff 'magnifyStaffValue 1)))
2438 (not (= old-mag mag))))
2440 (define-public (scale-fontSize func-name mag)
2441 "Used by @code{\\magnifyMusic} and @code{\\magnifyStaff}. Look up the
2442 current @code{fontSize} in the appropriate context and scale it by the
2443 magnification factor @var{mag}. @var{func-name} is either
2444 @code{'magnifyMusic} or @code{'magnifyStaff}."
2447 (if (or (eq? func-name 'magnifyMusic)
2448 ;; for \magnifyStaff, only scale the fontSize
2449 ;; if staff magnification is changing
2450 ;; and does not equal 1
2451 (and (staff-magnification-is-changing? context mag)
2453 (let* ((where (case func-name
2454 ((magnifyMusic) context)
2455 ((magnifyStaff) (ly:context-find context 'Staff))))
2456 (fontSize (ly:context-property where 'fontSize 0))
2457 (new-fontSize (+ fontSize (magnification->font-size mag))))
2458 (ly:context-set-property! where 'fontSize new-fontSize))))))
2460 (define-public (revert-fontSize func-name mag)
2461 "Used by @code{\\magnifyMusic} and @code{\\magnifyStaff}. Calculate
2462 the previous @code{fontSize} value (before scaling) by factoring out the
2463 magnification factor @var{mag} (if @var{func-name} is
2464 @code{'magnifyMusic}), or by factoring out the context property
2465 @code{magnifyStaffValue} (if @var{func-name} is @code{'magnifyStaff}).
2466 Revert the @code{fontSize} in the appropriate context accordingly.
2468 With @code{\\magnifyMusic}, the scaling is reverted after the music
2469 block it operates on. @code{\\magnifyStaff} does not operate on a music
2470 block, so the scaling from a previous call (if there is one) is reverted
2471 before the new scaling takes effect."
2474 (if (or (eq? func-name 'magnifyMusic)
2475 ;; for \magnifyStaff...
2477 ;; don't revert the user's fontSize choice
2478 ;; the first time \magnifyStaff is called
2479 (magnifyStaff-is-set? context mag)
2480 ;; only revert the previous fontSize
2481 ;; if staff magnification is changing
2482 (staff-magnification-is-changing? context mag)))
2485 ((magnifyMusic) context)
2486 ((magnifyStaff) (ly:context-find context 'Staff))))
2489 ((magnifyMusic) mag)
2491 (ly:context-property where 'magnifyStaffValue 1))))
2492 (fontSize (ly:context-property where 'fontSize 0))
2493 (old-fontSize (- fontSize (magnification->font-size old-mag))))
2494 (ly:context-set-property! where 'fontSize old-fontSize))))))
2496 (define-public (scale-props func-name mag allowed-to-shrink? props)
2497 "Used by @code{\\magnifyMusic} and @code{\\magnifyStaff}. For each
2498 prop in @var{props}, find the current value of the requested prop, scale
2499 it by the magnification factor @var{mag}, and do the equivalent of a
2500 @code{\\temporary@tie{}\\override} with the new value in the appropriate
2501 context. If @var{allowed-to-shrink?} is @code{#f}, don't let the new
2502 value be less than the current value. @var{func-name} is either
2503 @code{'magnifyMusic} or @code{'magnifyStaff}. The @var{props} list is
2507 (Slur line-thickness)
2512 (define (scale-prop grob-prop-list)
2513 (let* ((grob (car grob-prop-list))
2514 (prop (cadr grob-prop-list))
2515 (where (if (eq? grob 'SpacingSpanner)
2516 (ly:context-find context 'Score)
2518 ((magnifyMusic) context)
2519 ((magnifyStaff) (ly:context-find context 'Staff)))))
2520 (grob-def (ly:context-grob-definition where grob)))
2521 (if (eq? prop 'space-alist)
2522 (let* ((space-alist (ly:assoc-get prop grob-def))
2523 (scale-spacing-tuple (lambda (x)
2526 (* mag (cddr x))))))
2527 (scaled-tuples (if space-alist
2528 (map scale-spacing-tuple space-alist)
2530 (new-alist (append scaled-tuples space-alist)))
2531 (ly:context-pushpop-property where grob prop new-alist))
2532 (let* ((val (ly:assoc-get prop grob-def (case prop
2537 (if allowed-to-shrink?
2539 (* x (max 1 mag)))))
2540 (new-val (if (number-pair? val)
2541 (cons (proc (car val))
2544 (ly:context-pushpop-property where grob prop new-val)))))
2545 (if (or (eq? func-name 'magnifyMusic)
2546 ;; for \magnifyStaff, only scale the properties
2547 ;; if staff magnification is changing
2548 ;; and does not equal 1
2549 (and (staff-magnification-is-changing? context mag)
2551 (for-each scale-prop props)))))
2553 (define-public (revert-props func-name mag props)
2554 "Used by @code{\\magnifyMusic} and @code{\\magnifyStaff}. Revert each
2555 prop in @var{props} in the appropriate context. @var{func-name} is
2556 either @code{'magnifyMusic} or @code{'magnifyStaff}. The @var{props}
2557 list is formatted like:
2560 (Slur line-thickness)
2565 (define (revert-prop grob-prop-list)
2566 (let* ((grob (car grob-prop-list))
2567 (prop (cadr grob-prop-list))
2568 (where (if (eq? grob 'SpacingSpanner)
2569 (ly:context-find context 'Score)
2571 ((magnifyMusic) context)
2572 ((magnifyStaff) (ly:context-find context 'Staff))))))
2573 (ly:context-pushpop-property where grob prop)))
2574 (if (or (eq? func-name 'magnifyMusic)
2575 ;; for \magnifyStaff...
2577 ;; don't revert the user's property overrides
2578 ;; the first time \magnifyStaff is called
2579 (magnifyStaff-is-set? context mag)
2580 ;; revert the overrides from the previous \magnifyStaff,
2581 ;; but only if staff magnification is changing
2582 (staff-magnification-is-changing? context mag)))
2583 (for-each revert-prop props)))))
2585 ;; \magnifyMusic only
2586 (define-public (scale-beam-thickness mag)
2587 "Used by @code{\\magnifyMusic}. Scaling @code{Beam.beam-thickness}
2588 exactly to the @var{mag} value will not work. This uses two reference
2589 values for @code{beam-thickness} to determine an acceptable value when
2590 scaling, then does the equivalent of a
2591 @code{\\temporary@tie{}\\override} with the new value."
2594 (let* ((grob-def (ly:context-grob-definition context 'Beam))
2595 (val (ly:assoc-get 'beam-thickness grob-def 0.48))
2596 (ratio-to-default (/ val 0.48))
2597 ;; gives beam-thickness=0.48 when mag=1 (like default),
2598 ;; gives beam-thickness=0.35 when mag=0.63 (like CueVoice)
2599 (scaled-default (+ 119/925 (* mag 13/37)))
2600 (new-val (* scaled-default ratio-to-default)))
2601 (ly:context-pushpop-property context 'Beam 'beam-thickness new-val)))))
2606 (define tag-groups (make-hash-table))
2607 (call-after-session (lambda () (hash-clear! tag-groups)))
2609 (define-public (define-tag-group tags)
2610 "Define a tag-group consisting of the given @var{tags}, a@tie{}list
2611 of symbols. Returns @code{#f} if successful, and an error message if
2612 there is a conflicting tag group definition."
2613 (cond ((not (symbol-list? tags)) (format #f (_ "not a symbol list: ~a") tags))
2614 ((any (lambda (tag) (hashq-ref tag-groups tag)) tags)
2615 => (lambda (group) (and (not (lset= eq? group tags))
2616 (format #f (_ "conflicting tag group ~a") group))))
2619 (lambda (elt) (hashq-set! tag-groups elt tags))
2623 (define-public (tag-group-get tag)
2624 "Return the tag group (as a list of symbols) that the given
2625 @var{tag} symbol belongs to, @code{#f} if none."
2626 (hashq-ref tag-groups tag))
2628 (define-public (tags-remove-predicate tags)
2629 "Returns a predicate that returns @code{#f} for any music that is to
2630 be removed by @{\\removeWithTag} on the given symbol or list of
2631 symbols @var{tags}."
2634 (not (memq tags (ly:music-property m 'tags))))
2636 (not (any (lambda (t) (memq t tags))
2637 (ly:music-property m 'tags))))))
2639 (define-public (tags-keep-predicate tags)
2640 "Returns a predicate that returns @code{#f} for any music that is to
2641 be removed by @{\\keepWithTag} on the given symbol or list of symbols
2644 (let ((group (tag-group-get tags)))
2646 (let ((music-tags (ly:music-property m 'tags)))
2648 (null? music-tags) ; redundant but very frequent
2649 ;; We know of only one tag to keep. Either we find it in
2650 ;; the music tags, or all music tags must be from a
2652 (memq tags music-tags)
2653 (not (any (lambda (t) (eq? (tag-group-get t) group)) music-tags))))))
2654 (let ((groups (delete-duplicates (map tag-group-get tags) eq?)))
2656 (let ((music-tags (ly:music-property m 'tags)))
2658 (null? music-tags) ; redundant but very frequent
2659 (any (lambda (t) (memq t tags)) music-tags)
2660 ;; if no tag matches, no tag group should match either
2661 (not (any (lambda (t) (memq (tag-group-get t) groups)) music-tags))))))))