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