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