]> git.donarmstrong.com Git - lilypond.git/blob - scm/music-functions.scm
Reformat some files to let emacs do its work correctly.
[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            (apply 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            ,@(apply 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-safe-public (make-voice-props-set n)
507   (make-sequential-music
508    (append
509     (map (lambda (x) (make-grob-property-set x 'direction
510                                                   (if (odd? n) -1 1)))
511          direction-polyphonic-grobs)
512     (list
513      (make-property-set 'graceSettings
514                         ;; TODO: take this from voicedGraceSettings or similar.
515                         '((Voice Stem font-size -3)
516                           (Voice Flag font-size -3)
517                           (Voice NoteHead font-size -3)
518                           (Voice TabNoteHead font-size -4)
519                           (Voice Dots font-size -3)
520                           (Voice Stem length-fraction 0.8)
521                           (Voice Stem no-stem-extend #t)
522                           (Voice Beam beam-thickness 0.384)
523                           (Voice Beam length-fraction 0.8)
524                           (Voice Accidental font-size -4)
525                           (Voice AccidentalCautionary font-size -4)
526                           (Voice Script font-size -3)
527                           (Voice Fingering font-size -8)
528                           (Voice StringNumber font-size -8)))
529
530      (make-grob-property-set 'NoteColumn 'horizontal-shift (quotient n 2))))))
531
532
533 (define-safe-public (make-voice-props-override n)
534   (make-sequential-music
535    (append
536     (map (lambda (x) (make-grob-property-override x 'direction
537                                                   (if (odd? n) -1 1)))
538          direction-polyphonic-grobs)
539     (list
540      (make-property-set 'graceSettings
541                         ;; TODO: take this from voicedGraceSettings or similar.
542                         '((Voice Stem font-size -3)
543                           (Voice Flag font-size -3)
544                           (Voice NoteHead font-size -3)
545                           (Voice TabNoteHead font-size -4)
546                           (Voice Dots font-size -3)
547                           (Voice Stem length-fraction 0.8)
548                           (Voice Stem no-stem-extend #t)
549                           (Voice Beam beam-thickness 0.384)
550                           (Voice Beam length-fraction 0.8)
551                           (Voice Accidental font-size -4)
552                           (Voice AccidentalCautionary font-size -4)
553                           (Voice Script font-size -3)
554                           (Voice Fingering font-size -8)
555                           (Voice StringNumber font-size -8)))
556
557      (make-grob-property-override 'NoteColumn 'horizontal-shift (quotient n 2))
558      (make-grob-property-override 'MultiMeasureRest 'staff-position (if (odd? n) -4 4))))))
559
560 (define-safe-public (make-voice-props-revert)
561   (make-sequential-music
562    (append
563     (map (lambda (x) (make-grob-property-revert x 'direction))
564          direction-polyphonic-grobs)
565     (list (make-property-unset 'graceSettings)
566           (make-grob-property-revert 'NoteColumn 'horizontal-shift)
567           (make-grob-property-revert 'MultiMeasureRest 'staff-position)))))
568
569
570 (define-safe-public (context-spec-music m context #:optional id)
571   "Add \\context CONTEXT = ID to M."
572   (let ((cm (make-music 'ContextSpeccedMusic
573                         'element m
574                         'context-type context)))
575     (if (string? id)
576         (set! (ly:music-property cm 'context-id) id))
577     cm))
578
579 (define-public (descend-to-context m context)
580   "Like @code{context-spec-music}, but only descending."
581   (let ((cm (context-spec-music m context)))
582     (ly:music-set-property! cm 'descend-only #t)
583     cm))
584
585 (define-public (make-non-relative-music mus)
586   (make-music 'UnrelativableMusic
587               'element mus))
588
589 (define-public (make-apply-context func)
590   (make-music 'ApplyContext
591               'procedure func))
592
593 (define-public (make-sequential-music elts)
594   (make-music 'SequentialMusic
595               'elements elts))
596
597 (define-public (make-simultaneous-music elts)
598   (make-music 'SimultaneousMusic
599               'elements elts))
600
601 (define-safe-public (make-event-chord elts)
602   (make-music 'EventChord
603               'elements elts))
604
605 (define-public (make-skip-music dur)
606   (make-music 'SkipMusic
607               'duration dur))
608
609 (define-public (make-grace-music music)
610   (make-music 'GraceMusic
611               'element music))
612
613 ;;;;;;;;;;;;;;;;
614
615 ;; mmrest
616 (define-public (make-multi-measure-rest duration location)
617   (make-music 'MultiMeasureRestMusic
618               'origin location
619               'duration duration))
620
621 (define-public (make-property-set sym val)
622   (make-music 'PropertySet
623               'symbol sym
624               'value val))
625
626 (define-public (make-property-unset sym)
627   (make-music 'PropertyUnset
628               'symbol sym))
629
630 (define-safe-public (make-articulation name)
631   (make-music 'ArticulationEvent
632               'articulation-type name))
633
634 (define-public (make-lyric-event string duration)
635   (make-music 'LyricEvent
636               'duration duration
637               'text string))
638
639 (define-safe-public (make-span-event type span-dir)
640   (make-music type
641               'span-direction span-dir))
642
643 (define-public (override-head-style heads style)
644   "Override style for @var{heads} to @var{style}."
645   (make-sequential-music
646     (if (pair? heads)
647         (map (lambda (h)
648               (make-grob-property-override h 'style style))
649          heads)
650         (list (make-grob-property-override heads 'style style)))))
651
652 (define-public (revert-head-style heads)
653   "Revert style for @var{heads}."
654   (make-sequential-music
655     (if (pair? heads)
656         (map (lambda (h)
657               (make-grob-property-revert h 'style))
658          heads)
659         (list (make-grob-property-revert heads 'style)))))
660
661 (define-public (style-note-heads heads style music)
662  "Set @var{style} for all @var{heads} in @var{music}.  Works both
663 inside of and outside of chord construct."
664   ;; are we inside a <...>?
665   (if (eq? (ly:music-property music 'name) 'NoteEvent)
666       ;; yes -> use a tweak
667       (begin
668         (set! (ly:music-property music 'tweaks)
669               (acons 'style style (ly:music-property music 'tweaks)))
670         music)
671       ;; not in <...>, so use overrides
672       (make-sequential-music
673         (list
674           (override-head-style heads style)
675           music
676           (revert-head-style heads)))))
677
678  (define-public (set-mus-properties! m alist)
679   "Set all of @var{alist} as properties of @var{m}."
680   (if (pair? alist)
681       (begin
682         (set! (ly:music-property m (caar alist)) (cdar alist))
683         (set-mus-properties! m (cdr alist)))))
684
685 (define-public (music-separator? m)
686   "Is @var{m} a separator?"
687   (let ((ts (ly:music-property m 'types)))
688     (memq 'separator ts)))
689
690 ;;; expanding repeat chords
691 (define-public (copy-repeat-chord original-chord repeat-chord duration
692                                   event-types)
693   "Copies all events in @var{event-types} (be sure to include
694 @code{rhythmic-events}) from @var{original-chord} over to
695 @var{repeat-chord} with their articulations filtered as well.  Any
696 duration is replaced with the specified @var{duration}."
697   ;; First remove everything from event-types that can already be
698   ;; found in the repeated chord.  We don't need to look for
699   ;; articulations on individual events since they can't actually get
700   ;; into a repeat chord given its input syntax.
701
702   (define (keep-element? m)
703     (any (lambda (t) (music-is-of-type? m t))
704          event-types))
705   (define origin (ly:music-property repeat-chord 'origin #f))
706   (define (set-origin! l)
707     (if origin
708         (for-each (lambda (m) (set! (ly:music-property m 'origin) origin)) l))
709     l)
710
711   (for-each
712    (lambda (field)
713      (for-each (lambda (e)
714                  (for-each (lambda (x)
715                              (set! event-types (delq x event-types)))
716                            (ly:music-property e 'types)))
717                (ly:music-property repeat-chord field)))
718    '(elements articulations))
719
720   ;; now treat the elements
721   (set! (ly:music-property repeat-chord 'elements)
722         (let ((elts
723                (set-origin! (ly:music-deep-copy
724                              (filter keep-element?
725                                      (ly:music-property original-chord
726                                                         'elements))))))
727           (for-each
728            (lambda (m)
729              (let ((arts (ly:music-property m 'articulations)))
730                (if (pair? arts)
731                    (set! (ly:music-property m 'articulations)
732                          (set-origin! (filter! keep-element? arts))))
733                (if (ly:duration? (ly:music-property m 'duration))
734                    (set! (ly:music-property m 'duration) duration))))
735            elts)
736           (append! elts (ly:music-property repeat-chord 'elements))))
737   (let ((arts (filter keep-element?
738                       (ly:music-property original-chord
739                                          'articulations))))
740     (if (pair? arts)
741         (set! (ly:music-property repeat-chord 'articulations)
742               (append!
743                (set-origin! (ly:music-deep-copy arts))
744                (ly:music-property repeat-chord 'articulations))))))
745
746
747 (define-public (expand-repeat-chords! event-types music)
748   "Walks through @var{music} and fills repeated chords (notable by
749 having a duration in @code{duration}) with the notes from their
750 respective predecessor chord."
751   (let loop ((music music) (last-chord #f))
752     (if (music-is-of-type? music 'event-chord)
753         (let ((chord-repeat (ly:music-property music 'duration)))
754           (cond
755            ((not (ly:duration? chord-repeat))
756             (if (any (lambda (m) (ly:duration?
757                                   (ly:music-property m 'duration)))
758                      (ly:music-property music 'elements))
759                 music
760                 last-chord))
761            (last-chord
762             (set! (ly:music-property music 'duration) '())
763             (copy-repeat-chord last-chord music chord-repeat event-types)
764             music)
765            (else
766             (ly:music-warning music (_ "Bad chord repetition"))
767             #f)))
768         (let ((elt (ly:music-property music 'element)))
769           (fold loop (if (ly:music? elt) (loop elt last-chord) last-chord)
770                 (ly:music-property music 'elements)))))
771   music)
772
773 ;;; splitting chords into voices.
774 (define (voicify-list lst number)
775   "Make a list of Musics.
776
777 voicify-list :: [ [Music ] ] -> number -> [Music]
778 LST is a list music-lists.
779
780 NUMBER is 0-base, i.e., Voice=1 (upstems) has number 0.
781 "
782   (if (null? lst)
783       '()
784       (cons (context-spec-music
785              (make-sequential-music
786               (list (make-voice-props-set number)
787                     (make-simultaneous-music (car lst))))
788              'Bottom  (number->string (1+ number)))
789             (voicify-list (cdr lst) (1+ number)))))
790
791 (define (voicify-chord ch)
792   "Split the parts of a chord into different Voices using separator"
793   (let ((es (ly:music-property ch 'elements)))
794     (set! (ly:music-property  ch 'elements)
795           (voicify-list (split-list-by-separator es music-separator?) 0))
796     ch))
797
798 (define-public (voicify-music m)
799   "Recursively split chords that are separated with @code{\\\\}."
800   (if (not (ly:music? m))
801       (ly:error (_ "music expected: ~S") m))
802   (let ((es (ly:music-property m 'elements))
803         (e (ly:music-property m 'element)))
804
805     (if (pair? es)
806         (set! (ly:music-property m 'elements) (map voicify-music es)))
807     (if (ly:music? e)
808         (set! (ly:music-property m 'element)  (voicify-music e)))
809     (if (and (equal? (ly:music-property m 'name) 'SimultaneousMusic)
810              (any music-separator? es))
811         (set! m (context-spec-music (voicify-chord m) 'Staff)))
812     m))
813
814 (define-public (empty-music)
815   (make-music 'Music))
816
817 ;; Make a function that checks score element for being of a specific type.
818 (define-public (make-type-checker symbol)
819   (lambda (elt)
820     (grob::has-interface elt symbol)))
821
822 (define-public ((outputproperty-compatibility func sym val) grob g-context ao-context)
823   (if (func grob)
824       (set! (ly:grob-property grob sym) val)))
825
826
827 (define-public ((set-output-property grob-name symbol val)  grob grob-c context)
828   "Usage example:
829 @code{\\applyoutput #(set-output-property 'Clef 'extra-offset '(0 . 1))}"
830   (let ((meta (ly:grob-property grob 'meta)))
831     (if (equal? (assoc-get 'name meta) grob-name)
832         (set! (ly:grob-property grob symbol) val))))
833
834
835 (define-public (skip->rest mus)
836   "Replace @var{mus} by @code{RestEvent} of the same duration if it is a
837 @code{SkipEvent}.  Useful for extracting parts from crowded scores."
838
839   (if  (memq (ly:music-property mus 'name) '(SkipEvent SkipMusic))
840    (make-music 'RestEvent 'duration (ly:music-property mus 'duration))
841    mus))
842
843
844 (define-public (music-has-type music type)
845   (memq type (ly:music-property music 'types)))
846
847 (define-public (music-clone music . music-properties)
848   "Clone @var{music} and set properties according to
849 @var{music-properties}, a list of alternating property symbols and
850 values:
851 @example\n(music-clone start-span 'span-direction STOP)
852 @end example
853 Only properties that are not overriden by @var{music-properties} are
854 actually fully cloned."
855   (let ((old-props (list-copy (ly:music-mutable-properties music)))
856         (new-props '())
857         (m (ly:make-music (ly:prob-immutable-properties music))))
858     (define (set-props mus-props)
859       (if (and (not (null? mus-props))
860                (not (null? (cdr mus-props))))
861           (begin
862             (set! old-props (assq-remove! old-props (car mus-props)))
863             (set! new-props
864                   (assq-set! new-props
865                              (car mus-props) (cadr mus-props)))
866             (set-props (cddr mus-props)))))
867     (set-props music-properties)
868     (for-each
869      (lambda (pair)
870        (set! (ly:music-property m (car pair))
871              (ly:music-deep-copy (cdr pair))))
872      old-props)
873     (for-each
874      (lambda (pair)
875        (set! (ly:music-property m (car pair)) (cdr pair)))
876      new-props)
877     m))
878
879 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
880 ;; warn for bare chords at start.
881
882 (define-public (ly:music-message music msg)
883   (let ((ip (ly:music-property music 'origin)))
884     (if (ly:input-location? ip)
885         (ly:input-message ip msg)
886         (ly:message msg))))
887
888 (define-public (ly:music-warning music msg)
889   (let ((ip (ly:music-property music 'origin)))
890     (if (ly:input-location? ip)
891         (ly:input-warning ip msg)
892         (ly:warning msg))))
893
894 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
895 ;;
896 ;; setting stuff for grace context.
897 ;;
898
899 (define (vector-extend v x)
900   "Make a new vector consisting of V, with X added to the end."
901   (let* ((n (vector-length v))
902          (nv (make-vector (+ n 1) '())))
903     (vector-move-left! v 0 n nv 0)
904     (vector-set! nv n x)
905     nv))
906
907 (define (vector-map f v)
908   "Map F over V.  This function returns nothing."
909   (do ((n (vector-length v))
910        (i 0 (+ i 1)))
911       ((>= i n))
912     (f (vector-ref v i))))
913
914 (define (vector-reverse-map f v)
915   "Map F over V, N to 0 order.  This function returns nothing."
916   (do ((i (- (vector-length v) 1) (- i 1)))
917       ((< i 0))
918     (f (vector-ref v i))))
919
920 (define-public (add-grace-property context-name grob sym val)
921   "Set @var{sym}=@var{val} for @var{grob} in @var{context-name}."
922   (define (set-prop context)
923     (let* ((where (ly:context-property-where-defined context 'graceSettings))
924            (current (ly:context-property where 'graceSettings))
925            (new-settings (append current
926                                  (list (list context-name grob sym val)))))
927       (ly:context-set-property! where 'graceSettings new-settings)))
928   (context-spec-music (make-apply-context set-prop) 'Voice))
929
930 (define-public (remove-grace-property context-name grob sym)
931   "Remove all @var{sym} for @var{grob} in @var{context-name}."
932   (define (sym-grob-context? property sym grob context-name)
933     (and (eq? (car property) context-name)
934          (eq? (cadr property) grob)
935          (eq? (caddr property) sym)))
936   (define (delete-prop context)
937     (let* ((where (ly:context-property-where-defined context 'graceSettings))
938            (current (ly:context-property where 'graceSettings))
939            (prop-settings (filter
940                             (lambda(x) (sym-grob-context? x sym grob context-name))
941                             current))
942            (new-settings current))
943       (for-each (lambda(x)
944                  (set! new-settings (delete x new-settings)))
945                prop-settings)
946       (ly:context-set-property! where 'graceSettings new-settings)))
947   (context-spec-music (make-apply-context delete-prop) 'Voice))
948
949
950
951 (defmacro-public def-grace-function (start stop . docstring)
952   "Helper macro for defining grace music"
953   `(define-music-function (parser location music) (ly:music?)
954      ,@docstring
955      (make-music 'GraceMusic
956                  'origin location
957                  'element (make-music 'SequentialMusic
958                                       'elements (list (ly:music-deep-copy ,start)
959                                                       music
960                                                       (ly:music-deep-copy ,stop))))))
961
962 (defmacro-public define-syntax-function (type args signature . body)
963   "Helper macro for `ly:make-music-function'.
964 Syntax:
965   (define-syntax-function result-type? (parser location arg1 arg2 ...) (arg1-type arg2-type ...)
966     ...function body...)
967
968 argX-type can take one of the forms @code{predicate?} for mandatory
969 arguments satisfying the predicate, @code{(predicate?)} for optional
970 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
971 value)}} for optional parameters with a specified default
972 value (evaluated at definition time).  An optional parameter can be
973 omitted in a call only when it can't get confused with a following
974 parameter of different type.
975
976 Predicates with syntactical significance are @code{ly:pitch?},
977 @code{ly:duration?}, @code{ly:music?}, @code{markup?}.  Other
978 predicates require the parameter to be entered as Scheme expression.
979
980 @code{result-type?} can specify a default in the same manner as
981 predicates, to be used in case of a type error in arguments or
982 result."
983
984   (set! signature (map (lambda (pred)
985                          (if (pair? pred)
986                              `(cons ,(car pred)
987                                     ,(and (pair? (cdr pred)) (cadr pred)))
988                              pred))
989                        (cons type signature)))
990   (if (and (pair? body) (pair? (car body)) (eqv? '_i (caar body)))
991       ;; When the music function definition contains a i10n doc string,
992       ;; (_i "doc string"), keep the literal string only
993       (let ((docstring (cadar body))
994             (body (cdr body)))
995         `(ly:make-music-function (list ,@signature)
996                                  (lambda ,args
997                                    ,docstring
998                                    ,@body)))
999       `(ly:make-music-function (list ,@signature)
1000                                (lambda ,args
1001                                  ,@body))))
1002
1003 (defmacro-public define-music-function rest
1004   "Defining macro returning music functions.
1005 Syntax:
1006   (define-music-function (parser location arg1 arg2 ...) (arg1-type? arg2-type? ...)
1007     ...function body...)
1008
1009 argX-type can take one of the forms @code{predicate?} for mandatory
1010 arguments satisfying the predicate, @code{(predicate?)} for optional
1011 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
1012 value)}} for optional parameters with a specified default
1013 value (evaluated at definition time).  An optional parameter can be
1014 omitted in a call only when it can't get confused with a following
1015 parameter of different type.
1016
1017 Predicates with syntactical significance are @code{ly:pitch?},
1018 @code{ly:duration?}, @code{ly:music?}, @code{markup?}.  Other
1019 predicates require the parameter to be entered as Scheme expression.
1020
1021 Must return a music expression.  The @code{origin} is automatically
1022 set to the @code{location} parameter."
1023
1024   `(define-syntax-function (ly:music? (make-music 'Music 'void #t)) ,@rest))
1025
1026
1027 (defmacro-public define-scheme-function rest
1028   "Defining macro returning Scheme functions.
1029 Syntax:
1030   (define-scheme-function (parser location arg1 arg2 ...) (arg1-type? arg2-type? ...)
1031     ...function body...)
1032
1033 argX-type can take one of the forms @code{predicate?} for mandatory
1034 arguments satisfying the predicate, @code{(predicate?)} for optional
1035 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
1036 value)}} for optional parameters with a specified default
1037 value (evaluated at definition time).  An optional parameter can be
1038 omitted in a call only when it can't get confused with a following
1039 parameter of different type.
1040
1041 Predicates with syntactical significance are @code{ly:pitch?},
1042 @code{ly:duration?}, @code{ly:music?}, @code{markup?}.  Other
1043 predicates require the parameter to be entered as Scheme expression.
1044
1045 Can return arbitrary expressions.  If a music expression is returned,
1046 its @code{origin} is automatically set to the @code{location}
1047 parameter."
1048
1049   `(define-syntax-function scheme? ,@rest))
1050
1051 (defmacro-public define-void-function rest
1052   "This defines a Scheme function like @code{define-scheme-function} with
1053 void return value (i.e., what most Guile functions with `unspecified'
1054 value return).  Use this when defining functions for executing actions
1055 rather than returning values, to keep Lilypond from trying to interpret
1056 the return value."
1057   `(define-syntax-function (void? *unspecified*) ,@rest *unspecified*))
1058
1059 (defmacro-public define-event-function rest
1060   "Defining macro returning event functions.
1061 Syntax:
1062   (define-event-function (parser location arg1 arg2 ...) (arg1-type? arg2-type? ...)
1063     ...function body...)
1064
1065 argX-type can take one of the forms @code{predicate?} for mandatory
1066 arguments satisfying the predicate, @code{(predicate?)} for optional
1067 parameters of that type defaulting to @code{#f}, @code{@w{(predicate?
1068 value)}} for optional parameters with a specified default
1069 value (evaluated at definition time).  An optional parameter can be
1070 omitted in a call only when it can't get confused with a following
1071 parameter of different type.
1072
1073 Predicates with syntactical significance are @code{ly:pitch?},
1074 @code{ly:duration?}, @code{ly:music?}, @code{markup?}.  Other
1075 predicates require the parameter to be entered as Scheme expression.
1076
1077 Must return an event expression.  The @code{origin} is automatically
1078 set to the @code{location} parameter."
1079
1080   `(define-syntax-function (ly:event? (make-music 'Event 'void #t)) ,@rest))
1081
1082 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1083
1084 (define-public (cue-substitute quote-music)
1085   "Must happen after @code{quote-substitute}."
1086
1087   (if (vector? (ly:music-property quote-music 'quoted-events))
1088       (let* ((dir (ly:music-property quote-music 'quoted-voice-direction))
1089              (clef (ly:music-property quote-music 'quoted-music-clef #f))
1090              (main-voice (case dir ((1) 1) ((-1) 0) (else #f)))
1091              (cue-voice (and main-voice (- 1 main-voice)))
1092              (main-music (ly:music-property quote-music 'element))
1093              (return-value quote-music))
1094
1095         (if main-voice
1096             (set! (ly:music-property quote-music 'element)
1097                   (make-sequential-music
1098                    (list
1099                     (make-voice-props-override main-voice)
1100                     main-music
1101                     (make-voice-props-revert)))))
1102
1103         ;; if we have stem dirs, change both quoted and main music
1104         ;; to have opposite stems.
1105
1106         ;; cannot context-spec Quote-music, since context
1107         ;; for the quotes is determined in the iterator.
1108
1109         (make-sequential-music
1110          (delq! #f
1111                 (list
1112                  (and clef (make-cue-clef-set clef))
1113
1114                  ;; Need to establish CueVoice context even in #CENTER case
1115                  (context-spec-music
1116                   (if cue-voice
1117                       (make-voice-props-override cue-voice)
1118                       (make-music 'Music))
1119                   'CueVoice "cue")
1120                  quote-music
1121                  (and cue-voice
1122                       (context-spec-music
1123                        (make-voice-props-revert) 'CueVoice "cue"))
1124                  (and clef (make-cue-clef-unset))))))
1125       quote-music))
1126
1127 (define-public ((quote-substitute quote-tab) music)
1128   (let* ((quoted-name (ly:music-property music 'quoted-music-name))
1129          (quoted-vector (and (string? quoted-name)
1130                              (hash-ref quote-tab quoted-name #f))))
1131
1132
1133     (if (string? quoted-name)
1134         (if (vector? quoted-vector)
1135             (begin
1136               (set! (ly:music-property music 'quoted-events) quoted-vector)
1137               (set! (ly:music-property music 'iterator-ctor)
1138                     ly:quote-iterator::constructor))
1139             (ly:music-warning music (ly:format (_ "cannot find quoted music: `~S'") quoted-name))))
1140     music))
1141
1142
1143 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1144 ;; switch it on here, so parsing and init isn't checked (too slow!)
1145 ;;
1146 ;; automatic music transformations.
1147
1148 (define (switch-on-debugging m)
1149   (if (defined? 'set-debug-cell-accesses!)
1150       (set-debug-cell-accesses! 15000))
1151   m)
1152
1153 (define (music-check-error music)
1154   (define found #f)
1155   (define (signal m)
1156     (if (and (ly:music? m)
1157              (eq? (ly:music-property m 'error-found) #t))
1158         (set! found #t)))
1159
1160   (for-each signal (ly:music-property music 'elements))
1161   (signal (ly:music-property music 'element))
1162
1163   (if found
1164       (set! (ly:music-property music 'error-found) #t))
1165   music)
1166
1167 (define (precompute-music-length music)
1168   (set! (ly:music-property music 'length)
1169         (ly:music-length music))
1170   music)
1171
1172 (define-public (make-duration-of-length moment)
1173  "Make duration of the given @code{moment} length."
1174  (ly:make-duration 0 0
1175   (ly:moment-main-numerator moment)
1176   (ly:moment-main-denominator moment)))
1177
1178 (define (make-skipped moment bool)
1179  "Depending on BOOL, set or unset skipTypesetting,
1180 then make SkipMusic of the given MOMENT length, and
1181 then revert skipTypesetting."
1182  (make-sequential-music
1183   (list
1184    (context-spec-music (make-property-set 'skipTypesetting bool)
1185     'Score)
1186    (make-music 'SkipMusic 'duration
1187     (make-duration-of-length moment))
1188    (context-spec-music (make-property-set 'skipTypesetting (not bool))
1189     'Score))))
1190
1191 (define (skip-as-needed music parser)
1192   "Replace MUSIC by
1193  << {  \\set skipTypesetting = ##f
1194  LENGTHOF(\\showFirstLength)
1195  \\set skipTypesetting = ##t
1196  LENGTHOF(\\showLastLength) }
1197  MUSIC >>
1198  if appropriate.
1199
1200  When only showFirstLength is set,
1201  the 'length property of the music is
1202  overridden to speed up compiling."
1203   (let*
1204       ((show-last (ly:parser-lookup parser 'showLastLength))
1205        (show-first (ly:parser-lookup parser 'showFirstLength))
1206        (show-last-length (and (ly:music? show-last)
1207                               (ly:music-length show-last)))
1208        (show-first-length (and (ly:music? show-first)
1209                                (ly:music-length show-first)))
1210        (orig-length (ly:music-length music)))
1211
1212     ;;FIXME: if using either showFirst- or showLastLength,
1213     ;; make sure that skipBars is not set.
1214
1215     (cond
1216
1217      ;; both properties may be set.
1218      ((and show-first-length show-last-length)
1219       (let
1220           ((skip-length (ly:moment-sub orig-length show-last-length)))
1221         (make-simultaneous-music
1222          (list
1223           (make-sequential-music
1224            (list
1225             (make-skipped skip-length #t)
1226             ;; let's draw a separator between the beginning and the end
1227             (context-spec-music (make-property-set 'whichBar "||")
1228                                 'Timing)))
1229           (make-skipped show-first-length #f)
1230           music))))
1231
1232      ;; we may only want to print the last length
1233      (show-last-length
1234       (let
1235           ((skip-length (ly:moment-sub orig-length show-last-length)))
1236         (make-simultaneous-music
1237          (list
1238           (make-skipped skip-length #t)
1239           music))))
1240
1241      ;; we may only want to print the beginning; in this case
1242      ;; only the first length will be processed (much faster).
1243      (show-first-length
1244       ;; the first length must not exceed the original length.
1245       (if (ly:moment<? show-first-length orig-length)
1246           (set! (ly:music-property music 'length)
1247                 show-first-length))
1248       music)
1249
1250      (else music))))
1251
1252
1253 (define-public toplevel-music-functions
1254   (list
1255    (lambda (music parser) (expand-repeat-chords!
1256                            (cons 'rhythmic-event
1257                                  (ly:parser-lookup parser '$chord-repeat-events))
1258                            music))
1259    (lambda (music parser) (voicify-music music))
1260    (lambda (x parser) (music-map music-check-error x))
1261    (lambda (x parser) (music-map precompute-music-length x))
1262    (lambda (music parser)
1263
1264      (music-map (quote-substitute (ly:parser-lookup parser 'musicQuotes))  music))
1265
1266    ;; switch-on-debugging
1267    (lambda (x parser) (music-map cue-substitute x))
1268
1269    (lambda (x parser)
1270      (skip-as-needed x parser)
1271    )))
1272
1273 ;;;;;;;;;;
1274 ;;; general purpose music functions
1275
1276 (define (shift-octave pitch octave-shift)
1277   (_i "Add @var{octave-shift} to the octave of @var{pitch}.")
1278   (ly:make-pitch
1279      (+ (ly:pitch-octave pitch) octave-shift)
1280      (ly:pitch-notename pitch)
1281      (ly:pitch-alteration pitch)))
1282
1283
1284 ;;;;;;;;;;;;;;;;;
1285 ;; lyrics
1286
1287 (define (apply-durations lyric-music durations)
1288   (define (apply-duration music)
1289     (if (and (not (equal? (ly:music-length music) ZERO-MOMENT))
1290              (ly:duration?  (ly:music-property music 'duration)))
1291         (begin
1292           (set! (ly:music-property music 'duration) (car durations))
1293           (set! durations (cdr durations)))))
1294
1295   (music-map apply-duration lyric-music))
1296
1297
1298 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1299 ;; accidentals
1300
1301 (define (recent-enough? bar-number alteration-def laziness)
1302   (or (number? alteration-def)
1303       (equal? laziness #t)
1304       (<= bar-number (+ (cadr alteration-def) laziness))))
1305
1306 (define (accidental-invalid? alteration-def)
1307   "Checks an alteration entry for being invalid.
1308
1309 Non-key alterations are invalidated when tying into the next bar or
1310 when there is a clef change, since neither repetition nor cancellation
1311 can be omitted when the same note occurs again.
1312
1313 Returns @code{#f} or the reason for the invalidation, a symbol."
1314   (let* ((def (if (pair? alteration-def)
1315                   (car alteration-def)
1316                   alteration-def)))
1317     (and (symbol? def) def)))
1318
1319 (define (extract-alteration alteration-def)
1320   (cond ((number? alteration-def)
1321          alteration-def)
1322         ((pair? alteration-def)
1323          (car alteration-def))
1324         (else 0)))
1325
1326 (define (check-pitch-against-signature context pitch barnum laziness octaveness)
1327   "Checks the need for an accidental and a @q{restore} accidental against
1328 @code{localKeySignature}.  The @var{laziness} is the number of measures
1329 for which reminder accidentals are used (i.e., if @var{laziness} is zero,
1330 only cancel accidentals in the same measure; if @var{laziness} is three,
1331 we cancel accidentals up to three measures after they first appear.
1332 @var{octaveness} is either @code{'same-octave} or @code{'any-octave} and
1333 specifies whether accidentals should be canceled in different octaves."
1334   (let* ((ignore-octave (cond ((equal? octaveness 'any-octave) #t)
1335                               ((equal? octaveness 'same-octave) #f)
1336                               (else
1337                                (ly:warning (_ "Unknown octaveness type: ~S ") octaveness)
1338                                (ly:warning (_ "Defaulting to 'any-octave."))
1339                                #t)))
1340          (key-sig (ly:context-property context 'keySignature))
1341          (local-key-sig (ly:context-property context 'localKeySignature))
1342          (notename (ly:pitch-notename pitch))
1343          (octave (ly:pitch-octave pitch))
1344          (pitch-handle (cons octave notename))
1345          (need-restore #f)
1346          (need-accidental #f)
1347          (previous-alteration #f)
1348          (from-other-octaves #f)
1349          (from-same-octave (assoc-get pitch-handle local-key-sig))
1350          (from-key-sig (or (assoc-get notename local-key-sig)
1351
1352     ;; If no key signature match is found from localKeySignature, we may have a custom
1353     ;; type with octave-specific entries of the form ((octave . pitch) alteration)
1354     ;; instead of (pitch . alteration).  Since this type cannot coexist with entries in
1355     ;; localKeySignature, try extracting from keySignature instead.
1356                            (assoc-get pitch-handle key-sig))))
1357
1358     ;; loop through localKeySignature to search for a notename match from other octaves
1359     (let loop ((l local-key-sig))
1360       (if (pair? l)
1361           (let ((entry (car l)))
1362             (if (and (pair? (car entry))
1363                      (= (cdar entry) notename))
1364                 (set! from-other-octaves (cdr entry))
1365                 (loop (cdr l))))))
1366
1367     ;; find previous alteration-def for comparison with pitch
1368     (cond
1369      ;; from same octave?
1370      ((and (not ignore-octave)
1371            from-same-octave
1372            (recent-enough? barnum from-same-octave laziness))
1373       (set! previous-alteration from-same-octave))
1374
1375      ;; from any octave?
1376      ((and ignore-octave
1377            from-other-octaves
1378            (recent-enough? barnum from-other-octaves laziness))
1379       (set! previous-alteration from-other-octaves))
1380
1381      ;; not recent enough, extract from key signature/local key signature
1382      (from-key-sig
1383       (set! previous-alteration from-key-sig)))
1384
1385     (if (accidental-invalid? previous-alteration)
1386         (set! need-accidental #t)
1387
1388         (let* ((prev-alt (extract-alteration previous-alteration))
1389                (this-alt (ly:pitch-alteration pitch)))
1390
1391           (if (not (= this-alt prev-alt))
1392               (begin
1393                 (set! need-accidental #t)
1394                 (if (and (not (= this-alt 0))
1395                          (and (< (abs this-alt) (abs prev-alt))
1396                              (> (* prev-alt this-alt) 0)))
1397                     (set! need-restore #t))))))
1398
1399     (cons need-restore need-accidental)))
1400
1401 (define-public ((make-accidental-rule octaveness laziness) context pitch barnum measurepos)
1402   "Create an accidental rule that makes its decision based on the octave of
1403 the note and a laziness value.
1404
1405 @var{octaveness} is either @code{'same-octave} or @code{'any-octave} and
1406 defines whether the rule should respond to accidental changes in other
1407 octaves than the current.  @code{'same-octave} is the normal way to typeset
1408 accidentals -- an accidental is made if the alteration is different from the
1409 last active pitch in the same octave.  @code{'any-octave} looks at the last
1410 active pitch in any octave.
1411
1412 @var{laziness} states over how many bars an accidental should be remembered.
1413 @code{0}@tie{}is the default -- accidental lasts over 0@tie{}bar lines, that
1414 is, to the end of current measure.  A positive integer means that the
1415 accidental lasts over that many bar lines.  @w{@code{-1}} is `forget
1416 immediately', that is, only look at key signature.  @code{#t} is `forever'."
1417
1418   (check-pitch-against-signature context pitch barnum laziness octaveness))
1419
1420 (define (key-entry-notename entry)
1421   "Return the pitch of an @var{entry} in @code{localKeySignature}.
1422 The @samp{car} of the entry is either of the form @code{notename} or
1423 of the form @code{(octave . notename)}.  The latter form is used for special
1424 key signatures or to indicate an explicit accidental.
1425
1426 The @samp{cdr} of the entry is either a rational @code{alter} indicating
1427 a key signature alteration, or of the form
1428 @code{(alter . (barnum . measurepos))} indicating an alteration caused by
1429 an accidental in music."
1430   (if (pair? (car entry))
1431       (cdar entry)
1432       (car entry)))
1433
1434 (define (key-entry-octave entry)
1435   "Return the octave of an entry in @code{localKeySignature}
1436 or @code{#f} if the entry does not have an octave.
1437 See @code{key-entry-notename} for details."
1438   (and (pair? (car entry)) (caar entry)))
1439
1440 (define (key-entry-bar-number entry)
1441   "Return the bar number of an entry in @code{localKeySignature}
1442 or @code {#f} if the entry does not have a bar number.
1443 See @code{key-entry-notename} for details."
1444   (and (pair? (cdr entry)) (caddr entry)))
1445
1446 (define (key-entry-measure-position entry)
1447   "Return the measure position of an entry in @code{localKeySignature}
1448 or @code {#f} if the entry does not have a measure position.
1449 See @code{key-entry-notename} for details."
1450   (and (pair? (cdr entry)) (cdddr entry)))
1451
1452 (define (key-entry-alteration entry)
1453   "Return the alteration of an entry in localKeySignature.
1454
1455 For convenience, returns @code{0} if entry is @code{#f}."
1456   (if entry
1457       (if (number? (cdr entry))
1458           (cdr entry)
1459           (cadr entry))
1460       0))
1461
1462 (define-public (find-pitch-entry keysig pitch accept-global accept-local)
1463   "Return the first entry in @var{keysig} that matches @var{pitch}.
1464 @var{accept-global} states whether key signature entries should be included.
1465 @var{accept-local} states whether local accidentals should be included.
1466 If no matching entry is found, @var{#f} is returned."
1467   (and (pair? keysig)
1468        (let* ((entry (car keysig))
1469               (entryoct (key-entry-octave entry))
1470               (entrynn (key-entry-notename entry))
1471               (nn (ly:pitch-notename pitch)))
1472          (if (and (equal? nn entrynn)
1473                   (or (not entryoct)
1474                       (= entryoct (ly:pitch-octave pitch)))
1475                   (if (key-entry-bar-number entry)
1476                       accept-local
1477                       accept-global))
1478              entry
1479              (find-pitch-entry (cdr keysig) pitch accept-global accept-local)))))
1480
1481 (define-public (neo-modern-accidental-rule context pitch barnum measurepos)
1482   "An accidental rule that typesets an accidental if it differs from the
1483 key signature @emph{and} does not directly follow a note on the same
1484 staff line.  This rule should not be used alone because it does neither
1485 look at bar lines nor different accidentals at the same note name."
1486   (let* ((keysig (ly:context-property context 'localKeySignature))
1487          (entry (find-pitch-entry keysig pitch #t #t)))
1488     (if (not entry)
1489         (cons #f #f)
1490         (let* ((global-entry (find-pitch-entry keysig pitch #t #f))
1491                (key-acc (key-entry-alteration global-entry))
1492                (acc (ly:pitch-alteration pitch))
1493                (entrymp (key-entry-measure-position entry))
1494                (entrybn (key-entry-bar-number entry)))
1495           (cons #f (not (or (equal? acc key-acc)
1496                             (and (equal? entrybn barnum) (equal? entrymp measurepos)))))))))
1497
1498 (define-public (teaching-accidental-rule context pitch barnum measurepos)
1499   "An accidental rule that typesets a cautionary accidental if it is
1500 included in the key signature @emph{and} does not directly follow a note
1501 on the same staff line."
1502   (let* ((keysig (ly:context-property context 'localKeySignature))
1503          (entry (find-pitch-entry keysig pitch #t #t)))
1504     (if (not entry)
1505         (cons #f #f)
1506         (let* ((entrymp (key-entry-measure-position entry))
1507                (entrybn (key-entry-bar-number entry)))
1508           (cons #f (not (and (equal? entrybn barnum) (equal? entrymp measurepos))))))))
1509
1510 (define-public (set-accidentals-properties extra-natural
1511                                            auto-accs auto-cauts
1512                                            context)
1513   (context-spec-music
1514    (make-sequential-music
1515     (append (if (boolean? extra-natural)
1516                 (list (make-property-set 'extraNatural extra-natural))
1517                 '())
1518             (list (make-property-set 'autoAccidentals auto-accs)
1519                   (make-property-set 'autoCautionaries auto-cauts))))
1520    context))
1521
1522 (define-public (set-accidental-style style . rest)
1523   "Set accidental style to @var{style}.  Optionally take a context
1524 argument, e.g. @code{'Staff} or @code{'Voice}.  The context defaults
1525 to @code{Staff}, except for piano styles, which use @code{GrandStaff}
1526 as a context."
1527   (let ((context (if (pair? rest)
1528                      (car rest) 'Staff))
1529         (pcontext (if (pair? rest)
1530                       (car rest) 'GrandStaff)))
1531     (cond
1532       ;; accidentals as they were common in the 18th century.
1533       ((equal? style 'default)
1534        (set-accidentals-properties #t
1535                                    `(Staff ,(make-accidental-rule 'same-octave 0))
1536                                    '()
1537                                    context))
1538       ;; accidentals from one voice do NOT get canceled in other voices
1539       ((equal? style 'voice)
1540        (set-accidentals-properties #t
1541                                    `(Voice ,(make-accidental-rule 'same-octave 0))
1542                                    '()
1543                                    context))
1544       ;; accidentals as suggested by Kurt Stone, Music Notation in the 20th century.
1545       ;; This includes all the default accidentals, but accidentals also needs canceling
1546       ;; in other octaves and in the next measure.
1547       ((equal? style 'modern)
1548        (set-accidentals-properties #f
1549                                    `(Staff ,(make-accidental-rule 'same-octave 0)
1550                                            ,(make-accidental-rule 'any-octave 0)
1551                                            ,(make-accidental-rule 'same-octave 1))
1552                                    '()
1553                                    context))
1554       ;; the accidentals that Stone adds to the old standard as cautionaries
1555       ((equal? style 'modern-cautionary)
1556        (set-accidentals-properties #f
1557                                    `(Staff ,(make-accidental-rule 'same-octave 0))
1558                                    `(Staff ,(make-accidental-rule 'any-octave 0)
1559                                            ,(make-accidental-rule 'same-octave 1))
1560                                    context))
1561       ;; same as modern, but accidentals different from the key signature are always
1562       ;; typeset - unless they directly follow a note of the same pitch.
1563       ((equal? style 'neo-modern)
1564        (set-accidentals-properties #f
1565                                    `(Staff ,(make-accidental-rule 'same-octave 0)
1566                                            ,(make-accidental-rule 'any-octave 0)
1567                                            ,(make-accidental-rule 'same-octave 1)
1568                                            ,neo-modern-accidental-rule)
1569                                    '()
1570                                    context))
1571       ((equal? style 'neo-modern-cautionary)
1572        (set-accidentals-properties #f
1573                                    `(Staff ,(make-accidental-rule 'same-octave 0))
1574                                    `(Staff ,(make-accidental-rule 'any-octave 0)
1575                                            ,(make-accidental-rule 'same-octave 1)
1576                                            ,neo-modern-accidental-rule)
1577                                    context))
1578       ((equal? style 'neo-modern-voice)
1579        (set-accidentals-properties #f
1580                                    `(Voice ,(make-accidental-rule 'same-octave 0)
1581                                            ,(make-accidental-rule 'any-octave 0)
1582                                            ,(make-accidental-rule 'same-octave 1)
1583                                            ,neo-modern-accidental-rule
1584                                      Staff ,(make-accidental-rule 'same-octave 0)
1585                                            ,(make-accidental-rule 'any-octave 0)
1586                                            ,(make-accidental-rule 'same-octave 1)
1587                                       ,neo-modern-accidental-rule)
1588                                    '()
1589                                    context))
1590       ((equal? style 'neo-modern-voice-cautionary)
1591        (set-accidentals-properties #f
1592                                    `(Voice ,(make-accidental-rule 'same-octave 0))
1593                                    `(Voice ,(make-accidental-rule 'any-octave 0)
1594                                            ,(make-accidental-rule 'same-octave 1)
1595                                            ,neo-modern-accidental-rule
1596                                      Staff ,(make-accidental-rule 'same-octave 0)
1597                                            ,(make-accidental-rule 'any-octave 0)
1598                                            ,(make-accidental-rule 'same-octave 1)
1599                                            ,neo-modern-accidental-rule)
1600                                    context))
1601       ;; Accidentals as they were common in dodecaphonic music with no tonality.
1602       ;; Each note gets one accidental.
1603       ((equal? style 'dodecaphonic)
1604        (set-accidentals-properties #f
1605                                    `(Staff ,(lambda (c p bn mp) '(#f . #t)))
1606                                    '()
1607                                    context))
1608       ;; Multivoice accidentals to be read both by musicians playing one voice
1609       ;; and musicians playing all voices.
1610       ;; Accidentals are typeset for each voice, but they ARE canceled across voices.
1611       ((equal? style 'modern-voice)
1612        (set-accidentals-properties  #f
1613                                     `(Voice ,(make-accidental-rule 'same-octave 0)
1614                                             ,(make-accidental-rule 'any-octave 0)
1615                                             ,(make-accidental-rule 'same-octave 1)
1616                                       Staff ,(make-accidental-rule 'same-octave 0)
1617                                             ,(make-accidental-rule 'any-octave 0)
1618                                             ,(make-accidental-rule 'same-octave 1))
1619                                     '()
1620                                     context))
1621       ;; same as modernVoiceAccidental eccept that all special accidentals are typeset
1622       ;; as cautionaries
1623       ((equal? style 'modern-voice-cautionary)
1624        (set-accidentals-properties #f
1625                                    `(Voice ,(make-accidental-rule 'same-octave 0))
1626                                    `(Voice ,(make-accidental-rule 'any-octave 0)
1627                                            ,(make-accidental-rule 'same-octave 1)
1628                                      Staff ,(make-accidental-rule 'same-octave 0)
1629                                            ,(make-accidental-rule 'any-octave 0)
1630                                            ,(make-accidental-rule 'same-octave 1))
1631                                    context))
1632       ;; stone's suggestions for accidentals on grand staff.
1633       ;; Accidentals are canceled across the staves in the same grand staff as well
1634       ((equal? style 'piano)
1635        (set-accidentals-properties #f
1636                                    `(Staff ,(make-accidental-rule 'same-octave 0)
1637                                            ,(make-accidental-rule 'any-octave 0)
1638                                            ,(make-accidental-rule 'same-octave 1)
1639                                      GrandStaff
1640                                            ,(make-accidental-rule 'any-octave 0)
1641                                            ,(make-accidental-rule 'same-octave 1))
1642                                    '()
1643                                    pcontext))
1644       ((equal? style 'piano-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                                      GrandStaff
1650                                            ,(make-accidental-rule 'any-octave 0)
1651                                            ,(make-accidental-rule 'same-octave 1))
1652                                    pcontext))
1653
1654       ;; same as modern, but cautionary accidentals are printed for all sharp or flat
1655       ;; tones specified by the key signature.
1656        ((equal? style 'teaching)
1657        (set-accidentals-properties #f
1658                                     `(Staff ,(make-accidental-rule 'same-octave 0))
1659                                     `(Staff ,(make-accidental-rule 'same-octave 1)
1660                                            ,teaching-accidental-rule)
1661                                    context))
1662
1663       ;; do not set localKeySignature when a note alterated differently from
1664       ;; localKeySignature is found.
1665       ;; Causes accidentals to be printed at every note instead of
1666       ;; remembered for the duration of a measure.
1667       ;; accidentals not being remembered, causing accidentals always to
1668       ;; be typeset relative to the time signature
1669       ((equal? style 'forget)
1670        (set-accidentals-properties '()
1671                                    `(Staff ,(make-accidental-rule 'same-octave -1))
1672                                    '()
1673                                    context))
1674       ;; Do not reset the key at the start of a measure.  Accidentals will be
1675       ;; printed only once and are in effect until overridden, possibly many
1676       ;; measures later.
1677       ((equal? style 'no-reset)
1678        (set-accidentals-properties '()
1679                                    `(Staff ,(make-accidental-rule 'same-octave #t))
1680                                    '()
1681                                    context))
1682       (else
1683        (ly:warning (_ "unknown accidental style: ~S") style)
1684        (make-sequential-music '())))))
1685
1686 (define-public (invalidate-alterations context)
1687   "Invalidate alterations in @var{context}.
1688
1689 Elements of @code{'localKeySignature} corresponding to local
1690 alterations of the key signature have the form
1691 @code{'((octave . notename) . (alter barnum . measurepos))}.
1692 Replace them with a version where @code{alter} is set to @code{'clef}
1693 to force a repetition of accidentals.
1694
1695 Entries that conform with the current key signature are not invalidated."
1696   (let* ((keysig (ly:context-property context 'keySignature)))
1697     (set! (ly:context-property context 'localKeySignature)
1698           (map-in-order
1699            (lambda (entry)
1700              (let* ((localalt (key-entry-alteration entry)))
1701                (if (or (accidental-invalid? localalt)
1702                        (not (key-entry-bar-number entry))
1703                        (= localalt
1704                           (key-entry-alteration
1705                            (find-pitch-entry
1706                             keysig
1707                             (ly:make-pitch (key-entry-octave entry)
1708                                            (key-entry-notename entry)
1709                                            0)
1710                             #t #t))))
1711                    entry
1712                    (cons (car entry) (cons 'clef (cddr entry))))))
1713            (ly:context-property context 'localKeySignature)))))
1714
1715 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1716
1717 (define-public (skip-of-length mus)
1718   "Create a skip of exactly the same length as @var{mus}."
1719   (let* ((skip
1720           (make-music
1721            'SkipEvent
1722            'duration (ly:make-duration 0 0))))
1723
1724     (make-event-chord (list (ly:music-compress skip (ly:music-length mus))))))
1725
1726 (define-public (mmrest-of-length mus)
1727   "Create a multi-measure rest of exactly the same length as @var{mus}."
1728
1729   (let* ((skip
1730           (make-multi-measure-rest
1731            (ly:make-duration 0 0) '())))
1732     (ly:music-compress skip (ly:music-length mus))
1733     skip))
1734
1735 (define-public (pitch-of-note event-chord)
1736   (let ((evs (filter (lambda (x)
1737                        (music-has-type x 'note-event))
1738                      (ly:music-property event-chord 'elements))))
1739
1740     (and (pair? evs)
1741          (ly:music-property (car evs) 'pitch))))
1742
1743 (define-public (duration-of-note event-chord)
1744   (cond
1745    ((pair? event-chord)
1746     (or (duration-of-note (car event-chord))
1747         (duration-of-note (cdr event-chord))))
1748    ((ly:music? event-chord)
1749     (let ((dur (ly:music-property event-chord 'duration)))
1750       (if (ly:duration? dur)
1751           dur
1752           (duration-of-note (ly:music-property event-chord 'elements)))))
1753    (else #f)))
1754
1755 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1756
1757 (define-public (map-some-music map? music)
1758   "Walk through @var{music}, transform all elements calling @var{map?}
1759 and only recurse if this returns @code{#f}."
1760   (let loop ((music music))
1761     (or (map? music)
1762         (let ((elt (ly:music-property music 'element))
1763               (elts (ly:music-property music 'elements))
1764               (arts (ly:music-property music 'articulations)))
1765           (if (ly:music? elt)
1766               (set! (ly:music-property music 'element)
1767                     (loop elt)))
1768           (if (pair? elts)
1769               (set! (ly:music-property music 'elements)
1770                     (map loop elts)))
1771           (if (pair? arts)
1772               (set! (ly:music-property music 'articulations)
1773                     (map loop arts)))
1774           music))))
1775
1776 (define-public (for-some-music stop? music)
1777   "Walk through @var{music}, process all elements calling @var{stop?}
1778 and only recurse if this returns @code{#f}."
1779   (let loop ((music music))
1780     (if (not (stop? music))
1781         (let ((elt (ly:music-property music 'element)))
1782           (if (ly:music? elt)
1783               (loop elt))
1784           (for-each loop (ly:music-property music 'elements))
1785           (for-each loop (ly:music-property music 'articulations))))))
1786
1787 (define-public (fold-some-music pred? proc init music)
1788   "This works recursively on music like @code{fold} does on a list,
1789 calling @samp{(@var{pred?} music)} on every music element.  If
1790 @code{#f} is returned for an element, it is processed recursively
1791 with the same initial value of @samp{previous}, otherwise
1792 @samp{(@var{proc} music previous)} replaces @samp{previous}
1793 and no recursion happens.
1794 The top @var{music} is processed using @var{init} for @samp{previous}."
1795   (let loop ((music music) (previous init))
1796     (if (pred? music)
1797         (proc music previous)
1798         (fold loop
1799               (fold loop
1800                     (let ((elt (ly:music-property music 'element)))
1801                       (if (null? elt)
1802                           previous
1803                           (loop elt previous)))
1804                     (ly:music-property music 'elements))
1805               (ly:music-property music 'articulations)))))
1806
1807 (define-public (extract-music music pred?)
1808   "Return a flat list of all music matching @var{pred?} inside of
1809 @var{music}, not recursing into matches themselves."
1810   (reverse! (fold-some-music pred? cons '() music)))
1811
1812 (define-public (extract-named-music music music-name)
1813   "Return a flat list of all music named @var{music-name} (either a
1814 single event symbol or a list of alternatives) inside of @var{music},
1815 not recursing into matches themselves."
1816   (extract-music
1817    music
1818    (if (cheap-list? music-name)
1819        (lambda (m) (memq (ly:music-property m 'name) music-name))
1820        (lambda (m) (eq? (ly:music-property m 'name) music-name)))))
1821
1822 (define-public (extract-typed-music music type)
1823   "Return a flat list of all music with @var{type} (either a single
1824 type symbol or a list of alternatives) inside of @var{music}, not
1825 recursing into matches themselves."
1826   (extract-music
1827    music
1828    (if (cheap-list? type)
1829        (lambda (m)
1830          (any (lambda (t) (music-is-of-type? m t)) type))
1831        (lambda (m) (music-is-of-type? m type)))))
1832
1833 (define*-public (event-chord-wrap! music #:optional parser)
1834   "Wrap isolated rhythmic events and non-postevent events in
1835 @var{music} inside of an @code{EventChord}.  If the optional
1836 @var{parser} argument is given, chord repeats @samp{q} are expanded
1837 using the default settings.  Otherwise, you need to cater for them
1838 yourself."
1839   (map-some-music
1840    (lambda (m)
1841      (cond ((music-is-of-type? m 'event-chord)
1842             (if (pair? (ly:music-property m 'articulations))
1843                 (begin
1844                   (set! (ly:music-property m 'elements)
1845                         (append (ly:music-property m 'elements)
1846                                 (ly:music-property m 'articulations)))
1847                   (set! (ly:music-property m 'articulations) '())))
1848             m)
1849            ((music-is-of-type? m 'rhythmic-event)
1850             (let ((arts (ly:music-property m 'articulations)))
1851               (if (pair? arts)
1852                   (set! (ly:music-property m 'articulations) '()))
1853               (make-event-chord (cons m arts))))
1854            (else #f)))
1855    (if parser
1856        (expand-repeat-chords!
1857         (cons 'rhythmic-event
1858               (ly:parser-lookup parser '$chord-repeat-events))
1859         music)
1860        music)))
1861
1862 (define-public (event-chord-notes event-chord)
1863   "Return a list of all notes from @var{event-chord}."
1864   (filter
1865     (lambda (m) (eq? 'NoteEvent (ly:music-property m 'name)))
1866     (ly:music-property event-chord 'elements)))
1867
1868 (define-public (event-chord-pitches event-chord)
1869   "Return a list of all pitches from @var{event-chord}."
1870   (map (lambda (x) (ly:music-property x 'pitch))
1871        (event-chord-notes event-chord)))
1872
1873 (defmacro-public make-relative (pitches last-pitch music)
1874   "The list of pitch-carrying variables in @var{pitches} is used as a
1875 sequence for creating relativable music from @var{music}.
1876 The variables in @var{pitches} are, when considered inside of
1877 @code{\\relative}, all considered to be specifications to the preceding
1878 variable.  The first variable is relative to the preceding musical
1879 context, and @var{last-pitch} specifies the pitch passed as relative
1880 base onto the following musical context."
1881
1882   ;; pitch and music generator might be stored instead in music
1883   ;; properties, and it might make sense to create a music type of its
1884   ;; own for this kind of construct rather than using
1885   ;; RelativeOctaveMusic
1886   (define ((make-relative::to-relative-callback pitches p->m p->p) music pitch)
1887     (let* ((chord (make-event-chord
1888                    (map
1889                     (lambda (p)
1890                       (make-music 'NoteEvent
1891                                   'pitch p))
1892                     pitches)))
1893            (pitchout (begin
1894                        (ly:make-music-relative! chord pitch)
1895                        (event-chord-pitches chord))))
1896       (set! (ly:music-property music 'element)
1897             (apply p->m pitchout))
1898       (apply p->p pitchout)))
1899   `(make-music 'RelativeOctaveMusic
1900                'to-relative-callback
1901                (,make-relative::to-relative-callback
1902                 (list ,@pitches)
1903                 (lambda ,pitches ,music)
1904                 (lambda ,pitches ,last-pitch))
1905                'element ,music))
1906
1907 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1908 ;; The following functions are all associated with the crossStaff
1909 ;;  function
1910
1911 (define (close-enough? x y)
1912   "Values are close enough to ignore the difference"
1913    (< (abs (- x y)) 0.0001))
1914
1915 (define (extent-combine extents)
1916   "Combine a list of extents"
1917   (if (pair? (cdr extents))
1918       (interval-union (car extents) (extent-combine (cdr extents)))
1919       (car extents)))
1920
1921 (define ((stem-connectable? ref root) stem)
1922   "Check if the stem is connectable to the root"
1923   ;; The root is always connectable to itself
1924   (or (eq? root stem)
1925       (and
1926       ;; Horizontal positions of the stems must be almost the same
1927         (close-enough? (car (ly:grob-extent root ref X))
1928           (car (ly:grob-extent stem ref X)))
1929         ;; The stem must be in the direction away from the root's notehead
1930         (positive? (* (ly:grob-property root 'direction)
1931                      (- (car (ly:grob-extent stem ref Y))
1932                        (car (ly:grob-extent root ref Y))))))))
1933
1934 (define (stem-span-stencil span)
1935   "Connect stems if we have at least one stem connectable to the root"
1936   (let* ((system (ly:grob-system span))
1937           (root (ly:grob-parent span X))
1938           (stems (filter (stem-connectable? system root)
1939                          (ly:grob-object span 'stems))))
1940      (if (<= 2 (length stems))
1941          (let* ((yextents (map (lambda (st)
1942                                  (ly:grob-extent st system Y)) stems))
1943                 (yextent (extent-combine yextents))
1944                 (layout (ly:grob-layout root))
1945                 (blot (ly:output-def-lookup layout 'blot-diameter)))
1946            ;; Hide spanned stems
1947            (map (lambda (st)
1948                   (set! (ly:grob-property st 'stencil) #f))
1949              stems)
1950            ;; Draw a nice looking stem with rounded corners
1951            (ly:round-filled-box (ly:grob-extent root root X) yextent blot))
1952          ;; Nothing to connect, don't draw the span
1953          #f)))
1954
1955 (define ((make-stem-span! stems trans) root)
1956   "Create a stem span as a child of the cross-staff stem (the root)"
1957   (let ((span (ly:engraver-make-grob trans 'Stem '())))
1958     (ly:grob-set-parent! span X root)
1959     (set! (ly:grob-object span 'stems) stems)
1960     ;; Suppress positioning, the stem code is confused by this weird stem
1961     (set! (ly:grob-property span 'X-offset) 0)
1962     (set! (ly:grob-property span 'stencil) stem-span-stencil)))
1963
1964 (define-public (cross-staff-connect stem)
1965   "Set cross-staff property of the stem to this function to connect it to
1966 other stems automatically"
1967    #t)
1968
1969 (define (stem-is-root? stem)
1970   "Check if automatic connecting of the stem was requested.  Stems connected
1971 to cross-staff beams are cross-staff, but they should not be connected to
1972 other stems just because of that."
1973   (eq? cross-staff-connect (ly:grob-property-data stem 'cross-staff)))
1974
1975 (define (make-stem-spans! ctx stems trans)
1976   "Create stem spans for cross-staff stems"
1977   ;; Cannot do extensive checks here, just make sure there are at least
1978   ;; two stems at this musical moment
1979   (if (<= 2 (length stems))
1980     (let ((roots (filter stem-is-root? stems)))
1981     (map (make-stem-span! stems trans) roots))))
1982
1983 (define-public (Span_stem_engraver ctx)
1984   "Connect cross-staff stems to the stems above in the system"
1985   (let ((stems '()))
1986     (make-engraver
1987       ;; Record all stems for the given moment
1988       (acknowledgers
1989         ((stem-interface trans grob source)
1990         (set! stems (cons grob stems))))
1991       ;; Process stems and reset the stem list to empty
1992       ((process-acknowledged trans)
1993         (make-stem-spans! ctx stems trans)
1994         (set! stems '())))))
1995
1996 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1997 ;; The following is used by the alterBroken function.
1998
1999 (define-public ((value-for-spanner-piece arg) grob)
2000   "Associate a piece of broken spanner @var{grob} with an element
2001 of list @var{arg}."
2002   (let* ((orig (ly:grob-original grob))
2003          (siblings (ly:spanner-broken-into orig)))
2004
2005    (define (helper sibs arg)
2006      (if (null? arg)
2007          arg
2008          (if (eq? (car sibs) grob)
2009              (car arg)
2010              (helper (cdr sibs) (cdr arg)))))
2011
2012    (if (>= (length siblings) 2)
2013        (helper siblings arg)
2014        (car arg))))
2015
2016 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2017 ;; measure counter
2018
2019 (define (measure-counter-stencil grob)
2020   "Print a number for a measure count.  The number is centered using
2021 the extents of @code{BreakAlignment} grobs associated with
2022 @code{NonMusicalPaperColumn} grobs.  In the case of an unbroken measure, these
2023 columns are the left and right bounds of a @code{MeasureCounter} spanner.
2024 Broken measures are numbered in parentheses."
2025   (let* ((orig (ly:grob-original grob))
2026          (siblings (ly:spanner-broken-into orig)) ; have we been split?
2027          (bounds (ly:grob-array->list (ly:grob-object grob 'columns)))
2028          (refp (ly:grob-system grob))
2029          ;; we use the first and/or last NonMusicalPaperColumn grob(s) of
2030          ;; a system in the event that a MeasureCounter spanner is broken
2031          (all-cols (ly:grob-array->list (ly:grob-object refp 'columns)))
2032          (all-cols
2033            (filter
2034              (lambda (col) (eq? #t (ly:grob-property col 'non-musical)))
2035              all-cols))
2036          (left-bound
2037            (if (or (null? siblings) ; spanner is unbroken
2038                    (eq? grob (car siblings))) ; or the first piece
2039                (car bounds)
2040                (car all-cols)))
2041          (right-bound
2042            (if (or (null? siblings)
2043                    (eq? grob (car (reverse siblings))))
2044                (car (reverse bounds))
2045                (car (reverse all-cols))))
2046          (elts-L (ly:grob-array->list (ly:grob-object left-bound 'elements)))
2047          (elts-R (ly:grob-array->list (ly:grob-object right-bound 'elements)))
2048          (break-alignment-L
2049            (filter
2050              (lambda (elt) (grob::has-interface elt 'break-alignment-interface))
2051              elts-L))
2052          (break-alignment-R
2053            (filter
2054              (lambda (elt) (grob::has-interface elt 'break-alignment-interface))
2055              elts-R))
2056          (break-alignment-L-ext (ly:grob-extent (car break-alignment-L) refp X))
2057          (break-alignment-R-ext (ly:grob-extent (car break-alignment-R) refp X))
2058          (num (markup (number->string (ly:grob-property grob 'count-from))))
2059          (num
2060            (if (or (null? siblings)
2061                    (eq? grob (car siblings)))
2062                num
2063                (make-parenthesize-markup num)))
2064          (num (grob-interpret-markup grob num))
2065          (num (ly:stencil-aligned-to num X (ly:grob-property grob 'self-alignment-X)))
2066          (num
2067            (ly:stencil-translate-axis
2068              num
2069              (+ (interval-length break-alignment-L-ext)
2070                 (* 0.5
2071                    (- (car break-alignment-R-ext)
2072                       (cdr break-alignment-L-ext))))
2073              X)))
2074     num))