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