]> git.donarmstrong.com Git - lilypond.git/blob - scm/music-functions.scm
Issue 3648/3: Pitchless durations inherit previous pitch when scorifying
[lilypond.git] / scm / music-functions.scm
1 ;;;; This file is part of LilyPond, the GNU music typesetter.
2 ;;;;
3 ;;;; Copyright (C) 1998--2012 Jan Nieuwenhuizen <janneke@gnu.org>
4 ;;;;                 Han-Wen Nienhuys <hanwen@xs4all.nl>
5 ;;;;
6 ;;;; LilyPond is free software: you can redistribute it and/or modify
7 ;;;; it under the terms of the GNU General Public License as published by
8 ;;;; the Free Software Foundation, either version 3 of the License, or
9 ;;;; (at your option) any later version.
10 ;;;;
11 ;;;; LilyPond is distributed in the hope that it will be useful,
12 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 ;;;; GNU General Public License for more details.
15 ;;;;
16 ;;;; You should have received a copy of the GNU General Public License
17 ;;;; along with LilyPond.  If not, see <http://www.gnu.org/licenses/>.
18
19 ;; for define-safe-public when byte-compiling using Guile V2
20 (use-modules (scm safe-utility-defs))
21
22 (use-modules (ice-9 optargs))
23
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!))
32
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)))
36
37 ;; TODO move this
38 (define-public ly:grob-property
39   (make-procedure-with-setter ly:grob-property
40                               ly:grob-set-property!))
41
42 (define-public ly:grob-object
43   (make-procedure-with-setter ly:grob-object
44                               ly:grob-set-object!))
45
46 (define-public ly:grob-parent
47   (make-procedure-with-setter ly:grob-parent
48                               ly:grob-set-parent!))
49
50 (define-public ly:prob-property
51   (make-procedure-with-setter ly:prob-property
52                               ly:prob-set-property!))
53
54 (define-public ly:context-property
55   (make-procedure-with-setter ly:context-property
56                               ly:context-set-property!))
57
58 (define-public (music-map function music)
59   "Apply @var{function} to @var{music} and all of the music it contains.
60
61 First it recurses over the children, then the function is applied to
62 @var{music}."
63   (let ((es (ly:music-property music 'elements))
64         (e (ly:music-property music 'element)))
65     (if (pair? es)
66         (set! (ly:music-property music 'elements)
67               (map (lambda (y) (music-map function y)) es)))
68     (if (ly:music? e)
69         (set! (ly:music-property music 'element)
70               (music-map function  e)))
71     (function music)))
72
73 (define-public (music-filter pred? music)
74   "Filter out music expressions that do not satisfy @var{pred?}."
75
76   (define (inner-music-filter pred? music)
77     "Recursive function."
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)
84                            e))
85            (filtered-es (filter ly:music? (map (lambda (y) (inner-music-filter pred? y)) es))))
86       (if (not (null? e))
87           (set! (ly:music-property music 'element) filtered-e))
88       (if (not (null? es))
89           (set! (ly:music-property music 'elements) filtered-es))
90       (if (not (null? as))
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 '()))
96                        (ly:music? e))))
97           (set! music '()))
98       music))
99
100   (set! music (inner-music-filter pred? music))
101   (if (ly:music? music)
102       music
103       (make-music 'Music)))       ;must return music.
104
105 (define*-public (display-music music #:optional (port (current-output-port)))
106   "Display music, not done with @code{music-map} for clarity of
107 presentation."
108   (display music port)
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)
113     (if (pair? es)
114         (begin (display "\nElements: {\n" port)
115                (for-each (lambda (m) (display-music m port)) es)
116                (display "}\n" port)))
117     (if (ly:music? e)
118         (begin
119           (display "\nChild:" port)
120           (display-music e port))))
121   (display " }\n" port)
122   music)
123
124 ;;;
125 ;;; A scheme music pretty printer
126 ;;;
127 (define (markup-expression->make-markup markup-expression)
128   "Transform `markup-expression' into an equivalent, hopefuly readable, scheme expression.
129 For instance,
130   \\markup \\bold \\italic hello
131 ==>
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            (append-map inner-markup->make-markup arg))
141           ((and (not (string? arg)) (markup? arg)) ;; a markup
142            (inner-markup->make-markup arg))
143           (else                                  ;; scheme arg
144            (music->make-music arg))))
145   (define (inner-markup->make-markup mrkup)
146     (if (string? mrkup)
147         `(#:simple ,mrkup)
148         (let ((cmd (proc->command-keyword (car mrkup)))
149               (args (map transform-arg (cdr mrkup))))
150           `(,cmd ,@args))))
151   ;; body:
152   (if (string? markup-expression)
153       markup-expression
154       `(markup ,@(inner-markup->make-markup markup-expression))))
155
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
161          (markup? obj)
162          (markup-expression->make-markup obj))
163         (;; music expression
164          (ly:music? obj)
165          `(make-music
166            ',(ly:music-property obj 'name)
167            ,@(append-map (lambda (prop)
168                            `(',(car prop)
169                              ,(music->make-music (cdr prop))))
170                          (remove (lambda (prop)
171                                    (eqv? (car prop) 'origin))
172                                  (ly:music-mutable-properties obj)))))
173         (;; moment
174          (ly:moment? 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)))
179         (;; note duration
180          (ly:duration? obj)
181          `(ly:make-duration ,(ly:duration-log obj)
182                             ,(ly:duration-dot-count obj)
183                             ,(ly:duration-scale obj)))
184         (;; note pitch
185          (ly:pitch? obj)
186          `(ly:make-pitch ,(ly:pitch-octave obj)
187                          ,(ly:pitch-notename obj)
188                          ,(ly:pitch-alteration obj)))
189         (;; scheme procedure
190          (procedure? obj)
191          (or (procedure-name obj) obj))
192         (;; a symbol (avoid having an unquoted symbol)
193          (symbol? obj)
194          `',obj)
195         (;; an empty list (avoid having an unquoted empty list)
196          (null? obj)
197          `'())
198         (;; a proper list
199          (list? obj)
200          `(list ,@(map music->make-music obj)))
201         (;; a pair
202          (pair? obj)
203          `(cons ,(music->make-music (car obj))
204                 ,(music->make-music (cdr obj))))
205         (else
206          obj)))
207
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)
213   (newline port))
214
215 ;;;
216 ;;; Scheme music expression --> Lily-syntax-using string translator
217 ;;;
218 (use-modules (srfi srfi-39)
219              (scm display-lily))
220
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)
229                 (newline port)))
230
231 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
232
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)))
238     (if (ly:duration? d)
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)))
243                     cp)))
244           (set! (ly:music-property music 'duration) nd)))
245     music))
246
247 (define-public (shift-duration-log music shift dot)
248   (music-map (lambda (x) (shift-one-duration-log x shift dot))
249              music))
250
251 (define-public (make-repeat name times main alts)
252   "Create a repeat music expression, with all properties initialized
253 properly."
254   (define (first-note-duration music)
255     "Finds the duration of the first NoteEvent by searching depth-first
256 through MUSIC."
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))))
264           (and (pair? elts)
265                (let ((dur (first-note-duration (car elts))))
266                  (if (ly:duration? dur)
267                      dur
268                      (loop (cdr elts))))))))
269
270   (let ((talts (if (< times (length alts))
271                    (begin
272                      (ly:warning (_ "More alternatives than repeats.  Junking excess alternatives"))
273                      (take alts times))
274                    alts))
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
285                                                                  NoteEvent)))
286                              ;; \repeat tremolo n c4
287                              1))
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
291                ;; times * children
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)
297                                  1))
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)))
301               (ly:music-warning
302                main
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))
308         r)))
309
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)))
319
320     (if (every (lambda (d) (equal? d first-dur)) durs)
321         (max (- (ly:duration-log first-dur) 2) 1)
322         0)))
323
324 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
325 ;; clusters.
326
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))
333       music))
334
335 (define-public (notes-to-clusters music)
336   (music-map note-to-cluster music))
337
338 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
339 ;; repeats.
340
341 (define-public (unfold-repeats music)
342   "Replace all repeats with unfolded repeats."
343
344   (let ((es (ly:music-property music 'elements))
345         (e (ly:music-property music 'element)))
346
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
352                                               flattened)))
353
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
360                                                                     NoteEvent)))
361                                    ;; \repeat tremolo n c4
362                                    1))
363                      (times (ly:music-property music 'repeat-count))
364
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
368                      ;; times * children
369                      (mult (/ (* times children (ash 1 dots)) (1- (ash 2 dots))))
370                      (shift (- (ly:intlog2 (floor mult)))))
371
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))))))
376
377     (if (pair? es)
378         (set! (ly:music-property music 'elements)
379               (map unfold-repeats es)))
380     (if (ly:music? e)
381         (set! (ly:music-property music 'element)
382               (unfold-repeats e)))
383     music))
384
385 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
386 ;; property setting music objs.
387
388 (define-safe-public (check-grob-path path #:optional parser location
389                                      #:key
390                                      (start 0)
391                                      default
392                                      (min 1)
393                                      max)
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.
402
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.
407
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,
411 respectively."
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?))))
418     (define (grob? s)
419       (object-property s 'is-grob?))
420     (define (property? s)
421       (object-property s 'backend-type?))
422     (define (check c p) (c p))
423
424     (let* ((checkers
425             (and (< start 3)
426                  (drop (list unspecial? grob? property?) start)))
427            (res
428             (cond
429              ((null? path)
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) '()))
439              ((not checkers)
440               ;; no checkers, so we have a valid first element and just
441               ;; take the path as-is.
442               path)
443              (default
444                (if ((car checkers) (car path))
445                    (and (every check (cdr checkers) (cdr path))
446                         path)
447                    (and (every check (cdr checkers) path)
448                         (cons default path))))
449              (else
450               (and (every check checkers path)
451                    path)))))
452       (if (and res
453                (if max (<= min (length res) max)
454                    (<= min (length res))))
455           res
456           (begin
457             (if parser
458                 (ly:parser-error parser
459                                  (format #f (_ "bad grob property path ~a")
460                                          path)
461                                  location))
462             #f)))))
463
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
468               'symbol grob
469               'grob-property gprop
470               'grob-value val
471               'pop-first #t))
472
473 (define-public (make-grob-property-override grob gprop val)
474   "Make a @code{Music} expression that overrides @var{gprop} to @var{val}
475 in @var{grob}."
476   (make-music 'OverrideProperty
477               'symbol grob
478               'grob-property gprop
479               'grob-value val))
480
481 (define-public (make-grob-property-revert grob gprop)
482   "Revert the grob property @var{gprop} for @var{grob}."
483   (make-music 'RevertProperty
484               'symbol grob
485               'grob-property gprop))
486
487 (define direction-polyphonic-grobs
488   '(AccidentalSuggestion
489     DotColumn
490     Dots
491     Fingering
492     LaissezVibrerTie
493     LigatureBracket
494     MultiMeasureRest
495     PhrasingSlur
496     RepeatTie
497     Rest
498     Script
499     Slur
500     Stem
501     TextScript
502     Tie
503     TupletBracket
504     TrillSpanner))
505
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)))
521
522 (define-public score-grace-settings
523   (append
524     `((Voice Stem direction ,UP)
525       (Voice Slur direction ,DOWN))
526     general-grace-settings))
527
528 (define-safe-public (make-voice-props-set n)
529   (make-sequential-music
530    (append
531     (map (lambda (x) (make-grob-property-set x 'direction
532                                              (if (odd? n) -1 1)))
533          direction-polyphonic-grobs)
534     (list
535      (make-property-set 'graceSettings general-grace-settings)
536      (make-grob-property-set 'NoteColumn 'horizontal-shift (quotient n 2))))))
537
538 (define-safe-public (make-voice-props-override n)
539   (make-sequential-music
540    (append
541     (map (lambda (x) (make-grob-property-override x 'direction
542                                                   (if (odd? n) -1 1)))
543          direction-polyphonic-grobs)
544     (list
545      (make-property-set 'graceSettings general-grace-settings)
546      (make-grob-property-override 'NoteColumn 'horizontal-shift (quotient n 2))))))
547
548 (define-safe-public (make-voice-props-revert)
549   (make-sequential-music
550    (append
551     (map (lambda (x) (make-grob-property-revert x 'direction))
552          direction-polyphonic-grobs)
553     (list (make-property-unset 'graceSettings)
554           (make-grob-property-revert 'NoteColumn 'horizontal-shift)))))
555
556
557 (define-safe-public (context-spec-music m context #:optional id)
558   "Add \\context CONTEXT = ID to M."
559   (let ((cm (make-music 'ContextSpeccedMusic
560                         'element m
561                         'context-type context)))
562     (if (string? id)
563         (set! (ly:music-property cm 'context-id) id))
564     cm))
565
566 (define-public (descend-to-context m context)
567   "Like @code{context-spec-music}, but only descending."
568   (let ((cm (context-spec-music m context)))
569     (ly:music-set-property! cm 'descend-only #t)
570     cm))
571
572 (define-public (make-non-relative-music mus)
573   (make-music 'UnrelativableMusic
574               'element mus))
575
576 (define-public (make-apply-context func)
577   (make-music 'ApplyContext
578               'procedure func))
579
580 (define-public (make-sequential-music elts)
581   (make-music 'SequentialMusic
582               'elements elts))
583
584 (define-public (make-simultaneous-music elts)
585   (make-music 'SimultaneousMusic
586               'elements elts))
587
588 (define-safe-public (make-event-chord elts)
589   (make-music 'EventChord
590               'elements elts))
591
592 (define-public (make-skip-music dur)
593   (make-music 'SkipMusic
594               'duration dur))
595
596 (define-public (make-grace-music music)
597   (make-music 'GraceMusic
598               'element music))
599
600 ;;;;;;;;;;;;;;;;
601
602 ;; mmrest
603 (define-public (make-multi-measure-rest duration location)
604   (make-music 'MultiMeasureRestMusic
605               'origin location
606               'duration duration))
607
608 (define-public (make-property-set sym val)
609   (make-music 'PropertySet
610               'symbol sym
611               'value val))
612
613 (define-public (make-property-unset sym)
614   (make-music 'PropertyUnset
615               'symbol sym))
616
617 (define-safe-public (make-articulation name)
618   (make-music 'ArticulationEvent
619               'articulation-type name))
620
621 (define-public (make-lyric-event string duration)
622   (make-music 'LyricEvent
623               'duration duration
624               'text string))
625
626 (define-safe-public (make-span-event type span-dir)
627   (make-music type
628               'span-direction span-dir))
629
630 (define-public (override-head-style heads style)
631   "Override style for @var{heads} to @var{style}."
632   (make-sequential-music
633    (if (pair? heads)
634        (map (lambda (h)
635               (make-grob-property-override h 'style style))
636             heads)
637        (list (make-grob-property-override heads 'style style)))))
638
639 (define-public (revert-head-style heads)
640   "Revert style for @var{heads}."
641   (make-sequential-music
642    (if (pair? heads)
643        (map (lambda (h)
644               (make-grob-property-revert h 'style))
645             heads)
646        (list (make-grob-property-revert heads 'style)))))
647
648 (define-public (style-note-heads heads style music)
649   "Set @var{style} for all @var{heads} in @var{music}.  Works both
650 inside of and outside of chord construct."
651   ;; are we inside a <...>?
652   (if (eq? (ly:music-property music 'name) 'NoteEvent)
653       ;; yes -> use a tweak
654       (begin
655         (set! (ly:music-property music 'tweaks)
656               (acons 'style style (ly:music-property music 'tweaks)))
657         music)
658       ;; not in <...>, so use overrides
659       (make-sequential-music
660        (list
661         (override-head-style heads style)
662         music
663         (revert-head-style heads)))))
664
665 (define-public (set-mus-properties! m alist)
666   "Set all of @var{alist} as properties of @var{m}."
667   (if (pair? alist)
668       (begin
669         (set! (ly:music-property m (caar alist)) (cdar alist))
670         (set-mus-properties! m (cdr alist)))))
671
672 (define-public (music-separator? m)
673   "Is @var{m} a separator?"
674   (let ((ts (ly:music-property m 'types)))
675     (memq 'separator ts)))
676
677 ;;; expanding repeat chords
678 (define-public (copy-repeat-chord original-chord repeat-chord duration
679                                   event-types)
680   "Copies all events in @var{event-types} (be sure to include
681 @code{rhythmic-events}) from @var{original-chord} over to
682 @var{repeat-chord} with their articulations filtered as well.  Any
683 duration is replaced with the specified @var{duration}."
684   ;; First remove everything from event-types that can already be
685   ;; found in the repeated chord.  We don't need to look for
686   ;; articulations on individual events since they can't actually get
687   ;; into a repeat chord given its input syntax.
688
689   (define (keep-element? m)
690     (any (lambda (t) (music-is-of-type? m t))
691          event-types))
692   (define origin (ly:music-property repeat-chord 'origin #f))
693   (define (set-origin! l)
694     (if origin
695         (for-each (lambda (m) (set! (ly:music-property m 'origin) origin)) l))
696     l)
697
698   (for-each
699    (lambda (field)
700      (for-each (lambda (e)
701                  (for-each (lambda (x)
702                              (set! event-types (delq x event-types)))
703                            (ly:music-property e 'types)))
704                (ly:music-property repeat-chord field)))
705    '(elements articulations))
706
707   ;; now treat the elements
708   (set! (ly:music-property repeat-chord 'elements)
709         (let ((elts
710                (set-origin! (ly:music-deep-copy
711                              (filter keep-element?
712                                      (ly:music-property original-chord
713                                                         'elements))))))
714           (for-each
715            (lambda (m)
716              (let ((arts (ly:music-property m 'articulations)))
717                (if (pair? arts)
718                    (set! (ly:music-property m 'articulations)
719                          (set-origin! (filter! keep-element? arts))))
720                (if (ly:duration? (ly:music-property m 'duration))
721                    (set! (ly:music-property m 'duration) duration))))
722            elts)
723           (append! elts (ly:music-property repeat-chord 'elements))))
724   (let ((arts (filter keep-element?
725                       (ly:music-property original-chord
726                                          'articulations))))
727     (if (pair? arts)
728         (set! (ly:music-property repeat-chord 'articulations)
729               (append!
730                (set-origin! (ly:music-deep-copy arts))
731                (ly:music-property repeat-chord 'articulations)))))
732   repeat-chord)
733
734
735 (define-public (expand-repeat-chords! event-types music)
736   "Walks through @var{music} and fills repeated chords (notable by
737 having a duration in @code{duration}) with the notes from their
738 respective predecessor chord."
739   (let loop ((music music) (last-chord #f))
740     (if (music-is-of-type? music 'event-chord)
741         (let ((chord-repeat (ly:music-property music 'duration)))
742           (cond
743            ((not (ly:duration? chord-repeat))
744             (if (any (lambda (m) (ly:duration?
745                                   (ly:music-property m 'duration)))
746                      (ly:music-property music 'elements))
747                 music
748                 last-chord))
749            (last-chord
750             (set! (ly:music-property music 'duration) '())
751             (copy-repeat-chord last-chord music chord-repeat event-types))
752            (else
753             (ly:music-warning music (_ "Bad chord repetition"))
754             #f)))
755         (let ((elt (ly:music-property music 'element)))
756           (fold loop (if (ly:music? elt) (loop elt last-chord) last-chord)
757                 (ly:music-property music 'elements)))))
758   music)
759
760 ;;; This does _not_ copy any articulations.  Rationale: one main
761 ;;; incentive for pitch-repeating durations is after ties, such that
762 ;;; 4~2~8. can stand in for a 15/16 note in \partial 4 position.  In
763 ;;; this use case, any repeated articulations will be a nuisance.
764 ;;;
765 ;;; String assignments in TabStaff might seem like a worthwhile
766 ;;; exception, but they would be better tackled by the respective
767 ;;; engravers themselves (see issue 3662).
768 ;;;
769 ;;; Repeating chords as well seems problematic for things like
770 ;;; \score {
771 ;;;   <<
772 ;;;     \new Staff { c4 c c <c e> }
773 ;;;     \new RhythmicStaff { 4 4 4 4 }
774 ;;;   >>
775 ;;; }
776 ;;;
777 ;;; However, because of MIDI it is not advisable to use RhythmicStaff
778 ;;; without any initial pitch/drum-type.  For music functions taking
779 ;;; pure rhythms as an argument, the running of expand-repeat-notes!
780 ;;; at scorification time is irrelevant: at that point of time, the
781 ;;; music function has already run.
782
783 (define-public (expand-repeat-notes! music)
784   "Walks through @var{music} and gives pitchless notes (not having a
785 pitch in code{pitch} or a drum type in @code{drum-type}) the pitch(es)
786 from the predecessor note/chord if available."
787   (let ((last-pitch #f))
788     (map-some-music
789      (lambda (m)
790        (define (set-and-ret last)
791          (set! last-pitch last)
792          m)
793        (cond
794         ((music-is-of-type? m 'event-chord)
795          (set-and-ret m))
796         ((music-is-of-type? m 'note-event)
797          (cond
798           ((or (ly:music-property m 'pitch #f)
799                (ly:music-property m 'drum-type #f))
800            => set-and-ret)
801           ;; ok, naked rhythm.  Go through the various cases of
802           ;; last-pitch
803           ;; nothing available: just keep as-is
804           ((not last-pitch) m)
805           ((ly:pitch? last-pitch)
806            (set! (ly:music-property m 'pitch) last-pitch)
807            m)
808           ((symbol? last-pitch)
809            (set! (ly:music-property m 'drum-type) last-pitch)
810            m)
811           ;; Ok, this is the big bad one: the reference is a chord.
812           ;; For now, we use the repeat chord logic.  That's not
813           ;; really efficient as cleaning out all articulations is
814           ;; quite simpler than what copy-repeat-chord does.
815           (else
816            (copy-repeat-chord last-pitch
817                               (make-music 'EventChord
818                                           'elements
819                                           (ly:music-property m 'articulations)
820                                           'origin
821                                           (ly:music-property m 'origin))
822                               (ly:music-property m 'duration)
823                               '(rhythmic-event)))))
824         (else #f)))
825      music)))
826
827 ;;; splitting chords into voices.
828 (define (voicify-list lst number)
829   "Make a list of Musics.
830
831 voicify-list :: [ [Music ] ] -> number -> [Music]
832 LST is a list music-lists.
833
834 NUMBER is 0-base, i.e., Voice=1 (upstems) has number 0.
835 "
836   (if (null? lst)
837       '()
838       (cons (context-spec-music
839              (make-sequential-music
840               (list (make-voice-props-set number)
841                     (make-simultaneous-music (car lst))))
842              'Bottom  (number->string (1+ number)))
843             (voicify-list (cdr lst) (1+ number)))))
844
845 (define (voicify-chord ch)
846   "Split the parts of a chord into different Voices using separator"
847   (let ((es (ly:music-property ch 'elements)))
848     (set! (ly:music-property  ch 'elements)
849           (voicify-list (split-list-by-separator es music-separator?) 0))
850     ch))
851
852 (define-public (voicify-music m)
853   "Recursively split chords that are separated with @code{\\\\}."
854   (if (not (ly:music? m))
855       (ly:error (_ "music expected: ~S") m))
856   (let ((es (ly:music-property m 'elements))
857         (e (ly:music-property m 'element)))
858
859     (if (pair? es)
860         (set! (ly:music-property m 'elements) (map voicify-music es)))
861     (if (ly:music? e)
862         (set! (ly:music-property m 'element)  (voicify-music e)))
863     (if (and (equal? (ly:music-property m 'name) 'SimultaneousMusic)
864              (any music-separator? es))
865         (set! m (context-spec-music (voicify-chord m) 'Staff)))
866     m))
867
868 (define-public (empty-music)
869   (make-music 'Music))
870
871 ;; Make a function that checks score element for being of a specific type.
872 (define-public (make-type-checker symbol)
873   (lambda (elt)
874     (grob::has-interface elt symbol)))
875
876 (define-public ((outputproperty-compatibility func sym val) grob g-context ao-context)
877   (if (func grob)
878       (set! (ly:grob-property grob sym) val)))
879
880
881 (define-public ((set-output-property grob-name symbol val)  grob grob-c context)
882   "Usage example:
883 @code{\\applyoutput #(set-output-property 'Clef 'extra-offset '(0 . 1))}"
884   (let ((meta (ly:grob-property grob 'meta)))
885     (if (equal? (assoc-get 'name meta) grob-name)
886         (set! (ly:grob-property grob symbol) val))))
887
888
889 (define-public (skip->rest mus)
890   "Replace @var{mus} by @code{RestEvent} of the same duration if it is a
891 @code{SkipEvent}.  Useful for extracting parts from crowded scores."
892
893   (if  (memq (ly:music-property mus 'name) '(SkipEvent SkipMusic))
894        (make-music 'RestEvent 'duration (ly:music-property mus 'duration))
895        mus))
896
897
898 (define-public (music-has-type music type)
899   (memq type (ly:music-property music 'types)))
900
901 (define-public (music-clone music . music-properties)
902   "Clone @var{music} and set properties according to
903 @var{music-properties}, a list of alternating property symbols and
904 values:
905 @example\n(music-clone start-span 'span-direction STOP)
906 @end example
907 Only properties that are not overriden by @var{music-properties} are
908 actually fully cloned."
909   (let ((old-props (list-copy (ly:music-mutable-properties music)))
910         (new-props '())
911         (m (ly:make-music (ly:prob-immutable-properties music))))
912     (define (set-props mus-props)
913       (if (and (not (null? mus-props))
914                (not (null? (cdr mus-props))))
915           (begin
916             (set! old-props (assq-remove! old-props (car mus-props)))
917             (set! new-props
918                   (assq-set! new-props
919                              (car mus-props) (cadr mus-props)))
920             (set-props (cddr mus-props)))))
921     (set-props music-properties)
922     (for-each
923      (lambda (pair)
924        (set! (ly:music-property m (car pair))
925              (ly:music-deep-copy (cdr pair))))
926      old-props)
927     (for-each
928      (lambda (pair)
929        (set! (ly:music-property m (car pair)) (cdr pair)))
930      new-props)
931     m))
932
933 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
934 ;; warn for bare chords at start.
935
936 (define-public (ly:music-message music msg . rest)
937   (let ((ip (ly:music-property music 'origin)))
938     (if (ly:input-location? ip)
939         (apply ly:input-message ip msg rest)
940         (apply ly:message msg rest))))
941
942 (define-public (ly:music-warning music msg . rest)
943   (let ((ip (ly:music-property music 'origin)))
944     (if (ly:input-location? ip)
945         (apply ly:input-warning ip msg rest)
946         (apply ly:warning msg rest))))
947
948 (define-public (ly:event-warning event msg . rest)
949   (let ((ip (ly:event-property event 'origin)))
950     (if (ly:input-location? ip)
951         (apply ly:input-warning ip msg rest)
952         (apply ly:warning msg rest))))
953
954 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
955 ;;
956 ;; setting stuff for grace context.
957 ;;
958
959 (define (vector-extend v x)
960   "Make a new vector consisting of V, with X added to the end."
961   (let* ((n (vector-length v))
962          (nv (make-vector (+ n 1) '())))
963     (vector-move-left! v 0 n nv 0)
964     (vector-set! nv n x)
965     nv))
966
967 (define (vector-map f v)
968   "Map F over V.  This function returns nothing."
969   (do ((n (vector-length v))
970        (i 0 (+ i 1)))
971       ((>= i n))
972     (f (vector-ref v i))))
973
974 (define (vector-reverse-map f v)
975   "Map F over V, N to 0 order.  This function returns nothing."
976   (do ((i (- (vector-length v) 1) (- i 1)))
977       ((< i 0))
978     (f (vector-ref v i))))
979
980 (define-public (add-grace-property context-name grob sym val)
981   "Set @var{sym}=@var{val} for @var{grob} in @var{context-name}."
982   (define (set-prop context)
983     (let* ((where (or (ly:context-find context context-name) context))
984            (current (ly:context-property where 'graceSettings))
985            (new-settings (append current
986                                  (list (list context-name grob sym val)))))
987       (ly:context-set-property! where 'graceSettings new-settings)))
988   (make-apply-context set-prop))
989
990 (define-public (remove-grace-property context-name grob sym)
991   "Remove all @var{sym} for @var{grob} in @var{context-name}."
992   (define (sym-grob-context? property sym grob context-name)
993     (and (eq? (car property) context-name)
994          (eq? (cadr property) grob)
995          (eq? (caddr property) sym)))
996   (define (delete-prop context)
997     (let* ((where (or (ly:context-find context context-name) context))
998            (current (ly:context-property where 'graceSettings))
999            (prop-settings (filter
1000                            (lambda(x) (sym-grob-context? x sym grob context-name))
1001                            current))
1002            (new-settings current))
1003       (for-each (lambda(x)
1004                   (set! new-settings (delete x new-settings)))
1005                 prop-settings)
1006       (ly:context-set-property! where 'graceSettings new-settings)))
1007   (make-apply-context delete-prop))
1008
1009
1010 (defmacro-public def-grace-function (start stop . docstring)
1011   "Helper macro for defining grace music"
1012   `(define-music-function (parser location music) (ly:music?)
1013      ,@docstring
1014      (make-music 'GraceMusic
1015                  'origin location
1016                  'element (make-music 'SequentialMusic
1017                                       'elements (list (ly:music-deep-copy ,start)
1018                                                       music
1019                                                       (ly:music-deep-copy ,stop))))))
1020
1021 (defmacro-public define-syntax-function (type args signature . body)
1022   "Helper macro for `ly:make-music-function'.
1023 Syntax:
1024   (define-syntax-function result-type? (parser location arg1 arg2 ...) (arg1-type arg2-type ...)
1025     ...function body...)
1026
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.
1034
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.
1038
1039 @code{result-type?} can specify a default in the same manner as
1040 predicates, to be used in case of a type error in arguments or
1041 result."
1042
1043   (define (currying-lambda args doc-string? body)
1044     (if (and (pair? args)
1045              (pair? (car args)))
1046         (currying-lambda (car args) doc-string?
1047                          `((lambda ,(cdr args) ,@body)))
1048         (if doc-string?
1049             `(lambda ,args ,doc-string? ,@body)
1050             `(lambda ,args ,@body))))
1051
1052   (set! signature (map (lambda (pred)
1053                          (if (pair? pred)
1054                              `(cons ,(car pred)
1055                                     ,(and (pair? (cdr pred)) (cadr pred)))
1056                              pred))
1057                        (cons type signature)))
1058
1059   (let ((docstring
1060          (and (pair? body) (pair? (cdr body))
1061               (if (string? (car body))
1062                   (car body)
1063                   (and (pair? (car body))
1064                        (eq? '_i (caar body))
1065                        (pair? (cdar body))
1066                        (string? (cadar body))
1067                        (null? (cddar body))
1068                        (cadar body))))))
1069     ;; When the music function definition contains an i10n doc string,
1070     ;; (_i "doc string"), keep the literal string only
1071     `(ly:make-music-function
1072       (list ,@signature)
1073       ,(currying-lambda args docstring (if docstring (cdr body) body)))))
1074
1075 (defmacro-public define-music-function rest
1076   "Defining macro returning music functions.
1077 Syntax:
1078   (define-music-function (parser location arg1 arg2 ...) (arg1-type? arg2-type? ...)
1079     ...function body...)
1080
1081 argX-type can take one of the forms @code{predicate?} for mandatory
1082 arguments satisfying the predicate, @code{(predicate?)} for optional
1083 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
1084 value)}} for optional parameters with a specified default
1085 value (evaluated at definition time).  An optional parameter can be
1086 omitted in a call only when it can't get confused with a following
1087 parameter of different type.
1088
1089 Predicates with syntactical significance are @code{ly:pitch?},
1090 @code{ly:duration?}, @code{ly:music?}, @code{markup?}.  Other
1091 predicates require the parameter to be entered as Scheme expression.
1092
1093 Must return a music expression.  The @code{origin} is automatically
1094 set to the @code{location} parameter."
1095
1096   `(define-syntax-function (ly:music? (make-music 'Music 'void #t)) ,@rest))
1097
1098
1099 (defmacro-public define-scheme-function rest
1100   "Defining macro returning Scheme functions.
1101 Syntax:
1102   (define-scheme-function (parser location arg1 arg2 ...) (arg1-type? arg2-type? ...)
1103     ...function body...)
1104
1105 argX-type can take one of the forms @code{predicate?} for mandatory
1106 arguments satisfying the predicate, @code{(predicate?)} for optional
1107 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
1108 value)}} for optional parameters with a specified default
1109 value (evaluated at definition time).  An optional parameter can be
1110 omitted in a call only when it can't get confused with a following
1111 parameter of different type.
1112
1113 Predicates with syntactical significance are @code{ly:pitch?},
1114 @code{ly:duration?}, @code{ly:music?}, @code{markup?}.  Other
1115 predicates require the parameter to be entered as Scheme expression.
1116
1117 Can return arbitrary expressions.  If a music expression is returned,
1118 its @code{origin} is automatically set to the @code{location}
1119 parameter."
1120
1121   `(define-syntax-function scheme? ,@rest))
1122
1123 (defmacro-public define-void-function rest
1124   "This defines a Scheme function like @code{define-scheme-function} with
1125 void return value (i.e., what most Guile functions with `unspecified'
1126 value return).  Use this when defining functions for executing actions
1127 rather than returning values, to keep Lilypond from trying to interpret
1128 the return value."
1129   `(define-syntax-function (void? *unspecified*) ,@rest *unspecified*))
1130
1131 (defmacro-public define-event-function rest
1132   "Defining macro returning event functions.
1133 Syntax:
1134   (define-event-function (parser location arg1 arg2 ...) (arg1-type? arg2-type? ...)
1135     ...function body...)
1136
1137 argX-type can take one of the forms @code{predicate?} for mandatory
1138 arguments satisfying the predicate, @code{(predicate?)} for optional
1139 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
1140 value)}} for optional parameters with a specified default
1141 value (evaluated at definition time).  An optional parameter can be
1142 omitted in a call only when it can't get confused with a following
1143 parameter of different type.
1144
1145 Predicates with syntactical significance are @code{ly:pitch?},
1146 @code{ly:duration?}, @code{ly:music?}, @code{markup?}.  Other
1147 predicates require the parameter to be entered as Scheme expression.
1148
1149 Must return an event expression.  The @code{origin} is automatically
1150 set to the @code{location} parameter."
1151
1152   `(define-syntax-function (ly:event? (make-music 'Event 'void #t)) ,@rest))
1153
1154 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1155
1156 (define-public (cue-substitute quote-music)
1157   "Must happen after @code{quote-substitute}."
1158
1159   (if (vector? (ly:music-property quote-music 'quoted-events))
1160       (let* ((dir (ly:music-property quote-music 'quoted-voice-direction))
1161              (clef (ly:music-property quote-music 'quoted-music-clef #f))
1162              (main-voice (case dir ((1) 1) ((-1) 0) (else #f)))
1163              (cue-voice (and main-voice (- 1 main-voice)))
1164              (cue-type (ly:music-property quote-music 'quoted-context-type #f))
1165              (cue-id (ly:music-property quote-music 'quoted-context-id))
1166              (main-music (ly:music-property quote-music 'element))
1167              (return-value quote-music))
1168
1169         (if main-voice
1170             (set! (ly:music-property quote-music 'element)
1171                   (make-sequential-music
1172                    (list
1173                     (make-voice-props-override main-voice)
1174                     main-music
1175                     (make-voice-props-revert)))))
1176
1177         ;; if we have stem dirs, change both quoted and main music
1178         ;; to have opposite stems.
1179
1180         ;; cannot context-spec Quote-music, since context
1181         ;; for the quotes is determined in the iterator.
1182
1183         (make-sequential-music
1184          (delq! #f
1185                 (list
1186                  (and clef (make-cue-clef-set clef))
1187                  (and cue-type cue-voice
1188                       (context-spec-music
1189                        (make-voice-props-override cue-voice)
1190                        cue-type cue-id))
1191                  quote-music
1192                  (and cue-type cue-voice
1193                       (context-spec-music
1194                        (make-voice-props-revert)
1195                        cue-type cue-id))
1196                  (and clef (make-cue-clef-unset))))))
1197       quote-music))
1198
1199 (define-public ((quote-substitute quote-tab) music)
1200   (let* ((quoted-name (ly:music-property music 'quoted-music-name))
1201          (quoted-vector (and (string? quoted-name)
1202                              (hash-ref quote-tab quoted-name #f))))
1203
1204
1205     (if (string? quoted-name)
1206         (if (vector? quoted-vector)
1207             (begin
1208               (set! (ly:music-property music 'quoted-events) quoted-vector)
1209               (set! (ly:music-property music 'iterator-ctor)
1210                     ly:quote-iterator::constructor))
1211             (ly:music-warning music (ly:format (_ "cannot find quoted music: `~S'") quoted-name))))
1212     music))
1213
1214
1215 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1216 ;; switch it on here, so parsing and init isn't checked (too slow!)
1217 ;;
1218 ;; automatic music transformations.
1219
1220 (define (switch-on-debugging m)
1221   (if (defined? 'set-debug-cell-accesses!)
1222       (set-debug-cell-accesses! 15000))
1223   m)
1224
1225 (define (music-check-error music)
1226   (define found #f)
1227   (define (signal m)
1228     (if (and (ly:music? m)
1229              (eq? (ly:music-property m 'error-found) #t))
1230         (set! found #t)))
1231
1232   (for-each signal (ly:music-property music 'elements))
1233   (signal (ly:music-property music 'element))
1234
1235   (if found
1236       (set! (ly:music-property music 'error-found) #t))
1237   music)
1238
1239 (define (precompute-music-length music)
1240   (set! (ly:music-property music 'length)
1241         (ly:music-length music))
1242   music)
1243
1244 (define-public (make-duration-of-length moment)
1245   "Make duration of the given @code{moment} length."
1246   (ly:make-duration 0 0
1247                     (ly:moment-main-numerator moment)
1248                     (ly:moment-main-denominator moment)))
1249
1250 (define (make-skipped moment bool)
1251   "Depending on BOOL, set or unset skipTypesetting,
1252 then make SkipMusic of the given MOMENT length, and
1253 then revert skipTypesetting."
1254   (make-sequential-music
1255    (list
1256     (context-spec-music (make-property-set 'skipTypesetting bool)
1257                         'Score)
1258     (make-music 'SkipMusic 'duration
1259                 (make-duration-of-length moment))
1260     (context-spec-music (make-property-set 'skipTypesetting (not bool))
1261                         'Score))))
1262
1263 (define (skip-as-needed music parser)
1264   "Replace MUSIC by
1265  << {  \\set skipTypesetting = ##f
1266  LENGTHOF(\\showFirstLength)
1267  \\set skipTypesetting = ##t
1268  LENGTHOF(\\showLastLength) }
1269  MUSIC >>
1270  if appropriate.
1271
1272  When only showFirstLength is set,
1273  the 'length property of the music is
1274  overridden to speed up compiling."
1275   (let*
1276       ((show-last (ly:parser-lookup parser 'showLastLength))
1277        (show-first (ly:parser-lookup parser 'showFirstLength))
1278        (show-last-length (and (ly:music? show-last)
1279                               (ly:music-length show-last)))
1280        (show-first-length (and (ly:music? show-first)
1281                                (ly:music-length show-first)))
1282        (orig-length (ly:music-length music)))
1283
1284     ;;FIXME: if using either showFirst- or showLastLength,
1285     ;; make sure that skipBars is not set.
1286
1287     (cond
1288
1289      ;; both properties may be set.
1290      ((and show-first-length show-last-length)
1291       (let
1292           ((skip-length (ly:moment-sub orig-length show-last-length)))
1293         (make-simultaneous-music
1294          (list
1295           (make-sequential-music
1296            (list
1297             (make-skipped skip-length #t)
1298             ;; let's draw a separator between the beginning and the end
1299             (context-spec-music (make-property-set 'whichBar "||")
1300                                 'Timing)))
1301           (make-skipped show-first-length #f)
1302           music))))
1303
1304      ;; we may only want to print the last length
1305      (show-last-length
1306       (let
1307           ((skip-length (ly:moment-sub orig-length show-last-length)))
1308         (make-simultaneous-music
1309          (list
1310           (make-skipped skip-length #t)
1311           music))))
1312
1313      ;; we may only want to print the beginning; in this case
1314      ;; only the first length will be processed (much faster).
1315      (show-first-length
1316       ;; the first length must not exceed the original length.
1317       (if (ly:moment<? show-first-length orig-length)
1318           (set! (ly:music-property music 'length)
1319                 show-first-length))
1320       music)
1321
1322      (else music))))
1323
1324
1325 (define-public toplevel-music-functions
1326   (list
1327    (lambda (music parser) (expand-repeat-chords!
1328                            (cons 'rhythmic-event
1329                                  (ly:parser-lookup parser '$chord-repeat-events))
1330                            music))
1331    (lambda (music parser) (expand-repeat-notes! music))
1332    (lambda (music parser) (voicify-music music))
1333    (lambda (x parser) (music-map music-check-error x))
1334    (lambda (x parser) (music-map precompute-music-length x))
1335    (lambda (music parser)
1336
1337      (music-map (quote-substitute (ly:parser-lookup parser 'musicQuotes))  music))
1338
1339    ;; switch-on-debugging
1340    (lambda (x parser) (music-map cue-substitute x))
1341
1342    (lambda (x parser)
1343      (skip-as-needed x parser)
1344      )))
1345
1346 ;;;;;;;;;;
1347 ;;; general purpose music functions
1348
1349 (define (shift-octave pitch octave-shift)
1350   (_i "Add @var{octave-shift} to the octave of @var{pitch}.")
1351   (ly:make-pitch
1352    (+ (ly:pitch-octave pitch) octave-shift)
1353    (ly:pitch-notename pitch)
1354    (ly:pitch-alteration pitch)))
1355
1356
1357 ;;;;;;;;;;;;;;;;;
1358 ;; lyrics
1359
1360 (define (apply-durations lyric-music durations)
1361   (define (apply-duration music)
1362     (if (and (not (equal? (ly:music-length music) ZERO-MOMENT))
1363              (ly:duration?  (ly:music-property music 'duration)))
1364         (begin
1365           (set! (ly:music-property music 'duration) (car durations))
1366           (set! durations (cdr durations)))))
1367
1368   (music-map apply-duration lyric-music))
1369
1370
1371 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1372 ;; accidentals
1373
1374 (define (recent-enough? bar-number alteration-def laziness)
1375   (or (number? alteration-def)
1376       (equal? laziness #t)
1377       (<= bar-number (+ (cadr alteration-def) laziness))))
1378
1379 (define (accidental-invalid? alteration-def)
1380   "Checks an alteration entry for being invalid.
1381
1382 Non-key alterations are invalidated when tying into the next bar or
1383 when there is a clef change, since neither repetition nor cancellation
1384 can be omitted when the same note occurs again.
1385
1386 Returns @code{#f} or the reason for the invalidation, a symbol."
1387   (let* ((def (if (pair? alteration-def)
1388                   (car alteration-def)
1389                   alteration-def)))
1390     (and (symbol? def) def)))
1391
1392 (define (extract-alteration alteration-def)
1393   (cond ((number? alteration-def)
1394          alteration-def)
1395         ((pair? alteration-def)
1396          (car alteration-def))
1397         (else 0)))
1398
1399 (define (check-pitch-against-signature context pitch barnum laziness octaveness)
1400   "Checks the need for an accidental and a @q{restore} accidental against
1401 @code{localKeySignature}.  The @var{laziness} is the number of measures
1402 for which reminder accidentals are used (i.e., if @var{laziness} is zero,
1403 only cancel accidentals in the same measure; if @var{laziness} is three,
1404 we cancel accidentals up to three measures after they first appear.
1405 @var{octaveness} is either @code{'same-octave} or @code{'any-octave} and
1406 specifies whether accidentals should be canceled in different octaves."
1407   (let* ((ignore-octave (cond ((equal? octaveness 'any-octave) #t)
1408                               ((equal? octaveness 'same-octave) #f)
1409                               (else
1410                                (ly:warning (_ "Unknown octaveness type: ~S ") octaveness)
1411                                (ly:warning (_ "Defaulting to 'any-octave."))
1412                                #t)))
1413          (key-sig (ly:context-property context 'keySignature))
1414          (local-key-sig (ly:context-property context 'localKeySignature))
1415          (notename (ly:pitch-notename pitch))
1416          (octave (ly:pitch-octave pitch))
1417          (pitch-handle (cons octave notename))
1418          (need-restore #f)
1419          (need-accidental #f)
1420          (previous-alteration #f)
1421          (from-other-octaves #f)
1422          (from-same-octave (assoc-get pitch-handle local-key-sig))
1423          (from-key-sig (or (assoc-get notename local-key-sig)
1424
1425                            ;; If no key signature match is found from localKeySignature, we may have a custom
1426                            ;; type with octave-specific entries of the form ((octave . pitch) alteration)
1427                            ;; instead of (pitch . alteration).  Since this type cannot coexist with entries in
1428                            ;; localKeySignature, try extracting from keySignature instead.
1429                            (assoc-get pitch-handle key-sig))))
1430
1431     ;; loop through localKeySignature to search for a notename match from other octaves
1432     (let loop ((l local-key-sig))
1433       (if (pair? l)
1434           (let ((entry (car l)))
1435             (if (and (pair? (car entry))
1436                      (= (cdar entry) notename))
1437                 (set! from-other-octaves (cdr entry))
1438                 (loop (cdr l))))))
1439
1440     ;; find previous alteration-def for comparison with pitch
1441     (cond
1442      ;; from same octave?
1443      ((and (not ignore-octave)
1444            from-same-octave
1445            (recent-enough? barnum from-same-octave laziness))
1446       (set! previous-alteration from-same-octave))
1447
1448      ;; from any octave?
1449      ((and ignore-octave
1450            from-other-octaves
1451            (recent-enough? barnum from-other-octaves laziness))
1452       (set! previous-alteration from-other-octaves))
1453
1454      ;; not recent enough, extract from key signature/local key signature
1455      (from-key-sig
1456       (set! previous-alteration from-key-sig)))
1457
1458     (if (accidental-invalid? previous-alteration)
1459         (set! need-accidental #t)
1460
1461         (let* ((prev-alt (extract-alteration previous-alteration))
1462                (this-alt (ly:pitch-alteration pitch)))
1463
1464           (if (not (= this-alt prev-alt))
1465               (begin
1466                 (set! need-accidental #t)
1467                 (if (and (not (= this-alt 0))
1468                          (and (< (abs this-alt) (abs prev-alt))
1469                               (> (* prev-alt this-alt) 0)))
1470                     (set! need-restore #t))))))
1471
1472     (cons need-restore need-accidental)))
1473
1474 (define-public ((make-accidental-rule octaveness laziness) context pitch barnum measurepos)
1475   "Create an accidental rule that makes its decision based on the octave of
1476 the note and a laziness value.
1477
1478 @var{octaveness} is either @code{'same-octave} or @code{'any-octave} and
1479 defines whether the rule should respond to accidental changes in other
1480 octaves than the current.  @code{'same-octave} is the normal way to typeset
1481 accidentals -- an accidental is made if the alteration is different from the
1482 last active pitch in the same octave.  @code{'any-octave} looks at the last
1483 active pitch in any octave.
1484
1485 @var{laziness} states over how many bars an accidental should be remembered.
1486 @code{0}@tie{}is the default -- accidental lasts over 0@tie{}bar lines, that
1487 is, to the end of current measure.  A positive integer means that the
1488 accidental lasts over that many bar lines.  @w{@code{-1}} is `forget
1489 immediately', that is, only look at key signature.  @code{#t} is `forever'."
1490
1491   (check-pitch-against-signature context pitch barnum laziness octaveness))
1492
1493 (define (key-entry-notename entry)
1494   "Return the pitch of an @var{entry} in @code{localKeySignature}.
1495 The @samp{car} of the entry is either of the form @code{notename} or
1496 of the form @code{(octave . notename)}.  The latter form is used for special
1497 key signatures or to indicate an explicit accidental.
1498
1499 The @samp{cdr} of the entry is either a rational @code{alter} indicating
1500 a key signature alteration, or of the form
1501 @code{(alter . (barnum . measurepos))} indicating an alteration caused by
1502 an accidental in music."
1503   (if (pair? (car entry))
1504       (cdar entry)
1505       (car entry)))
1506
1507 (define (key-entry-octave entry)
1508   "Return the octave of an entry in @code{localKeySignature}
1509 or @code{#f} if the entry does not have an octave.
1510 See @code{key-entry-notename} for details."
1511   (and (pair? (car entry)) (caar entry)))
1512
1513 (define (key-entry-bar-number entry)
1514   "Return the bar number of an entry in @code{localKeySignature}
1515 or @code {#f} if the entry does not have a bar number.
1516 See @code{key-entry-notename} for details."
1517   (and (pair? (cdr entry)) (caddr entry)))
1518
1519 (define (key-entry-measure-position entry)
1520   "Return the measure position of an entry in @code{localKeySignature}
1521 or @code {#f} if the entry does not have a measure position.
1522 See @code{key-entry-notename} for details."
1523   (and (pair? (cdr entry)) (cdddr entry)))
1524
1525 (define (key-entry-alteration entry)
1526   "Return the alteration of an entry in localKeySignature.
1527
1528 For convenience, returns @code{0} if entry is @code{#f}."
1529   (if entry
1530       (if (number? (cdr entry))
1531           (cdr entry)
1532           (cadr entry))
1533       0))
1534
1535 (define-public (find-pitch-entry keysig pitch accept-global accept-local)
1536   "Return the first entry in @var{keysig} that matches @var{pitch}.
1537 @var{accept-global} states whether key signature entries should be included.
1538 @var{accept-local} states whether local accidentals should be included.
1539 If no matching entry is found, @var{#f} is returned."
1540   (and (pair? keysig)
1541        (let* ((entry (car keysig))
1542               (entryoct (key-entry-octave entry))
1543               (entrynn (key-entry-notename entry))
1544               (nn (ly:pitch-notename pitch)))
1545          (if (and (equal? nn entrynn)
1546                   (or (not entryoct)
1547                       (= entryoct (ly:pitch-octave pitch)))
1548                   (if (key-entry-bar-number entry)
1549                       accept-local
1550                       accept-global))
1551              entry
1552              (find-pitch-entry (cdr keysig) pitch accept-global accept-local)))))
1553
1554 (define-public (neo-modern-accidental-rule context pitch barnum measurepos)
1555   "An accidental rule that typesets an accidental if it differs from the
1556 key signature @emph{and} does not directly follow a note on the same
1557 staff line.  This rule should not be used alone because it does neither
1558 look at bar lines nor different accidentals at the same note name."
1559   (let* ((keysig (ly:context-property context 'localKeySignature))
1560          (entry (find-pitch-entry keysig pitch #t #t)))
1561     (if (not entry)
1562         (cons #f #f)
1563         (let* ((global-entry (find-pitch-entry keysig pitch #t #f))
1564                (key-acc (key-entry-alteration global-entry))
1565                (acc (ly:pitch-alteration pitch))
1566                (entrymp (key-entry-measure-position entry))
1567                (entrybn (key-entry-bar-number entry)))
1568           (cons #f (not (or (equal? acc key-acc)
1569                             (and (equal? entrybn barnum) (equal? entrymp measurepos)))))))))
1570
1571 (define-public (teaching-accidental-rule context pitch barnum measurepos)
1572   "An accidental rule that typesets a cautionary accidental if it is
1573 included in the key signature @emph{and} does not directly follow a note
1574 on the same staff line."
1575   (let* ((keysig (ly:context-property context 'localKeySignature))
1576          (entry (find-pitch-entry keysig pitch #t #t)))
1577     (if (not entry)
1578         (cons #f #f)
1579         (let* ((entrymp (key-entry-measure-position entry))
1580                (entrybn (key-entry-bar-number entry)))
1581           (cons #f (not (and (equal? entrybn barnum) (equal? entrymp measurepos))))))))
1582
1583 (define-public (set-accidentals-properties extra-natural
1584                                            auto-accs auto-cauts
1585                                            context)
1586   (context-spec-music
1587    (make-sequential-music
1588     (append (if (boolean? extra-natural)
1589                 (list (make-property-set 'extraNatural extra-natural))
1590                 '())
1591             (list (make-property-set 'autoAccidentals auto-accs)
1592                   (make-property-set 'autoCautionaries auto-cauts))))
1593    context))
1594
1595 (define-public (set-accidental-style style . rest)
1596   "Set accidental style to @var{style}.  Optionally take a context
1597 argument, e.g. @code{'Staff} or @code{'Voice}.  The context defaults
1598 to @code{Staff}, except for piano styles, which use @code{GrandStaff}
1599 as a context."
1600   (let ((context (if (pair? rest)
1601                      (car rest) 'Staff))
1602         (pcontext (if (pair? rest)
1603                       (car rest) 'GrandStaff)))
1604     (cond
1605      ;; accidentals as they were common in the 18th century.
1606      ((equal? style 'default)
1607       (set-accidentals-properties #t
1608                                   `(Staff ,(make-accidental-rule 'same-octave 0))
1609                                   '()
1610                                   context))
1611      ;; accidentals from one voice do NOT get canceled in other voices
1612      ((equal? style 'voice)
1613       (set-accidentals-properties #t
1614                                   `(Voice ,(make-accidental-rule 'same-octave 0))
1615                                   '()
1616                                   context))
1617      ;; accidentals as suggested by Kurt Stone, Music Notation in the 20th century.
1618      ;; This includes all the default accidentals, but accidentals also needs canceling
1619      ;; in other octaves and in the next measure.
1620      ((equal? style 'modern)
1621       (set-accidentals-properties #f
1622                                   `(Staff ,(make-accidental-rule 'same-octave 0)
1623                                           ,(make-accidental-rule 'any-octave 0)
1624                                           ,(make-accidental-rule 'same-octave 1))
1625                                   '()
1626                                   context))
1627      ;; the accidentals that Stone adds to the old standard as cautionaries
1628      ((equal? style 'modern-cautionary)
1629       (set-accidentals-properties #f
1630                                   `(Staff ,(make-accidental-rule 'same-octave 0))
1631                                   `(Staff ,(make-accidental-rule 'any-octave 0)
1632                                           ,(make-accidental-rule 'same-octave 1))
1633                                   context))
1634      ;; same as modern, but accidentals different from the key signature are always
1635      ;; typeset - unless they directly follow a note of the same pitch.
1636      ((equal? style 'neo-modern)
1637       (set-accidentals-properties #f
1638                                   `(Staff ,(make-accidental-rule 'same-octave 0)
1639                                           ,(make-accidental-rule 'any-octave 0)
1640                                           ,(make-accidental-rule 'same-octave 1)
1641                                           ,neo-modern-accidental-rule)
1642                                   '()
1643                                   context))
1644      ((equal? style 'neo-modern-cautionary)
1645       (set-accidentals-properties #f
1646                                   `(Staff ,(make-accidental-rule 'same-octave 0))
1647                                   `(Staff ,(make-accidental-rule 'any-octave 0)
1648                                           ,(make-accidental-rule 'same-octave 1)
1649                                           ,neo-modern-accidental-rule)
1650                                   context))
1651      ((equal? style 'neo-modern-voice)
1652       (set-accidentals-properties #f
1653                                   `(Voice ,(make-accidental-rule 'same-octave 0)
1654                                           ,(make-accidental-rule 'any-octave 0)
1655                                           ,(make-accidental-rule 'same-octave 1)
1656                                           ,neo-modern-accidental-rule
1657                                           Staff ,(make-accidental-rule 'same-octave 0)
1658                                           ,(make-accidental-rule 'any-octave 0)
1659                                           ,(make-accidental-rule 'same-octave 1)
1660                                           ,neo-modern-accidental-rule)
1661                                   '()
1662                                   context))
1663      ((equal? style 'neo-modern-voice-cautionary)
1664       (set-accidentals-properties #f
1665                                   `(Voice ,(make-accidental-rule 'same-octave 0))
1666                                   `(Voice ,(make-accidental-rule 'any-octave 0)
1667                                           ,(make-accidental-rule 'same-octave 1)
1668                                           ,neo-modern-accidental-rule
1669                                           Staff ,(make-accidental-rule 'same-octave 0)
1670                                           ,(make-accidental-rule 'any-octave 0)
1671                                           ,(make-accidental-rule 'same-octave 1)
1672                                           ,neo-modern-accidental-rule)
1673                                   context))
1674      ;; Accidentals as they were common in dodecaphonic music with no tonality.
1675      ;; Each note gets one accidental.
1676      ((equal? style 'dodecaphonic)
1677       (set-accidentals-properties #f
1678                                   `(Staff ,(lambda (c p bn mp) '(#f . #t)))
1679                                   '()
1680                                   context))
1681      ;; Multivoice accidentals to be read both by musicians playing one voice
1682      ;; and musicians playing all voices.
1683      ;; Accidentals are typeset for each voice, but they ARE canceled across voices.
1684      ((equal? style 'modern-voice)
1685       (set-accidentals-properties  #f
1686                                    `(Voice ,(make-accidental-rule 'same-octave 0)
1687                                            ,(make-accidental-rule 'any-octave 0)
1688                                            ,(make-accidental-rule 'same-octave 1)
1689                                            Staff ,(make-accidental-rule 'same-octave 0)
1690                                            ,(make-accidental-rule 'any-octave 0)
1691                                            ,(make-accidental-rule 'same-octave 1))
1692                                    '()
1693                                    context))
1694      ;; same as modernVoiceAccidental eccept that all special accidentals are typeset
1695      ;; as cautionaries
1696      ((equal? style 'modern-voice-cautionary)
1697       (set-accidentals-properties #f
1698                                   `(Voice ,(make-accidental-rule 'same-octave 0))
1699                                   `(Voice ,(make-accidental-rule 'any-octave 0)
1700                                           ,(make-accidental-rule 'same-octave 1)
1701                                           Staff ,(make-accidental-rule 'same-octave 0)
1702                                           ,(make-accidental-rule 'any-octave 0)
1703                                           ,(make-accidental-rule 'same-octave 1))
1704                                   context))
1705      ;; stone's suggestions for accidentals on grand staff.
1706      ;; Accidentals are canceled across the staves in the same grand staff as well
1707      ((equal? style 'piano)
1708       (set-accidentals-properties #f
1709                                   `(Staff ,(make-accidental-rule 'same-octave 0)
1710                                           ,(make-accidental-rule 'any-octave 0)
1711                                           ,(make-accidental-rule 'same-octave 1)
1712                                           GrandStaff
1713                                           ,(make-accidental-rule 'any-octave 0)
1714                                           ,(make-accidental-rule 'same-octave 1))
1715                                   '()
1716                                   pcontext))
1717      ((equal? style 'piano-cautionary)
1718       (set-accidentals-properties #f
1719                                   `(Staff ,(make-accidental-rule 'same-octave 0))
1720                                   `(Staff ,(make-accidental-rule 'any-octave 0)
1721                                           ,(make-accidental-rule 'same-octave 1)
1722                                           GrandStaff
1723                                           ,(make-accidental-rule 'any-octave 0)
1724                                           ,(make-accidental-rule 'same-octave 1))
1725                                   pcontext))
1726
1727      ;; same as modern, but cautionary accidentals are printed for all sharp or flat
1728      ;; tones specified by the key signature.
1729      ((equal? style 'teaching)
1730       (set-accidentals-properties #f
1731                                   `(Staff ,(make-accidental-rule 'same-octave 0))
1732                                   `(Staff ,(make-accidental-rule 'same-octave 1)
1733                                           ,teaching-accidental-rule)
1734                                   context))
1735
1736      ;; do not set localKeySignature when a note alterated differently from
1737      ;; localKeySignature is found.
1738      ;; Causes accidentals to be printed at every note instead of
1739      ;; remembered for the duration of a measure.
1740      ;; accidentals not being remembered, causing accidentals always to
1741      ;; be typeset relative to the time signature
1742      ((equal? style 'forget)
1743       (set-accidentals-properties '()
1744                                   `(Staff ,(make-accidental-rule 'same-octave -1))
1745                                   '()
1746                                   context))
1747      ;; Do not reset the key at the start of a measure.  Accidentals will be
1748      ;; printed only once and are in effect until overridden, possibly many
1749      ;; measures later.
1750      ((equal? style 'no-reset)
1751       (set-accidentals-properties '()
1752                                   `(Staff ,(make-accidental-rule 'same-octave #t))
1753                                   '()
1754                                   context))
1755      (else
1756       (ly:warning (_ "unknown accidental style: ~S") style)
1757       (make-sequential-music '())))))
1758
1759 (define-public (invalidate-alterations context)
1760   "Invalidate alterations in @var{context}.
1761
1762 Elements of @code{'localKeySignature} corresponding to local
1763 alterations of the key signature have the form
1764 @code{'((octave . notename) . (alter barnum . measurepos))}.
1765 Replace them with a version where @code{alter} is set to @code{'clef}
1766 to force a repetition of accidentals.
1767
1768 Entries that conform with the current key signature are not invalidated."
1769   (let* ((keysig (ly:context-property context 'keySignature)))
1770     (set! (ly:context-property context 'localKeySignature)
1771           (map-in-order
1772            (lambda (entry)
1773              (let* ((localalt (key-entry-alteration entry)))
1774                (if (or (accidental-invalid? localalt)
1775                        (not (key-entry-bar-number entry))
1776                        (= localalt
1777                           (key-entry-alteration
1778                            (find-pitch-entry
1779                             keysig
1780                             (ly:make-pitch (key-entry-octave entry)
1781                                            (key-entry-notename entry)
1782                                            0)
1783                             #t #t))))
1784                    entry
1785                    (cons (car entry) (cons 'clef (cddr entry))))))
1786            (ly:context-property context 'localKeySignature)))))
1787
1788 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1789
1790 (define-public (skip-of-length mus)
1791   "Create a skip of exactly the same length as @var{mus}."
1792   (let* ((skip
1793           (make-music
1794            'SkipEvent
1795            'duration (ly:make-duration 0 0))))
1796
1797     (make-event-chord (list (ly:music-compress skip (ly:music-length mus))))))
1798
1799 (define-public (mmrest-of-length mus)
1800   "Create a multi-measure rest of exactly the same length as @var{mus}."
1801
1802   (let* ((skip
1803           (make-multi-measure-rest
1804            (ly:make-duration 0 0) '())))
1805     (ly:music-compress skip (ly:music-length mus))
1806     skip))
1807
1808 (define-public (pitch-of-note event-chord)
1809   (let ((evs (filter (lambda (x)
1810                        (music-has-type x 'note-event))
1811                      (ly:music-property event-chord 'elements))))
1812
1813     (and (pair? evs)
1814          (ly:music-property (car evs) 'pitch))))
1815
1816 (define-public (duration-of-note event-chord)
1817   (cond
1818    ((pair? event-chord)
1819     (or (duration-of-note (car event-chord))
1820         (duration-of-note (cdr event-chord))))
1821    ((ly:music? event-chord)
1822     (let ((dur (ly:music-property event-chord 'duration)))
1823       (if (ly:duration? dur)
1824           dur
1825           (duration-of-note (ly:music-property event-chord 'elements)))))
1826    (else #f)))
1827
1828 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1829
1830 (define-public (map-some-music map? music)
1831   "Walk through @var{music}, transform all elements calling @var{map?}
1832 and only recurse if this returns @code{#f}.  @code{elements} or
1833 @code{articulations} that are not music expressions are discarded:
1834 this allows some amount of filtering.
1835
1836 @code{map-some-music} may overwrite the original @var{music}."
1837   (let loop ((music music))
1838     (or (map? music)
1839         (let ((elt (ly:music-property music 'element))
1840               (elts (ly:music-property music 'elements))
1841               (arts (ly:music-property music 'articulations)))
1842           (if (ly:music? elt)
1843               (set! (ly:music-property music 'element)
1844                     (loop elt)))
1845           (if (pair? elts)
1846               (set! (ly:music-property music 'elements)
1847                     (filter! ly:music? (map! loop elts))))
1848           (if (pair? arts)
1849               (set! (ly:music-property music 'articulations)
1850                     (filter! ly:music? (map! loop arts))))
1851           music))))
1852
1853 (define-public (for-some-music stop? music)
1854   "Walk through @var{music}, process all elements calling @var{stop?}
1855 and only recurse if this returns @code{#f}."
1856   (let loop ((music music))
1857     (if (not (stop? music))
1858         (let ((elt (ly:music-property music 'element)))
1859           (if (ly:music? elt)
1860               (loop elt))
1861           (for-each loop (ly:music-property music 'elements))
1862           (for-each loop (ly:music-property music 'articulations))))))
1863
1864 (define-public (fold-some-music pred? proc init music)
1865   "This works recursively on music like @code{fold} does on a list,
1866 calling @samp{(@var{pred?} music)} on every music element.  If
1867 @code{#f} is returned for an element, it is processed recursively
1868 with the same initial value of @samp{previous}, otherwise
1869 @samp{(@var{proc} music previous)} replaces @samp{previous}
1870 and no recursion happens.
1871 The top @var{music} is processed using @var{init} for @samp{previous}."
1872   (let loop ((music music) (previous init))
1873     (if (pred? music)
1874         (proc music previous)
1875         (fold loop
1876               (fold loop
1877                     (let ((elt (ly:music-property music 'element)))
1878                       (if (null? elt)
1879                           previous
1880                           (loop elt previous)))
1881                     (ly:music-property music 'elements))
1882               (ly:music-property music 'articulations)))))
1883
1884 (define-public (extract-music music pred?)
1885   "Return a flat list of all music matching @var{pred?} inside of
1886 @var{music}, not recursing into matches themselves."
1887   (reverse! (fold-some-music pred? cons '() music)))
1888
1889 (define-public (extract-named-music music music-name)
1890   "Return a flat list of all music named @var{music-name} (either a
1891 single event symbol or a list of alternatives) inside of @var{music},
1892 not recursing into matches themselves."
1893   (extract-music
1894    music
1895    (if (cheap-list? music-name)
1896        (lambda (m) (memq (ly:music-property m 'name) music-name))
1897        (lambda (m) (eq? (ly:music-property m 'name) music-name)))))
1898
1899 (define-public (extract-typed-music music type)
1900   "Return a flat list of all music with @var{type} (either a single
1901 type symbol or a list of alternatives) inside of @var{music}, not
1902 recursing into matches themselves."
1903   (extract-music
1904    music
1905    (if (cheap-list? type)
1906        (lambda (m)
1907          (any (lambda (t) (music-is-of-type? m t)) type))
1908        (lambda (m) (music-is-of-type? m type)))))
1909
1910 (define*-public (event-chord-wrap! music #:optional parser)
1911   "Wrap isolated rhythmic events and non-postevent events in
1912 @var{music} inside of an @code{EventChord}.  If the optional
1913 @var{parser} argument is given, chord repeats @samp{q} are expanded
1914 using the default settings.  Otherwise, you need to cater for them
1915 yourself."
1916   (map-some-music
1917    (lambda (m)
1918      (cond ((music-is-of-type? m 'event-chord)
1919             (if (pair? (ly:music-property m 'articulations))
1920                 (begin
1921                   (set! (ly:music-property m 'elements)
1922                         (append (ly:music-property m 'elements)
1923                                 (ly:music-property m 'articulations)))
1924                   (set! (ly:music-property m 'articulations) '())))
1925             m)
1926            ((music-is-of-type? m 'rhythmic-event)
1927             (let ((arts (ly:music-property m 'articulations)))
1928               (if (pair? arts)
1929                   (set! (ly:music-property m 'articulations) '()))
1930               (make-event-chord (cons m arts))))
1931            (else #f)))
1932    (if parser
1933        (expand-repeat-chords!
1934         (cons 'rhythmic-event
1935               (ly:parser-lookup parser '$chord-repeat-events))
1936         music)
1937        music)))
1938
1939 (define-public (event-chord-notes event-chord)
1940   "Return a list of all notes from @var{event-chord}."
1941   (filter
1942    (lambda (m) (eq? 'NoteEvent (ly:music-property m 'name)))
1943    (ly:music-property event-chord 'elements)))
1944
1945 (define-public (event-chord-pitches event-chord)
1946   "Return a list of all pitches from @var{event-chord}."
1947   (map (lambda (x) (ly:music-property x 'pitch))
1948        (event-chord-notes event-chord)))
1949
1950 (defmacro-public make-relative (pitches last-pitch music)
1951   "The list of pitch-carrying variables in @var{pitches} is used as a
1952 sequence for creating relativable music from @var{music}.
1953 The variables in @var{pitches} are, when considered inside of
1954 @code{\\relative}, all considered to be specifications to the preceding
1955 variable.  The first variable is relative to the preceding musical
1956 context, and @var{last-pitch} specifies the pitch passed as relative
1957 base onto the following musical context."
1958
1959   ;; pitch and music generator might be stored instead in music
1960   ;; properties, and it might make sense to create a music type of its
1961   ;; own for this kind of construct rather than using
1962   ;; RelativeOctaveMusic
1963   (define ((make-relative::to-relative-callback pitches p->m p->p) music pitch)
1964     (let* ((chord (make-event-chord
1965                    (map
1966                     (lambda (p)
1967                       (make-music 'NoteEvent
1968                                   'pitch p))
1969                     pitches)))
1970            (pitchout (begin
1971                        (ly:make-music-relative! chord pitch)
1972                        (event-chord-pitches chord))))
1973       (set! (ly:music-property music 'element)
1974             (apply p->m pitchout))
1975       (apply p->p pitchout)))
1976   `(make-music 'RelativeOctaveMusic
1977                'to-relative-callback
1978                (,make-relative::to-relative-callback
1979                 (list ,@pitches)
1980                 (lambda ,pitches ,music)
1981                 (lambda ,pitches ,last-pitch))
1982                'element ,music))
1983
1984 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1985 ;; The following functions are all associated with the crossStaff
1986 ;;  function
1987
1988 (define (close-enough? x y)
1989   "Values are close enough to ignore the difference"
1990   (< (abs (- x y)) 0.0001))
1991
1992 (define (extent-combine extents)
1993   "Combine a list of extents"
1994   (if (pair? (cdr extents))
1995       (interval-union (car extents) (extent-combine (cdr extents)))
1996       (car extents)))
1997
1998 (define ((stem-connectable? ref root) stem)
1999   "Check if the stem is connectable to the root"
2000   ;; The root is always connectable to itself
2001   (or (eq? root stem)
2002       (and
2003        ;; Horizontal positions of the stems must be almost the same
2004        (close-enough? (car (ly:grob-extent root ref X))
2005                       (car (ly:grob-extent stem ref X)))
2006        ;; The stem must be in the direction away from the root's notehead
2007        (positive? (* (ly:grob-property root 'direction)
2008                      (- (car (ly:grob-extent stem ref Y))
2009                         (car (ly:grob-extent root ref Y))))))))
2010
2011 (define (stem-span-stencil span)
2012   "Connect stems if we have at least one stem connectable to the root"
2013   (let* ((system (ly:grob-system span))
2014          (root (ly:grob-parent span X))
2015          (stems (filter (stem-connectable? system root)
2016                         (ly:grob-object span 'stems))))
2017     (if (<= 2 (length stems))
2018         (let* ((yextents (map (lambda (st)
2019                                 (ly:grob-extent st system Y)) stems))
2020                (yextent (extent-combine yextents))
2021                (layout (ly:grob-layout root))
2022                (blot (ly:output-def-lookup layout 'blot-diameter)))
2023           ;; Hide spanned stems
2024           (for-each (lambda (st)
2025                       (set! (ly:grob-property st 'stencil) #f))
2026                     stems)
2027           ;; Draw a nice looking stem with rounded corners
2028           (ly:round-filled-box (ly:grob-extent root root X) yextent blot))
2029         ;; Nothing to connect, don't draw the span
2030         #f)))
2031
2032 (define ((make-stem-span! stems trans) root)
2033   "Create a stem span as a child of the cross-staff stem (the root)"
2034   (let ((span (ly:engraver-make-grob trans 'Stem '())))
2035     (ly:grob-set-parent! span X root)
2036     (set! (ly:grob-object span 'stems) stems)
2037     ;; Suppress positioning, the stem code is confused by this weird stem
2038     (set! (ly:grob-property span 'X-offset) 0)
2039     (set! (ly:grob-property span 'stencil) stem-span-stencil)))
2040
2041 (define-public (cross-staff-connect stem)
2042   "Set cross-staff property of the stem to this function to connect it to
2043 other stems automatically"
2044   #t)
2045
2046 (define (stem-is-root? stem)
2047   "Check if automatic connecting of the stem was requested.  Stems connected
2048 to cross-staff beams are cross-staff, but they should not be connected to
2049 other stems just because of that."
2050   (eq? cross-staff-connect (ly:grob-property-data stem 'cross-staff)))
2051
2052 (define (make-stem-spans! ctx stems trans)
2053   "Create stem spans for cross-staff stems"
2054   ;; Cannot do extensive checks here, just make sure there are at least
2055   ;; two stems at this musical moment
2056   (if (<= 2 (length stems))
2057       (let ((roots (filter stem-is-root? stems)))
2058         (for-each (make-stem-span! stems trans) roots))))
2059
2060 (define-public (Span_stem_engraver ctx)
2061   "Connect cross-staff stems to the stems above in the system"
2062   (let ((stems '()))
2063     (make-engraver
2064      ;; Record all stems for the given moment
2065      (acknowledgers
2066       ((stem-interface trans grob source)
2067        (set! stems (cons grob stems))))
2068      ;; Process stems and reset the stem list to empty
2069      ((process-acknowledged trans)
2070       (make-stem-spans! ctx stems trans)
2071       (set! stems '())))))
2072
2073 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2074 ;; The following is used by the alterBroken function.
2075
2076 (define-public ((value-for-spanner-piece arg) grob)
2077   "Associate a piece of broken spanner @var{grob} with an element
2078 of list @var{arg}."
2079   (let* ((orig (ly:grob-original grob))
2080          (siblings (ly:spanner-broken-into orig)))
2081
2082     (define (helper sibs arg)
2083       (if (null? arg)
2084           arg
2085           (if (eq? (car sibs) grob)
2086               (car arg)
2087               (helper (cdr sibs) (cdr arg)))))
2088
2089     (if (>= (length siblings) 2)
2090         (helper siblings arg)
2091         (car arg))))
2092
2093 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2094 ;; measure counter
2095
2096 (define (measure-counter-stencil grob)
2097   "Print a number for a measure count.  The number is centered using
2098 the extents of @code{BreakAlignment} grobs associated with
2099 @code{NonMusicalPaperColumn} grobs.  In the case of an unbroken measure, these
2100 columns are the left and right bounds of a @code{MeasureCounter} spanner.
2101 Broken measures are numbered in parentheses."
2102   (let* ((orig (ly:grob-original grob))
2103          (siblings (ly:spanner-broken-into orig)) ; have we been split?
2104          (bounds (ly:grob-array->list (ly:grob-object grob 'columns)))
2105          (refp (ly:grob-system grob))
2106          ;; we use the first and/or last NonMusicalPaperColumn grob(s) of
2107          ;; a system in the event that a MeasureCounter spanner is broken
2108          (all-cols (ly:grob-array->list (ly:grob-object refp 'columns)))
2109          (all-cols
2110           (filter
2111            (lambda (col) (eq? #t (ly:grob-property col 'non-musical)))
2112            all-cols))
2113          (left-bound
2114           (if (or (null? siblings) ; spanner is unbroken
2115                   (eq? grob (car siblings))) ; or the first piece
2116               (car bounds)
2117               (car all-cols)))
2118          (right-bound
2119           (if (or (null? siblings)
2120                   (eq? grob (car (reverse siblings))))
2121               (car (reverse bounds))
2122               (car (reverse all-cols))))
2123          (elts-L (ly:grob-array->list (ly:grob-object left-bound 'elements)))
2124          (elts-R (ly:grob-array->list (ly:grob-object right-bound 'elements)))
2125          (break-alignment-L
2126           (filter
2127            (lambda (elt) (grob::has-interface elt 'break-alignment-interface))
2128            elts-L))
2129          (break-alignment-R
2130           (filter
2131            (lambda (elt) (grob::has-interface elt 'break-alignment-interface))
2132            elts-R))
2133          (break-alignment-L-ext (ly:grob-extent (car break-alignment-L) refp X))
2134          (break-alignment-R-ext (ly:grob-extent (car break-alignment-R) refp X))
2135          (num (markup (number->string (ly:grob-property grob 'count-from))))
2136          (num
2137           (if (or (null? siblings)
2138                   (eq? grob (car siblings)))
2139               num
2140               (make-parenthesize-markup num)))
2141          (num (grob-interpret-markup grob num))
2142          (num (ly:stencil-aligned-to num X (ly:grob-property grob 'self-alignment-X)))
2143          (num
2144           (ly:stencil-translate-axis
2145            num
2146            (+ (interval-length break-alignment-L-ext)
2147               (* 0.5
2148                  (- (car break-alignment-R-ext)
2149                     (cdr break-alignment-L-ext))))
2150            X)))
2151     num))
2152
2153 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2154 ;; The following are used by the \offset function
2155
2156 (define (find-value-to-offset prop self alist)
2157   "Return the first value of the property @var{prop} in the property
2158 alist @var{alist} -- after having found @var{self}.  If @var{self} is
2159 not found, return the first value of @var{prop}."
2160   (let ((segment (member (cons prop self) alist)))
2161     (if (not segment)
2162         (assoc-get prop alist)
2163         (assoc-get prop (cdr segment)))))
2164
2165 (define (offset-multiple-types arg offsets)
2166   "Displace @var{arg} by @var{offsets} if @var{arg} is a number, a
2167 number pair, or a list of number pairs.  If @var{offsets} is an empty
2168 list or if there is a type-mismatch, @var{arg} will be returned."
2169   (cond
2170     ((and (number? arg) (number? offsets))
2171      (+ arg offsets))
2172     ((and (number-pair? arg)
2173           (or (number? offsets)
2174               (number-pair? offsets)))
2175      (coord-translate arg offsets))
2176     ((and (number-pair-list? arg) (number-pair-list? offsets))
2177      (map
2178        (lambda (x y) (coord-translate x y))
2179        arg offsets))
2180     (else arg)))
2181
2182 (define-public (offsetter property offsets)
2183   "Apply @var{offsets} to the default values of @var{property} of @var{grob}.
2184 Offsets are restricted to immutable properties and values of type @code{number},
2185 @code{number-pair}, or @code{number-pair-list}."
2186   (define (self grob)
2187     (let* ((immutable (ly:grob-basic-properties grob))
2188            ; We need to search the basic-properties alist for our property to
2189            ; obtain values to offset.  Our search is complicated by the fact that
2190            ; calling the music function `offset' as an override conses a pair to
2191            ; the head of the alist.  This pair must be discounted.  The closure it
2192            ; contains is named `self' so it can be easily recognized.  If `offset'
2193            ; is called as a tweak, the basic-property alist is unaffected.
2194            (target (find-value-to-offset property self immutable))
2195            ; if target is a procedure, we need to apply it to our grob to calculate
2196            ; values to offset.
2197            (vals
2198              (if (procedure? target)
2199                  (target grob)
2200                  target))
2201            (can-type-be-offset?
2202              (or (number? vals)
2203                  (number-pair? vals)
2204                  (number-pair-list? vals))))
2205
2206       (if can-type-be-offset?
2207           ; '(+inf.0 . -inf.0) would offset to itself.  This will be confusing to a
2208           ; user unaware of the default value of the property, so issue a warning.
2209           (if (equal? empty-interval vals)
2210               (ly:warning "default '~a of ~a is ~a and can't be offset"
2211                 property grob vals)
2212               (let* ((orig (ly:grob-original grob))
2213                      (siblings
2214                        (if (ly:spanner? grob)
2215                            (ly:spanner-broken-into orig)
2216                            '()))
2217                      (total-found (length siblings))
2218                      ; Since there is some flexibility in input syntax,
2219                      ; structure of `offsets' is normalized.
2220                      (offsets
2221                        (if (or (not (pair? offsets))
2222                                (number-pair? offsets)
2223                                (and (number-pair-list? offsets)
2224                                     (number-pair-list? vals)))
2225                            (list offsets)
2226                            offsets)))
2227
2228                 (define (helper sibs offs)
2229                   ; apply offsets to the siblings of broken spanners
2230                   (if (pair? offs)
2231                       (if (eq? (car sibs) grob)
2232                           (offset-multiple-types vals (car offs))
2233                           (helper (cdr sibs) (cdr offs)))
2234                       vals))
2235
2236                 (if (>= total-found 2)
2237                     (helper siblings offsets)
2238                     (offset-multiple-types vals (car offsets)))))
2239
2240               (begin
2241                 (ly:warning "the property '~a of ~a cannot be offset" property grob)
2242                 vals))))
2243     ; return the closure named `self'
2244     self)