]> git.donarmstrong.com Git - lilypond.git/blob - scm/music-functions.scm
Merge master into nested-bookparts
[lilypond.git] / scm / music-functions.scm
1 ;;;; music-functions.scm --
2 ;;;;
3 ;;;;  source file of the GNU LilyPond music typesetter
4 ;;;; 
5 ;;;; (c) 1998--2007 Jan Nieuwenhuizen <janneke@gnu.org>
6 ;;;;                 Han-Wen Nienhuys <hanwen@xs4all.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-safe-public (music-is-of-type? mus type)
20   "Does @code{mus} belong to the music class @code{type}?"
21   (memq type (ly:music-property mus 'types)))
22
23 ;; TODO move this
24 (define-public ly:grob-property
25   (make-procedure-with-setter ly:grob-property
26                               ly:grob-set-property!))
27
28 (define-public ly:prob-property
29   (make-procedure-with-setter ly:prob-property
30                               ly:prob-set-property!))
31
32 (define-public (music-map function music)
33   "Apply @var{function} to @var{music} and all of the music it contains.
34
35 First it recurses over the children, then the function is applied to MUSIC.
36 "
37   (let ((es (ly:music-property music 'elements))
38         (e (ly:music-property music 'element)))
39     (set! (ly:music-property music 'elements) 
40           (map (lambda (y) (music-map function y)) es))
41     (if (ly:music? e)
42         (set! (ly:music-property music 'element)
43               (music-map function  e)))
44     (function music)))
45
46 (define-public (music-filter pred? music)
47   "Filter out music expressions that do not satisfy PRED."
48   
49   (define (inner-music-filter pred? music)
50     "Recursive function."
51     (let* ((es (ly:music-property music 'elements))
52            (e (ly:music-property music 'element))
53            (as (ly:music-property music 'articulations))
54            (filtered-as (filter ly:music? (map (lambda (y) (inner-music-filter pred? y)) as)))
55            (filtered-e (if (ly:music? e)
56                            (inner-music-filter pred? e)
57                            e))
58            (filtered-es (filter ly:music? (map (lambda (y) (inner-music-filter pred? y)) es))))
59       (set! (ly:music-property music 'element) filtered-e)
60       (set! (ly:music-property music 'elements) filtered-es)
61       (set! (ly:music-property music 'articulations) filtered-as)
62       ;; if filtering emptied the expression, we remove it completely.
63       (if (or (not (pred? music))
64               (and (eq? filtered-es '()) (not (ly:music? e))
65                    (or (not (eq? es '()))
66                        (ly:music? e))))
67           (set! music '()))
68       music))
69
70   (set! music (inner-music-filter pred? music))
71   (if (ly:music? music)
72       music
73       (make-music 'Music)))       ;must return music.
74
75 (define-public (display-music music)
76   "Display music, not done with music-map for clarity of presentation."
77
78   (display music)
79   (display ": { ")  
80   (let ((es (ly:music-property music 'elements))
81         (e (ly:music-property music 'element)))
82     (display (ly:music-mutable-properties music))
83     (if (pair? es)
84         (begin (display "\nElements: {\n")
85                (map display-music es)
86                (display "}\n")))
87     (if (ly:music? e)
88         (begin
89           (display "\nChild:")
90           (display-music e))))
91   (display " }\n")
92   music)
93
94 ;;;
95 ;;; A scheme music pretty printer
96 ;;;
97 (define (markup-expression->make-markup markup-expression)
98   "Transform `markup-expression' into an equivalent, hopefuly readable, scheme expression.
99 For instance, 
100   \\markup \\bold \\italic hello
101 ==>
102   (markup #:line (#:bold (#:italic (#:simple \"hello\"))))"
103   (define (proc->command-keyword proc)
104     "Return a keyword, eg. `#:bold', from the `proc' function, eg. #<procedure bold-markup (layout props arg)>"
105     (let ((cmd-markup (symbol->string (procedure-name proc))))
106       (symbol->keyword (string->symbol (substring cmd-markup 0 (- (string-length cmd-markup)
107                                                                   (string-length "-markup")))))))
108   (define (transform-arg arg)
109     (cond ((and (pair? arg) (markup? (car arg))) ;; a markup list
110            (apply append (map inner-markup->make-markup arg)))
111           ((and (not (string? arg)) (markup? arg)) ;; a markup
112            (inner-markup->make-markup arg))
113           (else                                  ;; scheme arg
114            arg)))
115   (define (inner-markup->make-markup mrkup)
116     (if (string? mrkup)
117         `(#:simple ,mrkup)
118         (let ((cmd (proc->command-keyword (car mrkup)))
119               (args (map transform-arg (cdr mrkup))))
120           `(,cmd ,@args))))
121   ;; body:
122   (if (string? markup-expression)
123       markup-expression
124       `(markup ,@(inner-markup->make-markup markup-expression))))
125
126 (define-public (music->make-music obj)
127   "Generate a expression that, once evaluated, may return an object equivalent to `obj',
128 that is, for a music expression, a (make-music ...) form."
129   (cond (;; markup expression
130          (markup? obj)
131          (markup-expression->make-markup obj))
132         (;; music expression
133          (ly:music? obj)
134          `(make-music 
135            ',(ly:music-property obj 'name)
136            ,@(apply append (map (lambda (prop)
137                                   `(',(car prop)
138                                     ,(music->make-music (cdr prop))))
139                                 (remove (lambda (prop)
140                                           (eqv? (car prop) 'origin))
141                                         (ly:music-mutable-properties obj))))))
142         (;; moment
143          (ly:moment? obj)
144          `(ly:make-moment ,(ly:moment-main-numerator obj)
145                           ,(ly:moment-main-denominator obj)
146                           ,(ly:moment-grace-numerator obj)
147                           ,(ly:moment-grace-denominator obj)))
148         (;; note duration
149          (ly:duration? obj)
150          `(ly:make-duration ,(ly:duration-log obj)
151                             ,(ly:duration-dot-count obj)
152                             ,(car (ly:duration-factor obj))
153                             ,(cdr (ly:duration-factor obj))))
154         (;; note pitch
155          (ly:pitch? obj)
156          `(ly:make-pitch ,(ly:pitch-octave obj)
157                          ,(ly:pitch-notename obj)
158                          ,(ly:pitch-alteration obj)))
159         (;; scheme procedure
160          (procedure? obj)
161          (or (procedure-name obj) obj))
162         (;; a symbol (avoid having an unquoted symbol)
163          (symbol? obj)
164          `',obj)
165         (;; an empty list (avoid having an unquoted empty list)
166          (null? obj)
167          `'())
168         (;; a proper list
169          (list? obj)
170          `(list ,@(map music->make-music obj)))
171         (;; a pair
172          (pair? obj)
173          `(cons ,(music->make-music (car obj)) 
174                 ,(music->make-music (cdr obj))))
175         (else
176          obj)))
177
178 (use-modules (ice-9 pretty-print))
179 (define*-public (display-scheme-music obj #:optional (port (current-output-port)))
180   "Displays `obj', typically a music expression, in a friendly fashion,
181 which often can be read back in order to generate an equivalent expression.
182
183 Returns `obj'.
184 "
185   (pretty-print (music->make-music obj) port)
186   (newline)
187   obj)
188
189 ;;;
190 ;;; Scheme music expression --> Lily-syntax-using string translator
191 ;;;
192 (use-modules (srfi srfi-39)
193              (scm display-lily))
194
195 (define*-public (display-lily-music expr parser #:key force-duration)
196   "Display the music expression using LilyPond syntax"
197   (memoize-clef-names supported-clefs)
198   (parameterize ((*indent* 0)
199                  (*previous-duration* (ly:make-duration 2))
200                  (*force-duration* force-duration))
201     (display (music->lily-string expr parser))
202     (newline)))
203
204 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
205
206 (define-public (shift-one-duration-log music shift dot)
207   "  add SHIFT to duration-log of 'duration in music and optionally 
208   a dot to any note encountered. This scales the music up by a factor 
209   2^shift * (2 - (1/2)^dot)"
210   (let ((d (ly:music-property music 'duration)))
211     (if (ly:duration? d)
212         (let* ((cp (ly:duration-factor d))
213                (nd (ly:make-duration (+ shift (ly:duration-log d))
214                                      (+ dot (ly:duration-dot-count d))
215                                      (car cp)
216                                      (cdr cp))))
217           (set! (ly:music-property music 'duration) nd)))
218     music))
219
220 (define-public (shift-duration-log music shift dot)
221   (music-map (lambda (x) (shift-one-duration-log x shift dot))
222              music))
223
224 (define-public (make-repeat name times main alts)
225   "create a repeat music expression, with all properties initialized properly"
226   (let ((talts (if (< times (length alts))
227                    (begin
228                      (ly:warning (_ "More alternatives than repeats.  Junking excess alternatives"))
229                      (take alts times))
230                    alts))
231         (r (make-repeated-music name)))
232     (set! (ly:music-property r 'element) main)
233     (set! (ly:music-property r 'repeat-count) (max times 1))
234     (set! (ly:music-property r 'elements) talts)
235     (if (equal? name "tremolo")
236         (let* ((dots (1- (logcount times)))
237                (mult (/ (* times (ash 1 dots)) (1- (ash 2 dots))))
238                (shift (- (ly:intlog2 (floor mult)))))
239           (if (not (integer?  mult))
240               (ly:warning (_ "invalid tremolo repeat count: ~a") times))
241           (if (memq 'sequential-music (ly:music-property main 'types))
242               ;; \repeat "tremolo" { c4 d4 }
243               (let ((children (length (ly:music-property main 'elements))))
244
245                 ;; fixme: should be more generic.
246                 (if (and (not (= children 2))
247                          (not (= children 1)))
248                     (ly:warning (_ "expecting 2 elements for chord tremolo, found ~a") children))
249                 (ly:music-compress r (ly:make-moment 1 children))
250                 (shift-duration-log r
251                                     (if (= children 2)  (1- shift) shift)
252                                     dots))
253               ;; \repeat "tremolo" c4
254               (shift-duration-log r shift dots)))
255         r)))
256
257 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
258 ;; clusters.
259
260 (define-public (note-to-cluster music)
261   "Replace NoteEvents by ClusterNoteEvents."
262   (if (eq? (ly:music-property music 'name) 'NoteEvent)
263       (make-music 'ClusterNoteEvent
264                   'pitch (ly:music-property music 'pitch)
265                   'duration (ly:music-property music 'duration))
266       music))
267
268 (define-public (notes-to-clusters music)
269   (music-map note-to-cluster music))
270
271 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
272 ;; repeats.
273
274 (define-public (unfold-repeats music)
275   "
276 This function replaces all repeats  with unfold repeats. "
277
278   (let ((es (ly:music-property music 'elements))
279         (e  (ly:music-property music 'element))
280         )
281     (if (memq 'repeated-music (ly:music-property music 'types))
282         (let*
283             ((props (ly:music-mutable-properties music))
284              (old-name (ly:music-property music 'name))
285              (flattened  (flatten-alist props)))
286
287           (set! music (apply make-music (cons 'UnfoldedRepeatedMusic
288                                               flattened)))
289
290           (if (equal? old-name 'TremoloRepeatedMusic)
291               (let* ((seq-arg? (memq 'sequential-music
292                                      (ly:music-property e 'types)))
293                      (count  (ly:music-property music 'repeat-count))
294                      (dot-shift (if (= 0 (remainder count 3))
295                                     -1 0)))
296
297                 (if (= 0 -1)
298                     (set! count (* 2 (quotient count 3))))
299                 
300                 (shift-duration-log music (+ (if seq-arg? 1 0)
301                                              (ly:intlog2 count)) dot-shift)
302                 
303                 (if seq-arg?
304                     (ly:music-compress e (ly:make-moment (length (ly:music-property
305                                                                   e 'elements)) 1)))))))
306           
307     
308     (if (pair? es)
309         (set! (ly:music-property music 'elements)
310               (map unfold-repeats es)))
311     (if (ly:music? e)
312         (set! (ly:music-property music 'element)
313               (unfold-repeats e)))
314     music))
315
316 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
317 ;; property setting music objs.
318
319 (define-public (make-grob-property-set grob gprop val)
320   "Make a Music expression that sets GPROP to VAL in GROB. Does a pop first,
321 i.e.  this is not an override"
322   (make-music 'OverrideProperty
323               'symbol grob
324               'grob-property gprop
325               'grob-value val
326               'pop-first #t))
327
328 (define-public (make-grob-property-override grob gprop val)
329   "Make a Music expression that sets GPROP to VAL in GROB. Does a pop first,
330 i.e.  this is not an override"
331   (make-music 'OverrideProperty
332               'symbol grob
333               'grob-property gprop
334               'grob-value val))
335
336 (define-public (make-grob-property-revert grob gprop)
337   "Revert the grob property GPROP for GROB."
338   (make-music 'RevertProperty
339               'symbol grob
340               'grob-property gprop))
341
342 (define direction-polyphonic-grobs
343   '(DotColumn
344     Dots
345     Fingering
346     LaissezVibrerTie
347     PhrasingSlur
348     RepeatTie
349     Rest
350     Script
351     Slur
352     Stem
353     TextScript
354     Tie))
355
356 (define-safe-public (make-voice-props-set n)
357   (make-sequential-music
358    (append
359     (map (lambda (x) (make-grob-property-set x 'direction
360                                              (if (odd? n) -1 1)))
361          direction-polyphonic-grobs)
362     (list
363      (make-property-set 'graceSettings
364                         ;; TODO: take this from voicedGraceSettings or similar.
365                         '((Voice Stem font-size -3)
366                           (Voice NoteHead font-size -3)
367                           (Voice Dots font-size -3)
368                           (Voice Stem length-fraction 0.8)
369                           (Voice Stem no-stem-extend #t)
370                           (Voice Beam thickness 0.384)
371                           (Voice Beam length-fraction 0.8)
372                           (Voice Accidental font-size -4)))
373     
374      (make-grob-property-set 'NoteColumn 'horizontal-shift (quotient n 2))
375      (make-grob-property-set 'MultiMeasureRest 'staff-position (if (odd? n) -4 4)))))) 
376
377 (define-safe-public (make-voice-props-revert)
378   (make-sequential-music
379    (append
380     (map (lambda (x) (make-grob-property-revert x 'direction))
381          direction-polyphonic-grobs)
382     (list (make-property-unset 'graceSettings)
383           (make-grob-property-revert 'NoteColumn 'horizontal-shift)
384           (make-grob-property-revert 'MultiMeasureRest 'staff-position)))))
385
386
387 (define-safe-public (context-spec-music m context #:optional id)
388   "Add \\context CONTEXT = ID to M. "
389   (let ((cm (make-music 'ContextSpeccedMusic
390                         'element m
391                         'context-type context)))
392     (if (string? id)
393         (set! (ly:music-property cm 'context-id) id))
394     cm))
395
396 (define-public (descend-to-context m context)
397   "Like context-spec-music, but only descending. "
398   (let ((cm (context-spec-music m context)))
399     (ly:music-set-property! cm 'descend-only #t)
400     cm))
401
402 (define-public (make-non-relative-music mus)
403   (make-music 'UnrelativableMusic
404               'element mus))
405
406 (define-public (make-apply-context func)
407   (make-music 'ApplyContext
408               'procedure func))
409
410 (define-public (make-sequential-music elts)
411   (make-music 'SequentialMusic
412               'elements elts))
413
414 (define-public (make-simultaneous-music elts)
415   (make-music 'SimultaneousMusic
416               'elements elts))
417
418 (define-safe-public (make-event-chord elts)
419   (make-music 'EventChord
420               'elements elts))
421
422 (define-public (make-skip-music dur)
423   (make-music 'SkipMusic
424               'duration dur))
425
426 (define-public (make-grace-music music)
427   (make-music 'GraceMusic
428               'element music))
429
430 ;;;;;;;;;;;;;;;;
431
432 ;; mmrest
433 (define-public (make-multi-measure-rest duration location)
434   (make-music 'MultiMeasureRestMusic
435               'origin location
436               'duration duration))
437
438 (define-public (make-property-set sym val)
439   (make-music 'PropertySet
440               'symbol sym
441               'value val))
442
443 (define-public (make-property-unset sym)
444   (make-music 'PropertyUnset
445               'symbol sym))
446
447 (define-public (make-ottava-set octavation)
448   (let ((m (make-music 'ApplyContext)))
449     (define (ottava-modify context)
450       "Either reset middleCPosition to the stored original, or remember
451 old middleCPosition, add OCTAVATION to middleCPosition, and set
452 OTTAVATION to `8va', or whatever appropriate."      
453       (if (number? (ly:context-property  context 'middleCOffset))
454           (let ((where (ly:context-property-where-defined context 'middleCOffset)))
455             (ly:context-unset-property where 'middleCOffset)
456             (ly:context-unset-property where 'ottavation)))
457
458       (let* ((offset (* -7 octavation))
459              (string (cdr (assoc octavation '((2 . "15ma")
460                                               (1 . "8va")
461                                               (0 . #f)
462                                               (-1 . "8vb")
463                                               (-2 . "15mb"))))))
464         (ly:context-set-property! context 'middleCOffset offset)
465         (ly:context-set-property! context 'ottavation string)
466         (ly:set-middle-C! context)))
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
477   (define (standard-beat-grouping num den)
478
479     "Some standard subdivisions for time signatures."
480     (let*
481         ((key (cons num den))
482          (entry (assoc key '(((6 . 8) . (3 3))
483                          ((5 . 8) . (3 2))
484                          ((9 . 8) . (3 3 3))
485                          ((12 . 8) . (3 3 3 3))
486                          ((8 . 8) . (3 3 2))
487                          ))))
488
489       (if entry
490           (cdr entry)
491           '())))    
492   
493   (let* ((set1 (make-property-set 'timeSignatureFraction (cons num den)))
494          (beat (ly:make-moment 1 den))
495          (len  (ly:make-moment num den))
496          (set2 (make-property-set 'beatLength beat))
497          (set3 (make-property-set 'measureLength len))
498          (set4 (make-property-set 'beatGrouping (if (pair? rest)
499                                                     (car rest)
500                                                     (standard-beat-grouping num den))))
501          (basic  (list set1 set2 set3 set4)))
502     (descend-to-context
503      (context-spec-music (make-sequential-music basic) 'Timing) 'Score)))
504
505 (define-public (make-mark-set label)
506   "Make the music for the \\mark command."  
507   (let* ((set (if (integer? label)
508                   (context-spec-music (make-property-set 'rehearsalMark label)
509                                       'Score)
510                   #f))
511          (ev (make-music 'MarkEvent))
512          (ch (make-event-chord (list ev))))
513     (if set
514         (make-sequential-music (list set ch))
515         (begin
516           (set! (ly:music-property ev 'label) label)
517           ch))))
518
519 (define-public (set-time-signature num den . rest)
520   (ly:export (apply make-time-signature-set `(,num ,den . ,rest))))
521
522 (define-safe-public (make-articulation name)
523   (make-music 'ArticulationEvent
524               'articulation-type name))
525
526 (define-public (make-lyric-event string duration)
527   (make-music 'LyricEvent
528               'duration duration
529               'text string))
530
531 (define-safe-public (make-span-event type span-dir)
532   (make-music type
533               'span-direction span-dir))
534
535 (define-public (set-mus-properties! m alist)
536   "Set all of ALIST as properties of M." 
537   (if (pair? alist)
538       (begin
539         (set! (ly:music-property m (caar alist)) (cdar alist))
540         (set-mus-properties! m (cdr alist)))))
541
542 (define-public (music-separator? m)
543   "Is M a separator?"
544   (let ((ts (ly:music-property m 'types)))
545     (memq 'separator ts)))
546
547 ;;; splitting chords into voices.
548 (define (voicify-list lst number)
549   "Make a list of Musics.
550
551    voicify-list :: [ [Music ] ] -> number -> [Music]
552    LST is a list music-lists.
553
554    NUMBER is 0-base, i.e. Voice=1 (upstems) has number 0.
555 "
556   (if (null? lst)
557       '()
558       (cons (context-spec-music
559              (make-sequential-music
560               (list (make-voice-props-set number)
561                     (make-simultaneous-music (car lst))))
562              'Voice  (number->string (1+ number)))
563             (voicify-list (cdr lst) (1+ number)))))
564
565 (define (voicify-chord ch)
566   "Split the parts of a chord into different Voices using separator"
567   (let ((es (ly:music-property ch 'elements)))
568     (set! (ly:music-property  ch 'elements)
569           (voicify-list (split-list-by-separator es music-separator?) 0))
570     ch))
571
572 (define-public (voicify-music m)
573   "Recursively split chords that are separated with \\ "
574   (if (not (ly:music? m))
575       (ly:error (_ "music expected: ~S") m))
576   (let ((es (ly:music-property m 'elements))
577         (e (ly:music-property m 'element)))
578
579     (if (pair? es)
580         (set! (ly:music-property m 'elements) (map voicify-music es)))
581     (if (ly:music? e)
582         (set! (ly:music-property m 'element)  (voicify-music e)))
583     (if (and (equal? (ly:music-property m 'name) 'SimultaneousMusic)
584              (reduce (lambda (x y ) (or x y)) #f (map music-separator? es)))
585         (set! m (context-spec-music (voicify-chord m) 'Staff)))
586     m))
587
588 (define-public (empty-music)
589   (ly:export (make-music 'Music)))
590
591 ;; Make a function that checks score element for being of a specific type. 
592 (define-public (make-type-checker symbol)
593   (lambda (elt)
594     ;;(display  symbol)
595     ;;(eq? #t (ly:grob-property elt symbol))
596     (not (eq? #f (memq symbol (ly:grob-property elt 'interfaces))))))
597
598 (define-public ((outputproperty-compatibility func sym val) grob g-context ao-context)
599   (if (func grob)
600       (set! (ly:grob-property grob sym) val)))
601
602
603 (define-public ((set-output-property grob-name symbol val)  grob grob-c context)
604   "Usage:
605
606 \\applyoutput #(set-output-property 'Clef 'extra-offset '(0 . 1))
607
608 "
609   (let ((meta (ly:grob-property grob 'meta)))
610     (if (equal?  (cdr (assoc 'name meta)) grob-name)
611         (set! (ly:grob-property grob symbol) val))))
612
613
614 ;;
615 (define-public (smart-bar-check n)
616   "Make  a bar check that checks for a specific bar number. 
617 "
618   (let ((m (make-music 'ApplyContext)))
619     (define (checker tr)
620       (let* ((bn (ly:context-property tr 'currentBarNumber)))
621         (if (= bn n)
622             #t
623             (ly:error
624              ;; FIXME: uncomprehensable message
625              (_ "Bar check failed.  Expect to be at ~a, instead at ~a")
626              n bn))))
627     (set! (ly:music-property m 'procedure) checker)
628     m))
629
630
631 (define-public (skip->rest mus)
632
633   "Replace MUS by RestEvent of the same duration if it is a
634 SkipEvent. Useful for extracting parts from crowded scores"
635
636   (if  (memq (ly:music-property mus 'name) '(SkipEvent SkipMusic))
637    (make-music 'RestEvent 'duration (ly:music-property mus 'duration))
638    mus))
639
640
641 (define-public (music-has-type music type)
642   (memq type (ly:music-property music 'types)))
643
644 (define-public (music-clone music)
645   (define (alist->args alist acc)
646     (if (null? alist)
647         acc
648         (alist->args (cdr alist)
649                      (cons (caar alist) (cons (cdar alist) acc)))))
650
651   (apply
652    make-music
653    (ly:music-property music 'name)
654    (alist->args (ly:music-mutable-properties music) '())))
655
656 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
657 ;; warn for bare chords at start.
658
659
660 (define-public (ly:music-message music msg)
661   (let ((ip (ly:music-property music 'origin)))
662     (if (ly:input-location? ip)
663         (ly:input-message ip msg)
664         (ly:warning msg))))
665
666 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
667 ;;
668 ;; setting stuff for grace context.
669 ;;
670
671 (define (vector-extend v x)
672   "Make a new vector consisting of V, with X added to the end."
673   (let* ((n (vector-length v))
674          (nv (make-vector (+ n 1) '())))
675     (vector-move-left! v 0 n nv 0)
676     (vector-set! nv n x)
677     nv))
678
679 (define (vector-map f v)
680   "Map  F over V. This function returns nothing."
681   (do ((n (vector-length v))
682        (i 0 (+ i 1)))
683       ((>= i n))
684     (f (vector-ref v i))))
685
686 (define (vector-reverse-map f v)
687   "Map  F over V, N to 0 order. This function returns nothing."
688   (do ((i (- (vector-length v) 1) (- i 1)))
689       ((< i 0))
690     (f (vector-ref v i))))
691
692 (define-public (add-grace-property context-name grob sym val)
693   "Set SYM=VAL for GROB in CONTEXT-NAME. "
694   (define (set-prop context)
695     (let* ((where (ly:context-property-where-defined context 'graceSettings))
696            (current (ly:context-property where 'graceSettings))
697            (new-settings (append current
698                                  (list (list context-name grob sym val)))))
699       (ly:context-set-property! where 'graceSettings new-settings)))
700   (ly:export (context-spec-music (make-apply-context set-prop) 'Voice)))
701
702 (define-public (remove-grace-property context-name grob sym)
703   "Remove all SYM for GROB in CONTEXT-NAME. "
704   (define (sym-grob-context? property sym grob context-name)
705     (and (eq? (car property) context-name)
706          (eq? (cadr property) grob)
707          (eq? (caddr property) sym)))
708   (define (delete-prop context)
709     (let* ((where (ly:context-property-where-defined context 'graceSettings))
710            (current (ly:context-property where 'graceSettings))
711            (prop-settings (filter 
712                             (lambda(x) (sym-grob-context? x sym grob context-name))
713                             current)) 
714            (new-settings current))
715       (for-each (lambda(x) 
716                  (set! new-settings (delete x new-settings)))
717                prop-settings)
718       (ly:context-set-property! where 'graceSettings new-settings)))
719   (ly:export (context-spec-music (make-apply-context delete-prop) 'Voice)))
720
721
722
723 (defmacro-public def-grace-function (start stop)
724   `(define-music-function (parser location music) (ly:music?)
725      (make-music 'GraceMusic
726                  'origin location
727                  'element (make-music 'SequentialMusic
728                                       'elements (list (ly:music-deep-copy ,start)
729                                                       music
730                                                       (ly:music-deep-copy ,stop))))))
731
732 (defmacro-public define-music-function (args signature . body)
733   "Helper macro for `ly:make-music-function'.
734 Syntax:
735   (define-music-function (parser location arg1 arg2 ...) (arg1-type? arg2-type? ...)
736     ...function body...)
737 "
738   `(ly:make-music-function (list ,@signature)
739                            (lambda (,@args)
740                              ,@body)))
741
742
743 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
744
745 (define-public (cue-substitute quote-music)
746   "Must happen after quote-substitute."
747   
748   (if (vector? (ly:music-property quote-music 'quoted-events))
749       (let* ((dir (ly:music-property quote-music 'quoted-voice-direction))
750              (main-voice (if (eq? 1 dir) 1 0))
751              (cue-voice (if (eq? 1 dir) 0 1))
752              (main-music (ly:music-property quote-music 'element))
753              (return-value quote-music))
754
755         (if (or (eq? 1 dir) (eq? -1 dir))
756             
757             ;; if we have stem dirs, change both quoted and main music
758             ;; to have opposite stems.
759             (begin
760               (set! return-value
761
762                     ;; cannot context-spec Quote-music, since context
763                     ;; for the quotes is determined in the iterator.
764                     (make-sequential-music
765                      (list
766                       (context-spec-music (make-voice-props-set cue-voice) 'CueVoice "cue")
767                       quote-music
768                       (context-spec-music (make-voice-props-revert)  'CueVoice "cue"))))
769               (set! main-music
770                     (make-sequential-music
771                      (list
772                       (make-voice-props-set main-voice)
773                       main-music
774                       (make-voice-props-revert))))
775               (set! (ly:music-property quote-music 'element) main-music)))
776
777         return-value)
778       quote-music))
779
780 (define-public ((quote-substitute quote-tab) music)
781   (let* ((quoted-name (ly:music-property music 'quoted-music-name))
782          (quoted-vector (if (string? quoted-name)
783                             (hash-ref quote-tab quoted-name #f)
784                             #f)))
785
786     
787     (if (string? quoted-name)
788         (if (vector? quoted-vector)
789             (begin
790               (set! (ly:music-property music 'quoted-events) quoted-vector)
791               (set! (ly:music-property music 'iterator-ctor)
792                     ly:quote-iterator::constructor))
793             (ly:warning (_ "cannot find quoted music: `~S'") quoted-name)))
794     music))
795
796
797 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
798 ;; switch it on here, so parsing and init isn't checked (too slow!)
799 ;;
800 ;; automatic music transformations.
801
802 (define (switch-on-debugging m)
803   (if (defined? 'set-debug-cell-accesses!)
804       (set-debug-cell-accesses! 15000))
805   m)
806
807 (define (music-check-error music)
808   (define found #f)
809   (define (signal m)
810     (if (and (ly:music? m)
811              (eq? (ly:music-property m 'error-found) #t))
812         (set! found #t)))
813   
814   (for-each signal (ly:music-property music 'elements))
815   (signal (ly:music-property music 'element))
816
817   (if found
818       (set! (ly:music-property music 'error-found) #t))
819   music)
820
821 (define (precompute-music-length music)
822   (set! (ly:music-property music 'length)
823         (ly:music-length music))
824   music)
825
826 (define (skip-to-last music parser)
827
828   "Replace MUSIC by
829
830 << { \\set skipTypesetting = ##t
831      LENGTHOF(\\showLastLength)
832      \\set skipTypesetting = ##t  }
833     MUSIC >>
834
835 if appropriate.
836  "
837   (let*
838       ((show-last  (ly:parser-lookup parser 'showLastLength)))
839     
840     (if (ly:music? show-last)
841         (let*
842             ((orig-length (ly:music-length music))
843              (skip-length (ly:moment-sub orig-length (ly:music-length show-last))))
844
845           (make-simultaneous-music
846            (list
847             (make-sequential-music
848              (list
849               (context-spec-music (make-property-set 'skipTypesetting #t)
850                                   'Score)
851               (make-music 'SkipMusic 'duration
852                           (ly:make-duration
853                            0 0
854                            (ly:moment-main-numerator skip-length)
855                            (ly:moment-main-denominator skip-length)))
856               (context-spec-music (make-property-set 'skipTypesetting #f)
857                                   'Score)))
858             music)))
859         music)))
860     
861
862 (define-public toplevel-music-functions
863   (list
864    (lambda (music parser) (voicify-music music))
865    (lambda (x parser) (music-map music-check-error x))
866    (lambda (x parser) (music-map precompute-music-length x))
867    (lambda (music parser)
868
869      (music-map (quote-substitute (ly:parser-lookup parser 'musicQuotes))  music))
870    
871    ;; switch-on-debugging
872    (lambda (x parser) (music-map cue-substitute x))
873  
874    (lambda (x parser)
875      (skip-to-last x parser)
876    )))
877
878
879 ;;;;;;;;;;;;;;;;;
880 ;; lyrics
881
882 (define (apply-durations lyric-music durations) 
883   (define (apply-duration music)
884     (if (and (not (equal? (ly:music-length music) ZERO-MOMENT))
885              (ly:duration?  (ly:music-property music 'duration)))
886         (begin
887           (set! (ly:music-property music 'duration) (car durations))
888           (set! durations (cdr durations)))))
889   
890   (music-map apply-duration lyric-music))
891
892
893 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
894 ;; accidentals
895
896 (define-public ((make-accidental-rule octaveness lazyness) context pitch barnum measurepos)
897   "Creates an accidental rule that makes its decision based on the octave of the note
898   and a laziness value.
899   octaveness is either 'same-octave or 'any-octave and defines whether the rule should
900   respond to accidental changes in other octaves than the current. 'same-octave is the
901   normal way to typeset accidentals - an accidental is made if the alteration is different
902   from the last active pitch in the same octave. 'any-octave looks at the last active pitch
903   in any octave.
904   lazyness states over how many bars an accidental should be remembered.
905   0 is default - accidental lasts over 0 bar lines, that is, to the end of current measure.
906   A positive integer means that the accidental lasts over that many bar lines.
907   -1 is 'forget immediately', that is, only look at key signature.
908   #t is forever."
909   (let ((keysig (ly:context-property context 'localKeySignature)))
910     (ly:find-accidentals-simple keysig pitch barnum lazyness octaveness)))
911
912 (define (key-entry-notename entry)
913   "Return the pitch of an entry in localKeySignature. The entry is either of the form
914   '(notename . alter) or '((octave . notename) . (alter barnum . measurepos))."
915   (if (number? (car entry))
916       (car entry)
917       (cdar entry)))
918
919 (define (key-entry-octave entry)
920   "Return the octave of an entry in localKeySignature (or #f if the entry does not have
921   an octave)."
922   (and (pair? (car entry)) (caar entry)))
923
924 (define (key-entry-bar-number entry)
925   "Return the bar number of an entry in localKeySignature (or #f if the entry does not
926   have a bar number)."
927   (and (pair? (car entry)) (caddr entry)))
928
929 (define (key-entry-measure-position entry)
930   "Return the measure position of an entry in localKeySignature (or #f if the entry does
931   not have a measure position)."
932   (and (pair? (car entry)) (cdddr entry)))
933
934 (define (key-entry-alteration entry)
935   "Return the alteration of an entry in localKeySignature."
936   (if (number? (car entry))
937       (cdr entry)
938       (cadr entry)))
939
940 (define-public (find-pitch-entry keysig pitch accept-global accept-local)
941   "Return the first entry in keysig that matches the pitch.
942   accept-global states whether key signature entries should be included.
943   accept-local states whether local accidentals should be included.
944   if no matching entry is found, #f is returned."
945   (if (pair? keysig)
946       (let* ((entry (car keysig))
947              (entryoct (key-entry-octave entry))
948              (entrynn (key-entry-notename entry))
949              (oct (ly:pitch-octave pitch))
950              (nn (ly:pitch-notename pitch)))
951         (if (and (equal? nn entrynn)
952                  (or (and accept-global (equal? #f entryoct))
953                      (and accept-local (equal? oct entryoct))))
954             entry
955             (find-pitch-entry (cdr keysig) pitch accept-global accept-local)))
956       #f))
957
958 (define-public (neo-modern-accidental-rule context pitch barnum measurepos)
959   "an accidental rule that typesets an accidental if it differs from the key signature
960    AND does not directly follow a note on the same staff-line.
961    This rule should not be used alone because it does neither look at bar lines
962    nor different accidentals at the same notename"
963   (let* ((keysig (ly:context-property context 'localKeySignature))
964          (entry (find-pitch-entry keysig pitch #t #t)))
965     (if (equal? #f entry)
966         (cons #f #f)
967         (let* ((global-entry (find-pitch-entry keysig pitch #t #f))
968                (key-acc (if (equal? global-entry #f)
969                             0
970                             (key-entry-alteration global-entry)))
971                (acc (ly:pitch-alteration pitch))
972                (entrymp (key-entry-measure-position entry))
973                (entrybn (key-entry-bar-number entry)))
974           (cons #f (not (or (equal? acc key-acc)
975                             (and (equal? entrybn barnum) (equal? entrymp measurepos)))))))))
976
977 (define-public (teaching-accidental-rule context pitch barnum measurepos)
978   "an accidental rule that typesets a cautionary accidental
979   if it is included in the key signature AND does not directly follow
980   a note on the same staff-line."
981   (let* ((keysig (ly:context-property context 'localKeySignature))
982          (entry (find-pitch-entry keysig pitch #t #t)))
983     (if (equal? #f entry)
984         (cons #f #f)
985         (let* ((global-entry (find-pitch-entry keysig pitch #f #f))
986                (key-acc (if (equal? global-entry #f)
987                             0
988                             (key-entry-alteration global-entry)))
989                (acc (ly:pitch-alteration pitch))
990                (entrymp (key-entry-measure-position entry))
991                (entrybn (key-entry-bar-number entry)))
992           (cons #f (not (or (equal? acc key-acc)
993                             (and (equal? entrybn barnum) (equal? entrymp measurepos)))))))))
994
995 (define-public (set-accidentals-properties extra-natural
996                                            auto-accs auto-cauts
997                                            context)
998   (context-spec-music
999    (make-sequential-music
1000     (append (if (boolean? extra-natural)
1001                 (list (make-property-set 'extraNatural extra-natural))
1002                 '())
1003             (list (make-property-set 'autoAccidentals auto-accs)
1004                   (make-property-set 'autoCautionaries auto-cauts))))
1005    context))
1006
1007 (define-public (set-accidental-style style . rest)
1008   "Set accidental style to STYLE. Optionally takes a context argument,
1009 e.g. 'Staff or 'Voice. The context defaults to Staff, except for piano styles, which
1010 use GrandStaff as a context. "
1011   (let ((context (if (pair? rest)
1012                      (car rest) 'Staff))
1013         (pcontext (if (pair? rest)
1014                       (car rest) 'GrandStaff)))
1015     (ly:export
1016      (cond
1017       ;; accidentals as they were common in the 18th century.
1018       ((equal? style 'default)
1019        (set-accidentals-properties #t
1020                                    `(Staff ,(make-accidental-rule 'same-octave 0))
1021                                    '()
1022                                    context))
1023       ;; accidentals from one voice do NOT get cancelled in other voices
1024       ((equal? style 'voice)
1025        (set-accidentals-properties #t
1026                                    `(Voice ,(make-accidental-rule 'same-octave 0))
1027                                    '()
1028                                    context))
1029       ;; accidentals as suggested by Kurt Stone, Music Notation in the 20th century.
1030       ;; This includes all the default accidentals, but accidentals also needs cancelling
1031       ;; in other octaves and in the next measure.
1032       ((equal? style 'modern)
1033        (set-accidentals-properties #f
1034                                    `(Staff ,(make-accidental-rule 'same-octave 0)
1035                                            ,(make-accidental-rule 'any-octave 0)
1036                                            ,(make-accidental-rule 'same-octave 1))
1037                                    '()
1038                                    context))
1039       ;; the accidentals that Stone adds to the old standard as cautionaries
1040       ((equal? style 'modern-cautionary)
1041        (set-accidentals-properties #f
1042                                    `(Staff ,(make-accidental-rule 'same-octave 0))
1043                                    `(Staff ,(make-accidental-rule 'any-octave 0)
1044                                            ,(make-accidental-rule 'same-octave 1))
1045                                    context))
1046       ;; same as modern, but accidentals different from the key signature are always
1047       ;; typeset - unless they directly follow a note of the same pitch.
1048       ((equal? style 'neo-modern)
1049        (set-accidentals-properties #f
1050                                    `(Staff ,(make-accidental-rule 'same-octave 0)
1051                                            ,(make-accidental-rule 'any-octave 0)
1052                                            ,(make-accidental-rule 'same-octave 1)
1053                                            ,neo-modern-accidental-rule)
1054                                    '()
1055                                    context))
1056       ((equal? style 'neo-modern-cautionary)
1057        (set-accidentals-properties #f
1058                                    `(Staff ,(make-accidental-rule 'same-octave 0))
1059                                    `(Staff ,(make-accidental-rule 'any-octave 0)
1060                                            ,(make-accidental-rule 'same-octave 1)
1061                                            ,neo-modern-accidental-rule)
1062                                    context))
1063       ;; Accidentals as they were common in dodecaphonic music with no tonality.
1064       ;; Each note gets one accidental.
1065       ((equal? style 'dodecaphonic)
1066        (set-accidentals-properties #f
1067                                    `(Staff ,(lambda (c p bn mp) '(#f . #t)))
1068                                    '()
1069                                    context))
1070       ;; Multivoice accidentals to be read both by musicians playing one voice
1071       ;; and musicians playing all voices.
1072       ;; Accidentals are typeset for each voice, but they ARE cancelled across voices.
1073       ((equal? style 'modern-voice)
1074        (set-accidentals-properties  #f
1075                                     `(Voice ,(make-accidental-rule 'same-octave 0)
1076                                             ,(make-accidental-rule 'any-octave 0)
1077                                             ,(make-accidental-rule 'same-octave 1)
1078                                       Staff ,(make-accidental-rule 'same-octave 0)
1079                                             ,(make-accidental-rule 'any-octave 0)
1080                                             ,(make-accidental-rule 'same-octave 1))
1081                                     '()
1082                                     context))
1083       ;; same as modernVoiceAccidental eccept that all special accidentals are typeset
1084       ;; as cautionaries
1085       ((equal? style 'modern-voice-cautionary)
1086        (set-accidentals-properties #f
1087                                    `(Voice ,(make-accidental-rule 'same-octave 0))
1088                                    `(Voice ,(make-accidental-rule 'any-octave 0)
1089                                            ,(make-accidental-rule 'same-octave 1)
1090                                      Staff ,(make-accidental-rule 'same-octave 0)
1091                                            ,(make-accidental-rule 'any-octave 0)
1092                                            ,(make-accidental-rule 'same-octave 1))
1093                                    context))
1094       ;; stone's suggestions for accidentals on grand staff.
1095       ;; Accidentals are cancelled across the staves in the same grand staff as well
1096       ((equal? style 'piano)
1097        (set-accidentals-properties #f
1098                                    `(Staff ,(make-accidental-rule 'same-octave 0)
1099                                            ,(make-accidental-rule 'any-octave 0)
1100                                            ,(make-accidental-rule 'same-octave 1)
1101                                      GrandStaff
1102                                            ,(make-accidental-rule 'any-octave 0)
1103                                            ,(make-accidental-rule 'same-octave 1))
1104                                    '()
1105                                    pcontext))
1106       ((equal? style 'piano-cautionary)
1107        (set-accidentals-properties #f
1108                                    `(Staff ,(make-accidental-rule 'same-octave 0))
1109                                    `(Staff ,(make-accidental-rule 'any-octave 0)
1110                                            ,(make-accidental-rule 'same-octave 1)
1111                                      GrandStaff
1112                                            ,(make-accidental-rule 'any-octave 0)
1113                                            ,(make-accidental-rule 'same-octave 1))
1114                                    pcontext))
1115
1116       ;; same as modern, but cautionary accidentals are printed for all sharp or flat
1117       ;; tones specified by the key signature.  
1118        ((equal? style 'teaching)
1119        (set-accidentals-properties #f
1120                                     `(Staff ,(make-accidental-rule 'same-octave 0))
1121                                     `(Staff ,(make-accidental-rule 'same-octave 1)
1122                                            ,teaching-accidental-rule)
1123                                    context))
1124       
1125       ;; do not set localKeySignature when a note alterated differently from
1126       ;; localKeySignature is found.
1127       ;; Causes accidentals to be printed at every note instead of
1128       ;; remembered for the duration of a measure.
1129       ;; accidentals not being remembered, causing accidentals always to
1130       ;; be typeset relative to the time signature
1131       ((equal? style 'forget)
1132        (set-accidentals-properties '()
1133                                    `(Staff ,(make-accidental-rule 'same-octave -1))
1134                                    '()
1135                                    context))
1136       ;; Do not reset the key at the start of a measure.  Accidentals will be
1137       ;; printed only once and are in effect until overridden, possibly many
1138       ;; measures later.
1139       ((equal? style 'no-reset)
1140        (set-accidentals-properties '()
1141                                    `(Staff ,(make-accidental-rule 'same-octave #t))
1142                                    '()
1143                                    context))
1144       (else
1145        (ly:warning (_ "unknown accidental style: ~S") style)
1146        (make-sequential-music '()))))))
1147
1148 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1149
1150 (define-public (skip-of-length mus)
1151   "Create a skip of exactly the same length as MUS."
1152   (let* ((skip
1153           (make-music
1154            'SkipEvent
1155            'duration (ly:make-duration 0 0))))
1156
1157     (make-event-chord (list (ly:music-compress skip (ly:music-length mus))))))
1158
1159 (define-public (mmrest-of-length mus)
1160   "Create a mmrest of exactly the same length as MUS."
1161   
1162   (let* ((skip
1163           (make-multi-measure-rest
1164            (ly:make-duration 0 0) '())))
1165     (ly:music-compress skip (ly:music-length mus))
1166     skip))
1167
1168 (define-public (pitch-of-note event-chord)
1169
1170   (let*
1171       ((evs (filter (lambda (x) (memq 'note-event (ly:music-property x 'types)))
1172                     (ly:music-property event-chord 'elements))))
1173
1174     (if (pair? evs)
1175         (ly:music-property (car evs) 'pitch)
1176         #f)))
1177        
1178 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1179
1180 (define-public (extract-named-music music music-name)
1181 "Return a flat list of all music named @code{music-name}
1182 from @code{music}."
1183    (let ((extracted-list
1184           (if (ly:music? music)
1185               (if (eq? (ly:music-property music 'name) music-name)
1186                   (list music)
1187                   (let ((elt (ly:music-property music 'element))
1188                         (elts (ly:music-property music 'elements)))
1189                     (if (ly:music? elt)
1190                         (extract-named-music elt music-name)
1191                         (if (null? elts)
1192                             '()
1193                             (map (lambda(x) 
1194                                     (extract-named-music x music-name ))
1195                              elts)))))
1196               '())))
1197      (flatten-list extracted-list)))
1198
1199 (define-public (event-chord-notes event-chord)
1200 "Return a list of all notes from @{event-chord}."
1201   (filter
1202     (lambda (m) (eq? 'NoteEvent (ly:music-property m 'name)))
1203     (ly:music-property event-chord 'elements)))
1204
1205 (define-public (event-chord-pitches event-chord)
1206 "Return a list of all pitches from @{event-chord}."
1207   (map (lambda (x) (ly:music-property x 'pitch))
1208        (event-chord-notes event-chord)))