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