+
+;; UGH. TODO: represent mm rests in a decent way as music expressions.
+;; Also eliminate glue-mm-rests while we are at it.
+(define-ly-syntax (multi-measure-rest parser location duration articulations)
+ (let* ((mus (make-multi-measure-rest duration location))
+ (elts (ly:music-property mus 'elements)))
+ (set! (ly:music-property mus 'elements)
+ (append elts articulations))
+ mus))
+
+(define-ly-syntax-simple (context-specification type id mus ops create-new)
+ (let* ((type-sym (if (symbol? type) type (string->symbol type)))
+ (csm (context-spec-music mus type-sym id)))
+ (set! (ly:music-property csm 'property-operations) ops)
+ (if create-new (set! (ly:music-property csm 'create-new) #t))
+ csm))
+
+(define-ly-syntax (property-operation parser location once ctx music-type symbol . args)
+ (let* ((props (case music-type
+ ((PropertySet) (list 'value (car args)))
+ ((PropertyUnset) '())
+ ((OverrideProperty) (list 'grob-value (car args)
+ 'grob-property-path (cdr args)
+ 'pop-first #t))
+ ((RevertProperty) (list 'grob-property-path args))
+ (else (ly:error (_ "Invalid property operation ~a") music-type))))
+ (oprops (if once (cons* 'once once props) props))
+ (m (apply make-music music-type
+ 'symbol symbol
+ 'origin location
+ oprops)))
+ (make-music 'ContextSpeccedMusic
+ 'element m
+ 'context-type ctx
+ 'origin location)))
+
+;; TODO: It seems that this function rarely returns anything useful.
+(define (get-first-context-id type mus)
+ "Find the name of a ContextSpeccedMusic with given type"
+ (let ((id (ly:music-property mus 'context-id)))
+ (if (and (eq? (ly:music-property mus 'type) 'ContextSpeccedMusic)
+ (eq? (ly:music-property mus 'context-type) type)
+ (string? id)
+ (not (string-null? id)))
+ id
+ '())))
+
+(define unique-counter -1)
+(define (get-next-unique-voice-name)
+ (set! unique-counter (1+ unique-counter))
+ (call-with-output-string (lambda (p) (format p "uniqueContext~s" unique-counter))))
+
+(define (lyric-combine-music sync music loc)
+ (make-music 'LyricCombineMusic
+ 'element music
+ 'associated-context sync
+ 'origin loc))
+
+(define-ly-syntax (lyric-combine parser location voice music)
+ (lyric-combine-music voice music location))
+
+(define-ly-syntax (add-lyrics parser location music addlyrics-list)
+ (let* ((existing-voice-name (get-first-context-id 'Voice music))
+ (voice-name (if (string? existing-voice-name)
+ existing-voice-name
+ (get-next-unique-voice-name)))
+ (voice (if (string? existing-voice-name)
+ (music)
+ (make-music 'ContextSpeccedMusic
+ 'element music
+ 'context-type 'Voice
+ 'context-id voice-name
+ 'origin (ly:music-property music 'origin))))
+ (lyricstos (map (lambda (mus)
+ (let* ((loc (ly:music-property mus 'origin))
+ (lyr (lyric-combine-music voice-name mus loc)))
+ (make-music 'ContextSpeccedMusic
+ 'create-new #t
+ 'context-type 'Lyrics
+ 'element lyr
+ 'origin loc)))
+ addlyrics-list)))
+ (make-simultaneous-music (cons voice lyricstos))))