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