]> git.donarmstrong.com Git - lilypond.git/blob - scm/define-music-display-methods.scm
* scm/define-context-properties.scm:
[lilypond.git] / scm / define-music-display-methods.scm
1 ;;; define-music-display-methods.scm -- data for displaying music
2 ;;; expressions using LilyPond notation.
3 ;;;
4 ;;; (c) 2005--2006 Nicolas Sceaux  <nicolas.sceaux@free.fr>
5 ;;;
6
7 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
8 ;;;
9 ;;; Display method implementation
10 ;;;
11
12 (define-module (scm display-lily))
13
14 ;;; `display-lily-init' must be called before using `display-lily-music'. It
15 ;;; takes a parser object as an argument.
16 (define-public (display-lily-init parser)
17   (*parser* parser)
18   #t)
19
20 ;;;
21 ;;; Scheme forms
22 ;;;
23 (define (scheme-expr->lily-string scm-arg)
24   (cond ((or (number? scm-arg)
25              (string? scm-arg))
26          (format #f "~s" scm-arg))
27         ((or (symbol? scm-arg)
28              (list? scm-arg))
29          (format #f "'~s" scm-arg))
30         ((procedure? scm-arg)
31          (format #f "~a"
32                  (or (procedure-name scm-arg)
33                      (with-output-to-string
34                        (lambda ()
35                          (pretty-print (procedure-source scm-arg)))))))
36         (else
37          (format #f "~a"
38                  (with-output-to-string
39                    (lambda ()
40                      (display-scheme-music scm-arg)))))))
41 ;;;
42 ;;; Markups
43 ;;;
44
45 (define-public (markup->lily-string markup-expr)
46   "Return a string describing, in LilyPond syntax, the given markup expression."
47   (define (proc->command proc)
48     (let ((cmd-markup (symbol->string (procedure-name proc))))
49       (substring cmd-markup 0 (- (string-length cmd-markup)
50                                  (string-length "-markup")))))
51   (define (arg->string arg)
52     (cond ((string? arg)
53            (format #f "~s" arg))
54           ((markup? arg) ;; a markup
55            (markup->lily-string-aux arg))
56           ((and (pair? arg) (every markup? arg)) ;; a markup list
57            (format #f "{~{ ~a~}}" (map-in-order markup->lily-string-aux arg)))
58           (else          ;; a scheme argument
59            (format #f "#~a" (scheme-expr->lily-string arg)))))
60   (define (markup->lily-string-aux expr)
61     (if (string? expr)
62         (format #f "~s" expr)
63         (let ((cmd (car expr))
64               (args (cdr expr)))
65           (if (eqv? cmd simple-markup) ;; a simple markup
66               (format #f "~s" (car args))
67               (format #f "\\~a~{ ~a~}" 
68                       (proc->command cmd)
69                       (map-in-order arg->string args))))))
70   (cond ((string? markup-expr)
71          (format #f "~s" markup-expr))
72         ((eqv? (car markup-expr) simple-markup)
73          (format #f "~s" (second markup-expr)))
74         (else
75          (format #f "\\markup ~a"
76                  (markup->lily-string-aux markup-expr)))))
77
78 ;;;
79 ;;; pitch names
80 ;;;
81
82 ;; It is a pity that there is no rassoc in Scheme.
83 (define* (rassoc item alist #:optional (test equal?))
84   (do ((alist alist (cdr alist))
85        (result #f result))
86       ((or result (null? alist)) result)
87     (if (and (car alist) (test item (cdar alist)))
88         (set! result (car alist)))))
89
90 (define (note-name->lily-string ly-pitch)
91   ;; here we define a custom pitch= function, since we do not want to
92   ;; test whether octaves are also equal. (otherwise, we would be using equal?)
93   (define (pitch= pitch1 pitch2)
94     (and (= (ly:pitch-notename pitch1) (ly:pitch-notename pitch2))
95          (= (ly:pitch-alteration pitch1) (ly:pitch-alteration pitch2))))
96   (let ((result (rassoc ly-pitch (ly:parser-lookup (*parser*) 'pitchnames) pitch=)))
97     (if result
98         (car result)
99         #f)))
100
101 (define (octave->lily-string pitch)
102   (let ((octave (ly:pitch-octave pitch)))
103     (cond ((>= octave 0)
104            (make-string (1+ octave) #\'))
105           ((< octave -1)
106            (make-string (1- (* -1 octave)) #\,))
107           (else ""))))
108
109 ;;;
110 ;;; durations
111 ;;;
112 (define* (duration->lily-string ly-duration #:key (prev-duration (*previous-duration*))
113                         (force-duration (*force-duration*))
114                         (time-factor-numerator (*time-factor-numerator*))
115                         (time-factor-denominator (*time-factor-denominator*)))
116   (let ((log2    (ly:duration-log ly-duration))
117         (dots    (ly:duration-dot-count ly-duration))
118         (num+den (ly:duration-factor ly-duration)))
119     (if (or force-duration (not prev-duration) (not (equal? ly-duration prev-duration)))
120         (string-append (case log2
121                          ((-1) "\\breve")
122                          ((-2) "\\longa")
123                          ((-3) "\\maxima")
124                          (else (number->string (expt 2 log2))))
125                        (make-string dots #\.)
126                        (let ((num? (not (or (= 1 (car num+den))
127                                             (and time-factor-numerator
128                                                  (= (car num+den) time-factor-numerator)))))
129                              (den? (not (or (= 1 (cdr num+den))
130                                             (and time-factor-denominator
131                                                  (= (cdr num+den) time-factor-denominator))))))
132                          (cond (den?
133                                 (format #f "*~a/~a" (car num+den) (cdr num+den)))
134                                (num?
135                                 (format #f "*~a" (car num+den)))
136                                (else ""))))
137         "")))
138
139 ;;;
140 ;;; post events
141 ;;;
142
143 (define post-event? (make-music-type-predicate  
144                      'StringNumberEvent
145                      'ArticulationEvent
146                      'FingerEvent
147                      'TextScriptEvent
148                      'MultiMeasureTextEvent
149                      'HyphenEvent
150                      'ExtenderEvent
151                      'BeamEvent
152                      'SlurEvent
153                      'TieEvent
154                      'CrescendoEvent
155                      'DecrescendoEvent
156                      'PhrasingSlurEvent
157                      'TremoloEvent
158                      'SustainEvent
159                      'SostenutoEvent
160                      'ManualMelismaEvent
161                      'TextSpanEvent
162                      'HarmonicEvent
163                      'BeamForbidEvent
164                      'AbsoluteDynamicEvent
165                      'TrillSpanEvent
166                      'GlissandoEvent
167                      'ArpeggioEvent
168                      'NoteGroupingEvent
169                      'UnaCordaEvent))
170
171 (define* (event-direction->lily-string event #:optional (required #t))
172   (let ((direction (ly:music-property event 'direction)))
173     (cond ((or (not direction) (null? direction) (= CENTER direction))
174            (if required "-" ""))
175           ((= UP direction) "^")
176           ((= DOWN direction) "_")
177           (else ""))))
178
179 (define-macro (define-post-event-display-method type vars direction-required str)
180   `(define-display-method ,type ,vars
181      (format #f "~a~a"
182              (event-direction->lily-string ,(car vars) ,direction-required)
183              ,str)))
184
185 (define-macro (define-span-event-display-method type vars direction-required str-start str-stop)
186   `(define-display-method ,type ,vars
187      (format #f "~a~a"
188              (event-direction->lily-string ,(car vars) ,direction-required)
189              (if (= START (ly:music-property ,(car vars) 'span-direction))
190                  ,str-start
191                  ,str-stop))))
192
193 (define-display-method HyphenEvent (event)
194   " --")
195 (define-display-method ExtenderEvent (event)
196   " __")
197 (define-display-method TieEvent (event)
198   " ~")
199 (define-display-method BeamForbidEvent (event)
200   "\\noBeam")
201 (define-display-method StringNumberEvent (event)
202   (format #f "\\~a" (ly:music-property event 'string-number)))
203
204
205 (define-display-method TremoloEvent (event)
206   (let ((tremolo-type (ly:music-property event 'tremolo-type)))
207     (format #f ":~a" (if (= 0 tremolo-type)
208                          ""
209                          tremolo-type))))
210
211 (define-post-event-display-method ArticulationEvent (event) #t
212   (let ((articulation  (ly:music-property event 'articulation-type)))
213     (case (string->symbol articulation)
214       ((marcato) "^")
215       ((stopped) "+")
216       ((tenuto)  "-")
217       ((staccatissimo) "|")
218       ((accent) ">")
219       ((staccato) ".")
220       ((portato) "_")
221       (else (format #f "\\~a" articulation)))))
222
223 (define-post-event-display-method FingerEvent (event) #t
224   (ly:music-property event 'digit))
225
226 (define-post-event-display-method TextScriptEvent (event) #t
227   (markup->lily-string (ly:music-property event 'text)))
228
229 (define-post-event-display-method MultiMeasureTextEvent (event) #t
230   (markup->lily-string (ly:music-property event 'text)))
231
232 (define-post-event-display-method HarmonicEvent (event) #t "\\harmonic")
233 (define-post-event-display-method GlissandoEvent (event) #t "\\glissando")
234 (define-post-event-display-method ArpeggioEvent (event) #t "\\arpeggio")
235 (define-post-event-display-method AbsoluteDynamicEvent (event) #f
236   (format #f "\\~a" (ly:music-property event 'text)))
237
238 (define-span-event-display-method BeamEvent (event) #f "[" "]")
239 (define-span-event-display-method SlurEvent (event) #f "(" ")")
240 (define-span-event-display-method CrescendoEvent (event) #f "\\<" "\\!")
241 (define-span-event-display-method DecrescendoEvent (event) #f "\\>" "\\!")
242 (define-span-event-display-method PhrasingSlurEvent (event) #f "\\(" "\\)")
243 (define-span-event-display-method SustainEvent (event) #f "\\sustainDown" "\\sustainUp")
244 (define-span-event-display-method SostenutoEvent (event) #f "\\sostenutoDown" "\\sostenutoUp")
245 (define-span-event-display-method ManualMelismaEvent (event) #f "\\melisma" "\\melismaEnd")
246 (define-span-event-display-method TextSpanEvent (event) #f "\\startTextSpan" "\\stopTextSpan")
247 (define-span-event-display-method TrillSpanEvent (event) #f "\\startTrillSpan" "\\stopTrillSpan")
248 (define-span-event-display-method StaffSpanEvent (event) #f "\\startStaff" "\\stopStaff")
249 (define-span-event-display-method NoteGroupingEvent (event) #f "\\startGroup" "\\stopGroup")
250 (define-span-event-display-method UnaCordaEvent (event) #f "\\unaCorda" "\\treCorde")
251
252 ;;;
253 ;;; Graces
254 ;;;
255
256 (define-display-method GraceMusic (expr)
257   (format #f "\\grace ~a" 
258           (music->lily-string (ly:music-property expr 'element))))
259
260 ;; \acciaccatura \appoggiatura \grace
261 ;; TODO: it would be better to compare ?start and ?stop
262 ;; with startAppoggiaturaMusic and stopAppoggiaturaMusic,
263 ;; using a custom music equality predicate.
264 (define-extra-display-method GraceMusic (expr)
265   "Display method for appoggiatura."
266   (with-music-match (expr (music
267                            'GraceMusic
268                            element (music
269                                     'SequentialMusic
270                                     elements (?start
271                                               ?music
272                                               ?stop))))
273     ;; we check whether ?start and ?stop look like
274     ;; startAppoggiaturaMusic stopAppoggiaturaMusic
275     (and (with-music-match (?start (music 
276                                     'SequentialMusic
277                                     elements ((music
278                                                'EventChord
279                                                elements ((music
280                                                           'SkipEvent
281                                                           duration (ly:make-duration 0 0 0 1))
282                                                          (music
283                                                           'SlurEvent
284                                                           span-direction START))))))
285                            #t)
286           (with-music-match (?stop (music 
287                                     'SequentialMusic
288                                     elements ((music
289                                                'EventChord
290                                                elements ((music
291                                                           'SkipEvent
292                                                           duration (ly:make-duration 0 0 0 1))
293                                                          (music
294                                                           'SlurEvent
295                                                           span-direction STOP))))))
296             (format #f "\\appoggiatura ~a" (music->lily-string ?music))))))
297
298
299 (define-extra-display-method GraceMusic (expr)
300   "Display method for acciaccatura."
301   (with-music-match (expr (music
302                            'GraceMusic
303                            element (music
304                                     'SequentialMusic
305                                     elements (?start
306                                               ?music
307                                               ?stop))))
308     ;; we check whether ?start and ?stop look like
309     ;; startAcciaccaturaMusic stopAcciaccaturaMusic
310     (and (with-music-match (?start (music 
311                                     'SequentialMusic
312                                     elements ((music
313                                                'EventChord
314                                                elements ((music
315                                                           'SkipEvent
316                                                           duration (ly:make-duration 0 0 0 1))
317                                                          (music
318                                                           'SlurEvent
319                                                           span-direction START)))
320                                               (music
321                                                'ContextSpeccedMusic
322                                                element (music
323                                                         'OverrideProperty
324                                                         grob-property-path '(stroke-style)
325                                                         grob-value "grace"
326                                                         symbol 'Stem)))))
327                            #t)
328          (with-music-match (?stop (music 
329                                    'SequentialMusic
330                                    elements ((music
331                                               'ContextSpeccedMusic
332                                               element (music
333                                                        'RevertProperty
334                                                        grob-property-path '(stroke-style)
335                                                        symbol 'Stem))
336                                              (music
337                                               'EventChord
338                                               elements ((music
339                                                          'SkipEvent
340                                                          duration (ly:make-duration 0 0 0 1))
341                                                         (music
342                                                          'SlurEvent
343                                                          span-direction STOP))))))
344            (format #f "\\acciaccatura ~a" (music->lily-string ?music))))))
345
346 (define-extra-display-method GraceMusic (expr)
347   "Display method for grace."
348   (with-music-match (expr (music
349                            'GraceMusic
350                            element (music
351                                     'SequentialMusic
352                                     elements (?start
353                                               ?music
354                                               ?stop))))
355     ;; we check whether ?start and ?stop look like
356     ;; startGraceMusic stopGraceMusic
357     (and (null? (ly:music-property ?start 'elements))
358          (null? (ly:music-property ?stop 'elements))
359          (format #f "\\grace ~a" (music->lily-string ?music)))))
360
361 ;;;
362 ;;; Music sequences
363 ;;;
364
365 (define-display-method SequentialMusic (seq)
366   (let ((force-line-break (and (*force-line-break*)
367                                ;; hm 
368                                (> (length (ly:music-property seq 'elements))
369                                   (*max-element-number-before-break*))))
370         (elements (ly:music-property seq 'elements))
371         (chord? (make-music-type-predicate 'EventChord))
372         (cluster? (make-music-type-predicate 'ClusterNoteEvent))
373         (note? (make-music-type-predicate 'NoteEvent)))
374     (format #f "~a~a{~v%~v_~{~a ~}~v%~v_}"
375             (if (any (lambda (e)
376                        (and (chord? e)
377                             (any cluster? (ly:music-property e 'elements))))
378                      elements)
379                 "\\makeClusters "
380                 "")
381             (if (*explicit-mode*)
382                 ;; if the sequence contains EventChord which contains figures ==> figuremode
383                 ;; if the sequence contains EventChord which contains lyrics ==> lyricmode
384                 ;; if the sequence contains EventChord which contains drum notes ==> drummode
385                 (cond ((any (lambda (chord)
386                               (any (make-music-type-predicate 'BassFigureEvent)
387                                    (ly:music-property chord 'elements)))
388                             (filter chord? elements))
389                        "\\figuremode ")
390                       ((any (lambda (chord)
391                               (any (make-music-type-predicate 'LyricEvent)
392                                    (ly:music-property chord 'elements)))
393                             (filter chord? elements))
394                        "\\lyricmode ")
395                       ((any (lambda (chord)
396                               (any (lambda (event)
397                                      (and (note? event)
398                                           (not (null? (ly:music-property event 'drum-type)))))
399                                    (ly:music-property chord 'elements)))
400                             (filter chord? elements))
401                        "\\drummode ")
402                       (else ;; TODO: other modes?
403                        ""))
404                 "")
405             (if force-line-break 1 0)
406             (if force-line-break (+ 2 (*indent*)) 1)
407             (parameterize ((*indent* (+ 2 (*indent*))))
408                           (map-in-order music->lily-string elements))
409             (if force-line-break 1 0)
410             (if force-line-break (*indent*) 0))))
411
412 (define-display-method SimultaneousMusic (sim)
413   (parameterize ((*indent* (+ 3 (*indent*))))
414     (format #f "<< ~{~a ~}>>"
415             (map-in-order music->lily-string (ly:music-property sim 'elements)))))
416
417 (define-extra-display-method SimultaneousMusic (expr)
418   "If `sim' is an \afterGrace expression, return \"\\afterGrace ...\".
419 Otherwise, return #f."
420   ;; TODO: do something with afterGraceFraction?
421   (with-music-match (expr (music 'SimultaneousMusic
422                                  elements (?before-grace
423                                            (music 'SequentialMusic
424                                                   elements ((music 'SkipMusic)
425                                                             (music 'GraceMusic
426                                                                    element ?grace))))))
427     (format #f "\\afterGrace ~a ~a"
428             (music->lily-string ?before-grace)
429             (music->lily-string ?grace))))
430   
431 ;;;
432 ;;; Chords
433 ;;;
434
435 (define-display-method EventChord (chord)
436   ;; event_chord : simple_element post_events
437   ;;               | command_element
438   ;;               | note_chord_element
439
440   ;; TODO : tagged post_events
441   ;; post_events : ( post_event | tagged_post_event )*
442   ;; tagged_post_event: '-' \tag embedded_scm post_event
443
444   (let* ((elements (ly:music-property chord 'elements))
445          (simple-elements (filter (make-music-type-predicate 
446                                    'NoteEvent 'ClusterNoteEvent 'RestEvent
447                                    'MultiMeasureRestEvent 'SkipEvent 'LyricEvent)
448                                   elements)))
449     (if ((make-music-type-predicate 'StaffSpanEvent 'BreathingSignEvent) (car elements))
450         ;; first, a special case: StaffSpanEvent (\startStaff, \stopStaff)
451         ;; and BreathingSignEvent (\breathe)
452         (music->lily-string (car elements))
453         (if (and (not (null? simple-elements))
454                  (null? (cdr simple-elements)))
455             ;; simple_element : note | figure | rest | mmrest | lyric_element | skip
456             (let* ((simple-element (car simple-elements))
457                    (duration (ly:music-property simple-element 'duration))
458                    (lily-string (format #f "~a~a~a~{~a ~}"
459                                         (music->lily-string simple-element)
460                                         (duration->lily-string duration)
461                                         (if (and ((make-music-type-predicate 'RestEvent) simple-element)
462                                                  (ly:pitch? (ly:music-property simple-element 'pitch)))
463                                             "\\rest"
464                                             "")
465                                         (map-in-order music->lily-string (filter post-event? elements)))))
466               (*previous-duration* duration)
467               lily-string)
468             (let ((chord-elements (filter (make-music-type-predicate
469                                            'NoteEvent 'ClusterNoteEvent 'BassFigureEvent)
470                                           elements))
471                   (post-events (filter post-event? elements)))
472               (if (not (null? chord-elements))
473                   ;; note_chord_element : '<' (notepitch | drumpitch)* '>" duration post_events
474                   (let ((lily-string (format #f "< ~{~a ~}>~a~{~a ~}"
475                                              (map-in-order music->lily-string chord-elements)
476                                              (duration->lily-string (ly:music-property (car chord-elements)
477                                                                                      'duration))
478                                              (map-in-order music->lily-string post-events))))
479                     (*previous-duration* (ly:music-property (car chord-elements) 'duration))
480                     lily-string)
481                   ;; command_element
482                   (format #f "~{~a ~}" (map-in-order music->lily-string elements))))))))
483
484 (define-display-method MultiMeasureRestMusicGroup (mmrest)
485   (format #f "~{~a ~}"
486           (map-in-order music->lily-string 
487                         (remove (make-music-type-predicate 'BarCheck)
488                                 (ly:music-property mmrest 'elements)))))
489
490 (define-display-method SkipMusic (skip)
491   (format #f "\\skip ~a" (duration->lily-string (ly:music-property skip 'duration) #:force-duration #t)))
492
493 ;;;
494 ;;; Notes, rests, skips...
495 ;;;
496
497 (define (simple-note->lily-string event)
498   (format #f "~a~a~a~a~{~a~}" ; pitchname octave !? octave-check articulations
499           (note-name->lily-string (ly:music-property event 'pitch))
500           (octave->lily-string (ly:music-property event 'pitch))
501           (let ((forced (ly:music-property event 'force-accidental))
502                 (cautionary (ly:music-property event 'cautionary)))
503             (cond ((and (not (null? forced))
504                         forced
505                         (not (null? cautionary))
506                         cautionary)
507                    "?")
508                   ((and (not (null? forced)) forced) "!")
509                   (else "")))
510           (let ((octave-check (ly:music-property event 'absolute-octave)))
511             (if (not (null? octave-check))
512                 (format #f "=~a" (cond ((>= octave-check 0)
513                                         (make-string (1+ octave-check) #\'))
514                                        ((< octave-check -1)
515                                         (make-string (1- (* -1 octave-check)) #\,))
516                                        (else "")))
517                 ""))
518           (map-in-order music->lily-string (ly:music-property event 'articulations))))
519
520 (define-display-method NoteEvent (note)
521   (cond ((not (null? (ly:music-property note 'pitch))) ;; note
522          (simple-note->lily-string note))
523         ((not (null? (ly:music-property note 'drum-type))) ;; drum
524          (format #f "~a" (ly:music-property note 'drum-type)))
525         (else ;; unknown?
526          "")))
527
528 (define-display-method ClusterNoteEvent (note)
529   (simple-note->lily-string note))
530
531 (define-display-method RestEvent (rest)
532   (if (not (null? (ly:music-property rest 'pitch)))
533       (simple-note->lily-string rest)
534       "r"))
535
536 (define-display-method MultiMeasureRestEvent (rest)
537   "R")
538
539 (define-display-method SkipEvent (rest)
540   "s")
541
542 (define-display-method MarkEvent (mark)
543   (let ((label (ly:music-property mark 'label)))
544     (if (null? label)
545         "\\mark \\default"
546         (format #f "\\mark ~a" (markup->lily-string label)))))
547
548 (define-display-method MetronomeChangeEvent (tempo)
549   (format #f "\\tempo ~a = ~a"
550           (duration->lily-string (ly:music-property tempo 'tempo-unit) #:force-duration #f #:prev-duration #f)
551           (ly:music-property tempo 'metronome-count)))
552
553 (define-display-method KeyChangeEvent (key)
554   (let ((pitch-alist (ly:music-property key 'pitch-alist))
555         (tonic (ly:music-property key 'tonic)))
556     (if (or (null? pitch-alist)
557             (null? tonic))
558         "\\key \\default"
559         (let ((c-pitch-alist (ly:transpose-key-alist pitch-alist 
560                                                      (ly:pitch-diff (ly:make-pitch 0 0 0) tonic))))
561           (format #f "\\key ~a \\~a~a"
562                   (note-name->lily-string (ly:music-property key 'tonic))
563                   (any (lambda (mode)
564                          (if (and (*parser*)
565                                   (equal? (ly:parser-lookup (*parser*) mode) c-pitch-alist))
566                              (symbol->string mode)
567                              #f))
568                        '(major minor ionian locrian aeolian mixolydian lydian phrygian dorian))
569                   (new-line->lily-string))))))
570
571 (define-display-method RelativeOctaveCheck (octave)
572   (let ((pitch (ly:music-property octave 'pitch)))
573     (format #f "\\octave ~a~a"
574             (note-name->lily-string pitch)
575             (octave->lily-string pitch))))
576
577 (define-display-method VoiceSeparator (sep)
578   "\\\\")
579
580 (define-display-method LigatureEvent (ligature)
581   (if (= START (ly:music-property ligature 'span-direction))
582       "\\["
583       "\\]"))
584
585 (define-display-method BarCheck (check)
586   (format #f "|~a" (new-line->lily-string)))
587
588 ;; TODO: also display something when there is a penalty?
589 (define-display-method LineBreakEvent (br)
590   (if (eq? (ly:music-property br 'break-permission) 'forbid)
591       ("\\noBreak")
592       ("\\break")))
593
594 (define-display-method PageBreakEvent (br)
595   (if (eq? (ly:music-property br 'break-permission) 'forbid)
596       ("\\noPageBreak")
597       ("\\pageBreak")))
598
599 (define-display-method PageTurnEvent (br)
600   (if (eq? (ly:music-property br 'break-permission) 'forbid)
601       ("\\noPageTurn")
602       ("\\pageTurn")))
603
604 (define-display-method PesOrFlexaEvent (expr)
605   "\\~")
606
607 (define-display-method BassFigureEvent (figure)
608   (let ((alteration (ly:music-property figure 'alteration))
609         (fig (ly:music-property figure 'figure))
610         (bracket-start (ly:music-property figure 'bracket-start))
611         (bracket-stop (ly:music-property figure 'bracket-stop)))
612     (format #f "~a~a~a~a"
613             (if (null? bracket-start) "" "[")
614             (cond ((null? fig) "_")
615                   ((markup? fig) (second fig)) ;; fig: (<number-markup> "number")
616                   (else fig))
617             (if (null? alteration)
618                 ""
619                 (case alteration
620                   ((-4) "--")
621                   ((-2) "-")
622                   ((0) "!")
623                   ((2) "+")
624                   ((4) "++")
625                   (else "")))
626             (if (null? bracket-stop) "" "]"))))
627
628 (define-display-method LyricEvent (lyric)
629   (let ((text (ly:music-property lyric 'text)))
630     (if (or (string? text)
631             (eqv? (first text) simple-markup))
632         ;; a string or a simple markup
633         (let ((string (if (string? text)
634                           text
635                           (second text))))
636           (if (string-match "(\"| |[0-9])" string)
637               ;; TODO check exactly in which cases double quotes should be used
638               (format #f "~s" string)
639               string))
640         (markup->lily-string text))))
641
642 (define-display-method BreathingSignEvent (event)
643   "\\breathe")
644
645 ;;;
646 ;;; Staff switches
647 ;;;
648
649 (define-display-method AutoChangeMusic (m)
650   (format #f "\\autochange ~a"
651           (music->lily-string (ly:music-property m 'element))))
652
653 (define-display-method ContextChange (m)
654   (format #f "\\change ~a = \"~a\""
655           (ly:music-property m 'change-to-type)
656           (ly:music-property m 'change-to-id)))
657
658 ;;;
659
660 (define-display-method TimeScaledMusic (times)
661   (let* ((num (ly:music-property times 'numerator))
662          (den (ly:music-property times 'denominator))
663          (nd-gcd (gcd num den)))
664     (parameterize ((*force-line-break* #f)
665                    (*time-factor-numerator* (/ num nd-gcd))
666                    (*time-factor-denominator* (/ den nd-gcd)))
667       (format #f "\\times ~a/~a ~a" 
668               num
669               den
670               (music->lily-string (ly:music-property times 'element))))))
671
672 (define-display-method RelativeOctaveMusic (m)
673   (music->lily-string (ly:music-property m 'element)))
674
675 (define-display-method TransposedMusic (m)
676   (music->lily-string (ly:music-property m 'element)))
677
678 ;;;
679 ;;; Repeats
680 ;;;
681
682 (define (repeat->lily-string expr repeat-type)
683   (format #f "\\repeat ~a ~a ~a ~a"
684           repeat-type
685           (ly:music-property expr 'repeat-count)
686           (music->lily-string (ly:music-property expr 'element))
687           (let ((alternatives (ly:music-property expr 'elements)))
688             (if (null? alternatives)
689                 ""
690                 (format #f "\\alternative { ~{~a ~}}"
691                         (map-in-order music->lily-string alternatives))))))
692
693 (define-display-method VoltaRepeatedMusic (expr)
694   (repeat->lily-string expr "volta"))
695
696 (define-display-method UnfoldedRepeatedMusic (expr)
697   (repeat->lily-string expr "unfold"))
698
699 (define-display-method FoldedRepeatedMusic (expr)
700   (repeat->lily-string expr "fold"))
701
702 (define-display-method PercentRepeatedMusic (expr)
703   (repeat->lily-string expr "percent"))
704
705 (define-display-method TremoloRepeatedMusic (expr)
706   (let* ((count (ly:music-property expr 'repeat-count))
707          (dots (if (= 0 (modulo count 3)) 0 1))
708          (shift (- (log2 (if (= 0 dots)
709                              (/ (* count 2) 3)
710                              count))))
711          (element (ly:music-property expr 'element))
712          (den-mult 1))
713     (if (eqv? (ly:music-property element 'name) 'SequentialMusic)
714         (begin
715           (set! shift (1- shift))
716           (set! den-mult (length (ly:music-property element 'elements)))))
717     (music-map (lambda (m)
718                  (let ((duration (ly:music-property m 'duration)))
719                    (if (ly:duration? duration)
720                        (let* ((dlog (ly:duration-log duration))
721                               (ddots (ly:duration-dot-count duration))
722                               (dfactor (ly:duration-factor duration))
723                               (dnum (car dfactor))
724                               (dden (cdr dfactor)))
725                          (set! (ly:music-property m 'duration)
726                                (ly:make-duration (- dlog shift)
727                                                  ddots ;;(- ddots dots) ; ????
728                                                  dnum
729                                                  (/ dden den-mult))))))
730                  m)
731                element)
732     (format #f "\\repeat tremolo ~a ~a"
733             count
734             (music->lily-string element))))
735
736 ;;;
737 ;;; Contexts
738 ;;; 
739
740 (define-display-method ContextSpeccedMusic (expr)
741   (let ((id    (ly:music-property expr 'context-id))
742         (create-new (ly:music-property expr 'create-new))
743         (music (ly:music-property expr 'element))
744         (operations (ly:music-property expr 'property-operations))
745         (ctype (ly:music-property expr 'context-type)))
746     (format #f "~a ~a~a~a ~a"
747             (if (and (not (null? create-new)) create-new)
748                 "\\new"
749                 "\\context")
750             ctype
751             (if (null? id)
752                 ""
753                 (format #f " = ~s" id))
754             (if (null? operations)
755                 "" 
756                 (format #f " \\with {~{~a~}~%~v_}" 
757                         (parameterize ((*indent* (+ (*indent*) 2)))
758                           (map (lambda (op)
759                                  (format #f "~%~v_\\~a ~s"
760                                          (*indent*)
761                                          (first op)
762                                          (second op)))
763                                (reverse operations)))
764                         (*indent*)))
765             (parameterize ((*current-context* ctype))
766               (music->lily-string music)))))
767
768 ;; special cases: \figures \lyrics \drums
769 (define-extra-display-method ContextSpeccedMusic (expr)
770   (with-music-match (expr (music 'ContextSpeccedMusic
771                                  create-new #t
772                                  property-operations ?op
773                                  context-type ?context-type
774                                  element ?sequence))
775     (if (null? ?op)
776         (parameterize ((*explicit-mode* #f))
777           (case ?context-type
778             ((FiguredBass)
779              (format #f "\\figures ~a" (music->lily-string ?sequence)))
780             ((Lyrics)
781              (format #f "\\lyrics ~a" (music->lily-string ?sequence)))
782             ((DrumStaff)
783              (format #f "\\drums ~a" (music->lily-string ?sequence)))
784             (else
785              #f)))
786         #f)))
787
788 ;;; Context properties
789
790 (define-extra-display-method ContextSpeccedMusic (expr)
791   (let ((element (ly:music-property expr 'element))
792         (property-tuning? (make-music-type-predicate 'PropertySet
793                                                      'PropertyUnset
794                                                      'OverrideProperty
795                                                      'RevertProperty))
796         (sequence? (make-music-type-predicate 'SequentialMusic)))
797     (if (and (ly:music? element)
798              (or (property-tuning? element)
799                  (and (sequence? element)
800                       (every property-tuning? (ly:music-property element 'elements)))))
801         (parameterize ((*current-context* (ly:music-property expr 'context-type)))
802           (music->lily-string element))
803         #f)))
804
805 (define (property-value->lily-string arg)
806   (cond ((ly:music? arg)
807          (music->lily-string arg))
808         ((string? arg)
809          (format #f "#~s" arg))
810         ((markup? arg)
811          (markup->lily-string arg))
812         (else
813          (format #f "#~a" (scheme-expr->lily-string arg)))))
814
815 (define-display-method PropertySet (expr)
816   (let ((property (ly:music-property expr 'symbol))
817         (value (ly:music-property expr 'value))
818         (once (ly:music-property expr 'once)))
819     (format #f "~a\\set ~a~a = ~a~a"
820             (if (and (not (null? once)))
821                 "\\once "
822                 "")
823             (if (eqv? (*current-context*) 'Bottom) 
824                 "" 
825                 (format #f "~a . " (*current-context*)))
826             property
827             (property-value->lily-string value)
828             (new-line->lily-string))))
829
830 (define-display-method PropertyUnset (expr)
831   (format #f "\\unset ~a~a~a"
832           (if (eqv? (*current-context*) 'Bottom) 
833               "" 
834               (format #f "~a . " (*current-context*)))
835           (ly:music-property expr 'symbol)
836           (new-line->lily-string)))
837
838 ;;; Layout properties
839
840 (define-display-method OverrideProperty (expr)
841   (let ((symbol   (ly:music-property expr 'symbol))
842         (properties (ly:music-property expr 'grob-property-path))
843         (value    (ly:music-property expr 'grob-value))
844         (once     (ly:music-property expr 'once)))
845     (format #f "~a\\override ~a~a #'~a = ~a~a"
846             (if (or (null? once)
847                     (not once))
848                 ""
849                 "\\once ")
850             (if (eqv? (*current-context*) 'Bottom) 
851                 "" 
852                 (format #f "~a . " (*current-context*)))
853             symbol
854             (if (null? (cdr properties))
855                 (car properties)
856                 properties)
857             (property-value->lily-string value)
858             (new-line->lily-string))))
859             
860 (define-display-method RevertProperty (expr)
861   (let ((symbol (ly:music-property expr 'symbol))
862         (properties (ly:music-property expr 'grob-property-path)))
863     (format #f "\\revert ~a~a #'~a~a"
864             (if (eqv? (*current-context*) 'Bottom) 
865                 "" 
866                 (format #f "~a . " (*current-context*)))
867             symbol
868             (if (null? (cdr properties))
869                 (car properties)
870                 properties)
871             (new-line->lily-string))))
872
873 ;;; \clef 
874 (define clef-name-alist (map (lambda (name+vals)
875                                (cons (cdr name+vals)
876                                      (car name+vals)))
877                              supported-clefs))
878
879 (define-extra-display-method ContextSpeccedMusic (expr)
880   "If `expr' is a clef change, return \"\\clef ...\"
881 Otherwise, return #f."
882   (with-music-match (expr (music 'ContextSpeccedMusic
883                                  context-type 'Staff
884                                  element (music 'SequentialMusic
885                                                 elements ((music 'PropertySet
886                                                                  value ?clef-glyph
887                                                                  symbol 'clefGlyph)
888                                                           (music 'PropertySet
889                                                                  symbol 'middleCPosition)
890                                                           (music 'PropertySet
891                                                                  value ?clef-position
892                                                                  symbol 'clefPosition)
893                                                           (music 'PropertySet
894                                                                  value ?clef-octavation
895                                                                  symbol 'clefOctavation)))))
896     (let ((clef-prop+name (assoc (list ?clef-glyph ?clef-position 0)
897                                  clef-name-alist)))
898       (if clef-prop+name
899           (format #f "\\clef \"~a~{~a~a~}\"~a"
900                   (cdr clef-prop+name)
901                   (cond ((= 0 ?clef-octavation)
902                          (list "" ""))
903                         ((> ?clef-octavation 0)
904                          (list "^" (1+ ?clef-octavation)))
905                         (else
906                          (list "_" (- 1 ?clef-octavation))))
907                   (new-line->lily-string))
908           #f))))
909
910 ;;; \time
911 (define-extra-display-method ContextSpeccedMusic (expr)
912   "If `expr' is a time signature set, return \"\\time ...\".
913 Otherwise, return #f."
914   (with-music-match (expr (music 
915                            'ContextSpeccedMusic
916                            element (music 
917                                     'ContextSpeccedMusic
918                                     context-type 'Timing
919                                     element (music 
920                                              'SequentialMusic
921                                              elements ((music 
922                                                         'PropertySet
923                                                         value ?num+den
924                                                         symbol 'timeSignatureFraction)
925                                                        (music
926                                                         'PropertySet
927                                                         symbol 'beatLength)
928                                                        (music
929                                                         'PropertySet
930                                                         symbol 'measureLength)
931                                                        (music
932                                                         'PropertySet
933                                                         value ?grouping
934                                                         symbol 'beatGrouping))))))
935     (if (null? ?grouping)
936         (format #f "\\time ~a/~a~a" (car ?num+den) (cdr ?num+den) (new-line->lily-string))
937         (format #f "#(set-time-signature ~a ~a '~s)~a"
938                 (car ?num+den) (cdr ?num+den) ?grouping (new-line->lily-string)))))
939
940 ;;; \bar
941 (define-extra-display-method ContextSpeccedMusic (expr)
942   "If `expr' is a bar, return \"\\bar ...\".
943 Otherwise, return #f."
944   (with-music-match (expr (music 'ContextSpeccedMusic
945                                  context-type 'Timing
946                                  element (music 'PropertySet
947                                                 value ?bar-type
948                                                 symbol 'whichBar)))
949      (format #f "\\bar \"~a\"~a" ?bar-type (new-line->lily-string))))
950
951 ;;; \partial
952 (define (duration->moment ly-duration)
953   (let ((log2    (ly:duration-log ly-duration))
954         (dots    (ly:duration-dot-count ly-duration))
955         (num+den (ly:duration-factor ly-duration)))
956     (let* ((m (expt 2 (- log2)))
957            (factor (/ (car num+den) (cdr num+den))))
958       (/ (do ((i 0 (1+ i))
959               (delta (/ m 2) (/ delta 2)))
960              ((= i dots) m)
961            (set! m (+ m delta)))
962          factor))))
963 (define moment-duration-alist (map (lambda (duration)
964                                      (cons (duration->moment duration)
965                                            duration))
966                                    (append-map (lambda (log2)
967                                                  (map (lambda (dots)
968                                                         (ly:make-duration log2 dots 1 1))
969                                                       (list 0 1 2 3)))
970                                                (list 0 1 2 3 4))))
971
972 (define (moment->duration moment)
973   (let ((result (assoc (- moment) moment-duration-alist)))
974     (and result 
975          (cdr result))))
976
977 (define-extra-display-method ContextSpeccedMusic (expr)
978   "If `expr' is a partial measure, return \"\\partial ...\".
979 Otherwise, return #f."
980   (with-music-match (expr (music
981                            'ContextSpeccedMusic
982                            element (music
983                                     'ContextSpeccedMusic
984                                     context-type 'Timing
985                                     element (music
986                                              'PropertySet
987                                              value ?moment
988                                              symbol 'measurePosition))))
989      (let ((duration (moment->duration (/ (ly:moment-main-numerator ?moment)
990                                           (ly:moment-main-denominator ?moment)))))
991        (and duration (format #f "\\partial ~a" (duration->lily-string duration #:force-duration #t))))))
992
993 ;;;
994 ;;;
995
996 (define-display-method ApplyOutputEvent (applyoutput)
997   (let ((proc (ly:music-property applyoutput 'procedure)))
998     (format #f "\\applyOutput #~a"
999             (or (procedure-name proc)
1000                 (with-output-to-string
1001                   (lambda ()
1002                     (pretty-print (procedure-source proc))))))))
1003
1004 (define-display-method ApplyContext (applycontext)
1005   (let ((proc (ly:music-property applycontext 'procedure)))
1006     (format #f "\\applyContext #~a"
1007             (or (procedure-name proc)
1008                 (with-output-to-string
1009                   (lambda ()
1010                     (pretty-print (procedure-source proc))))))))
1011
1012 ;;; \partcombine
1013 (define-display-method PartCombineMusic (expr)
1014   (format #f "\\partcombine ~{~a ~}"
1015           (map-in-order music->lily-string (ly:music-property expr 'elements))))
1016
1017 (define-extra-display-method PartCombineMusic (expr)
1018   (with-music-match (expr (music 'PartCombineMusic
1019                                  elements ((music 'UnrelativableMusic
1020                                                   element (music 'ContextSpeccedMusic
1021                                                                  context-id "one"
1022                                                                  context-type 'Voice
1023                                                                  element ?sequence1))
1024                                            (music 'UnrelativableMusic
1025                                                   element (music 'ContextSpeccedMusic
1026                                                                  context-id "two"
1027                                                                  context-type 'Voice
1028                                                                  element ?sequence2)))))
1029     (format #f "\\partcombine ~a~a~a"
1030             (music->lily-string ?sequence1)
1031             (new-line->lily-string)
1032             (music->lily-string ?sequence2))))
1033
1034 (define-display-method UnrelativableMusic (expr)
1035   (music->lily-string (ly:music-property expr 'element)))
1036
1037 ;;; Cue notes
1038 (define-display-method QuoteMusic (expr)
1039   (or (with-music-match (expr (music
1040                                'QuoteMusic
1041                                quoted-voice-direction ?quoted-voice-direction
1042                                quoted-music-name ?quoted-music-name
1043                                quoted-context-id "cue"
1044                                quoted-context-type 'Voice
1045                                element ?music))
1046         (format #f "\\cueDuring #~s #~a ~a"
1047                 ?quoted-music-name
1048                 ?quoted-voice-direction
1049                 (music->lily-string ?music)))
1050       (format #f "\\quoteDuring #~s ~a"
1051               (ly:music-property expr 'quoted-music-name)
1052               (music->lily-string (ly:music-property expr 'element)))))
1053
1054 ;;;
1055 ;;; Lyrics
1056 ;;;
1057
1058 ;;; \lyricsto
1059 (define-display-method LyricCombineMusic (expr)
1060   (format #f "\\lyricsto ~s ~a"
1061           (ly:music-property expr 'associated-context)
1062           (parameterize ((*explicit-mode* #f))
1063             (music->lily-string (ly:music-property expr 'element)))))
1064
1065 (define-display-method OldLyricCombineMusic (expr)
1066   (format #f "\\oldaddlyrics ~a~a~a"
1067           (music->lily-string (first (ly:music-property expr 'elements)))
1068           (new-line->lily-string)
1069           (music->lily-string (second (ly:music-property expr 'elements)))))
1070
1071 ;; \addlyrics
1072 (define-extra-display-method SimultaneousMusic (expr)
1073   (with-music-match (expr (music 'SimultaneousMusic
1074                                  elements ((music 'ContextSpeccedMusic
1075                                                   context-id ?id
1076                                                   context-type 'Voice
1077                                                   element ?note-sequence)
1078                                            (music 'ContextSpeccedMusic
1079                                                   context-type 'Lyrics
1080                                                   create-new #t
1081                                                   element (music 'LyricCombineMusic
1082                                                                  associated-context ?associated-id
1083                                                                  element ?lyric-sequence)))))
1084     (if (string=? ?id ?associated-id)
1085         (format #f "~a~a \\addlyrics ~a"
1086                 (music->lily-string ?note-sequence)
1087                 (new-line->lily-string)
1088                 (parameterize ((*explicit-mode* #f))
1089                   (music->lily-string ?lyric-sequence)))
1090         #f)))
1091
1092