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