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