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