1 ;;;; This file is part of LilyPond, the GNU music typesetter.
3 ;;;; Copyright (C) 1998--2012 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))
24 ;;; ly:music-property with setter
25 ;;; (ly:music-property my-music 'elements)
26 ;;; ==> the 'elements property
27 ;;; (set! (ly:music-property my-music 'elements) value)
28 ;;; ==> set the 'elements property and return it
29 (define-public ly:music-property
30 (make-procedure-with-setter ly:music-property
31 ly:music-set-property!))
33 (define-safe-public (music-is-of-type? mus type)
34 "Does @code{mus} belong to the music class @code{type}?"
35 (memq type (ly:music-property mus 'types)))
38 (define-public ly:grob-property
39 (make-procedure-with-setter ly:grob-property
40 ly:grob-set-property!))
42 (define-public ly:grob-object
43 (make-procedure-with-setter ly:grob-object
46 (define-public ly:grob-parent
47 (make-procedure-with-setter ly:grob-parent
50 (define-public ly:prob-property
51 (make-procedure-with-setter ly:prob-property
52 ly:prob-set-property!))
54 (define-public ly:context-property
55 (make-procedure-with-setter ly:context-property
56 ly:context-set-property!))
58 (define-public (music-map function music)
59 "Apply @var{function} to @var{music} and all of the music it contains.
61 First it recurses over the children, then the function is applied to
63 (let ((es (ly:music-property music 'elements))
64 (e (ly:music-property music 'element)))
66 (set! (ly:music-property music 'elements)
67 (map (lambda (y) (music-map function y)) es)))
69 (set! (ly:music-property music 'element)
70 (music-map function e)))
73 (define-public (music-filter pred? music)
74 "Filter out music expressions that do not satisfy @var{pred?}."
76 (define (inner-music-filter pred? music)
78 (let* ((es (ly:music-property music 'elements))
79 (e (ly:music-property music 'element))
80 (as (ly:music-property music 'articulations))
81 (filtered-as (filter ly:music? (map (lambda (y) (inner-music-filter pred? y)) as)))
82 (filtered-e (if (ly:music? e)
83 (inner-music-filter pred? e)
85 (filtered-es (filter ly:music? (map (lambda (y) (inner-music-filter pred? y)) es))))
87 (set! (ly:music-property music 'element) filtered-e))
89 (set! (ly:music-property music 'elements) filtered-es))
91 (set! (ly:music-property music 'articulations) filtered-as))
92 ;; if filtering emptied the expression, we remove it completely.
93 (if (or (not (pred? music))
94 (and (eq? filtered-es '()) (not (ly:music? e))
95 (or (not (eq? es '()))
100 (set! music (inner-music-filter pred? music))
101 (if (ly:music? music)
103 (make-music 'Music))) ;must return music.
105 (define*-public (display-music music #:optional (port (current-output-port)))
106 "Display music, not done with @code{music-map} for clarity of
109 (display ": { " port)
110 (let ((es (ly:music-property music 'elements))
111 (e (ly:music-property music 'element)))
112 (display (ly:music-mutable-properties music) port)
114 (begin (display "\nElements: {\n" port)
115 (for-each (lambda (m) (display-music m port)) es)
116 (display "}\n" port)))
119 (display "\nChild:" port)
120 (display-music e port))))
121 (display " }\n" port)
125 ;;; A scheme music pretty printer
127 (define (markup-expression->make-markup markup-expression)
128 "Transform `markup-expression' into an equivalent, hopefuly readable, scheme expression.
130 \\markup \\bold \\italic hello
132 (markup #:line (#:bold (#:italic (#:simple \"hello\"))))"
133 (define (proc->command-keyword proc)
134 "Return a keyword, eg. `#:bold', from the `proc' function, eg. #<procedure bold-markup (layout props arg)>"
135 (let ((cmd-markup (symbol->string (procedure-name proc))))
136 (symbol->keyword (string->symbol (substring cmd-markup 0 (- (string-length cmd-markup)
137 (string-length "-markup")))))))
138 (define (transform-arg arg)
139 (cond ((and (pair? arg) (markup? (car arg))) ;; a markup list
140 (apply append (map inner-markup->make-markup arg)))
141 ((and (not (string? arg)) (markup? arg)) ;; a markup
142 (inner-markup->make-markup arg))
144 (music->make-music arg))))
145 (define (inner-markup->make-markup mrkup)
148 (let ((cmd (proc->command-keyword (car mrkup)))
149 (args (map transform-arg (cdr mrkup))))
152 (if (string? markup-expression)
154 `(markup ,@(inner-markup->make-markup markup-expression))))
156 (define-public (music->make-music obj)
157 "Generate an expression that, once evaluated, may return an object
158 equivalent to @var{obj}, that is, for a music expression, a
159 @code{(make-music ...)} form."
160 (cond (;; markup expression
162 (markup-expression->make-markup obj))
166 ',(ly:music-property obj 'name)
167 ,@(apply append (map (lambda (prop)
169 ,(music->make-music (cdr prop))))
170 (remove (lambda (prop)
171 (eqv? (car prop) 'origin))
172 (ly:music-mutable-properties obj))))))
175 `(ly:make-moment ,(ly:moment-main-numerator obj)
176 ,(ly:moment-main-denominator obj)
177 ,(ly:moment-grace-numerator obj)
178 ,(ly:moment-grace-denominator obj)))
181 `(ly:make-duration ,(ly:duration-log obj)
182 ,(ly:duration-dot-count obj)
183 ,(ly:duration-scale obj)))
186 `(ly:make-pitch ,(ly:pitch-octave obj)
187 ,(ly:pitch-notename obj)
188 ,(ly:pitch-alteration obj)))
191 (or (procedure-name obj) obj))
192 (;; a symbol (avoid having an unquoted symbol)
195 (;; an empty list (avoid having an unquoted empty list)
200 `(list ,@(map music->make-music obj)))
203 `(cons ,(music->make-music (car obj))
204 ,(music->make-music (cdr obj))))
208 (use-modules (ice-9 pretty-print))
209 (define*-public (display-scheme-music obj #:optional (port (current-output-port)))
210 "Displays `obj', typically a music expression, in a friendly fashion,
211 which often can be read back in order to generate an equivalent expression."
212 (pretty-print (music->make-music obj) port)
216 ;;; Scheme music expression --> Lily-syntax-using string translator
218 (use-modules (srfi srfi-39)
221 (define*-public (display-lily-music expr parser #:optional (port (current-output-port))
222 #:key force-duration)
223 "Display the music expression using LilyPond syntax"
224 (memoize-clef-names supported-clefs)
225 (parameterize ((*indent* 0)
226 (*previous-duration* (ly:make-duration 2))
227 (*force-duration* force-duration))
228 (display (music->lily-string expr parser) port)
231 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
233 (define-public (shift-one-duration-log music shift dot)
234 "Add @var{shift} to @code{duration-log} of @code{'duration} in
235 @var{music} and optionally @var{dot} to any note encountered.
236 The number of dots in the shifted music may not be less than zero."
237 (let ((d (ly:music-property music 'duration)))
239 (let* ((cp (ly:duration-scale d))
240 (nd (ly:make-duration
241 (+ shift (ly:duration-log d))
242 (max 0 (+ dot (ly:duration-dot-count d)))
244 (set! (ly:music-property music 'duration) nd)))
247 (define-public (shift-duration-log music shift dot)
248 (music-map (lambda (x) (shift-one-duration-log x shift dot))
251 (define-public (make-repeat name times main alts)
252 "Create a repeat music expression, with all properties initialized
254 (define (first-note-duration music)
255 "Finds the duration of the first NoteEvent by searching depth-first
257 ;; NoteEvent or a non-expanded chord-repetition
258 ;; We just take anything that actually sports an announced duration.
259 (if (ly:duration? (ly:music-property music 'duration))
260 (ly:music-property music 'duration)
261 (let loop ((elts (if (ly:music? (ly:music-property music 'element))
262 (list (ly:music-property music 'element))
263 (ly:music-property music 'elements))))
265 (let ((dur (first-note-duration (car elts))))
266 (if (ly:duration? dur)
268 (loop (cdr elts))))))))
270 (let ((talts (if (< times (length alts))
272 (ly:warning (_ "More alternatives than repeats. Junking excess alternatives"))
275 (r (make-repeated-music name)))
276 (set! (ly:music-property r 'element) main)
277 (set! (ly:music-property r 'repeat-count) (max times 1))
278 (set! (ly:music-property r 'elements) talts)
279 (if (and (equal? name "tremolo")
280 (pair? (extract-named-music main '(EventChord NoteEvent))))
281 ;; This works for single-note and multi-note tremolos!
282 (let* ((children (if (music-is-of-type? main 'sequential-music)
283 ;; \repeat tremolo n { ... }
284 (length (extract-named-music main '(EventChord
286 ;; \repeat tremolo n c4
288 ;; # of dots is equal to the 1 in bitwise representation (minus 1)!
289 (dots (1- (logcount (* times children))))
290 ;; The remaining missing multiplicator to scale the notes by
292 (mult (/ (* times children (ash 1 dots)) (1- (ash 2 dots))))
293 (shift (- (ly:intlog2 (floor mult))))
294 (note-duration (first-note-duration r))
295 (duration-log (if (ly:duration? note-duration)
296 (ly:duration-log note-duration)
298 (tremolo-type (ash 1 duration-log)))
299 (set! (ly:music-property r 'tremolo-type) tremolo-type)
300 (if (not (and (integer? mult) (= (logcount mult) 1)))
303 (ly:format (_ "invalid tremolo repeat count: ~a") times)))
304 ;; Adjust the time of the notes
305 (ly:music-compress r (ly:make-moment 1 children))
306 ;; Adjust the displayed note durations
307 (shift-duration-log r shift dots))
310 (define (calc-repeat-slash-count music)
311 "Given the child-list @var{music} in @code{PercentRepeatMusic},
312 calculate the number of slashes based on the durations. Returns @code{0}
313 if durations in @var{music} vary, allowing slash beats and double-percent
314 beats to be distinguished."
315 (let* ((durs (map duration-of-note
316 (extract-named-music music '(EventChord NoteEvent
317 RestEvent SkipEvent))))
318 (first-dur (car durs)))
320 (if (every (lambda (d) (equal? d first-dur)) durs)
321 (max (- (ly:duration-log first-dur) 2) 1)
324 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
327 (define-public (note-to-cluster music)
328 "Replace @code{NoteEvents} by @code{ClusterNoteEvents}."
329 (if (eq? (ly:music-property music 'name) 'NoteEvent)
330 (make-music 'ClusterNoteEvent
331 'pitch (ly:music-property music 'pitch)
332 'duration (ly:music-property music 'duration))
335 (define-public (notes-to-clusters music)
336 (music-map note-to-cluster music))
338 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
341 (define-public (unfold-repeats music)
342 "Replace all repeats with unfolded repeats."
344 (let ((es (ly:music-property music 'elements))
345 (e (ly:music-property music 'element)))
347 (if (music-is-of-type? music 'repeated-music)
348 (let* ((props (ly:music-mutable-properties music))
349 (old-name (ly:music-property music 'name))
350 (flattened (flatten-alist props)))
351 (set! music (apply make-music (cons 'UnfoldedRepeatedMusic
354 (if (and (equal? old-name 'TremoloRepeatedMusic)
355 (pair? (extract-named-music e '(EventChord NoteEvent))))
356 ;; This works for single-note and multi-note tremolos!
357 (let* ((children (if (music-is-of-type? e 'sequential-music)
358 ;; \repeat tremolo n { ... }
359 (length (extract-named-music e '(EventChord
361 ;; \repeat tremolo n c4
363 (times (ly:music-property music 'repeat-count))
365 ;; # of dots is equal to the 1 in bitwise representation (minus 1)!
366 (dots (1- (logcount (* times children))))
367 ;; The remaining missing multiplicator to scale the notes by
369 (mult (/ (* times children (ash 1 dots)) (1- (ash 2 dots))))
370 (shift (- (ly:intlog2 (floor mult)))))
372 ;; Adjust the time of the notes
373 (ly:music-compress music (ly:make-moment children 1))
374 ;; Adjust the displayed note durations
375 (shift-duration-log music (- shift) (- dots))))))
378 (set! (ly:music-property music 'elements)
379 (map unfold-repeats es)))
381 (set! (ly:music-property music 'element)
385 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
386 ;; property setting music objs.
388 (define-safe-public (check-grob-path path #:optional parser location
394 "Check a grob path specification @var{path}, a symbol list (or a
395 single symbol), for validity and possibly complete it. Returns the
396 completed specification, or @code{#f} if invalid. If optional
397 @var{parser} is given, a syntax error is raised in that case,
398 optionally using @var{location}. If an optional keyword argument
399 @code{#:start @var{start}} is given, the parsing starts at the given
400 index in the sequence @samp{Context.Grob.property.sub-property...},
401 with the default of @samp{0} implying the full path.
403 If there is no valid first element of @var{path} fitting at the given
404 path location, an optionally given @code{#:default @var{default}} is
405 used as the respective element instead without checking it for
406 validity at this position.
408 The resulting path after possibly prepending @var{default} can be
409 constrained in length by optional arguments @code{#:min @var{min}} and
410 @code{#:max @var{max}}, defaulting to @samp{1} and unlimited,
412 (let ((path (if (symbol? path) (list path) path)))
413 ;; A Guile 1.x bug specific to optargs precludes moving the
414 ;; defines out of the let
415 (define (unspecial? s)
416 (not (or (object-property s 'is-grob?)
417 (object-property s 'backend-type?))))
419 (object-property s 'is-grob?))
420 (define (property? s)
421 (object-property s 'backend-type?))
422 (define (check c p) (c p))
426 (drop (list unspecial? grob? property?) start)))
430 ;; tricky. Should we make use of the default when the
431 ;; list is empty? In most cases, this question should be
432 ;; academical as an empty list can only be generated by
433 ;; Scheme and is likely an error. We consider this a case
434 ;; of "no valid first element, and default given".
435 ;; Usually, invalid use cases should be caught later using
436 ;; the #:min argument, and if the user explicitly does not
437 ;; catch this, we just follow through.
438 (if default (list default) '()))
440 ;; no checkers, so we have a valid first element and just
441 ;; take the path as-is.
444 (if ((car checkers) (car path))
445 (and (every check (cdr checkers) (cdr path))
447 (and (every check (cdr checkers) path)
448 (cons default path))))
450 (and (every check checkers path)
453 (if max (<= min (length res) max)
454 (<= min (length res))))
458 (ly:parser-error parser
459 (format #f (_ "bad grob property path ~a")
464 (define-public (make-grob-property-set grob gprop val)
465 "Make a @code{Music} expression that sets @var{gprop} to @var{val} in
466 @var{grob}. Does a pop first, i.e., this is not an override."
467 (make-music 'OverrideProperty
473 (define-public (make-grob-property-override grob gprop val)
474 "Make a @code{Music} expression that overrides @var{gprop} to @var{val}
476 (make-music 'OverrideProperty
481 (define-public (make-grob-property-revert grob gprop)
482 "Revert the grob property @var{gprop} for @var{grob}."
483 (make-music 'RevertProperty
485 'grob-property gprop))
487 (define direction-polyphonic-grobs
488 '(AccidentalSuggestion
506 (define general-grace-settings
507 `((Voice Stem font-size -3)
508 (Voice Flag font-size -3)
509 (Voice NoteHead font-size -3)
510 (Voice TabNoteHead font-size -4)
511 (Voice Dots font-size -3)
512 (Voice Stem length-fraction 0.8)
513 (Voice Stem no-stem-extend #t)
514 (Voice Beam beam-thickness 0.384)
515 (Voice Beam length-fraction 0.8)
516 (Voice Accidental font-size -4)
517 (Voice AccidentalCautionary font-size -4)
518 (Voice Script font-size -3)
519 (Voice Fingering font-size -8)
520 (Voice StringNumber font-size -8)))
522 (define-public score-grace-settings
524 `((Voice Stem direction ,UP)
525 (Voice Slur direction ,DOWN))
526 general-grace-settings))
528 (define-safe-public (make-voice-props-set n)
529 (make-sequential-music
531 (map (lambda (x) (make-grob-property-set x 'direction
533 direction-polyphonic-grobs)
535 (make-property-set 'graceSettings general-grace-settings)
536 (make-grob-property-set 'NoteColumn 'horizontal-shift (quotient n 2))))))
538 (define-safe-public (make-voice-props-override n)
539 (make-sequential-music
541 (map (lambda (x) (make-grob-property-override x 'direction
543 direction-polyphonic-grobs)
545 (make-property-set 'graceSettings general-grace-settings)
546 (make-grob-property-override 'NoteColumn 'horizontal-shift (quotient n 2))
547 (make-grob-property-override 'MultiMeasureRest 'staff-position (if (odd? n) -4 4))))))
549 (define-safe-public (make-voice-props-revert)
550 (make-sequential-music
552 (map (lambda (x) (make-grob-property-revert x 'direction))
553 direction-polyphonic-grobs)
554 (list (make-property-unset 'graceSettings)
555 (make-grob-property-revert 'NoteColumn 'horizontal-shift)
556 (make-grob-property-revert 'MultiMeasureRest 'staff-position)))))
559 (define-safe-public (context-spec-music m context #:optional id)
560 "Add \\context CONTEXT = ID to M."
561 (let ((cm (make-music 'ContextSpeccedMusic
563 'context-type context)))
565 (set! (ly:music-property cm 'context-id) id))
568 (define-public (descend-to-context m context)
569 "Like @code{context-spec-music}, but only descending."
570 (let ((cm (context-spec-music m context)))
571 (ly:music-set-property! cm 'descend-only #t)
574 (define-public (make-non-relative-music mus)
575 (make-music 'UnrelativableMusic
578 (define-public (make-apply-context func)
579 (make-music 'ApplyContext
582 (define-public (make-sequential-music elts)
583 (make-music 'SequentialMusic
586 (define-public (make-simultaneous-music elts)
587 (make-music 'SimultaneousMusic
590 (define-safe-public (make-event-chord elts)
591 (make-music 'EventChord
594 (define-public (make-skip-music dur)
595 (make-music 'SkipMusic
598 (define-public (make-grace-music music)
599 (make-music 'GraceMusic
605 (define-public (make-multi-measure-rest duration location)
606 (make-music 'MultiMeasureRestMusic
610 (define-public (make-property-set sym val)
611 (make-music 'PropertySet
615 (define-public (make-property-unset sym)
616 (make-music 'PropertyUnset
619 (define-safe-public (make-articulation name)
620 (make-music 'ArticulationEvent
621 'articulation-type name))
623 (define-public (make-lyric-event string duration)
624 (make-music 'LyricEvent
628 (define-safe-public (make-span-event type span-dir)
630 'span-direction span-dir))
632 (define-public (override-head-style heads style)
633 "Override style for @var{heads} to @var{style}."
634 (make-sequential-music
637 (make-grob-property-override h 'style style))
639 (list (make-grob-property-override heads 'style style)))))
641 (define-public (revert-head-style heads)
642 "Revert style for @var{heads}."
643 (make-sequential-music
646 (make-grob-property-revert h 'style))
648 (list (make-grob-property-revert heads 'style)))))
650 (define-public (style-note-heads heads style music)
651 "Set @var{style} for all @var{heads} in @var{music}. Works both
652 inside of and outside of chord construct."
653 ;; are we inside a <...>?
654 (if (eq? (ly:music-property music 'name) 'NoteEvent)
655 ;; yes -> use a tweak
657 (set! (ly:music-property music 'tweaks)
658 (acons 'style style (ly:music-property music 'tweaks)))
660 ;; not in <...>, so use overrides
661 (make-sequential-music
663 (override-head-style heads style)
665 (revert-head-style heads)))))
667 (define-public (set-mus-properties! m alist)
668 "Set all of @var{alist} as properties of @var{m}."
671 (set! (ly:music-property m (caar alist)) (cdar alist))
672 (set-mus-properties! m (cdr alist)))))
674 (define-public (music-separator? m)
675 "Is @var{m} a separator?"
676 (let ((ts (ly:music-property m 'types)))
677 (memq 'separator ts)))
679 ;;; expanding repeat chords
680 (define-public (copy-repeat-chord original-chord repeat-chord duration
682 "Copies all events in @var{event-types} (be sure to include
683 @code{rhythmic-events}) from @var{original-chord} over to
684 @var{repeat-chord} with their articulations filtered as well. Any
685 duration is replaced with the specified @var{duration}."
686 ;; First remove everything from event-types that can already be
687 ;; found in the repeated chord. We don't need to look for
688 ;; articulations on individual events since they can't actually get
689 ;; into a repeat chord given its input syntax.
691 (define (keep-element? m)
692 (any (lambda (t) (music-is-of-type? m t))
694 (define origin (ly:music-property repeat-chord 'origin #f))
695 (define (set-origin! l)
697 (for-each (lambda (m) (set! (ly:music-property m 'origin) origin)) l))
702 (for-each (lambda (e)
703 (for-each (lambda (x)
704 (set! event-types (delq x event-types)))
705 (ly:music-property e 'types)))
706 (ly:music-property repeat-chord field)))
707 '(elements articulations))
709 ;; now treat the elements
710 (set! (ly:music-property repeat-chord 'elements)
712 (set-origin! (ly:music-deep-copy
713 (filter keep-element?
714 (ly:music-property original-chord
718 (let ((arts (ly:music-property m 'articulations)))
720 (set! (ly:music-property m 'articulations)
721 (set-origin! (filter! keep-element? arts))))
722 (if (ly:duration? (ly:music-property m 'duration))
723 (set! (ly:music-property m 'duration) duration))))
725 (append! elts (ly:music-property repeat-chord 'elements))))
726 (let ((arts (filter keep-element?
727 (ly:music-property original-chord
730 (set! (ly:music-property repeat-chord 'articulations)
732 (set-origin! (ly:music-deep-copy arts))
733 (ly:music-property repeat-chord 'articulations))))))
736 (define-public (expand-repeat-chords! event-types music)
737 "Walks through @var{music} and fills repeated chords (notable by
738 having a duration in @code{duration}) with the notes from their
739 respective predecessor chord."
740 (let loop ((music music) (last-chord #f))
741 (if (music-is-of-type? music 'event-chord)
742 (let ((chord-repeat (ly:music-property music 'duration)))
744 ((not (ly:duration? chord-repeat))
745 (if (any (lambda (m) (ly:duration?
746 (ly:music-property m 'duration)))
747 (ly:music-property music 'elements))
751 (set! (ly:music-property music 'duration) '())
752 (copy-repeat-chord last-chord music chord-repeat event-types)
755 (ly:music-warning music (_ "Bad chord repetition"))
757 (let ((elt (ly:music-property music 'element)))
758 (fold loop (if (ly:music? elt) (loop elt last-chord) last-chord)
759 (ly:music-property music 'elements)))))
762 ;;; splitting chords into voices.
763 (define (voicify-list lst number)
764 "Make a list of Musics.
766 voicify-list :: [ [Music ] ] -> number -> [Music]
767 LST is a list music-lists.
769 NUMBER is 0-base, i.e., Voice=1 (upstems) has number 0.
773 (cons (context-spec-music
774 (make-sequential-music
775 (list (make-voice-props-set number)
776 (make-simultaneous-music (car lst))))
777 'Bottom (number->string (1+ number)))
778 (voicify-list (cdr lst) (1+ number)))))
780 (define (voicify-chord ch)
781 "Split the parts of a chord into different Voices using separator"
782 (let ((es (ly:music-property ch 'elements)))
783 (set! (ly:music-property ch 'elements)
784 (voicify-list (split-list-by-separator es music-separator?) 0))
787 (define-public (voicify-music m)
788 "Recursively split chords that are separated with @code{\\\\}."
789 (if (not (ly:music? m))
790 (ly:error (_ "music expected: ~S") m))
791 (let ((es (ly:music-property m 'elements))
792 (e (ly:music-property m 'element)))
795 (set! (ly:music-property m 'elements) (map voicify-music es)))
797 (set! (ly:music-property m 'element) (voicify-music e)))
798 (if (and (equal? (ly:music-property m 'name) 'SimultaneousMusic)
799 (any music-separator? es))
800 (set! m (context-spec-music (voicify-chord m) 'Staff)))
803 (define-public (empty-music)
806 ;; Make a function that checks score element for being of a specific type.
807 (define-public (make-type-checker symbol)
809 (grob::has-interface elt symbol)))
811 (define-public ((outputproperty-compatibility func sym val) grob g-context ao-context)
813 (set! (ly:grob-property grob sym) val)))
816 (define-public ((set-output-property grob-name symbol val) grob grob-c context)
818 @code{\\applyoutput #(set-output-property 'Clef 'extra-offset '(0 . 1))}"
819 (let ((meta (ly:grob-property grob 'meta)))
820 (if (equal? (assoc-get 'name meta) grob-name)
821 (set! (ly:grob-property grob symbol) val))))
824 (define-public (skip->rest mus)
825 "Replace @var{mus} by @code{RestEvent} of the same duration if it is a
826 @code{SkipEvent}. Useful for extracting parts from crowded scores."
828 (if (memq (ly:music-property mus 'name) '(SkipEvent SkipMusic))
829 (make-music 'RestEvent 'duration (ly:music-property mus 'duration))
833 (define-public (music-has-type music type)
834 (memq type (ly:music-property music 'types)))
836 (define-public (music-clone music . music-properties)
837 "Clone @var{music} and set properties according to
838 @var{music-properties}, a list of alternating property symbols and
840 @example\n(music-clone start-span 'span-direction STOP)
842 Only properties that are not overriden by @var{music-properties} are
843 actually fully cloned."
844 (let ((old-props (list-copy (ly:music-mutable-properties music)))
846 (m (ly:make-music (ly:prob-immutable-properties music))))
847 (define (set-props mus-props)
848 (if (and (not (null? mus-props))
849 (not (null? (cdr mus-props))))
851 (set! old-props (assq-remove! old-props (car mus-props)))
854 (car mus-props) (cadr mus-props)))
855 (set-props (cddr mus-props)))))
856 (set-props music-properties)
859 (set! (ly:music-property m (car pair))
860 (ly:music-deep-copy (cdr pair))))
864 (set! (ly:music-property m (car pair)) (cdr pair)))
868 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
869 ;; warn for bare chords at start.
871 (define-public (ly:music-message music msg . rest)
872 (let ((ip (ly:music-property music 'origin)))
873 (if (ly:input-location? ip)
874 (apply ly:input-message ip msg rest)
875 (apply ly:message msg rest))))
877 (define-public (ly:music-warning music msg . rest)
878 (let ((ip (ly:music-property music 'origin)))
879 (if (ly:input-location? ip)
880 (apply ly:input-warning ip msg rest)
881 (apply ly:warning msg rest))))
883 (define-public (ly:event-warning event msg . rest)
884 (let ((ip (ly:event-property event 'origin)))
885 (if (ly:input-location? ip)
886 (apply ly:input-warning ip msg rest)
887 (apply ly:warning msg rest))))
889 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
891 ;; setting stuff for grace context.
894 (define (vector-extend v x)
895 "Make a new vector consisting of V, with X added to the end."
896 (let* ((n (vector-length v))
897 (nv (make-vector (+ n 1) '())))
898 (vector-move-left! v 0 n nv 0)
902 (define (vector-map f v)
903 "Map F over V. This function returns nothing."
904 (do ((n (vector-length v))
907 (f (vector-ref v i))))
909 (define (vector-reverse-map f v)
910 "Map F over V, N to 0 order. This function returns nothing."
911 (do ((i (- (vector-length v) 1) (- i 1)))
913 (f (vector-ref v i))))
915 (define-public (add-grace-property context-name grob sym val)
916 "Set @var{sym}=@var{val} for @var{grob} in @var{context-name}."
917 (define (set-prop context)
918 (let* ((where (or (ly:context-find context context-name) context))
919 (current (ly:context-property where 'graceSettings))
920 (new-settings (append current
921 (list (list context-name grob sym val)))))
922 (ly:context-set-property! where 'graceSettings new-settings)))
923 (make-apply-context set-prop))
925 (define-public (remove-grace-property context-name grob sym)
926 "Remove all @var{sym} for @var{grob} in @var{context-name}."
927 (define (sym-grob-context? property sym grob context-name)
928 (and (eq? (car property) context-name)
929 (eq? (cadr property) grob)
930 (eq? (caddr property) sym)))
931 (define (delete-prop context)
932 (let* ((where (or (ly:context-find context context-name) context))
933 (current (ly:context-property where 'graceSettings))
934 (prop-settings (filter
935 (lambda(x) (sym-grob-context? x sym grob context-name))
937 (new-settings current))
939 (set! new-settings (delete x new-settings)))
941 (ly:context-set-property! where 'graceSettings new-settings)))
942 (make-apply-context delete-prop))
945 (defmacro-public def-grace-function (start stop . docstring)
946 "Helper macro for defining grace music"
947 `(define-music-function (parser location music) (ly:music?)
949 (make-music 'GraceMusic
951 'element (make-music 'SequentialMusic
952 'elements (list (ly:music-deep-copy ,start)
954 (ly:music-deep-copy ,stop))))))
956 (defmacro-public define-syntax-function (type args signature . body)
957 "Helper macro for `ly:make-music-function'.
959 (define-syntax-function result-type? (parser location arg1 arg2 ...) (arg1-type arg2-type ...)
962 argX-type can take one of the forms @code{predicate?} for mandatory
963 arguments satisfying the predicate, @code{(predicate?)} for optional
964 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
965 value)}} for optional parameters with a specified default
966 value (evaluated at definition time). An optional parameter can be
967 omitted in a call only when it can't get confused with a following
968 parameter of different type.
970 Predicates with syntactical significance are @code{ly:pitch?},
971 @code{ly:duration?}, @code{ly:music?}, @code{markup?}. Other
972 predicates require the parameter to be entered as Scheme expression.
974 @code{result-type?} can specify a default in the same manner as
975 predicates, to be used in case of a type error in arguments or
978 (set! signature (map (lambda (pred)
981 ,(and (pair? (cdr pred)) (cadr pred)))
983 (cons type signature)))
984 (if (and (pair? body) (pair? (car body)) (eqv? '_i (caar body)))
985 ;; When the music function definition contains a i10n doc string,
986 ;; (_i "doc string"), keep the literal string only
987 (let ((docstring (cadar body))
989 `(ly:make-music-function (list ,@signature)
993 `(ly:make-music-function (list ,@signature)
997 (defmacro-public define-music-function rest
998 "Defining macro returning music functions.
1000 (define-music-function (parser location arg1 arg2 ...) (arg1-type? arg2-type? ...)
1001 ...function body...)
1003 argX-type can take one of the forms @code{predicate?} for mandatory
1004 arguments satisfying the predicate, @code{(predicate?)} for optional
1005 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
1006 value)}} for optional parameters with a specified default
1007 value (evaluated at definition time). An optional parameter can be
1008 omitted in a call only when it can't get confused with a following
1009 parameter of different type.
1011 Predicates with syntactical significance are @code{ly:pitch?},
1012 @code{ly:duration?}, @code{ly:music?}, @code{markup?}. Other
1013 predicates require the parameter to be entered as Scheme expression.
1015 Must return a music expression. The @code{origin} is automatically
1016 set to the @code{location} parameter."
1018 `(define-syntax-function (ly:music? (make-music 'Music 'void #t)) ,@rest))
1021 (defmacro-public define-scheme-function rest
1022 "Defining macro returning Scheme functions.
1024 (define-scheme-function (parser location arg1 arg2 ...) (arg1-type? arg2-type? ...)
1025 ...function body...)
1027 argX-type can take one of the forms @code{predicate?} for mandatory
1028 arguments satisfying the predicate, @code{(predicate?)} for optional
1029 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
1030 value)}} for optional parameters with a specified default
1031 value (evaluated at definition time). An optional parameter can be
1032 omitted in a call only when it can't get confused with a following
1033 parameter of different type.
1035 Predicates with syntactical significance are @code{ly:pitch?},
1036 @code{ly:duration?}, @code{ly:music?}, @code{markup?}. Other
1037 predicates require the parameter to be entered as Scheme expression.
1039 Can return arbitrary expressions. If a music expression is returned,
1040 its @code{origin} is automatically set to the @code{location}
1043 `(define-syntax-function scheme? ,@rest))
1045 (defmacro-public define-void-function rest
1046 "This defines a Scheme function like @code{define-scheme-function} with
1047 void return value (i.e., what most Guile functions with `unspecified'
1048 value return). Use this when defining functions for executing actions
1049 rather than returning values, to keep Lilypond from trying to interpret
1051 `(define-syntax-function (void? *unspecified*) ,@rest *unspecified*))
1053 (defmacro-public define-event-function rest
1054 "Defining macro returning event functions.
1056 (define-event-function (parser location arg1 arg2 ...) (arg1-type? arg2-type? ...)
1057 ...function body...)
1059 argX-type can take one of the forms @code{predicate?} for mandatory
1060 arguments satisfying the predicate, @code{(predicate?)} for optional
1061 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
1062 value)}} for optional parameters with a specified default
1063 value (evaluated at definition time). An optional parameter can be
1064 omitted in a call only when it can't get confused with a following
1065 parameter of different type.
1067 Predicates with syntactical significance are @code{ly:pitch?},
1068 @code{ly:duration?}, @code{ly:music?}, @code{markup?}. Other
1069 predicates require the parameter to be entered as Scheme expression.
1071 Must return an event expression. The @code{origin} is automatically
1072 set to the @code{location} parameter."
1074 `(define-syntax-function (ly:event? (make-music 'Event 'void #t)) ,@rest))
1076 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1078 (define-public (cue-substitute quote-music)
1079 "Must happen after @code{quote-substitute}."
1081 (if (vector? (ly:music-property quote-music 'quoted-events))
1082 (let* ((dir (ly:music-property quote-music 'quoted-voice-direction))
1083 (clef (ly:music-property quote-music 'quoted-music-clef #f))
1084 (main-voice (case dir ((1) 1) ((-1) 0) (else #f)))
1085 (cue-voice (and main-voice (- 1 main-voice)))
1086 (cue-type (ly:music-property quote-music 'quoted-context-type #f))
1087 (cue-id (ly:music-property quote-music 'quoted-context-id))
1088 (main-music (ly:music-property quote-music 'element))
1089 (return-value quote-music))
1092 (set! (ly:music-property quote-music 'element)
1093 (make-sequential-music
1095 (make-voice-props-override main-voice)
1097 (make-voice-props-revert)))))
1099 ;; if we have stem dirs, change both quoted and main music
1100 ;; to have opposite stems.
1102 ;; cannot context-spec Quote-music, since context
1103 ;; for the quotes is determined in the iterator.
1105 (make-sequential-music
1108 (and clef (make-cue-clef-set clef))
1109 (and cue-type cue-voice
1111 (make-voice-props-override cue-voice)
1114 (and cue-type cue-voice
1116 (make-voice-props-revert)
1118 (and clef (make-cue-clef-unset))))))
1121 (define-public ((quote-substitute quote-tab) music)
1122 (let* ((quoted-name (ly:music-property music 'quoted-music-name))
1123 (quoted-vector (and (string? quoted-name)
1124 (hash-ref quote-tab quoted-name #f))))
1127 (if (string? quoted-name)
1128 (if (vector? quoted-vector)
1130 (set! (ly:music-property music 'quoted-events) quoted-vector)
1131 (set! (ly:music-property music 'iterator-ctor)
1132 ly:quote-iterator::constructor))
1133 (ly:music-warning music (ly:format (_ "cannot find quoted music: `~S'") quoted-name))))
1137 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1138 ;; switch it on here, so parsing and init isn't checked (too slow!)
1140 ;; automatic music transformations.
1142 (define (switch-on-debugging m)
1143 (if (defined? 'set-debug-cell-accesses!)
1144 (set-debug-cell-accesses! 15000))
1147 (define (music-check-error music)
1150 (if (and (ly:music? m)
1151 (eq? (ly:music-property m 'error-found) #t))
1154 (for-each signal (ly:music-property music 'elements))
1155 (signal (ly:music-property music 'element))
1158 (set! (ly:music-property music 'error-found) #t))
1161 (define (precompute-music-length music)
1162 (set! (ly:music-property music 'length)
1163 (ly:music-length music))
1166 (define-public (make-duration-of-length moment)
1167 "Make duration of the given @code{moment} length."
1168 (ly:make-duration 0 0
1169 (ly:moment-main-numerator moment)
1170 (ly:moment-main-denominator moment)))
1172 (define (make-skipped moment bool)
1173 "Depending on BOOL, set or unset skipTypesetting,
1174 then make SkipMusic of the given MOMENT length, and
1175 then revert skipTypesetting."
1176 (make-sequential-music
1178 (context-spec-music (make-property-set 'skipTypesetting bool)
1180 (make-music 'SkipMusic 'duration
1181 (make-duration-of-length moment))
1182 (context-spec-music (make-property-set 'skipTypesetting (not bool))
1185 (define (skip-as-needed music parser)
1187 << { \\set skipTypesetting = ##f
1188 LENGTHOF(\\showFirstLength)
1189 \\set skipTypesetting = ##t
1190 LENGTHOF(\\showLastLength) }
1194 When only showFirstLength is set,
1195 the 'length property of the music is
1196 overridden to speed up compiling."
1198 ((show-last (ly:parser-lookup parser 'showLastLength))
1199 (show-first (ly:parser-lookup parser 'showFirstLength))
1200 (show-last-length (and (ly:music? show-last)
1201 (ly:music-length show-last)))
1202 (show-first-length (and (ly:music? show-first)
1203 (ly:music-length show-first)))
1204 (orig-length (ly:music-length music)))
1206 ;;FIXME: if using either showFirst- or showLastLength,
1207 ;; make sure that skipBars is not set.
1211 ;; both properties may be set.
1212 ((and show-first-length show-last-length)
1214 ((skip-length (ly:moment-sub orig-length show-last-length)))
1215 (make-simultaneous-music
1217 (make-sequential-music
1219 (make-skipped skip-length #t)
1220 ;; let's draw a separator between the beginning and the end
1221 (context-spec-music (make-property-set 'whichBar "||")
1223 (make-skipped show-first-length #f)
1226 ;; we may only want to print the last length
1229 ((skip-length (ly:moment-sub orig-length show-last-length)))
1230 (make-simultaneous-music
1232 (make-skipped skip-length #t)
1235 ;; we may only want to print the beginning; in this case
1236 ;; only the first length will be processed (much faster).
1238 ;; the first length must not exceed the original length.
1239 (if (ly:moment<? show-first-length orig-length)
1240 (set! (ly:music-property music 'length)
1247 (define-public toplevel-music-functions
1249 (lambda (music parser) (expand-repeat-chords!
1250 (cons 'rhythmic-event
1251 (ly:parser-lookup parser '$chord-repeat-events))
1253 (lambda (music parser) (voicify-music music))
1254 (lambda (x parser) (music-map music-check-error x))
1255 (lambda (x parser) (music-map precompute-music-length x))
1256 (lambda (music parser)
1258 (music-map (quote-substitute (ly:parser-lookup parser 'musicQuotes)) music))
1260 ;; switch-on-debugging
1261 (lambda (x parser) (music-map cue-substitute x))
1264 (skip-as-needed x parser)
1268 ;;; general purpose music functions
1270 (define (shift-octave pitch octave-shift)
1271 (_i "Add @var{octave-shift} to the octave of @var{pitch}.")
1273 (+ (ly:pitch-octave pitch) octave-shift)
1274 (ly:pitch-notename pitch)
1275 (ly:pitch-alteration pitch)))
1281 (define (apply-durations lyric-music durations)
1282 (define (apply-duration music)
1283 (if (and (not (equal? (ly:music-length music) ZERO-MOMENT))
1284 (ly:duration? (ly:music-property music 'duration)))
1286 (set! (ly:music-property music 'duration) (car durations))
1287 (set! durations (cdr durations)))))
1289 (music-map apply-duration lyric-music))
1292 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1295 (define (recent-enough? bar-number alteration-def laziness)
1296 (or (number? alteration-def)
1297 (equal? laziness #t)
1298 (<= bar-number (+ (cadr alteration-def) laziness))))
1300 (define (accidental-invalid? alteration-def)
1301 "Checks an alteration entry for being invalid.
1303 Non-key alterations are invalidated when tying into the next bar or
1304 when there is a clef change, since neither repetition nor cancellation
1305 can be omitted when the same note occurs again.
1307 Returns @code{#f} or the reason for the invalidation, a symbol."
1308 (let* ((def (if (pair? alteration-def)
1309 (car alteration-def)
1311 (and (symbol? def) def)))
1313 (define (extract-alteration alteration-def)
1314 (cond ((number? alteration-def)
1316 ((pair? alteration-def)
1317 (car alteration-def))
1320 (define (check-pitch-against-signature context pitch barnum laziness octaveness)
1321 "Checks the need for an accidental and a @q{restore} accidental against
1322 @code{localKeySignature}. The @var{laziness} is the number of measures
1323 for which reminder accidentals are used (i.e., if @var{laziness} is zero,
1324 only cancel accidentals in the same measure; if @var{laziness} is three,
1325 we cancel accidentals up to three measures after they first appear.
1326 @var{octaveness} is either @code{'same-octave} or @code{'any-octave} and
1327 specifies whether accidentals should be canceled in different octaves."
1328 (let* ((ignore-octave (cond ((equal? octaveness 'any-octave) #t)
1329 ((equal? octaveness 'same-octave) #f)
1331 (ly:warning (_ "Unknown octaveness type: ~S ") octaveness)
1332 (ly:warning (_ "Defaulting to 'any-octave."))
1334 (key-sig (ly:context-property context 'keySignature))
1335 (local-key-sig (ly:context-property context 'localKeySignature))
1336 (notename (ly:pitch-notename pitch))
1337 (octave (ly:pitch-octave pitch))
1338 (pitch-handle (cons octave notename))
1340 (need-accidental #f)
1341 (previous-alteration #f)
1342 (from-other-octaves #f)
1343 (from-same-octave (assoc-get pitch-handle local-key-sig))
1344 (from-key-sig (or (assoc-get notename local-key-sig)
1346 ;; If no key signature match is found from localKeySignature, we may have a custom
1347 ;; type with octave-specific entries of the form ((octave . pitch) alteration)
1348 ;; instead of (pitch . alteration). Since this type cannot coexist with entries in
1349 ;; localKeySignature, try extracting from keySignature instead.
1350 (assoc-get pitch-handle key-sig))))
1352 ;; loop through localKeySignature to search for a notename match from other octaves
1353 (let loop ((l local-key-sig))
1355 (let ((entry (car l)))
1356 (if (and (pair? (car entry))
1357 (= (cdar entry) notename))
1358 (set! from-other-octaves (cdr entry))
1361 ;; find previous alteration-def for comparison with pitch
1363 ;; from same octave?
1364 ((and (not ignore-octave)
1366 (recent-enough? barnum from-same-octave laziness))
1367 (set! previous-alteration from-same-octave))
1372 (recent-enough? barnum from-other-octaves laziness))
1373 (set! previous-alteration from-other-octaves))
1375 ;; not recent enough, extract from key signature/local key signature
1377 (set! previous-alteration from-key-sig)))
1379 (if (accidental-invalid? previous-alteration)
1380 (set! need-accidental #t)
1382 (let* ((prev-alt (extract-alteration previous-alteration))
1383 (this-alt (ly:pitch-alteration pitch)))
1385 (if (not (= this-alt prev-alt))
1387 (set! need-accidental #t)
1388 (if (and (not (= this-alt 0))
1389 (and (< (abs this-alt) (abs prev-alt))
1390 (> (* prev-alt this-alt) 0)))
1391 (set! need-restore #t))))))
1393 (cons need-restore need-accidental)))
1395 (define-public ((make-accidental-rule octaveness laziness) context pitch barnum measurepos)
1396 "Create an accidental rule that makes its decision based on the octave of
1397 the note and a laziness value.
1399 @var{octaveness} is either @code{'same-octave} or @code{'any-octave} and
1400 defines whether the rule should respond to accidental changes in other
1401 octaves than the current. @code{'same-octave} is the normal way to typeset
1402 accidentals -- an accidental is made if the alteration is different from the
1403 last active pitch in the same octave. @code{'any-octave} looks at the last
1404 active pitch in any octave.
1406 @var{laziness} states over how many bars an accidental should be remembered.
1407 @code{0}@tie{}is the default -- accidental lasts over 0@tie{}bar lines, that
1408 is, to the end of current measure. A positive integer means that the
1409 accidental lasts over that many bar lines. @w{@code{-1}} is `forget
1410 immediately', that is, only look at key signature. @code{#t} is `forever'."
1412 (check-pitch-against-signature context pitch barnum laziness octaveness))
1414 (define (key-entry-notename entry)
1415 "Return the pitch of an @var{entry} in @code{localKeySignature}.
1416 The @samp{car} of the entry is either of the form @code{notename} or
1417 of the form @code{(octave . notename)}. The latter form is used for special
1418 key signatures or to indicate an explicit accidental.
1420 The @samp{cdr} of the entry is either a rational @code{alter} indicating
1421 a key signature alteration, or of the form
1422 @code{(alter . (barnum . measurepos))} indicating an alteration caused by
1423 an accidental in music."
1424 (if (pair? (car entry))
1428 (define (key-entry-octave entry)
1429 "Return the octave of an entry in @code{localKeySignature}
1430 or @code{#f} if the entry does not have an octave.
1431 See @code{key-entry-notename} for details."
1432 (and (pair? (car entry)) (caar entry)))
1434 (define (key-entry-bar-number entry)
1435 "Return the bar number of an entry in @code{localKeySignature}
1436 or @code {#f} if the entry does not have a bar number.
1437 See @code{key-entry-notename} for details."
1438 (and (pair? (cdr entry)) (caddr entry)))
1440 (define (key-entry-measure-position entry)
1441 "Return the measure position of an entry in @code{localKeySignature}
1442 or @code {#f} if the entry does not have a measure position.
1443 See @code{key-entry-notename} for details."
1444 (and (pair? (cdr entry)) (cdddr entry)))
1446 (define (key-entry-alteration entry)
1447 "Return the alteration of an entry in localKeySignature.
1449 For convenience, returns @code{0} if entry is @code{#f}."
1451 (if (number? (cdr entry))
1456 (define-public (find-pitch-entry keysig pitch accept-global accept-local)
1457 "Return the first entry in @var{keysig} that matches @var{pitch}.
1458 @var{accept-global} states whether key signature entries should be included.
1459 @var{accept-local} states whether local accidentals should be included.
1460 If no matching entry is found, @var{#f} is returned."
1462 (let* ((entry (car keysig))
1463 (entryoct (key-entry-octave entry))
1464 (entrynn (key-entry-notename entry))
1465 (nn (ly:pitch-notename pitch)))
1466 (if (and (equal? nn entrynn)
1468 (= entryoct (ly:pitch-octave pitch)))
1469 (if (key-entry-bar-number entry)
1473 (find-pitch-entry (cdr keysig) pitch accept-global accept-local)))))
1475 (define-public (neo-modern-accidental-rule context pitch barnum measurepos)
1476 "An accidental rule that typesets an accidental if it differs from the
1477 key signature @emph{and} does not directly follow a note on the same
1478 staff line. This rule should not be used alone because it does neither
1479 look at bar lines nor different accidentals at the same note name."
1480 (let* ((keysig (ly:context-property context 'localKeySignature))
1481 (entry (find-pitch-entry keysig pitch #t #t)))
1484 (let* ((global-entry (find-pitch-entry keysig pitch #t #f))
1485 (key-acc (key-entry-alteration global-entry))
1486 (acc (ly:pitch-alteration pitch))
1487 (entrymp (key-entry-measure-position entry))
1488 (entrybn (key-entry-bar-number entry)))
1489 (cons #f (not (or (equal? acc key-acc)
1490 (and (equal? entrybn barnum) (equal? entrymp measurepos)))))))))
1492 (define-public (teaching-accidental-rule context pitch barnum measurepos)
1493 "An accidental rule that typesets a cautionary accidental if it is
1494 included in the key signature @emph{and} does not directly follow a note
1495 on the same staff line."
1496 (let* ((keysig (ly:context-property context 'localKeySignature))
1497 (entry (find-pitch-entry keysig pitch #t #t)))
1500 (let* ((entrymp (key-entry-measure-position entry))
1501 (entrybn (key-entry-bar-number entry)))
1502 (cons #f (not (and (equal? entrybn barnum) (equal? entrymp measurepos))))))))
1504 (define-public (set-accidentals-properties extra-natural
1505 auto-accs auto-cauts
1508 (make-sequential-music
1509 (append (if (boolean? extra-natural)
1510 (list (make-property-set 'extraNatural extra-natural))
1512 (list (make-property-set 'autoAccidentals auto-accs)
1513 (make-property-set 'autoCautionaries auto-cauts))))
1516 (define-public (set-accidental-style style . rest)
1517 "Set accidental style to @var{style}. Optionally take a context
1518 argument, e.g. @code{'Staff} or @code{'Voice}. The context defaults
1519 to @code{Staff}, except for piano styles, which use @code{GrandStaff}
1521 (let ((context (if (pair? rest)
1523 (pcontext (if (pair? rest)
1524 (car rest) 'GrandStaff)))
1526 ;; accidentals as they were common in the 18th century.
1527 ((equal? style 'default)
1528 (set-accidentals-properties #t
1529 `(Staff ,(make-accidental-rule 'same-octave 0))
1532 ;; accidentals from one voice do NOT get canceled in other voices
1533 ((equal? style 'voice)
1534 (set-accidentals-properties #t
1535 `(Voice ,(make-accidental-rule 'same-octave 0))
1538 ;; accidentals as suggested by Kurt Stone, Music Notation in the 20th century.
1539 ;; This includes all the default accidentals, but accidentals also needs canceling
1540 ;; in other octaves and in the next measure.
1541 ((equal? style 'modern)
1542 (set-accidentals-properties #f
1543 `(Staff ,(make-accidental-rule 'same-octave 0)
1544 ,(make-accidental-rule 'any-octave 0)
1545 ,(make-accidental-rule 'same-octave 1))
1548 ;; the accidentals that Stone adds to the old standard as cautionaries
1549 ((equal? style 'modern-cautionary)
1550 (set-accidentals-properties #f
1551 `(Staff ,(make-accidental-rule 'same-octave 0))
1552 `(Staff ,(make-accidental-rule 'any-octave 0)
1553 ,(make-accidental-rule 'same-octave 1))
1555 ;; same as modern, but accidentals different from the key signature are always
1556 ;; typeset - unless they directly follow a note of the same pitch.
1557 ((equal? style 'neo-modern)
1558 (set-accidentals-properties #f
1559 `(Staff ,(make-accidental-rule 'same-octave 0)
1560 ,(make-accidental-rule 'any-octave 0)
1561 ,(make-accidental-rule 'same-octave 1)
1562 ,neo-modern-accidental-rule)
1565 ((equal? style 'neo-modern-cautionary)
1566 (set-accidentals-properties #f
1567 `(Staff ,(make-accidental-rule 'same-octave 0))
1568 `(Staff ,(make-accidental-rule 'any-octave 0)
1569 ,(make-accidental-rule 'same-octave 1)
1570 ,neo-modern-accidental-rule)
1572 ((equal? style 'neo-modern-voice)
1573 (set-accidentals-properties #f
1574 `(Voice ,(make-accidental-rule 'same-octave 0)
1575 ,(make-accidental-rule 'any-octave 0)
1576 ,(make-accidental-rule 'same-octave 1)
1577 ,neo-modern-accidental-rule
1578 Staff ,(make-accidental-rule 'same-octave 0)
1579 ,(make-accidental-rule 'any-octave 0)
1580 ,(make-accidental-rule 'same-octave 1)
1581 ,neo-modern-accidental-rule)
1584 ((equal? style 'neo-modern-voice-cautionary)
1585 (set-accidentals-properties #f
1586 `(Voice ,(make-accidental-rule 'same-octave 0))
1587 `(Voice ,(make-accidental-rule 'any-octave 0)
1588 ,(make-accidental-rule 'same-octave 1)
1589 ,neo-modern-accidental-rule
1590 Staff ,(make-accidental-rule 'same-octave 0)
1591 ,(make-accidental-rule 'any-octave 0)
1592 ,(make-accidental-rule 'same-octave 1)
1593 ,neo-modern-accidental-rule)
1595 ;; Accidentals as they were common in dodecaphonic music with no tonality.
1596 ;; Each note gets one accidental.
1597 ((equal? style 'dodecaphonic)
1598 (set-accidentals-properties #f
1599 `(Staff ,(lambda (c p bn mp) '(#f . #t)))
1602 ;; Multivoice accidentals to be read both by musicians playing one voice
1603 ;; and musicians playing all voices.
1604 ;; Accidentals are typeset for each voice, but they ARE canceled across voices.
1605 ((equal? style 'modern-voice)
1606 (set-accidentals-properties #f
1607 `(Voice ,(make-accidental-rule 'same-octave 0)
1608 ,(make-accidental-rule 'any-octave 0)
1609 ,(make-accidental-rule 'same-octave 1)
1610 Staff ,(make-accidental-rule 'same-octave 0)
1611 ,(make-accidental-rule 'any-octave 0)
1612 ,(make-accidental-rule 'same-octave 1))
1615 ;; same as modernVoiceAccidental eccept that all special accidentals are typeset
1617 ((equal? style 'modern-voice-cautionary)
1618 (set-accidentals-properties #f
1619 `(Voice ,(make-accidental-rule 'same-octave 0))
1620 `(Voice ,(make-accidental-rule 'any-octave 0)
1621 ,(make-accidental-rule 'same-octave 1)
1622 Staff ,(make-accidental-rule 'same-octave 0)
1623 ,(make-accidental-rule 'any-octave 0)
1624 ,(make-accidental-rule 'same-octave 1))
1626 ;; stone's suggestions for accidentals on grand staff.
1627 ;; Accidentals are canceled across the staves in the same grand staff as well
1628 ((equal? style 'piano)
1629 (set-accidentals-properties #f
1630 `(Staff ,(make-accidental-rule 'same-octave 0)
1631 ,(make-accidental-rule 'any-octave 0)
1632 ,(make-accidental-rule 'same-octave 1)
1634 ,(make-accidental-rule 'any-octave 0)
1635 ,(make-accidental-rule 'same-octave 1))
1638 ((equal? style 'piano-cautionary)
1639 (set-accidentals-properties #f
1640 `(Staff ,(make-accidental-rule 'same-octave 0))
1641 `(Staff ,(make-accidental-rule 'any-octave 0)
1642 ,(make-accidental-rule 'same-octave 1)
1644 ,(make-accidental-rule 'any-octave 0)
1645 ,(make-accidental-rule 'same-octave 1))
1648 ;; same as modern, but cautionary accidentals are printed for all sharp or flat
1649 ;; tones specified by the key signature.
1650 ((equal? style 'teaching)
1651 (set-accidentals-properties #f
1652 `(Staff ,(make-accidental-rule 'same-octave 0))
1653 `(Staff ,(make-accidental-rule 'same-octave 1)
1654 ,teaching-accidental-rule)
1657 ;; do not set localKeySignature when a note alterated differently from
1658 ;; localKeySignature is found.
1659 ;; Causes accidentals to be printed at every note instead of
1660 ;; remembered for the duration of a measure.
1661 ;; accidentals not being remembered, causing accidentals always to
1662 ;; be typeset relative to the time signature
1663 ((equal? style 'forget)
1664 (set-accidentals-properties '()
1665 `(Staff ,(make-accidental-rule 'same-octave -1))
1668 ;; Do not reset the key at the start of a measure. Accidentals will be
1669 ;; printed only once and are in effect until overridden, possibly many
1671 ((equal? style 'no-reset)
1672 (set-accidentals-properties '()
1673 `(Staff ,(make-accidental-rule 'same-octave #t))
1677 (ly:warning (_ "unknown accidental style: ~S") style)
1678 (make-sequential-music '())))))
1680 (define-public (invalidate-alterations context)
1681 "Invalidate alterations in @var{context}.
1683 Elements of @code{'localKeySignature} corresponding to local
1684 alterations of the key signature have the form
1685 @code{'((octave . notename) . (alter barnum . measurepos))}.
1686 Replace them with a version where @code{alter} is set to @code{'clef}
1687 to force a repetition of accidentals.
1689 Entries that conform with the current key signature are not invalidated."
1690 (let* ((keysig (ly:context-property context 'keySignature)))
1691 (set! (ly:context-property context 'localKeySignature)
1694 (let* ((localalt (key-entry-alteration entry)))
1695 (if (or (accidental-invalid? localalt)
1696 (not (key-entry-bar-number entry))
1698 (key-entry-alteration
1701 (ly:make-pitch (key-entry-octave entry)
1702 (key-entry-notename entry)
1706 (cons (car entry) (cons 'clef (cddr entry))))))
1707 (ly:context-property context 'localKeySignature)))))
1709 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1711 (define-public (skip-of-length mus)
1712 "Create a skip of exactly the same length as @var{mus}."
1716 'duration (ly:make-duration 0 0))))
1718 (make-event-chord (list (ly:music-compress skip (ly:music-length mus))))))
1720 (define-public (mmrest-of-length mus)
1721 "Create a multi-measure rest of exactly the same length as @var{mus}."
1724 (make-multi-measure-rest
1725 (ly:make-duration 0 0) '())))
1726 (ly:music-compress skip (ly:music-length mus))
1729 (define-public (pitch-of-note event-chord)
1730 (let ((evs (filter (lambda (x)
1731 (music-has-type x 'note-event))
1732 (ly:music-property event-chord 'elements))))
1735 (ly:music-property (car evs) 'pitch))))
1737 (define-public (duration-of-note event-chord)
1739 ((pair? event-chord)
1740 (or (duration-of-note (car event-chord))
1741 (duration-of-note (cdr event-chord))))
1742 ((ly:music? event-chord)
1743 (let ((dur (ly:music-property event-chord 'duration)))
1744 (if (ly:duration? dur)
1746 (duration-of-note (ly:music-property event-chord 'elements)))))
1749 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1751 (define-public (map-some-music map? music)
1752 "Walk through @var{music}, transform all elements calling @var{map?}
1753 and only recurse if this returns @code{#f}. @code{elements} or
1754 @code{articulations} that are not music expressions are discarded:
1755 this allows some amount of filtering.
1757 @code{map-some-music} may overwrite the original @var{music}."
1758 (let loop ((music music))
1760 (let ((elt (ly:music-property music 'element))
1761 (elts (ly:music-property music 'elements))
1762 (arts (ly:music-property music 'articulations)))
1764 (set! (ly:music-property music 'element)
1767 (set! (ly:music-property music 'elements)
1768 (filter! ly:music? (map! loop elts))))
1770 (set! (ly:music-property music 'articulations)
1771 (filter! ly:music? (map! loop arts))))
1774 (define-public (for-some-music stop? music)
1775 "Walk through @var{music}, process all elements calling @var{stop?}
1776 and only recurse if this returns @code{#f}."
1777 (let loop ((music music))
1778 (if (not (stop? music))
1779 (let ((elt (ly:music-property music 'element)))
1782 (for-each loop (ly:music-property music 'elements))
1783 (for-each loop (ly:music-property music 'articulations))))))
1785 (define-public (fold-some-music pred? proc init music)
1786 "This works recursively on music like @code{fold} does on a list,
1787 calling @samp{(@var{pred?} music)} on every music element. If
1788 @code{#f} is returned for an element, it is processed recursively
1789 with the same initial value of @samp{previous}, otherwise
1790 @samp{(@var{proc} music previous)} replaces @samp{previous}
1791 and no recursion happens.
1792 The top @var{music} is processed using @var{init} for @samp{previous}."
1793 (let loop ((music music) (previous init))
1795 (proc music previous)
1798 (let ((elt (ly:music-property music 'element)))
1801 (loop elt previous)))
1802 (ly:music-property music 'elements))
1803 (ly:music-property music 'articulations)))))
1805 (define-public (extract-music music pred?)
1806 "Return a flat list of all music matching @var{pred?} inside of
1807 @var{music}, not recursing into matches themselves."
1808 (reverse! (fold-some-music pred? cons '() music)))
1810 (define-public (extract-named-music music music-name)
1811 "Return a flat list of all music named @var{music-name} (either a
1812 single event symbol or a list of alternatives) inside of @var{music},
1813 not recursing into matches themselves."
1816 (if (cheap-list? music-name)
1817 (lambda (m) (memq (ly:music-property m 'name) music-name))
1818 (lambda (m) (eq? (ly:music-property m 'name) music-name)))))
1820 (define-public (extract-typed-music music type)
1821 "Return a flat list of all music with @var{type} (either a single
1822 type symbol or a list of alternatives) inside of @var{music}, not
1823 recursing into matches themselves."
1826 (if (cheap-list? type)
1828 (any (lambda (t) (music-is-of-type? m t)) type))
1829 (lambda (m) (music-is-of-type? m type)))))
1831 (define*-public (event-chord-wrap! music #:optional parser)
1832 "Wrap isolated rhythmic events and non-postevent events in
1833 @var{music} inside of an @code{EventChord}. If the optional
1834 @var{parser} argument is given, chord repeats @samp{q} are expanded
1835 using the default settings. Otherwise, you need to cater for them
1839 (cond ((music-is-of-type? m 'event-chord)
1840 (if (pair? (ly:music-property m 'articulations))
1842 (set! (ly:music-property m 'elements)
1843 (append (ly:music-property m 'elements)
1844 (ly:music-property m 'articulations)))
1845 (set! (ly:music-property m 'articulations) '())))
1847 ((music-is-of-type? m 'rhythmic-event)
1848 (let ((arts (ly:music-property m 'articulations)))
1850 (set! (ly:music-property m 'articulations) '()))
1851 (make-event-chord (cons m arts))))
1854 (expand-repeat-chords!
1855 (cons 'rhythmic-event
1856 (ly:parser-lookup parser '$chord-repeat-events))
1860 (define-public (event-chord-notes event-chord)
1861 "Return a list of all notes from @var{event-chord}."
1863 (lambda (m) (eq? 'NoteEvent (ly:music-property m 'name)))
1864 (ly:music-property event-chord 'elements)))
1866 (define-public (event-chord-pitches event-chord)
1867 "Return a list of all pitches from @var{event-chord}."
1868 (map (lambda (x) (ly:music-property x 'pitch))
1869 (event-chord-notes event-chord)))
1871 (defmacro-public make-relative (pitches last-pitch music)
1872 "The list of pitch-carrying variables in @var{pitches} is used as a
1873 sequence for creating relativable music from @var{music}.
1874 The variables in @var{pitches} are, when considered inside of
1875 @code{\\relative}, all considered to be specifications to the preceding
1876 variable. The first variable is relative to the preceding musical
1877 context, and @var{last-pitch} specifies the pitch passed as relative
1878 base onto the following musical context."
1880 ;; pitch and music generator might be stored instead in music
1881 ;; properties, and it might make sense to create a music type of its
1882 ;; own for this kind of construct rather than using
1883 ;; RelativeOctaveMusic
1884 (define ((make-relative::to-relative-callback pitches p->m p->p) music pitch)
1885 (let* ((chord (make-event-chord
1888 (make-music 'NoteEvent
1892 (ly:make-music-relative! chord pitch)
1893 (event-chord-pitches chord))))
1894 (set! (ly:music-property music 'element)
1895 (apply p->m pitchout))
1896 (apply p->p pitchout)))
1897 `(make-music 'RelativeOctaveMusic
1898 'to-relative-callback
1899 (,make-relative::to-relative-callback
1901 (lambda ,pitches ,music)
1902 (lambda ,pitches ,last-pitch))
1905 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1906 ;; The following functions are all associated with the crossStaff
1909 (define (close-enough? x y)
1910 "Values are close enough to ignore the difference"
1911 (< (abs (- x y)) 0.0001))
1913 (define (extent-combine extents)
1914 "Combine a list of extents"
1915 (if (pair? (cdr extents))
1916 (interval-union (car extents) (extent-combine (cdr extents)))
1919 (define ((stem-connectable? ref root) stem)
1920 "Check if the stem is connectable to the root"
1921 ;; The root is always connectable to itself
1924 ;; Horizontal positions of the stems must be almost the same
1925 (close-enough? (car (ly:grob-extent root ref X))
1926 (car (ly:grob-extent stem ref X)))
1927 ;; The stem must be in the direction away from the root's notehead
1928 (positive? (* (ly:grob-property root 'direction)
1929 (- (car (ly:grob-extent stem ref Y))
1930 (car (ly:grob-extent root ref Y))))))))
1932 (define (stem-span-stencil span)
1933 "Connect stems if we have at least one stem connectable to the root"
1934 (let* ((system (ly:grob-system span))
1935 (root (ly:grob-parent span X))
1936 (stems (filter (stem-connectable? system root)
1937 (ly:grob-object span 'stems))))
1938 (if (<= 2 (length stems))
1939 (let* ((yextents (map (lambda (st)
1940 (ly:grob-extent st system Y)) stems))
1941 (yextent (extent-combine yextents))
1942 (layout (ly:grob-layout root))
1943 (blot (ly:output-def-lookup layout 'blot-diameter)))
1944 ;; Hide spanned stems
1946 (set! (ly:grob-property st 'stencil) #f))
1948 ;; Draw a nice looking stem with rounded corners
1949 (ly:round-filled-box (ly:grob-extent root root X) yextent blot))
1950 ;; Nothing to connect, don't draw the span
1953 (define ((make-stem-span! stems trans) root)
1954 "Create a stem span as a child of the cross-staff stem (the root)"
1955 (let ((span (ly:engraver-make-grob trans 'Stem '())))
1956 (ly:grob-set-parent! span X root)
1957 (set! (ly:grob-object span 'stems) stems)
1958 ;; Suppress positioning, the stem code is confused by this weird stem
1959 (set! (ly:grob-property span 'X-offset) 0)
1960 (set! (ly:grob-property span 'stencil) stem-span-stencil)))
1962 (define-public (cross-staff-connect stem)
1963 "Set cross-staff property of the stem to this function to connect it to
1964 other stems automatically"
1967 (define (stem-is-root? stem)
1968 "Check if automatic connecting of the stem was requested. Stems connected
1969 to cross-staff beams are cross-staff, but they should not be connected to
1970 other stems just because of that."
1971 (eq? cross-staff-connect (ly:grob-property-data stem 'cross-staff)))
1973 (define (make-stem-spans! ctx stems trans)
1974 "Create stem spans for cross-staff stems"
1975 ;; Cannot do extensive checks here, just make sure there are at least
1976 ;; two stems at this musical moment
1977 (if (<= 2 (length stems))
1978 (let ((roots (filter stem-is-root? stems)))
1979 (map (make-stem-span! stems trans) roots))))
1981 (define-public (Span_stem_engraver ctx)
1982 "Connect cross-staff stems to the stems above in the system"
1985 ;; Record all stems for the given moment
1987 ((stem-interface trans grob source)
1988 (set! stems (cons grob stems))))
1989 ;; Process stems and reset the stem list to empty
1990 ((process-acknowledged trans)
1991 (make-stem-spans! ctx stems trans)
1992 (set! stems '())))))
1994 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1995 ;; The following is used by the alterBroken function.
1997 (define-public ((value-for-spanner-piece arg) grob)
1998 "Associate a piece of broken spanner @var{grob} with an element
2000 (let* ((orig (ly:grob-original grob))
2001 (siblings (ly:spanner-broken-into orig)))
2003 (define (helper sibs arg)
2006 (if (eq? (car sibs) grob)
2008 (helper (cdr sibs) (cdr arg)))))
2010 (if (>= (length siblings) 2)
2011 (helper siblings arg)
2014 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2017 (define (measure-counter-stencil grob)
2018 "Print a number for a measure count. The number is centered using
2019 the extents of @code{BreakAlignment} grobs associated with
2020 @code{NonMusicalPaperColumn} grobs. In the case of an unbroken measure, these
2021 columns are the left and right bounds of a @code{MeasureCounter} spanner.
2022 Broken measures are numbered in parentheses."
2023 (let* ((orig (ly:grob-original grob))
2024 (siblings (ly:spanner-broken-into orig)) ; have we been split?
2025 (bounds (ly:grob-array->list (ly:grob-object grob 'columns)))
2026 (refp (ly:grob-system grob))
2027 ;; we use the first and/or last NonMusicalPaperColumn grob(s) of
2028 ;; a system in the event that a MeasureCounter spanner is broken
2029 (all-cols (ly:grob-array->list (ly:grob-object refp 'columns)))
2032 (lambda (col) (eq? #t (ly:grob-property col 'non-musical)))
2035 (if (or (null? siblings) ; spanner is unbroken
2036 (eq? grob (car siblings))) ; or the first piece
2040 (if (or (null? siblings)
2041 (eq? grob (car (reverse siblings))))
2042 (car (reverse bounds))
2043 (car (reverse all-cols))))
2044 (elts-L (ly:grob-array->list (ly:grob-object left-bound 'elements)))
2045 (elts-R (ly:grob-array->list (ly:grob-object right-bound 'elements)))
2048 (lambda (elt) (grob::has-interface elt 'break-alignment-interface))
2052 (lambda (elt) (grob::has-interface elt 'break-alignment-interface))
2054 (break-alignment-L-ext (ly:grob-extent (car break-alignment-L) refp X))
2055 (break-alignment-R-ext (ly:grob-extent (car break-alignment-R) refp X))
2056 (num (markup (number->string (ly:grob-property grob 'count-from))))
2058 (if (or (null? siblings)
2059 (eq? grob (car siblings)))
2061 (make-parenthesize-markup num)))
2062 (num (grob-interpret-markup grob num))
2063 (num (ly:stencil-aligned-to num X (ly:grob-property grob 'self-alignment-X)))
2065 (ly:stencil-translate-axis
2067 (+ (interval-length break-alignment-L-ext)
2069 (- (car break-alignment-R-ext)
2070 (cdr break-alignment-L-ext))))