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