]> git.donarmstrong.com Git - lilypond.git/blob - scm/music-functions.scm
* scm/music-functions.scm (skip-to-last): new function. Show only
[lilypond.git] / scm / music-functions.scm
1 ;;;; music-functions.scm --
2 ;;;;
3 ;;;;  source file of the GNU LilyPond music typesetter
4 ;;;; 
5 ;;;; (c) 1998--2005 Jan Nieuwenhuizen <janneke@gnu.org>
6 ;;;;                 Han-Wen Nienhuys <hanwen@cs.uu.nl>
7
8 ;; (use-modules (ice-9 optargs)) 
9
10 ;;; ly:music-property with setter
11 ;;; (ly:music-property my-music 'elements)
12 ;;;   ==> the 'elements property
13 ;;; (set! (ly:music-property my-music 'elements) value)
14 ;;;   ==> set the 'elements property and return it
15 (define-public ly:music-property
16   (make-procedure-with-setter ly:music-property
17                               ly:music-set-property!))
18
19 (define-public ly:grob-property
20   (make-procedure-with-setter ly:grob-property
21                               ly:grob-set-property!))
22
23 (define-public (music-map function music)
24   "Apply @var{function} to @var{music} and all of the music it contains.
25
26 First it recurses over the children, then the function is applied to MUSIC.
27 "
28   (let ((es (ly:music-property music 'elements))
29         (e (ly:music-property music 'element)))
30     (set! (ly:music-property music 'elements) 
31           (map (lambda (y) (music-map function y)) es))
32     (if (ly:music? e)
33         (set! (ly:music-property music 'element)
34               (music-map function  e)))
35     (function music)))
36
37 (define-public (music-filter pred? music)
38   "Filter out music expressions that do not satisfy PRED."
39   
40   (define (inner-music-filter pred? music)
41     "Recursive function."
42     (let* ((es (ly:music-property music 'elements))
43            (e (ly:music-property music 'element))
44            (as (ly:music-property music 'articulations))
45            (filtered-as (filter ly:music? (map (lambda (y) (inner-music-filter pred? y)) as)))
46            (filtered-e (if (ly:music? e)
47                            (inner-music-filter pred? e)
48                            e))
49            (filtered-es (filter ly:music? (map (lambda (y) (inner-music-filter pred? y)) es))))
50       (set! (ly:music-property music 'element) filtered-e)
51       (set! (ly:music-property music 'elements) filtered-es)
52       (set! (ly:music-property music 'articulations) filtered-as)
53       ;; if filtering emptied the expression, we remove it completely.
54       (if (or (not (pred? music))
55               (and (eq? filtered-es '()) (not (ly:music? e))
56                    (or (not (eq? es '()))
57                        (ly:music? e))))
58           (set! music '()))
59       music))
60
61   (set! music (inner-music-filter pred? music))
62   (if (ly:music? music)
63       music
64       (make-music 'Music)))       ;must return music.
65
66 (define-public (display-music music)
67   "Display music, not done with music-map for clarity of presentation."
68   (display music)
69   (display ": { ")  
70   (let ((es (ly:music-property music 'elements))
71         (e (ly:music-property music 'element)))
72     (display (ly:music-mutable-properties music))
73     (if (pair? es)
74         (begin (display "\nElements: {\n")
75                (map display-music es)
76                (display "}\n")))
77     (if (ly:music? e)
78         (begin
79           (display "\nChild:")
80           (display-music e))))
81   (display " }\n")
82   music)
83
84 ;;;
85 ;;; A scheme music pretty printer
86 ;;;
87 (define (markup-expression->make-markup markup-expression)
88   "Transform `markup-expression' into an equivalent, hopefuly readable, scheme expression.
89 For instance, 
90   \\markup \\bold \\italic hello
91 ==>
92   (markup #:line (#:bold (#:italic (#:simple \"hello\"))))"
93   (define (proc->command-keyword proc)
94     "Return a keyword, eg. `#:bold', from the `proc' function, eg. #<procedure bold-markup (layout props arg)>"
95     (let ((cmd-markup (symbol->string (procedure-name proc))))
96       (symbol->keyword (string->symbol (substring cmd-markup 0 (- (string-length cmd-markup)
97                                                                   (string-length "-markup")))))))
98   (define (transform-arg arg)
99     (cond ((and (pair? arg) (markup? (car arg))) ;; a markup list
100            (apply append (map inner-markup->make-markup arg)))
101           ((and (not (string? arg)) (markup? arg)) ;; a markup
102            (inner-markup->make-markup arg))
103           (else                                  ;; scheme arg
104            arg)))
105   (define (inner-markup->make-markup mrkup)
106     (let ((cmd (proc->command-keyword (car mrkup)))
107           (args (map transform-arg (cdr mrkup))))
108       `(,cmd ,@args)))
109   ;; body:
110   (if (string? markup-expression)
111       markup-expression
112       `(markup ,@(inner-markup->make-markup markup-expression))))
113
114 (define-public (music->make-music obj)
115   "Generate a expression that, once evaluated, may return an object equivalent to `obj',
116 that is, for a music expression, a (make-music ...) form."
117   (cond (;; markup expression
118          (markup? obj)
119          (markup-expression->make-markup obj))
120         (;; music expression
121          (ly:music? obj)
122          `(make-music 
123            ',(ly:music-property obj 'name)
124            ,@(apply append (map (lambda (prop)
125                                   `(',(car prop)
126                                     ,(if (and (not (markup? (cdr prop)))
127                                               (list? (cdr prop))
128                                               (pair? (cdr prop))) ;; property is a non-empty list
129                                          `(list ,@(map music->make-music (cdr prop)))
130                                          (music->make-music (cdr prop)))))
131                                 (remove (lambda (prop)
132                                           (eqv? (car prop) 'origin))
133                                         (ly:music-mutable-properties obj))))))
134         (;; moment
135          (ly:moment? obj)
136          `(ly:make-moment ,(ly:moment-main-numerator obj)
137                           ,(ly:moment-main-denominator obj)
138                           ,(ly:moment-grace-numerator obj)
139                           ,(ly:moment-grace-denominator obj)))
140         (;; note duration
141          (ly:duration? obj)
142          `(ly:make-duration ,(ly:duration-log obj)
143                             ,(ly:duration-dot-count obj)
144                             ,(car (ly:duration-factor obj))
145                             ,(cdr (ly:duration-factor obj))))
146         (;; note pitch
147          (ly:pitch? obj)
148          `(ly:make-pitch ,(ly:pitch-octave obj)
149                          ,(ly:pitch-notename obj)
150                          ,(ly:pitch-alteration obj)))
151         (;; scheme procedure
152          (procedure? obj)
153          (or (procedure-name obj) obj))
154         (;; a symbol (avoid having an unquoted symbol)
155          (symbol? obj)
156          `',obj)
157         (;; an empty list (avoid having an unquoted empty list)
158          (null? obj)
159          `'())
160         (else
161          obj)))
162
163 (use-modules (ice-9 pretty-print))
164 (define*-public (display-scheme-music obj #:optional (port (current-output-port)))
165   "Displays `obj', typically a music expression, in a friendly fashion,
166 which often can be read back in order to generate an equivalent expression.
167
168 Returns `obj'.
169 "
170   (pretty-print (music->make-music obj) port)
171   (newline)
172   obj)
173
174 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
175
176 (define (shift-one-duration-log music shift dot)
177   "  add SHIFT to ly:duration-log and optionally 
178   a dot to any note encountered. This scales the music up by a factor 
179   2^shift * (2 - (1/2)^dot)"
180   (let ((d (ly:music-property music 'duration)))
181     (if (ly:duration? d)
182         (let* ((cp (ly:duration-factor d))
183                (nd (ly:make-duration (+ shift (ly:duration-log d))
184                                      (+ dot (ly:duration-dot-count d))
185                                      (car cp)
186                                      (cdr cp))))
187           (set! (ly:music-property music 'duration) nd)))
188     music))
189
190
191
192 (define-public (shift-duration-log music shift dot)
193   (music-map (lambda (x) (shift-one-duration-log x shift dot))
194              music))
195
196 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
197 ;; clusters.
198
199 (define-public (note-to-cluster music)
200   "Replace NoteEvents by ClusterNoteEvents."
201   (if (eq? (ly:music-property music 'name) 'NoteEvent)
202       (make-music 'ClusterNoteEvent
203                   'pitch (ly:music-property music 'pitch)
204                   'duration (ly:music-property music 'duration))
205       music))
206
207 (define-public (notes-to-clusters music)
208   (music-map note-to-cluster music))
209
210 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
211 ;; repeats.
212
213 (define-public (unfold-repeats music)
214   "
215 This function replaces all repeats  with unfold repeats. "
216
217   (let ((es (ly:music-property music 'elements))
218         (e  (ly:music-property music 'element))
219         )
220     (if (memq 'repeated-music (ly:music-property music 'types))
221         (let*
222             ((props (ly:music-mutable-properties music))
223              (old-name (ly:music-property music 'name))
224              (flattened  (flatten-alist props)))
225
226           (set! music (apply make-music (cons 'UnfoldedRepeatedMusic
227                                               flattened)))
228
229           (if (equal? old-name 'TremoloRepeatedMusic)
230               (let* ((seq-arg? (memq 'sequential-music
231                                      (ly:music-property e 'types)))
232                      (count  (ly:music-property music 'repeat-count))
233                      (dot-shift (if (= 0 (remainder count 3))
234                                     -1 0)))
235
236                 (if (= 0 -1)
237                     (set! count (* 2 (quotient count 3))))
238                 
239                 (shift-duration-log music (+ (if seq-arg? 1 0)
240                                              (ly:intlog2 count)) dot-shift)
241                 
242                 (if seq-arg?
243                     (ly:music-compress e (ly:make-moment (length (ly:music-property
244                                                                   e 'elements)) 1)))))))
245           
246     
247     (if (pair? es)
248         (set! (ly:music-property music 'elements)
249               (map unfold-repeats es)))
250     (if (ly:music? e)
251         (set! (ly:music-property music 'element)
252               (unfold-repeats e)))
253     music))
254
255 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
256 ;; property setting music objs.
257
258 (define-public (make-grob-property-set grob gprop val)
259   "Make a Music expression that sets GPROP to VAL in GROB. Does a pop first,
260 i.e.  this is not an override"
261   (make-music 'OverrideProperty
262               'symbol grob
263               'grob-property gprop
264               'grob-value val
265               'pop-first #t))
266
267 (define-public (make-grob-property-override grob gprop val)
268   "Make a Music expression that sets GPROP to VAL in GROB. Does a pop first,
269 i.e.  this is not an override"
270   (make-music 'OverrideProperty
271               'symbol grob
272               'grob-property gprop
273               'grob-value val))
274
275 (define-public (make-grob-property-revert grob gprop)
276   "Revert the grob property GPROP for GROB."
277   (make-music 'OverrideProperty
278               'symbol grob
279               'grob-property gprop))
280
281 (define direction-polyphonic-grobs
282   '(Stem Tie Rest Slur Script TextScript Dots DotColumn Fingering))
283
284 (define-safe-public (make-voice-props-set n)
285   (make-sequential-music
286    (append
287     (map (lambda (x) (make-grob-property-set x 'direction
288                                              (if (odd? n) -1 1)))
289          direction-polyphonic-grobs)
290     (list
291      (make-grob-property-set 'NoteColumn 'horizontal-shift (quotient n 2))
292      (make-grob-property-set 'MultiMeasureRest 'staff-position (if (odd? n) -4 4)))))) 
293
294 (define-safe-public (make-voice-props-revert)
295   (make-sequential-music
296    (append
297     (map (lambda (x) (make-grob-property-revert x 'direction))
298          direction-polyphonic-grobs)
299     (list (make-grob-property-revert 'NoteColumn 'horizontal-shift))
300     (list (make-grob-property-revert 'MultiMeasureRest 'staff-position)))))
301
302
303 (define-safe-public (context-spec-music m context #:optional id)
304   "Add \\context CONTEXT = ID to M. "
305   (let ((cm (make-music 'ContextSpeccedMusic
306                         'element m
307                         'context-type context)))
308     (if (string? id)
309         (set! (ly:music-property cm 'context-id) id))
310     cm))
311
312 (define-public (descend-to-context m context)
313   "Like context-spec-music, but only descending. "
314   (let ((cm (context-spec-music m context)))
315     (ly:music-set-property! cm 'descend-only #t)
316     cm))
317
318 (define-public (make-non-relative-music mus)
319   (make-music 'UnrelativableMusic
320               'element mus))
321
322 (define-public (make-apply-context func)
323   (make-music 'ApplyContext
324               'procedure func))
325
326 (define-public (make-sequential-music elts)
327   (make-music 'SequentialMusic
328               'elements elts))
329
330 (define-public (make-simultaneous-music elts)
331   (make-music 'SimultaneousMusic
332               'elements elts))
333
334 (define-safe-public (make-event-chord elts)
335   (make-music 'EventChord
336               'elements elts))
337
338 (define-public (make-skip-music dur)
339   (make-music 'SkipMusic
340               'duration dur))
341
342 (define-public (make-grace-music music)
343   (make-music 'GraceMusic
344               'element music))
345
346 ;;;;;;;;;;;;;;;;
347
348 ;; mmrest
349 (define-public (make-multi-measure-rest duration location)
350   (make-music 'MultiMeasureRestMusicGroup
351               'origin location
352               'elements (list (make-music 'BarCheck
353                                           'origin location)
354                               (make-event-chord (list (make-music 'MultiMeasureRestEvent
355                                                                   'origin location
356                                                                   'duration duration)))
357                               (make-music 'BarCheck
358                                           'origin location))))
359
360 (define-public (glue-mm-rest-texts music)
361   "Check if we have R1*4-\\markup { .. }, and if applicable convert to
362 a property set for MultiMeasureRestNumber."
363   (define (script-to-mmrest-text script-music)
364     "Extract 'direction and 'text from SCRIPT-MUSIC, and transform into property sets."
365     (let ((dir (ly:music-property script-music 'direction))
366           (p   (make-music 'MultiMeasureTextEvent
367                            'text (ly:music-property script-music 'text))))
368       (if (ly:dir? dir)
369           (set! (ly:music-property p 'direction) dir))
370       p))
371   (if (eq? (ly:music-property music 'name) 'MultiMeasureRestMusicGroup)
372       (let* ((text? (lambda (x) (memq 'script-event (ly:music-property x 'types))))
373              (es (ly:music-property  music 'elements))
374              (texts (map script-to-mmrest-text  (filter text? es)))
375              (others (remove text? es)))
376         (if (pair? texts)
377             (set! (ly:music-property music 'elements)
378                   (cons (make-event-chord texts) others)))))
379   music)
380
381
382 (define-public (make-property-set sym val)
383   (make-music 'PropertySet
384               'symbol sym
385               'value val))
386
387 (define-public (make-ottava-set octavation)
388   (let ((m (make-music 'ApplyContext)))
389     (define (ottava-modify context)
390       "Either reset middleCPosition to the stored original, or remember
391 old middleCPosition, add OCTAVATION to middleCPosition, and set
392 OTTAVATION to `8va', or whatever appropriate."      
393       (if (number? (ly:context-property  context 'middleCPosition))
394           (if (= octavation 0)
395               (let ((where (ly:context-property-where-defined context 'middleCPosition))
396                     (oc0 (ly:context-property context 'originalCentralCPosition)))
397                 (ly:context-set-property! context 'middleCPosition oc0)
398                 (ly:context-unset-property where 'originalCentralCPosition)
399                 (ly:context-unset-property where 'ottavation))
400               (let* ((where (ly:context-property-where-defined context 'middleCPosition))
401                      (c0 (ly:context-property context 'middleCPosition))
402                      (new-c0 (+ c0 (* -7 octavation)))
403                      (string (cdr (assoc octavation '((2 . "15ma")
404                                                       (1 . "8va")
405                                                       (0 . #f)
406                                                       (-1 . "8va bassa")
407                                                       (-2 . "15ma bassa"))))))
408                 (ly:context-set-property! context 'middleCPosition new-c0)
409                 (ly:context-set-property! context 'originalCentralCPosition c0)
410                 (ly:context-set-property! context 'ottavation string)))))
411     (set! (ly:music-property m 'procedure) ottava-modify)
412     (context-spec-music m 'Staff)))
413
414 (define-public (set-octavation ottavation)
415   (ly:export (make-ottava-set ottavation)))
416
417 (define-public (make-time-signature-set num den . rest)
418   "Set properties for time signature NUM/DEN.  Rest can contain a list
419 of beat groupings "
420   (let* ((set1 (make-property-set 'timeSignatureFraction (cons num den)))
421          (beat (ly:make-moment 1 den))
422          (len  (ly:make-moment num den))
423          (set2 (make-property-set 'beatLength beat))
424          (set3 (make-property-set 'measureLength len))
425          (set4 (make-property-set 'beatGrouping (if (pair? rest)
426                                                     (car rest)
427                                                     '())))
428          (basic  (list set1 set2 set3 set4)))
429     (descend-to-context
430      (context-spec-music (make-sequential-music basic) 'Timing) 'Score)))
431
432 (define-public (make-mark-set label)
433   "Make the music for the \\mark command."  
434   (let* ((set (if (integer? label)
435                   (context-spec-music (make-property-set 'rehearsalMark label)
436                                       'Score)
437                   #f))
438          (ev (make-music 'MarkEvent))
439          (ch (make-event-chord (list ev))))
440     (if set
441         (make-sequential-music (list set ch))
442         (begin
443           (set! (ly:music-property ev 'label) label)
444           ch))))
445
446 (define-public (set-time-signature num den . rest)
447   (ly:export (apply make-time-signature-set `(,num ,den . ,rest))))
448
449 (define-safe-public (make-penalty-music pen page-pen)
450   (make-music 'BreakEvent
451               'penalty pen
452               'page-penalty page-pen))
453
454 (define-safe-public (make-articulation name)
455   (make-music 'ArticulationEvent
456               'articulation-type name))
457
458 (define-public (make-lyric-event string duration)
459   (make-music 'LyricEvent
460               'duration duration
461               'text string))
462
463 (define-safe-public (make-span-event type spandir)
464   (make-music type
465               'span-direction spandir))
466
467 (define-public (set-mus-properties! m alist)
468   "Set all of ALIST as properties of M." 
469   (if (pair? alist)
470       (begin
471         (set! (ly:music-property m (caar alist)) (cdar alist))
472         (set-mus-properties! m (cdr alist)))))
473
474 (define-public (music-separator? m)
475   "Is M a separator?"
476   (let ((ts (ly:music-property m 'types)))
477     (memq 'separator ts)))
478
479 ;;; splitting chords into voices.
480 (define (voicify-list lst number)
481   "Make a list of Musics.
482
483    voicify-list :: [ [Music ] ] -> number -> [Music]
484    LST is a list music-lists.
485
486    NUMBER is 0-base, i.e. Voice=1 (upstems) has number 0.
487 "
488   (if (null? lst)
489       '()
490       (cons (context-spec-music
491              (make-sequential-music
492               (list (make-voice-props-set number)
493                     (make-simultaneous-music (car lst))))
494              'Voice  (number->string (1+ number)))
495             (voicify-list (cdr lst) (1+ number)))))
496
497 (define (voicify-chord ch)
498   "Split the parts of a chord into different Voices using separator"
499   (let ((es (ly:music-property ch 'elements)))
500     (set! (ly:music-property  ch 'elements)
501           (voicify-list (split-list es music-separator?) 0))
502     ch))
503
504 (define-public (voicify-music m)
505   "Recursively split chords that are separated with \\ "
506   (if (not (ly:music? m))
507       (ly:error (_ "music expected: ~S") m))
508   (let ((es (ly:music-property m 'elements))
509         (e (ly:music-property m 'element)))
510
511     (if (pair? es)
512         (set! (ly:music-property m 'elements) (map voicify-music es)))
513     (if (ly:music? e)
514         (set! (ly:music-property m 'element)  (voicify-music e)))
515     (if (and (equal? (ly:music-property m 'name) 'SimultaneousMusic)
516              (reduce (lambda (x y ) (or x y)) #f (map music-separator? es)))
517         (set! m (context-spec-music (voicify-chord m) 'Staff)))
518     m))
519
520 (define-public (empty-music)
521   (ly:export (make-music 'Music)))
522 ;;;
523
524                                         ; Make a function that checks score element for being of a specific type. 
525 (define-public (make-type-checker symbol)
526   (lambda (elt)
527     ;;(display  symbol)
528     ;;(eq? #t (ly:grob-property elt symbol))
529     (not (eq? #f (memq symbol (ly:grob-property elt 'interfaces))))))
530
531 (define-public ((outputproperty-compatibility func sym val) grob g-context ao-context)
532   (if (func grob)
533       (set! (ly:grob-property grob sym) val)))
534
535
536 (define-public ((set-output-property grob-name symbol val)  grob grob-c context)
537   "Usage:
538
539 \\applyoutput #(set-output-property 'Clef 'extra-offset '(0 . 1))
540
541 "
542   (let ((meta (ly:grob-property grob 'meta)))
543     (if (equal?  (cdr (assoc 'name meta)) grob-name)
544         (set! (ly:grob-property grob symbol) val))))
545
546
547 ;;
548 (define-public (smart-bar-check n)
549   "Make  a bar check that checks for a specific bar number. 
550 "
551   (let ((m (make-music 'ApplyContext)))
552     (define (checker tr)
553       (let* ((bn (ly:context-property tr 'currentBarNumber)))
554         (if (= bn n)
555             #t
556             (ly:error
557              ;; FIXME: uncomprehensable message
558              (_ "Bar check failed.  Expect to be at ~a, instead at ~a")
559              n bn))))
560     (set! (ly:music-property m 'procedure) checker)
561     m))
562
563 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
564 ;; warn for bare chords at start.
565
566 (define (has-request-chord elts)
567   (reduce (lambda (x y) (or x y)) #f
568           (map (lambda (x)
569                  (equal? (ly:music-property x 'name) 'RequestChord))
570                elts)))
571
572 (define (ly:music-message music msg)
573   (let ((ip (ly:music-property music 'origin)))
574     (if (ly:input-location? ip)
575         (ly:input-message ip msg)
576         (ly:warning msg))))
577
578 (define (check-start-chords music)
579   "Check music expression for a Simultaneous_music containing notes\n(ie. Request_chords),
580 without context specification. Called  from parser."
581   (let ((es (ly:music-property music 'elements))
582         (e (ly:music-property music 'element))
583         (name (ly:music-property music 'name)))
584     (cond ((equal? name "Context_specced_music") #t)
585           ((equal? name "Simultaneous_music")
586            (if (has-request-chord es)
587                (ly:music-message music "Starting score with a chord.\nInsert an explicit \\context before chord")
588                (map check-start-chords es)))
589           ((equal? name "SequentialMusic")
590            (if (pair? es)
591                (check-start-chords (car es))))
592           (else (if (ly:music? e) (check-start-chords e)))))
593   music)
594
595
596
597 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
598 ;;
599 ;; setting stuff for grace context.
600 ;;
601
602 (define (vector-extend v x)
603   "Make a new vector consisting of V, with X added to the end."
604   (let* ((n (vector-length v))
605          (nv (make-vector (+ n 1) '())))
606     (vector-move-left! v 0 n nv 0)
607     (vector-set! nv n x)
608     nv))
609
610 (define (vector-map f v)
611   "Map  F over V. This function returns nothing."
612   (do ((n (vector-length v))
613        (i 0 (+ i 1)))
614       ((>= i n))
615     (f (vector-ref v i))))
616
617 (define (vector-reverse-map f v)
618   "Map  F over V, N to 0 order. This function returns nothing."
619   (do ((i (- (vector-length v) 1) (- i 1)))
620       ((< i 0))
621     (f (vector-ref v i))))
622
623 ;; TODO:  make a remove-grace-property too.
624 (define-public (add-grace-property context-name grob sym val)
625   "Set SYM=VAL for GROB in CONTEXT-NAME. "
626   (define (set-prop context)
627     (let* ((where (ly:context-property-where-defined context 'graceSettings))
628            (current (ly:context-property where 'graceSettings))
629            (new-settings (append current
630                                  (list (list context-name grob sym val)))))
631       (ly:context-set-property! where 'graceSettings new-settings)))
632   (ly:export (context-spec-music (make-apply-context set-prop) 'Voice)))
633
634
635
636 (defmacro-public def-grace-function (start stop)
637   `(def-music-function (parser location music) (ly:music?)
638      (make-music 'GraceMusic
639                  'origin location
640                  'element (make-music 'SequentialMusic
641                                       'elements (list (ly:music-deep-copy ,start)
642                                                       music
643                                                       (ly:music-deep-copy ,stop))))))
644
645 (defmacro-public def-music-function (args signature . body)
646   "Helper macro for `ly:make-music-function'.
647 Syntax:
648   (def-music-function (parser location arg1 arg2 ...) (arg1-type? arg2-type? ...)
649     ...function body...)
650 "
651   `(ly:make-music-function (list ,@signature)
652                            (lambda (,@args)
653                              ,@body)))
654
655
656 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
657
658 (define-public (cue-substitute quote-music)
659   "Must happen after quote-substitute."
660   
661   (if (vector? (ly:music-property quote-music 'quoted-events))
662       (let* ((dir (ly:music-property quote-music 'quoted-voice-direction))
663              (main-voice (if (eq? 1 dir) 1 0))
664              (cue-voice (if (eq? 1 dir) 0 1))
665              (main-music (ly:music-property quote-music 'element))
666              (return-value quote-music))
667         
668         (if (or (eq? 1 dir) (eq? -1 dir))
669             
670             ;; if we have stem dirs, change both quoted and main music
671             ;; to have opposite stems.
672             (begin
673               (set! return-value
674
675                     ;; cannot context-spec Quote-music, since context
676                     ;; for the quotes is determined in the iterator.
677                     (make-sequential-music
678                      (list
679                       (context-spec-music (make-voice-props-set cue-voice) 'CueVoice "cue")
680                       quote-music
681                       (context-spec-music (make-voice-props-revert)  'CueVoice "cue"))))
682               (set! main-music
683                     (make-sequential-music
684                      (list
685                       (make-voice-props-set main-voice)
686                       main-music
687                       (make-voice-props-revert))))
688               (set! (ly:music-property quote-music 'element) main-music)))
689
690         return-value)
691       quote-music))
692
693 (define-public ((quote-substitute quote-tab) music)
694   (let* ((quoted-name (ly:music-property music 'quoted-music-name))
695          (quoted-vector (if (string? quoted-name)
696                             (hash-ref quote-tab quoted-name #f)
697                             #f)))
698     
699     (if (string? quoted-name)
700         (if  (vector? quoted-vector)
701              (set! (ly:music-property music 'quoted-events) quoted-vector)
702              (ly:warning (_ "can't find quoted music `~S'" quoted-name))))
703     music))
704
705
706 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
707 ;; switch it on here, so parsing and init isn't checked (too slow!)
708 ;;
709 ;; automatic music transformations.
710
711 (define (switch-on-debugging m)
712   (if (defined? 'set-debug-cell-accesses!)
713       (set-debug-cell-accesses! 15000))
714   m)
715
716 (define (music-check-error music)
717   (define found #f)
718   (define (signal m)
719     (if (and (ly:music? m)
720              (eq? (ly:music-property m 'error-found) #t))
721         (set! found #t)))
722   
723   (for-each signal (ly:music-property music 'elements))
724   (signal (ly:music-property music 'element))
725
726   (if found
727       (set! (ly:music-property music 'error-found) #t))
728   music)
729
730 (define (precompute-music-length music)
731   (set! (ly:music-property music 'length)
732         (ly:music-length music))
733   music)
734
735 (define (skip-to-last music parser)
736
737   "Replace MUSIC by
738
739 << { \\set skipTypesetting = ##t
740      LENGTHOF(\\showLastLength)
741      \\set skipTypesetting = ##t  }
742     MUSIC >>
743
744 if appropriate.
745  "
746   (let*
747       ((show-last  (ly:parser-lookup parser 'showLastLength)))
748     
749     (if (ly:music? show-last)
750         (let*
751             ((orig-length (ly:music-length music))
752              (skip-length (ly:moment-sub orig-length (ly:music-length show-last))))
753
754           (make-simultaneous-music
755            (list
756             (make-sequential-music
757              (list
758               (context-spec-music (make-property-set 'skipTypesetting #t) 'Score)
759               (make-music 'SkipMusic 'duration
760                           (ly:make-duration 0 0
761                                             (ly:moment-main-numerator skip-length)
762                                             (ly:moment-main-denominator skip-length)))
763               (context-spec-music (make-property-set 'skipTypesetting #f) 'Score)))
764             music)))
765         music)))
766     
767
768 (define-public toplevel-music-functions
769   (list
770    (lambda (music parser) (voicify-music music))
771    (lambda (x parser) (music-map glue-mm-rest-texts x))
772    (lambda (x parser) (music-map music-check-error x))
773    (lambda (x parser) (music-map precompute-music-length x))
774    (lambda (music parser)
775
776      (music-map (quote-substitute (ly:parser-lookup parser 'musicQuotes))  music))
777    
778    ;; switch-on-debugging
779    (lambda (x parser) (music-map cue-substitute x))
780  
781    (lambda (x parser)
782      (skip-to-last x parser)
783    )))
784
785 ;;;;;;;;;;;;;;;;;
786 ;; lyrics
787
788 (define (apply-durations lyric-music durations) 
789   (define (apply-duration music)
790     (if (and (not (equal? (ly:music-length music) ZERO-MOMENT))
791              (ly:duration?  (ly:music-property music 'duration)))
792         (begin
793           (set! (ly:music-property music 'duration) (car durations))
794           (set! durations (cdr durations)))))
795   
796   (music-map apply-duration lyric-music))
797
798
799 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
800 ;;
801
802 (define-public ((add-balloon-text object-name text off) grob orig-context cur-context)
803   "Usage: see input/regression/balloon.ly "
804   (let* ((meta (ly:grob-property grob 'meta))
805          (nm (if (pair? meta) (cdr (assoc 'name meta)) "nonexistant"))
806          (cb (ly:grob-property grob 'print-function)))
807     (if (equal? nm object-name)
808         (begin
809           (set! (ly:grob-property grob 'print-function) Balloon_interface::print)
810           (set! (ly:grob-property grob 'balloon-original-callback) cb)
811           (set! (ly:grob-property grob 'balloon-text) text)
812           (set! (ly:grob-property grob 'balloon-text-offset) off)
813           (set! (ly:grob-property grob 'balloon-text-props) '((font-family . roman)))))))
814
815 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
816 ;; accidentals
817
818 (define-public (set-accidentals-properties extra-natural
819                                            auto-accs auto-cauts
820                                            context)
821   (context-spec-music
822    (make-sequential-music
823     (append (if (boolean? extra-natural)
824                 (list (make-property-set 'extraNatural extra-natural))
825                 '())
826             (list (make-property-set 'autoAccidentals auto-accs)
827                   (make-property-set 'autoCautionaries auto-cauts))))
828    context))
829
830 (define-public (set-accidental-style style . rest)
831   "Set accidental style to STYLE. Optionally takes a context argument,
832 e.g. 'Staff or 'Voice. The context defaults to Voice, except for piano styles, which
833 use GrandStaff as a context. "
834   (let ((context (if (pair? rest)
835                      (car rest) 'Staff))
836         (pcontext (if (pair? rest)
837                       (car rest) 'GrandStaff)))
838     (ly:export
839      (cond
840       ;; accidentals as they were common in the 18th century.
841       ((equal? style 'default)
842        (set-accidentals-properties #t '(Staff (same-octave . 0))
843                                    '() context))
844       ;; accidentals from one voice do NOT get cancelled in other voices
845       ((equal? style 'voice)
846        (set-accidentals-properties #t '(Voice (same-octave . 0))
847                                    '() context))
848       ;; accidentals as suggested by Kurt Stone, Music Notation in the 20th century.
849       ;; This includes all the default accidentals, but accidentals also needs cancelling
850       ;; in other octaves and in the next measure.
851       ((equal? style 'modern)
852        (set-accidentals-properties #f '(Staff (same-octave . 0) (any-octave . 0) (same-octave . 1))
853                                    '()  context))
854       ;; the accidentals that Stone adds to the old standard as cautionaries
855       ((equal? style 'modern-cautionary)
856        (set-accidentals-properties #f '(Staff (same-octave . 0))
857                                    '(Staff (any-octave . 0) (same-octave . 1))
858                                    context))
859       ;; Multivoice accidentals to be read both by musicians playing one voice
860       ;; and musicians playing all voices.
861       ;; Accidentals are typeset for each voice, but they ARE cancelled across voices.
862       ((equal? style 'modern-voice)
863        (set-accidentals-properties  #f
864                                     '(Voice (same-octave . 0) (any-octave . 0) (same-octave . 1)
865                                             Staff (same-octave . 0) (any-octave . 0) (same-octave . 1))
866                                     '()
867                                     context))
868       ;; same as modernVoiceAccidental eccept that all special accidentals are typeset
869       ;; as cautionaries
870       ((equal? style 'modern-voice-cautionary)
871        (set-accidentals-properties #f
872                                    '(Voice (same-octave . 0))
873                                    '(Voice (any-octave . 0) (same-octave . 1)
874                                            Staff (same-octave . 0) (any-octave . 0) (same-octave . 1))
875                                    context))
876       ;; stone's suggestions for accidentals on grand staff.
877       ;; Accidentals are cancelled across the staves in the same grand staff as well
878       ((equal? style 'piano)
879        (set-accidentals-properties #f
880                                    '(Staff (same-octave . 0)
881                                            (any-octave . 0) (same-octave . 1)
882                                            GrandStaff (any-octave . 0) (same-octave . 1))
883                                    '()
884                                    pcontext))
885       ((equal? style 'piano-cautionary)
886        (set-accidentals-properties #f
887                                    '(Staff (same-octave . 0))
888                                    '(Staff (any-octave . 0) (same-octave . 1)
889                                            GrandStaff (any-octave . 0) (same-octave . 1))
890                                    pcontext))
891       ;; do not set localKeySignature when a note alterated differently from
892       ;; localKeySignature is found.
893       ;; Causes accidentals to be printed at every note instead of
894       ;; remembered for the duration of a measure.
895       ;; accidentals not being remembered, causing accidentals always to be typeset relative to the time signature
896       ((equal? style 'forget)
897        (set-accidentals-properties '()
898                                    '(Staff (same-octave . -1))
899                                    '() context))
900       ;; Do not reset the key at the start of a measure.  Accidentals will be
901       ;; printed only once and are in effect until overridden, possibly many
902       ;; measures later.
903       ((equal? style 'no-reset)
904        (set-accidentals-properties '()
905                                    '(Staff (same-octave . #t))
906                                    '()
907                                    context))
908       (else
909        (ly:warning (_ "unknown accidental style: ~S" style))
910        (make-sequential-music '()))))))
911
912 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
913
914 (define-public (skip-of-length mus)
915   "Create a skip of exactly the same length as MUS."
916   (let* ((skip
917           (make-music
918            'SkipEvent
919            'duration (ly:make-duration 0 0))))
920
921     (make-event-chord (list (ly:music-compress skip (ly:music-length mus))))))
922
923 (define-public (mmrest-of-length mus)
924   "Create a mmrest of exactly the same length as MUS."
925   
926   (let* ((skip
927           (make-multi-measure-rest
928            (ly:make-duration 0 0) '())))
929     (ly:music-compress skip (ly:music-length mus))
930     skip))