]> git.donarmstrong.com Git - lilypond.git/blob - scm/part-combiner.scm
Issue 4485: Refactor \partcombine and \autochange iterators
[lilypond.git] / scm / part-combiner.scm
1 ;;;; This file is part of LilyPond, the GNU music typesetter.
2 ;;;;
3 ;;;; Copyright (C) 2004--2015 Han-Wen Nienhuys <hanwen@xs4all.nl>
4 ;;;;
5 ;;;; LilyPond is free software: you can redistribute it and/or modify
6 ;;;; it under the terms of the GNU General Public License as published by
7 ;;;; the Free Software Foundation, either version 3 of the License, or
8 ;;;; (at your option) any later version.
9 ;;;;
10 ;;;; LilyPond is distributed in the hope that it will be useful,
11 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 ;;;; GNU General Public License for more details.
14 ;;;;
15 ;;;; You should have received a copy of the GNU General Public License
16 ;;;; along with LilyPond.  If not, see <http://www.gnu.org/licenses/>.
17
18 ;; todo: figure out how to make module,
19 ;; without breaking nested ly scopes
20
21 (define-class <Voice-state> ()
22   (event-list #:init-value '() #:accessor events #:init-keyword #:events)
23   (when-moment #:accessor moment #:init-keyword #:moment)
24   (tuning #:accessor tuning #:init-keyword #:tuning)
25   (split-index #:accessor split-index)
26   (vector-index)
27   (state-vector)
28   ;;;
29   ;; spanner-state is an alist
30   ;; of (SYMBOL . RESULT-INDEX), which indicates where
31   ;; said spanner was started.
32   (spanner-state #:init-value '() #:accessor span-state))
33
34 (define-method (write (x <Voice-state> ) file)
35   (display (moment x) file)
36   (display " evs = " file)
37   (display (events x) file)
38   (display " active = " file)
39   (display (span-state x) file)
40   (display "\n" file))
41
42 (define-method (note-events (vs <Voice-state>))
43   (define (f? x)
44     (ly:in-event-class? x 'note-event))
45   (filter f? (events vs)))
46
47 ; Return a list of note events which is sorted and stripped of
48 ; properties that we do not want to prevent combining parts.
49 (define-method (comparable-note-events (vs <Voice-state>))
50   (define (note<? note1 note2)
51     (let ((p1 (ly:event-property note1 'pitch))
52           (p2 (ly:event-property note2 'pitch)))
53       (cond ((ly:pitch<? p1 p2) #t)
54             ((ly:pitch<? p2 p1) #f)
55             (else (ly:duration<? (ly:event-property note1 'duration)
56                                  (ly:event-property note2 'duration))))))
57   ;; TODO we probably should compare articulations too
58   (sort (map (lambda (x)
59                (ly:make-stream-event
60                 (ly:make-event-class 'note-event)
61                 (list (cons 'duration (ly:event-property x 'duration))
62                       (cons 'pitch (ly:event-property x 'pitch)))))
63              (note-events vs))
64         note<?))
65
66 (define-method (rest-or-skip-events (vs <Voice-state>))
67   (define (filtered-events event-class)
68     (filter (lambda(x) (ly:in-event-class? x event-class))
69             (events vs)))
70   (let ((result (filtered-events 'rest-event)))
71     ;; There may be skips in the same part with rests for various
72     ;; reasons.  Regard the skips only if there are no rests.
73     (if (and (not (pair? result)) (not (any-mmrest-events vs)))
74         (set! result (filtered-events 'skip-event)))
75   result))
76
77 (define-method (any-mmrest-events (vs <Voice-state>))
78   (define (f? x)
79     (ly:in-event-class? x 'multi-measure-rest-event))
80   (any f? (events vs)))
81
82 (define-method (previous-voice-state (vs <Voice-state>))
83   (let ((i (slot-ref vs 'vector-index))
84         (v (slot-ref vs 'state-vector)))
85     (if (< 0 i)
86         (vector-ref v (1- i))
87         #f)))
88
89 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
90
91 (define-class <Split-state> ()
92   ;; The automatically determined split configuration
93   (configuration #:init-value '() #:accessor configuration)
94   ;; Allow overriding split configuration, takes precedence over configuration
95   (forced-configuration #:init-value #f #:accessor forced-configuration)
96   (when-moment #:accessor moment #:init-keyword #:moment)
97   ;; voice-states are states starting with the Split-state or later
98   ;;
99   (is #:init-keyword #:voice-states #:accessor voice-states)
100   (synced  #:init-keyword #:synced #:init-value  #f #:getter synced?))
101
102
103 (define-method (write (x <Split-state> ) f)
104   (display (moment x) f)
105   (display " = " f)
106   (display (configuration x) f)
107   (if (synced? x)
108       (display " synced "))
109   (display "\n" f))
110
111 (define-method (current-or-previous-voice-states (ss <Split-state>))
112   "Return voice states meeting the following conditions.  For a voice
113 in sync, return the current voice state.  For a voice out of sync,
114 return the previous voice state."
115   (let* ((vss (voice-states ss))
116          (vs1 (car vss))
117          (vs2 (cdr vss)))
118     (if (and vs1 (not (equal? (moment vs1) (moment ss))))
119         (set! vs1 (previous-voice-state vs1)))
120     (if (and vs2 (not (equal? (moment vs2) (moment ss))))
121         (set! vs2 (previous-voice-state vs2)))
122     (cons vs1 vs2)))
123
124 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
125
126
127 (define (previous-span-state vs)
128   (let ((p (previous-voice-state vs)))
129     (if p (span-state p) '())))
130
131 (define (make-voice-states evl)
132   (let ((vec (list->vector (map (lambda (v)
133                                   (make <Voice-state>
134                                     #:moment (caar v)
135                                     #:tuning (cdar v)
136                                     #:events (map car (cdr v))))
137                                 evl))))
138     (do ((i 0 (1+ i)))
139         ((= i (vector-length vec)) vec)
140       (slot-set! (vector-ref vec i) 'vector-index i)
141       (slot-set! (vector-ref vec i) 'state-vector vec))))
142
143 (define (make-split-state vs1 vs2)
144   "Merge lists VS1 and VS2, containing Voice-state objects into vector
145 of Split-state objects, crosslinking the Split-state vector and
146 Voice-state objects
147 "
148   (define (helper ss-idx ss-list idx1 idx2)
149     (let* ((state1 (if (< idx1 (vector-length vs1)) (vector-ref vs1 idx1) #f))
150            (state2 (if (< idx2 (vector-length vs2)) (vector-ref vs2 idx2) #f))
151            (min (cond ((and state1 state2) (moment-min (moment state1) (moment state2)))
152                       (state1 (moment state1))
153                       (state2 (moment state2))
154                       (else #f)))
155            (inc1 (if (and state1 (equal? min (moment state1))) 1 0))
156            (inc2 (if (and state2 (equal? min (moment state2))) 1 0))
157            (ss-object (if min
158                           (make <Split-state>
159                             #:moment min
160                             #:voice-states (cons state1 state2)
161                             #:synced (= inc1 inc2))
162                           #f)))
163       (if state1
164           (set! (split-index state1) ss-idx))
165       (if state2
166           (set! (split-index state2) ss-idx))
167       (if min
168           (helper (1+ ss-idx)
169                   (cons ss-object ss-list)
170                   (+ idx1 inc1)
171                   (+ idx2 inc2))
172           ss-list)))
173   (list->vector (reverse! (helper 0 '() 0  0) '())))
174
175 (define (analyse-spanner-states voice-state-vec)
176
177   (define (helper index active)
178     "Analyse EVS at INDEX, given state ACTIVE."
179
180     (define (analyse-tie-start active ev)
181       (if (ly:in-event-class? ev 'tie-event)
182           (acons 'tie (split-index (vector-ref voice-state-vec index))
183                  active)
184           active))
185
186     (define (analyse-tie-end active ev)
187       (if (ly:in-event-class? ev 'note-event)
188           (assoc-remove! active 'tie)
189           active))
190
191     (define (analyse-absdyn-end active ev)
192       (if (or (ly:in-event-class? ev 'absolute-dynamic-event)
193               (and (ly:in-event-class? ev 'span-dynamic-event)
194                    (equal? STOP (ly:event-property ev 'span-direction))))
195           (assoc-remove! (assoc-remove! active 'cresc) 'decr)
196           active))
197
198     (define (active<? a b)
199       (cond ((symbol<? (car a) (car b)) #t)
200             ((symbol<? (car b) (car a)) #f)
201             (else (< (cdr a) (cdr b)))))
202
203     (define (analyse-span-event active ev)
204       (let* ((name (car (ly:event-property ev 'class)))
205              (key (cond ((equal? name 'slur-event) 'slur)
206                         ((equal? name 'phrasing-slur-event) 'tie)
207                         ((equal? name 'beam-event) 'beam)
208                         ((equal? name 'crescendo-event) 'cresc)
209                         ((equal? name 'decrescendo-event) 'decr)
210                         (else #f)))
211              (sp (ly:event-property ev 'span-direction)))
212         (if (and (symbol? key) (ly:dir? sp))
213             (if (= sp STOP)
214                 (assoc-remove! active key)
215                 (acons key
216                        (split-index (vector-ref voice-state-vec index))
217                        active))
218             active)))
219
220     (define (analyse-events active evs)
221       "Run all analyzers on ACTIVE and EVS"
222       (define (run-analyzer analyzer active evs)
223         (if (pair? evs)
224             (run-analyzer analyzer (analyzer active (car evs)) (cdr evs))
225             active))
226       (define (run-analyzers analyzers active evs)
227         (if (pair? analyzers)
228             (run-analyzers (cdr analyzers)
229                            (run-analyzer (car analyzers) active evs)
230                            evs)
231             active))
232       (sort ;; todo: use fold or somesuch.
233        (run-analyzers (list analyse-absdyn-end analyse-span-event
234                             ;; note: tie-start/span comes after tie-end/absdyn.
235                             analyse-tie-end analyse-tie-start)
236                       active evs)
237        active<?))
238
239     ;; must copy, since we use assoc-remove!
240     (if (< index (vector-length voice-state-vec))
241         (begin
242           (set! active (analyse-events active (events (vector-ref voice-state-vec index))))
243           (set! (span-state (vector-ref voice-state-vec index))
244                 (list-copy active))
245           (helper (1+ index) active))))
246
247   (helper 0 '()))
248
249 (define recording-group-functions
250   ;;Selected parts from @var{toplevel-music-functions} not requiring @code{parser}.
251   (list
252    (lambda (music) (expand-repeat-chords! '(rhythmic-event) music))
253    expand-repeat-notes!))
254
255
256 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
257 (define-public (recording-group-emulate music odef)
258   "Interpret @var{music} according to @var{odef}, but store all events
259 in a chronological list, similar to the @code{Recording_group_engraver} in
260 LilyPond version 2.8 and earlier."
261   (let*
262       ((context-list '())
263        (now-mom (ly:make-moment 0 0))
264        (global (ly:make-global-context odef))
265        (mom-listener (lambda (tev) (set! now-mom (ly:event-property tev 'moment))))
266        (new-context-listener
267         (lambda (sev)
268           (let*
269               ((child (ly:event-property sev 'context))
270                (this-moment-list (cons (ly:context-id child) '()))
271                (dummy (set! context-list (cons this-moment-list context-list)))
272                (acc '())
273                (accumulate-event-listener
274                 (lambda (ev)
275                   (set! acc (cons (cons ev #t) acc))))
276                (save-acc-listener
277                 (lambda (tev)
278                   (if (pair? acc)
279                       (let ((this-moment
280                              (cons (cons now-mom
281                                          (ly:context-property child 'instrumentTransposition))
282                                    ;; The accumulate-event-listener above creates
283                                    ;; the list of events in reverse order, so we
284                                    ;; have to revert it to the original order again
285                                    (reverse acc))))
286                         (set-cdr! this-moment-list
287                                   (cons this-moment (cdr this-moment-list)))
288                         (set! acc '()))))))
289             (ly:add-listener accumulate-event-listener
290                              (ly:context-event-source child) 'StreamEvent)
291             (ly:add-listener save-acc-listener
292                              (ly:context-event-source global) 'OneTimeStep)))))
293     (ly:add-listener new-context-listener
294                      (ly:context-events-below global) 'AnnounceNewContext)
295     (ly:add-listener mom-listener (ly:context-event-source global) 'Prepare)
296     (ly:interpret-music-expression
297      (make-non-relative-music
298       (fold (lambda (x m) (x m)) music recording-group-functions))
299      global)
300     context-list))
301
302 (define-public (determine-split-list evl1 evl2 chord-range)
303   "@var{evl1} and @var{evl2} should be ascending. @var{chord-range} is a pair of numbers (min . max) defining the distance in steps between notes that may be combined into a chord or unison."
304   (let* ((pc-debug #f)
305          (voice-state-vec1 (make-voice-states evl1))
306          (voice-state-vec2 (make-voice-states evl2))
307          (result (make-split-state voice-state-vec1 voice-state-vec2))
308          (chord-min-diff (car chord-range))
309          (chord-max-diff (cdr chord-range)))
310
311     ;; Go through all moments recursively and check if the events of that
312     ;; moment contain a part-combine-force-event override. If so, store its
313     ;; value in the forced-configuration field, which will override. The
314     ;; previous configuration is used to determine non-terminated settings.
315     (define (analyse-forced-combine result-idx prev-res)
316
317       (define (get-forced-event x)
318         (and (ly:in-event-class? x 'part-combine-force-event)
319              (cons (ly:event-property x 'forced-type)
320                    (ly:event-property x 'once))))
321       (define (part-combine-events vs)
322         (if (not vs)
323             '()
324             (filter-map get-forced-event (events vs))))
325       ;; end part-combine-events
326
327       ;; forced-result: Take the previous config and analyse whether
328       ;; any change happened.... Return new once and permanent config
329       (define (forced-result evt state)
330         ;; sanity check, evt should always be (new-state . once)
331         (if (not (and (pair? evt) (pair? state)))
332             state
333             (if (cdr evt)
334                 ;; Once-event, leave permanent state unchanged
335                 (cons (car evt) (cdr state))
336                 ;; permanent change, leave once state unchanged
337                 (cons (car state) (car evt)))))
338       ;; end forced-combine-result
339
340       ;; body of analyse-forced-combine:
341       (if (< result-idx (vector-length result))
342           (let* ((now-state (vector-ref result result-idx)) ; current result
343                  ;; Extract all part-combine force events
344                  (evts (if (synced? now-state)
345                            (append
346                             (part-combine-events (car (voice-states now-state)))
347                             (part-combine-events (cdr (voice-states now-state))))
348                            '()))
349                  ;; result is (once-state permament-state):
350                  (state (fold forced-result (cons 'automatic prev-res) evts))
351                  ;; Now let once override permanent changes:
352                  (force-state (if (equal? (car state) 'automatic)
353                                   (cdr state)
354                                   (car state))))
355             (set! (forced-configuration (vector-ref result result-idx))
356                   force-state)
357             ;; For the next moment, ignore the once override (car stat)
358             ;; and pass on the permanent override, stored as (cdr state)
359             (analyse-forced-combine (1+ result-idx) (cdr state)))))
360     ;; end analyse-forced-combine
361
362
363     (define (analyse-time-step result-idx)
364       (define (put x . index)
365         "Put the result to X, starting from INDEX backwards.
366
367 Only set if not set previously.
368 "
369         (let ((i (if (pair? index) (car index) result-idx)))
370           (if (and (<= 0 i)
371                    (not (symbol? (configuration (vector-ref result i)))))
372               (begin
373                 (set! (configuration (vector-ref result i)) x)
374                 (put x (1- i))))))
375
376       (define (copy-state-from state-vec vs)
377         (define (copy-one-state key-idx)
378           (let* ((idx (cdr key-idx))
379                  (prev-ss (vector-ref result idx))
380                  (prev (configuration prev-ss)))
381             (if (symbol? prev)
382                 (put prev))))
383         (for-each copy-one-state (span-state vs)))
384
385       (define (analyse-notes now-state)
386         (let* ((vs1 (car (voice-states now-state)))
387                (vs2 (cdr (voice-states now-state)))
388                (notes1 (comparable-note-events vs1))
389                (notes2 (comparable-note-events vs2)))
390           (cond
391            ;; if neither part has notes, do nothing
392            ((and (not (pair? notes1)) (not (pair? notes2))))
393
394            ;; if one part has notes and the other does not
395            ((or (not (pair? notes1)) (not (pair? notes2))) (put 'apart))
396
397            ;; if either part has a chord
398            ((or (> (length notes1) 1) 
399                 (> (length notes2) 1))
400             (if (and (<= chord-min-diff 0) ; user requests combined unisons
401                      (equal? notes1 notes2)) ; both parts have the same chord
402                 (put 'chords)
403                 (put 'apart)))
404
405            ;; if the durations are different
406            ;; TODO articulations too?
407            ((and (not (equal? (ly:event-property (car notes1) 'duration)
408                               (ly:event-property (car notes2) 'duration))))
409             (put 'apart))
410
411            (else
412             ;; Is the interval outside of chord-range?
413             (if (let ((diff (ly:pitch-steps
414                              (ly:pitch-diff 
415                               (ly:event-property (car notes1) 'pitch)
416                               (ly:event-property (car notes2) 'pitch)))))
417                   (or (< diff chord-min-diff)
418                       (> diff chord-max-diff)
419                       ))
420                 (put 'apart)
421                 ;; copy previous split state from spanner state
422                 (begin
423                   (if (previous-voice-state vs1)
424                       (copy-state-from voice-state-vec1
425                                        (previous-voice-state vs1)))
426                   (if (previous-voice-state vs2)
427                       (copy-state-from voice-state-vec2
428                                        (previous-voice-state vs2)))
429                   (if (and (null? (span-state vs1)) (null? (span-state vs2)))
430                       (put 'chords))))))))
431
432       (if (< result-idx (vector-length result))
433           (let* ((now-state (vector-ref result result-idx))
434                  (vs1 (car (voice-states now-state)))
435                  (vs2 (cdr (voice-states now-state))))
436
437             (cond ((not vs1) (put 'apart))
438                   ((not vs2) (put 'apart))
439                   (else
440                    (let ((active1 (previous-span-state vs1))
441                          (active2 (previous-span-state vs2))
442                          (new-active1 (span-state vs1))
443                          (new-active2 (span-state vs2)))
444                      (if #f ; debug
445                          (display (list (moment now-state) result-idx
446                                         active1 "->" new-active1
447                                         active2 "->" new-active2
448                                         "\n")))
449                      (if (and (synced? now-state)
450                               (equal? active1 active2)
451                               (equal? new-active1 new-active2))
452                          (analyse-notes now-state)
453
454                          ;; active states different:
455                          (put 'apart)))
456
457                    ;; go to the next one, if it exists.
458                    (analyse-time-step (1+ result-idx)))))))
459
460     (define (analyse-a2 result-idx)
461       (if (< result-idx (vector-length result))
462           (let* ((now-state (vector-ref result result-idx))
463                  (vs1 (car (voice-states now-state)))
464                  (vs2 (cdr (voice-states now-state))))
465
466             (define (analyse-synced-silence)
467               (let ((rests1 (if vs1 (rest-or-skip-events vs1) '()))
468                     (rests2 (if vs2 (rest-or-skip-events vs2) '())))
469                 (cond
470
471                  ;; multi-measure rests (probably), which the
472                  ;; part-combine iterator handles well
473                  ((and (= 0 (length rests1))
474                        (= 0 (length rests2)))
475                   (set! (configuration now-state) 'unisilence))
476
477                  ;; equal rests or equal skips, but not one of each
478                  ((and (= 1 (length rests1))
479                        (= 1 (length rests2))
480                        (equal? (ly:event-property (car rests1) 'class)
481                                (ly:event-property (car rests2) 'class))
482                        (equal? (ly:event-property (car rests1) 'duration)
483                                (ly:event-property (car rests2) 'duration)))
484                   (set! (configuration now-state) 'unisilence))
485
486                  ;; rests of different durations or mixed with
487                  ;; skips or multi-measure rests
488                  (else
489                   ;; TODO For skips, route the rest to the shared
490                   ;; voice and the skip to the voice for its part?
491                   (set! (configuration now-state) 'apart-silence))
492
493                  )))
494
495             (define (analyse-unsynced-silence vs1 vs2)
496               (let ((any-mmrests1 (if vs1 (any-mmrest-events vs1) #f))
497                     (any-mmrests2 (if vs2 (any-mmrest-events vs2) #f)))
498                 (cond
499                  ;; If a multi-measure rest begins now while the other
500                  ;; part has an ongoing multi-measure rest (or has
501                  ;; ended), start displaying the one that begins now.
502                  ((and any-mmrests1
503                        (equal? (moment vs1) (moment now-state))
504                        (or (not vs2) any-mmrests2))
505                   (set! (configuration now-state) 'silence1))
506
507                  ;; as above with parts swapped
508                  ((and any-mmrests2
509                        (equal? (moment vs2) (moment now-state))
510                        (or (not vs1) any-mmrests1))
511                   (set! (configuration now-state) 'silence2))
512                  )))
513
514             (if (or vs1 vs2)
515                 (let ((notes1 (if vs1 (comparable-note-events vs1) '()))
516                       (notes2 (if vs2 (comparable-note-events vs2) '())))
517                   (cond ((and (equal? (configuration now-state) 'chords)
518                               (pair? notes1)
519                               (equal? notes1 notes2))
520                          (set! (configuration now-state) 'unisono))
521
522                         ((synced? now-state)
523                          (if (and (= 0 (length notes1))
524                                   (= 0 (length notes2)))
525                              (analyse-synced-silence)))
526
527                         (else ;; not synchronized
528                          (let* ((vss
529                                  (current-or-previous-voice-states now-state))
530                                 (vs1 (car vss))
531                                 (vs2 (cdr vss)))
532                            (if (and
533                                 (or (not vs1) (= 0 (length (note-events vs1))))
534                                 (or (not vs2) (= 0 (length (note-events vs2)))))
535                                (analyse-unsynced-silence vs1 vs2))))
536                         )))
537             (analyse-a2 (1+ result-idx)))))
538
539     (define (analyse-solo12 result-idx)
540
541       (define (previous-config vs)
542         (let* ((pvs (previous-voice-state vs))
543                (spi (if pvs (split-index pvs) #f))
544                (prev-split (if spi (vector-ref result spi) #f)))
545           (if prev-split
546               (configuration prev-split)
547               'apart)))
548
549       (define (put-range x a b)
550         ;; (display (list "put range "  x a b "\n"))
551         (do ((i a (1+ i)))
552             ((> i b) b)
553           (set! (configuration (vector-ref result i)) x)))
554
555       (define (put x)
556         ;; (display (list "putting "  x "\n"))
557         (set! (configuration (vector-ref result result-idx)) x))
558
559       (define (current-voice-state now-state voice-num)
560         (define vs ((if (= 1 voice-num) car cdr)
561                     (voice-states now-state)))
562         (if (or (not vs) (equal? (moment now-state) (moment vs)))
563             vs
564             (previous-voice-state vs)))
565
566       (define (try-solo type start-idx current-idx)
567         "Find a maximum stretch that can be marked as solo.  Only set
568 the mark when there are no spanners active.
569
570       return next idx to analyse.
571 "
572         (if (< current-idx (vector-length result))
573             (let* ((now-state (vector-ref result current-idx))
574                    (solo-state (current-voice-state now-state (if (equal? type 'solo1) 1 2)))
575                    (silent-state (current-voice-state now-state (if (equal? type 'solo1) 2 1)))
576                    (silent-notes (if silent-state (note-events silent-state) '()))
577                    (solo-notes (if solo-state (note-events solo-state) '())))
578               ;; (display (list "trying " type " at "  (moment now-state) solo-state silent-state        "\n"))
579               (cond ((not (equal? (configuration now-state) 'apart))
580                      current-idx)
581                     ((> (length silent-notes) 0) start-idx)
582                     ((not solo-state)
583                      (put-range type start-idx current-idx)
584                      current-idx)
585                     ((and
586                       (null? (span-state solo-state)))
587
588                      ;;
589                      ;; This includes rests. This isn't a problem: long rests
590                      ;; will be shared with the silent voice, and be marked
591                      ;; as unisilence. Therefore, long rests won't
592                      ;;  accidentally be part of a solo.
593                      ;;
594                      (put-range type start-idx current-idx)
595                      (try-solo type (1+ current-idx) (1+  current-idx)))
596                     (else
597                      (try-solo type start-idx (1+ current-idx)))))
598             ;; try-solo
599             start-idx))
600
601       (define (analyse-apart-silence result-idx)
602         "Analyse 'apart-silence starting at RESULT-IDX.  Return next index."
603         (let* ((now-state (vector-ref result result-idx))
604                (vs1 (current-voice-state now-state 1))
605                (vs2 (current-voice-state now-state 2))
606                (rests1 (if vs1 (rest-or-skip-events vs1) '()))
607                (rests2 (if vs2 (rest-or-skip-events vs2) '()))
608                (prev-state (if (> result-idx 0)
609                                (vector-ref result (- result-idx 1))
610                                #f))
611                (prev-config (if prev-state
612                                 (configuration prev-state)
613                                 'apart-silence)))
614           (cond
615            ;; rest with multi-measure rest: choose the rest
616            ((and (synced? now-state)
617                  (= 1 (length rests1))
618                  (ly:in-event-class? (car rests1) 'rest-event)
619                  (= 0 (length rests2))) ; probably mmrest
620             (put 'silence1))
621
622            ;; as above with parts swapped
623            ((and (synced? now-state)
624                  (= 1 (length rests2))
625                  (ly:in-event-class? (car rests2) 'rest-event)
626                  (= 0 (length rests1))) ; probably mmrest
627             (put 'silence2))
628
629            ((synced? now-state)
630             (put 'apart-silence))
631
632            ;; remain in the silence1/2 states until resync
633            ((equal? prev-config 'silence1)
634             (put 'silence1))
635
636            ((equal? prev-config 'silence2)
637             (put 'silence2))
638
639            (else
640             (put 'apart-silence)))
641
642           (1+ result-idx)))
643
644       (define (analyse-apart result-idx)
645         "Analyse 'apart starting at RESULT-IDX.  Return next index."
646         (let* ((now-state (vector-ref result result-idx))
647                (vs1 (current-voice-state now-state 1))
648                (vs2 (current-voice-state now-state 2))
649                ;; (vs1 (car (voice-states now-state)))
650                ;; (vs2 (cdr (voice-states now-state)))
651                (notes1 (if vs1 (note-events vs1) '()))
652                (notes2 (if vs2 (note-events vs2) '()))
653                (n1 (length notes1))
654                (n2 (length notes2)))
655           ;; (display (list "analyzing step " result-idx "  moment " (moment now-state) vs1 vs2  "\n"))
656           (max
657            ;; we should always increase.
658            (cond ((and (= n1 0) (= n2 0))
659                   ;; If we hit this, it means that the previous passes
660                   ;; have designated as 'apart what is really
661                   ;; 'apart-silence.
662                   (analyse-apart-silence result-idx))
663                  ((and (= n2 0)
664                        (equal? (moment vs1) (moment now-state))
665                        (null? (previous-span-state vs1)))
666                   (try-solo 'solo1 result-idx result-idx))
667                  ((and (= n1 0)
668                        (equal? (moment vs2) (moment now-state))
669                        (null? (previous-span-state vs2)))
670                   (try-solo 'solo2 result-idx result-idx))
671
672                  (else (1+ result-idx)))
673            ;; analyse-moment
674            (1+ result-idx))))
675
676       (if (< result-idx (vector-length result))
677           (let ((conf (configuration (vector-ref result result-idx))))
678             (cond
679              ((equal? conf 'apart)
680               (analyse-solo12 (analyse-apart result-idx)))
681              ((equal? conf 'apart-silence)
682               (analyse-solo12 (analyse-apart-silence result-idx)))
683              (else
684               (analyse-solo12 (1+ result-idx))))))) ; analyse-solo12
685
686     (analyse-spanner-states voice-state-vec1)
687     (analyse-spanner-states voice-state-vec2)
688     (if #f
689         (begin
690           (display voice-state-vec1)
691           (display "***\n")
692           (display voice-state-vec2)
693           (display "***\n")
694           (display result)
695           (display "***\n")))
696
697     ;; Extract all forced combine strategies, i.e. events inserted by
698     ;; \partcombine(Apart|Automatic|SoloI|SoloII|Chords)[Once]
699     ;; They will in the end override the automaically determined ones.
700     ;; Initial state for both voices is no override
701     (analyse-forced-combine 0 #f)
702     ;; Now go through all time steps in a loop and find a combination strategy
703     ;; based only on the events of that one moment (i.e. neglecting longer
704     ;; periods of solo/apart, etc.)
705     (analyse-time-step 0)
706     ;; (display result)
707     ;; Check for unisono or unisilence moments
708     (analyse-a2 0)
709     ;;(display result)
710     (analyse-solo12 0)
711     ;; (display result)
712     (set! result (map
713                   ;; forced-configuration overrides, if it is set
714                   (lambda (x) (cons (moment x) (or (forced-configuration x) (configuration x))))
715                   (vector->list result)))
716     (if #f ;; pc-debug
717         (display result))
718     result))
719
720 (define-public default-part-combine-mark-state-machine
721   ;; (current-state . ((split-state-event .
722   ;;                      (output-voice output-event next-state)) ...))
723   '((Initial . ((solo1   . (solo   SoloOneEvent Solo1))
724                 (solo2   . (solo   SoloTwoEvent Solo2))
725                 (unisono . (shared UnisonoEvent Unisono))))
726     (Solo1   . ((apart   . (#f     #f           Initial))
727                 (chords  . (#f     #f           Initial))
728                 (solo2   . (solo   SoloTwoEvent Solo2))
729                 (unisono . (shared UnisonoEvent Unisono))))
730     (Solo2   . ((apart   . (#f     #f           Initial))
731                 (chords  . (#f     #f           Initial))
732                 (solo1   . (solo   SoloOneEvent Solo1))
733                 (unisono . (shared UnisonoEvent Unisono))))
734     (Unisono . ((apart   . (#f     #f           Initial))
735                 (chords  . (#f     #f           Initial))
736                 (solo1   . (solo   SoloOneEvent Solo1))
737                 (solo2   . (solo   SoloTwoEvent Solo2))))))
738
739 (define-public (make-part-combine-marks state-machine split-list)
740   "Generate a sequence of part combiner events from a split list"
741
742   (define (get-state state-name)
743     (assq-ref state-machine state-name))
744
745   (let ((full-seq '()) ; sequence of { \context Voice = "x" {} ... }
746         (segment '()) ; sequence within \context Voice = "x" {...}
747         (prev-moment ZERO-MOMENT)
748         (prev-voice #f)
749         (state (get-state 'Initial)))
750
751     (define (commit-segment)
752       "Add the current segment to the full sequence and begin another."
753       (if (pair? segment)
754           (set! full-seq
755                 (cons (make-music 'ContextSpeccedMusic
756                                   'context-id (symbol->string prev-voice)
757                                   'context-type 'Voice
758                                   'element (make-sequential-music (reverse! segment)))
759                       full-seq)))
760       (set! segment '()))
761
762     (define (handle-split split)
763       (let* ((moment (car split))
764              (action (assq-ref state (cdr split))))
765         (if action
766             (let ((voice (car action))
767                   (part-combine-event (cadr action))
768                   (next-state-name (caddr action)))
769               (if part-combine-event
770                   (let ((dur (ly:moment-sub moment prev-moment)))
771                     ;; start a new segment when the voice changes
772                     (if (not (eq? voice prev-voice))
773                         (begin
774                           (commit-segment)
775                           (set! prev-voice voice)))
776                     (if (not (equal? dur ZERO-MOMENT))
777                         (set! segment (cons (make-music 'SkipEvent
778                                                           'duration (make-duration-of-length dur)) segment)))
779                     (set! segment (cons (make-music part-combine-event) segment))
780
781                     (set! prev-moment moment)))
782               (set! state (get-state next-state-name))))))
783
784     (for-each handle-split split-list)
785     (commit-segment)
786     (make-sequential-music (reverse! full-seq))))
787
788 (define-public default-part-combine-context-change-state-machine-one
789   ;; (current-state . ((split-state-event . (output-voice next-state)) ...))
790   '((Initial . ((apart         . (one    . Initial))
791                 (apart-silence . (one    . Initial))
792                 (apart-spanner . (one    . Initial))
793                 (chords        . (shared . Initial))
794                 (silence1      . (shared . Initial))
795                 (silence2      . (null   . Demoted))
796                 (solo1         . (solo   . Initial))
797                 (solo2         . (null   . Demoted))
798                 (unisono       . (shared . Initial))
799                 (unisilence    . (shared . Initial))))
800
801     ;; After a part has been used as the exclusive input for a
802     ;; passage, we want to use it by default for unisono/unisilence
803     ;; passages because Part_combine_iterator might have killed
804     ;; multi-measure rests in the other part.  Here we call such a
805     ;; part "promoted".  Part one begins promoted.
806     (Demoted . ((apart         . (one    . Demoted))
807                 (apart-silence . (one    . Demoted))
808                 (apart-spanner . (one    . Demoted))
809                 (chords        . (shared . Demoted))
810                 (silence1      . (shared . Initial))
811                 (silence2      . (null   . Demoted))
812                 (solo1         . (solo   . Initial))
813                 (solo2         . (null   . Demoted))
814                 (unisono       . (null   . Demoted))
815                 (unisilence    . (null   . Demoted))))))
816
817 (define-public default-part-combine-context-change-state-machine-two
818   ;; (current-state . ((split-state-event . (output-voice next-state)) ...))
819   '((Initial . ((apart         . (two    . Initial))
820                 (apart-silence . (two    . Initial))
821                 (apart-spanner . (two    . Initial))
822                 (chords        . (shared . Initial))
823                 (silence1      . (null   . Initial))
824                 (silence2      . (shared . Promoted))
825                 (solo1         . (null   . Initial))
826                 (solo2         . (solo   . Promoted))
827                 (unisono       . (null   . Initial))
828                 (unisilence    . (null   . Initial))))
829
830     ;; See the part-one state machine for the meaning of "promoted".
831     (Promoted . ((apart         . (two    . Promoted))
832                  (apart-silence . (two    . Promoted))
833                  (apart-spanner . (two    . Promoted))
834                  (chords        . (shared . Promoted))
835                  (silence1      . (null   . Initial))
836                  (silence2      . (shared . Promoted))
837                  (solo1         . (null   . Initial))
838                  (solo2         . (solo   . Promoted))
839                  (unisono       . (shared . Promoted))
840                  (unisilence    . (shared . Promoted))))))
841
842 (define-public (make-part-combine-context-changes state-machine split-list)
843   "Generate a sequence of part combiner context changes from a split list"
844
845   (define (get-state state-name)
846     (assq-ref state-machine state-name))
847
848   (let ((change-list '())
849         (prev-voice #f)
850         (state (get-state 'Initial)))
851
852     (define (handle-split split)
853       (let* ((moment (car split))
854              (action (assq-ref state (cdr split))))
855         (if action
856             (let ((voice (car action))
857                   (next-state-name (cdr action)))
858               (if (not (eq? voice prev-voice))
859                   (begin
860                     (set! change-list (cons (cons moment voice) change-list))
861                     (set! prev-voice voice)))
862               (set! state (get-state next-state-name))))))
863
864     (for-each handle-split split-list)
865     (reverse! change-list)))
866
867 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
868
869 (define-public (add-quotable name mus)
870   (let* ((tab (eval 'musicQuotes (current-module)))
871          (voicename (get-next-unique-voice-name))
872          ;; recording-group-emulate returns an assoc list (reversed!), so
873          ;; hand it a proper unique context name and extract that key:
874          (ctx-spec (context-spec-music mus 'Voice voicename))
875          (listener (ly:parser-lookup 'partCombineListener))
876          (context-list (reverse (recording-group-emulate ctx-spec listener)))
877          (raw-voice (assoc voicename context-list))
878          (quote-contents (if (pair? raw-voice) (cdr raw-voice) '())))
879
880     ;; If the context-specced quoted music does not contain anything, try to
881     ;; use the first child, i.e. the next in context-list after voicename
882     ;; That's the case e.g. for \addQuote "x" \relative c \new Voice {...}
883     (if (null? quote-contents)
884         (let find-non-empty ((current-tail (member raw-voice context-list)))
885           ;; if voice has contents, use them, otherwise check next ctx
886           (cond ((null? current-tail) #f)
887                 ((and (pair? (car current-tail))
888                       (pair? (cdar current-tail)))
889                  (set! quote-contents (cdar current-tail)))
890                 (else (find-non-empty (cdr current-tail))))))
891
892     (if (not (null? quote-contents))
893         (hash-set! tab name (list->vector (reverse! quote-contents '())))
894         (ly:music-warning mus (ly:format (_ "quoted music `~a' is empty") name)))))