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