]> git.donarmstrong.com Git - lilypond.git/blob - scm/music-functions.scm
* lily/score.cc (Score): unprotect copy of Output_def. Plugs
[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           (display old-name)
230           (if (equal? old-name 'TremoloRepeatedMusic)
231               (let* ((seq-arg? (memq 'sequential-music
232                                      (ly:music-property e 'types)))
233                      (count  (ly:music-property music 'repeat-count))
234                      (dot-shift (if (= 0 (remainder count 3))
235                                     -1 0)))
236
237                 (if (= 0 -1)
238                     (set! count (* 2 (quotient count 3))))
239                 
240                 (shift-duration-log music (+ (if seq-arg? 1 0)
241                                              (ly:intlog2 count)) dot-shift)
242                 
243                 (if seq-arg?
244                     (ly:music-compress e (ly:make-moment (length (ly:music-property
245                                                                   e 'elements)) 1)))))))
246           
247     
248     (if (pair? es)
249         (set! (ly:music-property music 'elements)
250               (map unfold-repeats es)))
251     (if (ly:music? e)
252         (set! (ly:music-property music 'element)
253               (unfold-repeats e)))
254     music))
255
256 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
257 ;; property setting music objs.
258
259 (define-public (make-grob-property-set grob gprop val)
260   "Make a Music expression that sets GPROP to VAL in GROB. Does a pop first,
261 i.e.  this is not an override"
262   (make-music 'OverrideProperty
263               'symbol grob
264               'grob-property gprop
265               'grob-value val
266               'pop-first #t))
267
268 (define-public (make-grob-property-override grob gprop val)
269   "Make a Music expression that sets GPROP to VAL in GROB. Does a pop first,
270 i.e.  this is not an override"
271   (make-music 'OverrideProperty
272               'symbol grob
273               'grob-property gprop
274               'grob-value val))
275
276 (define-public (make-grob-property-revert grob gprop)
277   "Revert the grob property GPROP for GROB."
278   (make-music 'OverrideProperty
279               'symbol grob
280               'grob-property gprop))
281
282 (define direction-polyphonic-grobs
283   '(Stem Tie Rest Slur Script TextScript Dots DotColumn Fingering))
284
285 (define-safe-public (make-voice-props-set n)
286   (make-sequential-music
287    (append
288     (map (lambda (x) (make-grob-property-set x 'direction
289                                              (if (odd? n) -1 1)))
290          direction-polyphonic-grobs)
291     (list
292      (make-grob-property-set 'NoteColumn 'horizontal-shift (quotient n 2))
293      (make-grob-property-set 'MultiMeasureRest 'staff-position (if (odd? n) -4 4)))))) 
294
295 (define-safe-public (make-voice-props-revert)
296   (make-sequential-music
297    (append
298     (map (lambda (x) (make-grob-property-revert x 'direction))
299          direction-polyphonic-grobs)
300     (list (make-grob-property-revert 'NoteColumn 'horizontal-shift))
301     (list (make-grob-property-revert 'MultiMeasureRest 'staff-position)))))
302
303
304 (define-safe-public (context-spec-music m context #:optional id)
305   "Add \\context CONTEXT = ID to M. "
306   (let ((cm (make-music 'ContextSpeccedMusic
307                         'element m
308                         'context-type context)))
309     (if (string? id)
310         (set! (ly:music-property cm 'context-id) id))
311     cm))
312
313 (define-public (descend-to-context m context)
314   "Like context-spec-music, but only descending. "
315   (let ((cm (context-spec-music m context)))
316     (ly:music-set-property! cm 'descend-only #t)
317     cm))
318
319 (define-public (make-non-relative-music mus)
320   (make-music 'UnrelativableMusic
321               'element mus))
322
323 (define-public (make-apply-context func)
324   (make-music 'ApplyContext
325               'procedure func))
326
327 (define-public (make-sequential-music elts)
328   (make-music 'SequentialMusic
329               'elements elts))
330
331 (define-public (make-simultaneous-music elts)
332   (make-music 'SimultaneousMusic
333               'elements elts))
334
335 (define-safe-public (make-event-chord elts)
336   (make-music 'EventChord
337               'elements elts))
338
339 (define-public (make-skip-music dur)
340   (make-music 'SkipMusic
341               'duration dur))
342
343 (define-public (make-grace-music music)
344   (make-music 'GraceMusic
345               'element music))
346
347 ;;;;;;;;;;;;;;;;
348
349 ;; mmrest
350 (define-public (make-multi-measure-rest duration location)
351   (make-music 'MultiMeasureRestMusicGroup
352               'origin location
353               'elements (list (make-music 'BarCheck
354                                           'origin location)
355                               (make-event-chord (list (make-music 'MultiMeasureRestEvent
356                                                                   'origin location
357                                                                   'duration duration)))
358                               (make-music 'BarCheck
359                                           'origin location))))
360
361 (define-public (glue-mm-rest-texts music)
362   "Check if we have R1*4-\\markup { .. }, and if applicable convert to
363 a property set for MultiMeasureRestNumber."
364   (define (script-to-mmrest-text script-music)
365     "Extract 'direction and 'text from SCRIPT-MUSIC, and transform into property sets."
366     (let ((dir (ly:music-property script-music 'direction))
367           (p   (make-music 'MultiMeasureTextEvent
368                            'text (ly:music-property script-music 'text))))
369       (if (ly:dir? dir)
370           (set! (ly:music-property p 'direction) dir))
371       p))
372   (if (eq? (ly:music-property music 'name) 'MultiMeasureRestMusicGroup)
373       (let* ((text? (lambda (x) (memq 'script-event (ly:music-property x 'types))))
374              (es (ly:music-property  music 'elements))
375              (texts (map script-to-mmrest-text  (filter text? es)))
376              (others (remove text? es)))
377         (if (pair? texts)
378             (set! (ly:music-property music 'elements)
379                   (cons (make-event-chord texts) others)))))
380   music)
381
382
383 (define-public (make-property-set sym val)
384   (make-music 'PropertySet
385               'symbol sym
386               'value val))
387
388 (define-public (make-ottava-set octavation)
389   (let ((m (make-music 'ApplyContext)))
390     (define (ottava-modify context)
391       "Either reset middleCPosition to the stored original, or remember
392 old middleCPosition, add OCTAVATION to middleCPosition, and set
393 OTTAVATION to `8va', or whatever appropriate."      
394       (if (number? (ly:context-property  context 'middleCPosition))
395           (if (= octavation 0)
396               (let ((where (ly:context-property-where-defined context 'middleCPosition))
397                     (oc0 (ly:context-property context 'originalCentralCPosition)))
398                 (ly:context-set-property! context 'middleCPosition oc0)
399                 (ly:context-unset-property where 'originalCentralCPosition)
400                 (ly:context-unset-property where 'ottavation))
401               (let* ((where (ly:context-property-where-defined context 'middleCPosition))
402                      (c0 (ly:context-property context 'middleCPosition))
403                      (new-c0 (+ c0 (* -7 octavation)))
404                      (string (cdr (assoc octavation '((2 . "15ma")
405                                                       (1 . "8va")
406                                                       (0 . #f)
407                                                       (-1 . "8va bassa")
408                                                       (-2 . "15ma bassa"))))))
409                 (ly:context-set-property! context 'middleCPosition new-c0)
410                 (ly:context-set-property! context 'originalCentralCPosition c0)
411                 (ly:context-set-property! context 'ottavation string)))))
412     (set! (ly:music-property m 'procedure) ottava-modify)
413     (context-spec-music m 'Staff)))
414
415 (define-public (set-octavation ottavation)
416   (ly:export (make-ottava-set ottavation)))
417
418 (define-public (make-time-signature-set num den . rest)
419   "Set properties for time signature NUM/DEN.  Rest can contain a list
420 of beat groupings "
421   (let* ((set1 (make-property-set 'timeSignatureFraction (cons num den)))
422          (beat (ly:make-moment 1 den))
423          (len  (ly:make-moment num den))
424          (set2 (make-property-set 'beatLength beat))
425          (set3 (make-property-set 'measureLength len))
426          (set4 (make-property-set 'beatGrouping (if (pair? rest)
427                                                     (car rest)
428                                                     '())))
429          (basic  (list set1 set2 set3 set4)))
430     (descend-to-context
431      (context-spec-music (make-sequential-music basic) 'Timing) 'Score)))
432
433 (define-public (make-mark-set label)
434   "Make the music for the \\mark command."  
435   (let* ((set (if (integer? label)
436                   (context-spec-music (make-property-set 'rehearsalMark label)
437                                       'Score)
438                   #f))
439          (ev (make-music 'MarkEvent))
440          (ch (make-event-chord (list ev))))
441     (if set
442         (make-sequential-music (list set ch))
443         (begin
444           (set! (ly:music-property ev 'label) label)
445           ch))))
446
447 (define-public (set-time-signature num den . rest)
448   (ly:export (apply make-time-signature-set `(,num ,den . ,rest))))
449
450 (define-safe-public (make-penalty-music pen page-pen)
451   (make-music 'BreakEvent
452               'penalty pen
453               'page-penalty page-pen))
454
455 (define-safe-public (make-articulation name)
456   (make-music 'ArticulationEvent
457               'articulation-type name))
458
459 (define-public (make-lyric-event string duration)
460   (make-music 'LyricEvent
461               'duration duration
462               'text string))
463
464 (define-safe-public (make-span-event type spandir)
465   (make-music type
466               'span-direction spandir))
467
468 (define-public (set-mus-properties! m alist)
469   "Set all of ALIST as properties of M." 
470   (if (pair? alist)
471       (begin
472         (set! (ly:music-property m (caar alist)) (cdar alist))
473         (set-mus-properties! m (cdr alist)))))
474
475 (define-public (music-separator? m)
476   "Is M a separator?"
477   (let ((ts (ly:music-property m 'types)))
478     (memq 'separator ts)))
479
480 ;;; splitting chords into voices.
481 (define (voicify-list lst number)
482   "Make a list of Musics.
483
484    voicify-list :: [ [Music ] ] -> number -> [Music]
485    LST is a list music-lists.
486
487    NUMBER is 0-base, i.e. Voice=1 (upstems) has number 0.
488 "
489   (if (null? lst)
490       '()
491       (cons (context-spec-music
492              (make-sequential-music
493               (list (make-voice-props-set number)
494                     (make-simultaneous-music (car lst))))
495              'Voice  (number->string (1+ number)))
496             (voicify-list (cdr lst) (1+ number)))))
497
498 (define (voicify-chord ch)
499   "Split the parts of a chord into different Voices using separator"
500   (let ((es (ly:music-property ch 'elements)))
501     (set! (ly:music-property  ch 'elements)
502           (voicify-list (split-list es music-separator?) 0))
503     ch))
504
505 (define-public (voicify-music m)
506   "Recursively split chords that are separated with \\ "
507   (if (not (ly:music? m))
508       (ly:error (_ "music expected: ~S") m))
509   (let ((es (ly:music-property m 'elements))
510         (e (ly:music-property m 'element)))
511
512     (if (pair? es)
513         (set! (ly:music-property m 'elements) (map voicify-music es)))
514     (if (ly:music? e)
515         (set! (ly:music-property m 'element)  (voicify-music e)))
516     (if (and (equal? (ly:music-property m 'name) 'SimultaneousMusic)
517              (reduce (lambda (x y ) (or x y)) #f (map music-separator? es)))
518         (set! m (context-spec-music (voicify-chord m) 'Staff)))
519     m))
520
521 (define-public (empty-music)
522   (ly:export (make-music 'Music)))
523 ;;;
524
525                                         ; Make a function that checks score element for being of a specific type. 
526 (define-public (make-type-checker symbol)
527   (lambda (elt)
528     ;;(display  symbol)
529     ;;(eq? #t (ly:grob-property elt symbol))
530     (not (eq? #f (memq symbol (ly:grob-property elt 'interfaces))))))
531
532 (define-public ((outputproperty-compatibility func sym val) grob g-context ao-context)
533   (if (func grob)
534       (set! (ly:grob-property grob sym) val)))
535
536
537 (define-public ((set-output-property grob-name symbol val)  grob grob-c context)
538   "Usage:
539
540 \\applyoutput #(set-output-property 'Clef 'extra-offset '(0 . 1))
541
542 "
543   (let ((meta (ly:grob-property grob 'meta)))
544     (if (equal?  (cdr (assoc 'name meta)) grob-name)
545         (set! (ly:grob-property grob symbol) val))))
546
547
548 ;;
549 (define-public (smart-bar-check n)
550   "Make  a bar check that checks for a specific bar number. 
551 "
552   (let ((m (make-music 'ApplyContext)))
553     (define (checker tr)
554       (let* ((bn (ly:context-property tr 'currentBarNumber)))
555         (if (= bn n)
556             #t
557             (ly:error
558              ;; FIXME: uncomprehensable message
559              (_ "Bar check failed.  Expect to be at ~a, instead at ~a")
560              n bn))))
561     (set! (ly:music-property m 'procedure) checker)
562     m))
563
564 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
565 ;; warn for bare chords at start.
566
567 (define (has-request-chord elts)
568   (reduce (lambda (x y) (or x y)) #f
569           (map (lambda (x)
570                  (equal? (ly:music-property x 'name) 'RequestChord))
571                elts)))
572
573 (define (ly:music-message music msg)
574   (let ((ip (ly:music-property music 'origin)))
575     (if (ly:input-location? ip)
576         (ly:input-message ip msg)
577         (ly:warning msg))))
578
579 (define (check-start-chords music)
580   "Check music expression for a Simultaneous_music containing notes\n(ie. Request_chords),
581 without context specification. Called  from parser."
582   (let ((es (ly:music-property music 'elements))
583         (e (ly:music-property music 'element))
584         (name (ly:music-property music 'name)))
585     (cond ((equal? name "Context_specced_music") #t)
586           ((equal? name "Simultaneous_music")
587            (if (has-request-chord es)
588                (ly:music-message music "Starting score with a chord.\nInsert an explicit \\context before chord")
589                (map check-start-chords es)))
590           ((equal? name "SequentialMusic")
591            (if (pair? es)
592                (check-start-chords (car es))))
593           (else (if (ly:music? e) (check-start-chords e)))))
594   music)
595
596
597
598 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
599 ;;
600 ;; setting stuff for grace context.
601 ;;
602
603 (define (vector-extend v x)
604   "Make a new vector consisting of V, with X added to the end."
605   (let* ((n (vector-length v))
606          (nv (make-vector (+ n 1) '())))
607     (vector-move-left! v 0 n nv 0)
608     (vector-set! nv n x)
609     nv))
610
611 (define (vector-map f v)
612   "Map  F over V. This function returns nothing."
613   (do ((n (vector-length v))
614        (i 0 (+ i 1)))
615       ((>= i n))
616     (f (vector-ref v i))))
617
618 (define (vector-reverse-map f v)
619   "Map  F over V, N to 0 order. This function returns nothing."
620   (do ((i (- (vector-length v) 1) (- i 1)))
621       ((< i 0))
622     (f (vector-ref v i))))
623
624 ;; TODO:  make a remove-grace-property too.
625 (define-public (add-grace-property context-name grob sym val)
626   "Set SYM=VAL for GROB in CONTEXT-NAME. "
627   (define (set-prop context)
628     (let* ((where (ly:context-property-where-defined context 'graceSettings))
629            (current (ly:context-property where 'graceSettings))
630            (new-settings (append current
631                                  (list (list context-name grob sym val)))))
632       (ly:context-set-property! where 'graceSettings new-settings)))
633   (ly:export (context-spec-music (make-apply-context set-prop) 'Voice)))
634
635
636
637 (defmacro-public def-grace-function (start stop)
638   `(def-music-function (parser location music) (ly:music?)
639      (make-music 'GraceMusic
640                  'origin location
641                  'element (make-music 'SequentialMusic
642                                       'elements (list (ly:music-deep-copy ,start)
643                                                       music
644                                                       (ly:music-deep-copy ,stop))))))
645
646 (defmacro-public def-music-function (args signature . body)
647   "Helper macro for `ly:make-music-function'.
648 Syntax:
649   (def-music-function (parser location arg1 arg2 ...) (arg1-type? arg2-type? ...)
650     ...function body...)
651 "
652   `(ly:make-music-function (list ,@signature)
653                            (lambda (,@args)
654                              ,@body)))
655
656
657 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
658
659 (define-public (cue-substitute quote-music)
660   "Must happen after quote-substitute."
661   
662   (if (vector? (ly:music-property quote-music 'quoted-events))
663       (let* ((dir (ly:music-property quote-music 'quoted-voice-direction))
664              (main-voice (if (eq? 1 dir) 1 0))
665              (cue-voice (if (eq? 1 dir) 0 1))
666              (main-music (ly:music-property quote-music 'element))
667              (return-value quote-music))
668         
669         (if (or (eq? 1 dir) (eq? -1 dir))
670             
671             ;; if we have stem dirs, change both quoted and main music
672             ;; to have opposite stems.
673             (begin
674               (set! return-value
675
676                     ;; cannot context-spec Quote-music, since context
677                     ;; for the quotes is determined in the iterator.
678                     (make-sequential-music
679                      (list
680                       (context-spec-music (make-voice-props-set cue-voice) 'CueVoice "cue")
681                       quote-music
682                       (context-spec-music (make-voice-props-revert)  'CueVoice "cue"))))
683               (set! main-music
684                     (make-sequential-music
685                      (list
686                       (make-voice-props-set main-voice)
687                       main-music
688                       (make-voice-props-revert))))
689               (set! (ly:music-property quote-music 'element) main-music)))
690
691         return-value)
692       quote-music))
693
694 (define-public ((quote-substitute quote-tab) music)
695   (let* ((quoted-name (ly:music-property music 'quoted-music-name))
696          (quoted-vector (if (string? quoted-name)
697                             (hash-ref quote-tab quoted-name #f)
698                             #f)))
699     
700     (if (string? quoted-name)
701         (if  (vector? quoted-vector)
702              (set! (ly:music-property music 'quoted-events) quoted-vector)
703              (ly:warning (_ "can't find quoted music `~S'" quoted-name))))
704     music))
705
706
707 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
708 ;; switch it on here, so parsing and init isn't checked (too slow!)
709 ;;
710 ;; automatic music transformations.
711
712 (define (switch-on-debugging m)
713   (if (defined? 'set-debug-cell-accesses!)
714       (set-debug-cell-accesses! 15000))
715   m)
716
717 (define (music-check-error music)
718   (define found #f)
719   (define (signal m)
720     (if (and (ly:music? m)
721              (eq? (ly:music-property m 'error-found) #t))
722         (set! found #t)))
723   
724   (for-each signal (ly:music-property music 'elements))
725   (signal (ly:music-property music 'element))
726
727   (if found
728       (set! (ly:music-property music 'error-found) #t))
729   music)
730
731 (define (precompute-music-length music)
732   (set! (ly:music-property music 'length)
733         (ly:music-length music))
734   music)
735
736 (define-public toplevel-music-functions
737   (list
738    (lambda (music parser) (voicify-music music))
739    (lambda (x parser) (music-map glue-mm-rest-texts x))
740    (lambda (x parser) (music-map music-check-error x))
741    (lambda (x parser) (music-map precompute-music-length x))
742    (lambda (music parser)
743
744      (music-map (quote-substitute (ly:parser-lookup parser 'musicQuotes))  music))
745    
746    ;; switch-on-debugging
747    (lambda (x parser) (music-map cue-substitute x))
748 ;   (lambda (x parser) (music-map display-scheme-music x))
749
750    ))
751
752 ;;;;;;;;;;;;;;;;;
753 ;; lyrics
754
755 (define (apply-durations lyric-music durations) 
756   (define (apply-duration music)
757     (if (and (not (equal? (ly:music-length music) ZERO-MOMENT))
758              (ly:duration?  (ly:music-property music 'duration)))
759         (begin
760           (set! (ly:music-property music 'duration) (car durations))
761           (set! durations (cdr durations)))))
762   
763   (music-map apply-duration lyric-music))
764
765
766 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
767 ;;
768
769 (define-public ((add-balloon-text object-name text off) grob orig-context cur-context)
770   "Usage: see input/regression/balloon.ly "
771   (let* ((meta (ly:grob-property grob 'meta))
772          (nm (if (pair? meta) (cdr (assoc 'name meta)) "nonexistant"))
773          (cb (ly:grob-property grob 'print-function)))
774     (if (equal? nm object-name)
775         (begin
776           (set! (ly:grob-property grob 'print-function) Balloon_interface::print)
777           (set! (ly:grob-property grob 'balloon-original-callback) cb)
778           (set! (ly:grob-property grob 'balloon-text) text)
779           (set! (ly:grob-property grob 'balloon-text-offset) off)
780           (set! (ly:grob-property grob 'balloon-text-props) '((font-family . roman)))))))
781
782 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
783 ;; accidentals
784
785 (define-public (set-accidentals-properties extra-natural
786                                            auto-accs auto-cauts
787                                            context)
788   (context-spec-music
789    (make-sequential-music
790     (append (if (boolean? extra-natural)
791                 (list (make-property-set 'extraNatural extra-natural))
792                 '())
793             (list (make-property-set 'autoAccidentals auto-accs)
794                   (make-property-set 'autoCautionaries auto-cauts))))
795    context))
796
797 (define-public (set-accidental-style style . rest)
798   "Set accidental style to STYLE. Optionally takes a context argument,
799 e.g. 'Staff or 'Voice. The context defaults to Voice, except for piano styles, which
800 use GrandStaff as a context. "
801   (let ((context (if (pair? rest)
802                      (car rest) 'Staff))
803         (pcontext (if (pair? rest)
804                       (car rest) 'GrandStaff)))
805     (ly:export
806      (cond
807       ;; accidentals as they were common in the 18th century.
808       ((equal? style 'default)
809        (set-accidentals-properties #t '(Staff (same-octave . 0))
810                                    '() context))
811       ;; accidentals from one voice do NOT get cancelled in other voices
812       ((equal? style 'voice)
813        (set-accidentals-properties #t '(Voice (same-octave . 0))
814                                    '() context))
815       ;; accidentals as suggested by Kurt Stone, Music Notation in the 20th century.
816       ;; This includes all the default accidentals, but accidentals also needs cancelling
817       ;; in other octaves and in the next measure.
818       ((equal? style 'modern)
819        (set-accidentals-properties #f '(Staff (same-octave . 0) (any-octave . 0) (same-octave . 1))
820                                    '()  context))
821       ;; the accidentals that Stone adds to the old standard as cautionaries
822       ((equal? style 'modern-cautionary)
823        (set-accidentals-properties #f '(Staff (same-octave . 0))
824                                    '(Staff (any-octave . 0) (same-octave . 1))
825                                    context))
826       ;; Multivoice accidentals to be read both by musicians playing one voice
827       ;; and musicians playing all voices.
828       ;; Accidentals are typeset for each voice, but they ARE cancelled across voices.
829       ((equal? style 'modern-voice)
830        (set-accidentals-properties  #f
831                                     '(Voice (same-octave . 0) (any-octave . 0) (same-octave . 1)
832                                             Staff (same-octave . 0) (any-octave . 0) (same-octave . 1))
833                                     '()
834                                     context))
835       ;; same as modernVoiceAccidental eccept that all special accidentals are typeset
836       ;; as cautionaries
837       ((equal? style 'modern-voice-cautionary)
838        (set-accidentals-properties #f
839                                    '(Voice (same-octave . 0))
840                                    '(Voice (any-octave . 0) (same-octave . 1)
841                                            Staff (same-octave . 0) (any-octave . 0) (same-octave . 1))
842                                    context))
843       ;; stone's suggestions for accidentals on grand staff.
844       ;; Accidentals are cancelled across the staves in the same grand staff as well
845       ((equal? style 'piano)
846        (set-accidentals-properties #f
847                                    '(Staff (same-octave . 0)
848                                            (any-octave . 0) (same-octave . 1)
849                                            GrandStaff (any-octave . 0) (same-octave . 1))
850                                    '()
851                                    pcontext))
852       ((equal? style 'piano-cautionary)
853        (set-accidentals-properties #f
854                                    '(Staff (same-octave . 0))
855                                    '(Staff (any-octave . 0) (same-octave . 1)
856                                            GrandStaff (any-octave . 0) (same-octave . 1))
857                                    pcontext))
858       ;; do not set localKeySignature when a note alterated differently from
859       ;; localKeySignature is found.
860       ;; Causes accidentals to be printed at every note instead of
861       ;; remembered for the duration of a measure.
862       ;; accidentals not being remembered, causing accidentals always to be typeset relative to the time signature
863       ((equal? style 'forget)
864        (set-accidentals-properties '()
865                                    '(Staff (same-octave . -1))
866                                    '() context))
867       ;; Do not reset the key at the start of a measure.  Accidentals will be
868       ;; printed only once and are in effect until overridden, possibly many
869       ;; measures later.
870       ((equal? style 'no-reset)
871        (set-accidentals-properties '()
872                                    '(Staff (same-octave . #t))
873                                    '()
874                                    context))
875       (else
876        (ly:warning (_ "unknown accidental style: ~S" style))
877        (make-sequential-music '()))))))
878
879 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
880
881 (define-public (skip-of-length mus)
882   "Create a skip of exactly the same length as MUS."
883   (let* ((skip
884           (make-music
885            'SkipEvent
886            'duration (ly:make-duration 0 0))))
887
888     (make-event-chord (list (ly:music-compress skip (ly:music-length mus))))))
889
890 (define-public (mmrest-of-length mus)
891   "Create a mmrest of exactly the same length as MUS."
892   
893   (let* ((skip
894           (make-multi-measure-rest
895            (ly:make-duration 0 0) '())))
896     (ly:music-compress skip (ly:music-length mus))
897     skip))