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