Use proper score/book handler so scores inside a book work automatically
[orchestrallily.git] / orchestrallily.ily
blob8c92b52bf623c87042ffdb548cb147258a75a231
1 \version "2.11.41"
3 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4 % OrchestralLily
5 % ==============
6 % Desciption:  Lilypond package to make writing large orchestral scores easier.
7 % Documentation: http://wiki.kainhofer.com/lilypond/orchestrallily
8 % Version: 0.02, 2008-03-06
9 % Author: Reinhold Kainhofer, reinhold@kainhofer.com
10 % Copyright: (C) 2008 by Reinhold Kainhofer
11 % License: GPL v3.0, http://www.gnu.org/licenses/gpl.html
13 % Version History:
14 % 0.01 (2008-03-02): Initial Version
15 % 0.02 (2008-03-06): Added basic MIDI support (*MidiInstrument and \setCreateMIDI)
16 % 0.03 (2008-07-xx): General staff/voice types, title pages, etc.
17 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
19 #(use-modules (ice-9 match))
22 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
23 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
24 %%%%%   SCORE STRUCTURE AND AUTOMATIC GENERATION
25 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
26 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
31 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
32 % Helper functions
33 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
35 % Helper function to filter all non-null entries
36 #(define (not-null? x) (not (null? x)))
38 % Helper function to extract a given variable, built from [Piece][Instrument]Identifier
39 #(define (namedPieceInstrObject piece instr name)
40   (let* (
41          (fullname  (string->symbol (string-append piece instr name)))
42          (instrname (string->symbol (string-append instr name)))
43          (piecename (string->symbol (string-append piece name)))
44         )
45     (cond
46       ((defined? fullname) (primitive-eval fullname))
47       ((defined? instrname) (primitive-eval instrname))
48       ((defined? piecename) (primitive-eval piecename))
49       (else '())
50     )
51   )
54 %% Print text as a justified paragraph, taken from the lilypond Notation Reference
55 #(define-markup-list-command (paragraph layout props args) (markup-list?)
56    (let ((indent (chain-assoc-get 'par-indent props 2)))
57      (interpret-markup-list layout props
58        (make-justified-lines-markup-list (cons (make-hspace-markup indent)
59                                                args)))))
61 conditionalBreak = #(define-music-function (parser location) ()
62    #{ \tag #'instrumental-score \pageBreak #}
65 #(define (oly:piece-title-markup title) (markup #:column (#:line (#:fontsize #'3 #:bold title))) )
67 #(define-markup-command (piece-title layout props title) (markup?)
68      (interpret-markup layout props (oly:piece-title-markup title))
71 #(define (oly:generate_object_name piece instr obj )
72   (if (and (string? piece) (string? instr) (string? obj))
73     (string-append piece instr obj)
74     #f
75   )
77 #(define (oly:generate_staff_name piece instr) (oly:generate_object_name piece instr "St"))
79 #(define (set-context-property context property value)
80   (set! (ly:music-property context property) value)
84 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
85 % Score structure and voice types
86 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
88 #(define oly:LiedScoreStructure '(
89   ("SoloScore" "SimultaneousMusic" ("Singstimme"))
90   ("Pfe" "PianoStaff" ("PfeI" "PfeII"))
91   ;("PfeI" "ParallelVoicesStaff" ("OIa" "OIb"))
92   ;("PfeII" "ParallelVoicesStaff" ("OIIa" "OIIb"))
93   ("FullScore" "SimultaneousMusic" ("Singstimme" "Pfe"))
94   ("VocalScore" "SimultaneousMusic" ("Singstimme" "Pfe"))
97 #(define oly:fullOrchestraScoreStructure '(
98 ; Part-combined staves for full score
99   ("Fl" "PartCombinedStaff" ("FlI" "FlII"))
100   ("Ob" "PartCombinedStaff" ("ObI" "ObII"))
101   ("Cl" "PartCombinedStaff" ("ClI" "ClII"))
102   ("Fag" "PartCombinedStaff" ("FagI" "FagII"))
103   ("Wd" "StaffGroup" ("Fl" "Ob" "Cl" "Fag" "CFag"))
105   ("Cor" "PartCombinedStaff" ("CorI" "CorII"))
106   ("Trb" "PartCombinedStaff" ("TrbI" "TrbII"))
107   ("Tbe" "PartCombinedStaff" ("TbeI" "TbeII"))
108   ("Br" "StaffGroup" ("Cor" "Trb" "Tbe" "Tba"))
110 ; long score; no part-combined staves, but GrandStaves instead
111   ("FlLong" "GrandStaff" ("FlI" "FlII"))
112   ("ObLong" "GrandStaff" ("ObI" "ObII"))
113   ("ClLong" "GrandStaff" ("ClI" "ClII"))
114   ("FagLong" "GrandStaff" ("FagI" "FagII"))
115   ("WdLong" "StaffGroup" ("FlLong" "ObLong" "ClLong" "FagLong" "CFag"))
117   ("CorLong" "GrandStaff" ("CorI" "CorII"))
118   ("TrbLong" "GrandStaff" ("TrbI" "TrbII"))
119   ("TbeLong" "GrandStaff" ("TbeI" "TbeII" "TbeIII"))
120   ("BrLong" "StaffGroup" ("CorLong" "TrbLong" "TbeLong" "Tba"))
122 ; Percussion
123   ("Perc" "StaffGroup" ("Tim"))
125 ; Strings, they are the same in long and short full score  
126   ("V" "GrandStaff" ("VI" "VII"))
127   ("Str" "StaffGroup" ("V" "Va"))
128   ("VceB" "StaffGroup" ("Vc" "Cb" "VcB"))
129   ("FullStr" "StaffGroup" ("V" "Va" "Vc" "Cb" "VcB"))
131 ; Choral score
132   ("Solo" "SimultaneousMusic" ("SSolo" "ASolo" "TSolo" "BSolo"))
133   ("Ch" "ChoirStaff" ("S" "A" "T" "B"))
134   ("ChoralScore" "SimultaneousMusic" ("Ch"))
135   ("SoloScore" "SimultaneousMusic" ("Solo"))
136   ("SoloChoirScore" "SimultaneousMusic" ("Solo" "Ch"))
138 ; Organ score (inkl. Figured bass)
139   ("BCFb" "FiguredBass" ())
140   ("FiguredBass" "FiguredBass" ())
141   ;("Organ" "SimultaneousMusic" ("BCFb" "O"))
142   ("Organ" "ParallelVoicesStaff" ("BCFb" "BC" "FiguredBass"))
143   ("Continuo" "ParallelVoicesStaff" ("BCFb" "BC" "FiguredBass"))
144   
145   ("O" "PianoStaff" ("OI" "OII"))
146   ("OI" "ParallelVoicesStaff" ("OIa" "OIb"))
147   ("OII" "ParallelVoicesStaff" ("OIIa" "OIIb"))
148   ;("BassGroup" "ParallelVoicesStaff" ("Organ" "O" "BC" "VceB"))
149   ("BassGroup" "StaffGroup" ("O" "Continuo"))
151 ; Full Scores
152   ("FullScore" "SimultaneousMusic" ("Wd" "Br" "Perc" "Str" "SoloChoirScore" "BassGroup"))
153   ("LongScore" "SimultaneousMusic" ("WdLong" "BrLong" "Perc" "Str" "SoloChoirScore" "BassGroup"))
155 ; Piano reduction
156   ;("Piano" "SimultaneousMusic" ("Organ"))
157   ("OrganScore" "SimultaneousMusic" ("ChoralScore" "O"))
158   ("VocalScore" "SimultaneousMusic" ("ChoralScore" "Piano"))
159   ("Particell"  "SimultaneousMusic" ("ChoralScore" "Continuo"))
161 ; Full scores: Orchestral score and long score including organ
162   ("ChStrQ" "SimultaneousMusic" ("Str" "Ch" "VceB"))
164 #(define oly:orchestral_score_structure oly:fullOrchestraScoreStructure)
166 #(define (oly:set_score_structure struct)
167   (if (list? struct)
168     (set! oly:orchestral_score_structure struct)
169     (ly:warning (_ "oly:set_score_structure needs an association list as argument!"))
170   )
173 #(define (oly:modify_score_structure entry)
174   (if (list? entry)
175     (set! oly:orchestral_score_structure (assoc-set! oly:orchestral_score_structure  (car entry) (cdr entry)))
176     (ly:warning (_ "oly:modify_score_structure expects a list (\"key\" \"type\" '(children)) as argument!"))))
178 #(define (oly:remove_from_score_structure entry)
179   (if (list? entry)
180     (map oly:remove_from_score_structure entry)
181     (set! oly:orchestral_score_structure (assoc-remove! oly:orchestral_score_structure  entry))))
183 orchestralScoreStructure = #(define-music-function (parser location structure) (list?) 
184   (oly:set_score_structure structure)
185   (make-music 'Music 'void #t)
188 #(define oly:voice_types '())
190 #(define (oly:set_voice_types types)
191   (if (list? types)
192     (set! oly:voice_types types)
193     (ly:warning (_ "oly:set_voice_types needs an association list as argument!"))
194   )
197 orchestralVoiceTypes = #(define-music-function (parser location types) (list?)
198   (oly:set_voice_types types)
199   (make-music 'Music 'void #t)
203 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
204 % Automatic staff and group generation
205 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
207 % Retrieve all music definitions for the given 
208 #(define (oly:get_music_object piece instrument)
209   (namedPieceInstrObject piece instrument "Music")
211 #(define (oly:get_music_objects piece instruments)
212   (filter not-null? (map (lambda (i) (oly:get_music_object piece i)) instruments))
215 % Given a property name and the extensions, either generate the pair to set 
216 % the property or an empty list, if no pre-defined variable could be found
217 #(define (oly:generate_property_pair prop piece instr type)
218   (let* ((val (namedPieceInstrObject piece instr type)))
219     (if (not-null? val) (list 'assign prop val) '() )
220   )
222   
223 #(define (oly:staff_type type)
224   (cond 
225     ((string? type) (string->symbol type))
226     ((symbol? type) type)
227     (else 'Staff)
228   )
231 #(define (oly:extractPitch music)
232   (let* (
233          (elems  (if (ly:music? music) (ly:music-property music 'elements)))
234          (note   (if (pair? elems) (car elems)))
235          (pitch  (if (ly:music? note) (ly:music-property note 'pitch)))
236         )
237     (if (and (not-null? music) (not (ly:pitch? pitch))) 
238       (ly:warning "Unable to interpret as a pitch!")
239     )
240     pitch
241   )
244 #(define (oly:extractTranspositionPitch piece name)
245   (let* (
246          (trpFromPitch (oly:extractPitch (namedPieceInstrObject piece name "TransposeFrom")))
247          (trpToPitch   (oly:extractPitch (namedPieceInstrObject piece name "TransposeTo")))
248         )
249     (if (ly:pitch? trpFromPitch)
250       (if (ly:pitch? trpToPitch)
251         ; Both pitches
252         (ly:pitch-diff trpFromPitch trpToPitch)
253         (ly:pitch-diff trpFromPitch (ly:make-pitch 0 0 0))
254       )
255       (if (ly:pitch? trpToPitch)
256         (ly:pitch-diff (ly:make-pitch 0 0 0) trpToPitch)
257         #f
258       )
259     )
260   )
263 #(define (oly:musiccontent_for_voice parser piece name music additional)
264   (let* ((musiccontent additional))
265     
266     ; Append the settings, key and clef (if defined)
267     (map 
268       (lambda (type) 
269         (let* ((object (namedPieceInstrObject piece name type)))
270           (if (ly:music? object)
271             (set! musiccontent (append musiccontent (list (ly:music-deep-copy object))))
272             (if (not-null? object) (ly:warning (_ "Wrong type (no ly:music) for ~S for instrument ~S in piece ~S") type name piece))
273           )
274         )
275       )
276       ; TODO: Does the "Tempo" work here???
277       '("Settings" "Key" "Clef" "TimeSignature" ;"Tempo"
278       )
279     )
281     (if (ly:music? music)
282       (begin
283         (set! musiccontent (make-simultaneous-music (append musiccontent (list music))))
284         ;(ly:message "Generating staff for ~a" name)
285         (let* ((trpPitch (oly:extractTranspositionPitch piece name)))
286           (if (ly:pitch? trpPitch) 
287             (set! musiccontent (ly:music-transpose musiccontent trpPitch))
288           )
289         )
290         musiccontent
291       )
292       ; For empty music, return empty 
293       '()
294     )
295   )
297 #(define (oly:voice_handler_internal parser piece name type music)
298   (let* (
299          (lyrics   (namedPieceInstrObject piece name "Lyrics"))
300          (additional '())
301         )
302     
303     (if (ly:music? lyrics)
304       (set! additional (list dynamicUp))
305       (if (not-null? lyrics) (ly:warning (_ "Wrong type (no lyrics) for lyrics for instrument ~S in piece ~S") name piece))
306     )
308     (if (ly:music? music)
309       (let* ((musiccontent (oly:musiccontent_for_voice parser piece name music additional))
310              (voicename  (oly:generate_object_name piece name "Voice" ))
311              (voicetype  (oly:staff_type type))
312              (voice      (context-spec-music musiccontent voicetype voicename))
313              (staffcont  (list voice))
314             )
315         ; If we have lyrics, create a lyrics context containing LyricCombineMusic 
316         ; and add that as second element to the staff's elements list...
317         (if (ly:music? lyrics)
318           (let* (
319                  (lyricsname (oly:generate_object_name piece name "Lyrics" ))
320                  (lyricscont (make-music 'LyricCombineMusic 'element lyrics 'associated-context voicename))
321                 )
322             (set! staffcont (append staffcont 
323               (list (context-spec-music lyricscont 'Lyrics lyricsname))))
324           )
325         )
326         staffcont
327       )
328       ; For empty music, return empty 
329       '()
330     )
331   )
334 #(define (oly:voice_handler parser piece name type)
335   (let* ((music (oly:get_music_object piece name))
336         )
337     (oly:voice_handler_internal parser piece name type music)
338   )
342 #(define (oly:staff_handler_internal parser piece name type voices)
343   (if (not-null? voices)
344     (let* (
345            (staffname  (oly:generate_staff_name piece name))
346            (stafftype  (oly:staff_type type))
347            (staff      (make-simultaneous-music voices))
348            (propops    (oly:staff_handler_properties piece name))
349           )
350       (case stafftype
351         ((SimultaneousMusic ParallelMusic) #f)
352         (else (set! staff (context-spec-music staff stafftype staffname)))
353       )
354       (if (not-null? propops)
355         (set! (ly:music-property staff 'property-operations) propops)
356       )
357       staff
358     )
359     ; For empty music, return empty 
360     '()
361   )
364 #(define (oly:staff_handler parser piece name type children)
365   (let* ((c (if (not-null? children) children (list name)))
366          (voices (apply append (map (lambda (v) (oly:create_voice parser piece v)) c)) ) 
367         )
368     (if (not-null? voices)
369       (oly:staff_handler_internal parser piece name type voices)
370       '()
371     )
372   )
374   
375 #(define (oly:parallel_voices_staff_handler parser piece name type children) 
376   (let* (
377          (voices (map (lambda (i) (oly:create_voice parser piece i)) children))
378          ; get the list of non-empty voices and flatten it!
379          (nonemptyvoices (apply append (filter not-null? voices)))
380         )
381     (if (not-null? nonemptyvoices)
382       (oly:staff_handler_internal parser piece name "Staff" nonemptyvoices)
383       '()
384     )
385   )
388 #(define (oly:part_combined_staff_handler parser piece name type children) 
389   (let* ((rawmusic (map (lambda (c) (oly:musiccontent_for_voice parser piece name (oly:get_music_object piece c) '())) children))
390          (music (filter not-null? rawmusic)))
391   (cond
392       ((and (pair? music) (ly:music? (car music)) (not-null? (cdr music)) (ly:music? (cadr music)))
393           ;(ly:message "Part-combine with two music expressions")
394           (oly:staff_handler_internal parser piece name "Staff" (list (make-part-combine-music parser music))))
395       ((null? music) 
396           (ly:warning "Part-combine without any music expressions")
397           '())
398       ; exactly one is a music expression, simply use that by joining 
399       ((list? music) 
400           (ly:message "Part-combine with only one music expressions")
401           (oly:staff_handler_internal parser piece name "Staff" (list (apply append music))))
402       (else 
403           ;(ly:message "make_part_combined_staff: ~S ~S ~a" piece instr instruments) 
404           '() )
405     )
406   )
409 % Generate the properties for the staff for piece and instr. Typically, these
410 % are the instrument name and the short instrument name (if defined).
411 % return a (possibly empty) list of all assignments.
412 #(define (oly:staff_handler_properties piece instr)
413   (let* (
414          (mapping '( 
415               (instrumentName . "InstrumentName") 
416               (shortInstrumentName . "ShortInstrumentName")
417               (midiInstrument . "MidiInstrument")
418             ))
419          (assignments (map 
420              (lambda (pr) 
421                  (oly:generate_property_pair (car pr) piece instr (cdr pr))
422              )
423              mapping))
424          (props (filter not-null? assignments))
425         )
426     props
427   )
429   
430 % Figured bass is a special case, as it can be voice- or staff-type. When
431 % given as a staff type, simply call the voice handler, instead
433 #(define (oly:figured_bass_staff_handler parser piece name type children)
434   (let* ((c (if (not-null? children) children (list name)))
435          (voice  (oly:voice_handler parser piece (car c) type)))
436     (if (pair? voice) (car voice) ())
437   )
439   
441 #(define (oly:staff_group_handler parser piece name type children)
442   (let* (
443          (staves (map (lambda (i) (oly:create_staff_or_group parser piece i)) children))
444          (nonemptystaves (filter not-null? staves))
445         )
446     (if (not-null? nonemptystaves)
447       (let* (
448              (musicexpr (if (= 1 (length nonemptystaves)) 
449                           (car nonemptystaves) 
450                           (make-simultaneous-music nonemptystaves)))
451              (groupname (oly:generate_staff_name piece name))
452              (grouptype (oly:staff_type type))
453              (group     musicexpr)
454              (propops   (oly:staff_handler_properties piece name))
455             )
456         (case grouptype
457           ((SimultaneousMusic ParallelMusic) #f)
458           (else (set! group (context-spec-music group grouptype groupname)))
459         )
460         (if (pair? propops)
461           (set! (ly:music-property group 'property-operations) propops))
462         group
463       )
464       ; Return empty list if no staves are generated
465       '()
466     )
467   )
470 #(define (oly:create_voice parser piece name)
471   (let* ( (voice (namedPieceInstrObject piece name "Voice"))
472           (type (assoc-ref oly:voice_types name)) )
473     (if (not-null? voice)
474       ; Explicit voice variable, use that
475       voice
476       
477       (if (not type)
478         ; No entry in structure found => simple voice
479         (oly:voice_handler parser piece name "Voice")
480         ; Entry found in structure => use the handler for the given type
481         (let* (
482                (voicetype (car type))
483                (handler (assoc-ref oly:voice_handlers voicetype))
484               )
485           (if handler
486             ((primitive-eval handler) parser piece name voicetype)
487             (begin
488               (ly:warning "No handler found for voice type ~a, using default voice handler" voicetype)
489               (oly:voice_handler parser piece name voicetype)
490             )
491           )
492         )
493       )
494     )
495   )
498 #(define (oly:create_staff_or_group parser piece name)
499   (let* ( (staff (namedPieceInstrObject piece name "Staff"))
500           (type_from_structure (assoc-ref oly:orchestral_score_structure name)) )
501     ;(if (not-null? staff)
502     ;  (ly:message "Found staff variable for instrument ~a in piece ~a"  instr piece)
503     ;  (ly:message "Staff variable for instrument ~a in piece ~a NOT FOUND"  instr piece)
504     ;)
505     (if (not-null? staff)
506       ; Explicit staff variable, use that
507       staff
508       
509       (if (not (list? type_from_structure)) 
510         ; No entry in structure found => simple staff
511         (oly:staff_handler parser piece name "Staff" '())
512         
513         ; Entry found in structure => use the handler for the given type
514         (let* ((type (car type_from_structure))
515                (handler (assoc-ref oly:staff_handlers type))
516                (children (cadr type_from_structure))
517               )
518           (if handler
519             ((primitive-eval handler) parser piece name type children)
520             (begin
521               (ly:warning "No handler found for staff type ~a, using default staff handler" type)
522               (oly:staff_handler parser piece name type children)
523             )
524           )
525         )
526       )
527     )
528   )
531 #(define oly:staff_handlers
532   (list
533     ; staff group types
534     '("GrandStaff" . oly:staff_group_handler )
535     '("PianoStaff" . oly:staff_group_handler )
536     '("ChoirStaff" . oly:staff_group_handler )
537     '("StaffGroup" . oly:staff_group_handler )
538     '("InnerChoirStaff" . oly:staff_group_handler )
539     '("InnerStaffGroup" . oly:staff_group_handler )
540     '("ParallelMusic" . oly:staff_group_handler )
541     '("SimultaneousMusic" . oly:staff_group_handler )
542     ; staff types
543     '("Staff" . oly:staff_handler )
544     '("DrumStaff" . oly:staff_handler )
545     '("RhythmicStaff" . oly:staff_handler )
546     '("TabStaff" . oly:staff_handler )
547     '("GregorianTranscriptionStaff" . oly:staff_handler )
548     '("MensuralStaff" . oly:staff_handler )
549     '("VaticanaStaff" . oly:staff_handler )
550     ; staves with multiple voices
551     '("PartCombinedStaff" . oly:part_combined_staff_handler )
552     '("ParallelVoicesStaff" . oly:parallel_voices_staff_handler )
553     ; special cases: Figured bass can be staff or voice type!
554     '("FiguredBass" . oly:figured_bass_staff_handler )
555   )
558 #(define oly:voice_handlers
559   (list
560     ; voice types
561     '("Voice" . oly:voice_handler )
562     '("CueVoice" . oly:voice_handler )
563     '("DrumVoice" . oly:voice_handler )
564     '("FiguredBass" . oly:voice_handler )
565     '("GregorianTranscriptionVoice" . oly:voice_handler )
566     '("NoteNames" . oly:voice_handler )
567     '("TabVoice" . oly:voice_handler )
568     '("VaticanaVoice" . oly:voice_handler )
569     ;'("Dynamics" . oly:dynamics_handler )
570   )
574 #(define (oly:register_staff_type_handler type func)
575 ;  (ly:message "Registering staff handler ~a for type ~a" func type)
576   (set! oly:staff_handlers (assoc-set! oly:staff_handlers type func))
579 #(define (oly:register_voice_type_handler type func)
580 ;  (ly:message "Registering voice type handler ~a for type ~a" func type)
581   (set! oly:voice_handlers (assoc-set! oly:voice_handlers type func))
584 % handlers for deprecated API
585 #(oly:register_staff_type_handler 'StaffGroup 'oly:staff_group_handler)
586 #(oly:register_staff_type_handler 'GrandStaff 'oly:staff_group_handler)
587 #(oly:register_staff_type_handler 'PianoStaff 'oly:staff_group_handler)
588 #(oly:register_staff_type_handler 'ChoirStaff 'oly:staff_group_handler)
589 #(oly:register_staff_type_handler 'Staff 'oly:staff_handler )
590 #(oly:register_staff_type_handler 'ParallelMusic 'oly:staff_group_handler)
591 #(oly:register_staff_type_handler 'SimultaneousMusic 'oly:staff_group_handler)
592 #(oly:register_staff_type_handler #t 'oly:part_combined_staff_handler )
593 #(oly:register_staff_type_handler #f 'oly:parallel_voices_staff_handler )
595     
597 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
598 % Automatic score generation
599 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
601 % \setUseBook ##t/##f sets a flag to determine whether the calls to createScore
602 % are from within a book block or not
603 % #(define oly:score_handler collect-scores-for-book)
604 % #(define oly:score_handler toplevel-score-handler)
605 % #(define oly:music_handler toplevel-music-handler)
606 % #(define oly:text_handler toplevel-text-handler)
608 % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
609 #(define-public (add-score parser score)
610    (ly:parser-define! parser 'toplevel-scores
611                       (cons score (ly:parser-lookup parser 'toplevel-scores))))
613 #(define-public (add-text parser text)
614   (add-score parser (list text)))
616 #(define-public (add-music parser music)
617   (collect-music-aux (lambda (score)
618                        (add-score parser score))
619                      parser
620                      music))
622 #(define-public (toplevel-book-handler parser book)
623    (map (lambda (score)
624           (ly:book-add-score! book score))
625         (reverse! (ly:parser-lookup parser 'toplevel-scores)))
626    (ly:parser-define! parser 'toplevel-scores (list))
627    (print-book-with-defaults parser book))
629 #(define-public (book-score-handler book score)
630    (add-score parser score))
632 #(define-public (book-text-handler book text)
633    (add-text parser text))
635 #(define-public (book-music-handler parser book music)
636    (add-music parser music))
638 #(define oly:score_handler add-score)
639 #(define oly:music_handler add-music)
640 #(define oly:text_handler add-text)
641 % ~~~~~~~~~~~~~~~~~~
643 % TODO: deprecate
644 setUseBook = #(define-music-function (parser location usebook) (boolean?) 
645   (ly:warning "\\setUseBook has been deprecated! Books are now automatically handled without any hacks")
646   (make-music 'Music 'void #t)
650 % Two functions to handle midi-blocks: Either don't set one, or set an empty 
651 % one so that MIDI is generated
652 #(define (oly:set_no_midi_block score) '())
653 #(define (oly:set_midi_block score) 
654   (let* ((midiblock (if (defined? '$defaultmidi) 
655                         (ly:output-def-clone $defaultmidi) 
656                         (ly:make-output-def))))
657     (ly:output-def-set-variable! midiblock 'is-midi #t)
658     (ly:score-add-output-def! score midiblock)
659   )
662 % \setCreateMidi ##t/##f sets a flag to determine wheter MIDI output should
663 % be generated
664 #(define oly:apply_score_midi oly:set_no_midi_block)
665 setCreateMIDI = #(define-music-function (parser location createmidi) (boolean?)
666   (if createmidi
667     (set! oly:apply_score_midi oly:set_midi_block)
668     (set! oly:apply_score_midi oly:set_no_midi_block)
669   )
670   (make-music 'Music 'void #t)
674 % Two functions to handle layout-blocks: Either don't set one, or set an empty 
675 % one so that a PDF is generated
676 #(define (oly:set_no_layout_block score) '())
677 #(define (oly:set_layout_block score) 
678   (let* ((layoutblock (if (defined? '$defaultlayout) 
679                         (ly:output-def-clone $defaultlayout) 
680                         (ly:make-output-def))))
681     (ly:output-def-set-variable! layoutblock 'is-layout #t)
682     (ly:score-add-output-def! score layoutblock)
683   )
686 % \setCreatePDF ##t/##f sets a flag to determine wheter PDF output should
687 % be generated
688 #(define oly:apply_score_layout oly:set_no_layout_block)
689 setCreatePDF = #(define-music-function (parser location createlayout) (boolean?)
690   (if createlayout
691     (set! oly:apply_score_layout oly:set_layout_block)
692     (set! oly:apply_score_layout oly:set_no_layout_block)
693   )
694   (make-music 'Music 'void #t)
698 % Set the piece title in a new header block.
699 #(define (oly:set_piece_header score piecename)
700   (if (not-null? piecename)
701     (let* ((header (make-module)))
702       (module-define! header 'piece piecename)
703       (ly:score-set-header! score header)
704     )
705   )
709 % post-filter functions. By default, no filtering is done. However,
710 % for the *NoCues* function, the cue notes should be killed
711 identity = #(define-music-function (parser location music) (ly:music?) music)
712 cuefilter = #(define-music-function (parser location music) (ly:music?)
713   ((ly:music-function-extract removeWithTag) parser location 'cued ((ly:music-function-extract killCues) parser location music))
717 #(define (oly:create-toc-file layout pages)
718   (let* ((label-table (ly:output-def-lookup layout 'label-page-table)))
719     (if (not (null? label-table))
720       (let* ((format-line (lambda (toc-item)
721              (let* ((label (car toc-item))
722                     (text  (caddr toc-item))
723                     (label-page (and (list? label-table) 
724                                      (assoc label label-table)))
725                     (page (and label-page (cdr label-page))))
726                (format #f "~a, section, 1, {~a}, ~a" page text label))))
727              (formatted-toc-items (map format-line (toc-items)))
728              (whole-string (string-join formatted-toc-items ",\n"))
729              (output-name (ly:parser-output-name parser))
730              (outfilename (format "~a.toc" output-name))
731              (outfile (open-output-file outfilename)))
732         (if (output-port? outfile)
733             (display whole-string outfile)
734             (ly:warning (_ "Unable to open output file ~a for the TOC information") outfilename))
735         (close-output-port outfile)))))
738 #(define-public (oly:add-toc-item parser markup-symbol text)
739   (oly:music_handler parser (add-toc-item! markup-symbol text)))
742 #(define (oly:add-score parser score piecename)
743   (if (not-null? piecename)
744     (oly:add-toc-item parser 'tocItemMarkup piecename))
745   (oly:score_handler parser score)
747 % The helper function to build a score.
748 #(define (oly:createScoreHelper parser location piece children func)
749   (let* (
750          (staves    (oly:staff_group_handler parser piece "" "SimultaneousMusic" children))
751          (music     (if (not-null? staves)
752                         ((ly:music-function-extract func) parser location staves)
753                         '()
754                     ))
755          (score     '())
756          (piecename (namedPieceInstrObject piece (car children) "PieceName"))
757          (piecenametacet (namedPieceInstrObject piece (car children) "PieceNameTacet"))
758          (header    '())
759         )
760     (if (null? music)
761       ; No staves, print tacet
762       (begin 
763         (if (not-null? piecenametacet) (set! piecename piecenametacet))
764         (if (not-null? piecename)
765           (oly:add-score parser (list (oly:piece-title-markup piecename)) piecename)
766           (ly:warning (_ "No music and no score title found for part ~a and instrument ~a") piece children)
767         )
768       )
769       ; we have staves, apply the piecename to the score and add layout/midi blocks if needed
770       (begin
771         (set! score (scorify-music music parser))
772         (oly:set_piece_header score piecename)
773         (oly:apply_score_midi score)
774         (oly:apply_score_layout score)
775         ; Schedule the score for typesetting
776         (oly:add-score parser score piecename)
777       )
778     )
779   )
780   ; This is a void function, the score has been schedulled for typesetting already
781   (make-music 'Music 'void #t)
784 createScore = #(define-music-function (parser location piece children) (string? list?)
785   (oly:createScoreHelper parser location piece children identity)
787 createNoCuesScore = #(define-music-function (parser location piece children) (string? list?)
788   (oly:createScoreHelper parser location piece children cuefilter)
791 createHeadline = #(define-music-function (parser location headline) (string?)
792   (oly:add-toc-item parser 'tocItemMarkup headline)
793   (oly:score_handler parser (list (oly:piece-title-markup headline)))
794   (make-music 'Music 'void #t)
799 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
800 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
801 %%%%%   CUE NOTES
802 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
803 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
805 newInstrument = #(define-music-function (parser location instr) (string?)
807   \set Voice.instrumentCueName = #$(string-join (list "+" instr))
810 cueText = #(define-music-function (parser location instr) (string?)
812   \set Voice.instrumentCueName = $instr
816 % generate a cue music section with instrument names
817 % Parameters: \namedCueDuring NameOfQuote CueDirection CueInstrument OriginalInstrument music
818 %                 -) NameOfQuote CueDirection music are the parameters for \cueDuring
819 %                 -) CueInstrument and OriginalInstrument are the displayed instrument names
820 % typical call:
821 % \namedCueDuring #"vIQuote" #UP #"V.I" #"Sop." { R1*3 }
822 %      This adds the notes from vIQuote (defined via \addQuote) to three measures, prints "V.I" at
823 %      the beginning of the cue notes and "Sop." at the end
824 namedCueDuring = #(define-music-function (parser location cuevoice direction instrcue instr cuemusic) (string? number? string? string? ly:music?)
825    #{
826      \cueDuring #$cuevoice #$direction { \tag #'cued \cueText #$instrcue $cuemusic \tag #'cued \cueText #$instr }
827 %      \tag #'uncued $cuemusic
828    #}
830 namedTransposedCueDuring = #(define-music-function (parser location cuevoice direction instrcue instr trans cuemusic) (string? number? string? string? ly:music? ly:music?)
831    #{
832      \transposedCueDuring #$cuevoice #$direction $trans { \tag #'cued \cueText #$instrcue $cuemusic \tag #'cued \cueText #$instr }
833 %      \tag #'uncued $cuemusic
834    #}
837 % set the cue instrument name and clef
838 setClefCue = #(define-music-function (parser location instr clef) 
839                                                      (string? ly:music?)
840    #{
841      \once \override Staff.Clef #'font-size = #-3 $clef
842      \set Voice.instrumentCueName = $instr
843    #} )
845 % generate a cue music section with instrument names and clef changes
846 % Parameters: \cleffedCueDuring NameOfQuote CueDirection CueInstrument CueClef OriginalInstrument OriginalClef music
847 %                 -) NameOfQuote CueDirection music are the parameters for \cueDuring
848 %                 -) CueInstrument and OriginalInstrument are the displayed instrument names
849 %                 -) CueClef and OriginalClef are the clefs for the the cue notes and the clef of the containing voice
850 % typical call:
851 % \cleffedCueDuring #"vIQuote" #UP #"V.I" #"treble" #"Basso" #"bass" { R1*3 }
852 %      This adds the notes from vIQuote (defined via \addQuote) to three measures, prints "V.I" at
853 %      the beginning of the cue notes and "Basso" at the end. The clef is changed to treble at the 
854 %      beginning of the cue notes and reset to bass at the end
855 cleffedCueDuring = #(define-music-function (parser location cuevoice direction instrcue clefcue instr clefinstr cuemusic) 
856                                                         (string? number? string? ly:music? string? ly:music? ly:music?)
857    #{
858      \cueDuring #$cuevoice #$direction { \tag #'cued \setClefCue #$instrcue $clefcue $cuemusic \tag #'cued \setClefCue #$instr $clefinstr }
859 %      \tag #'uncued $cuemusic
860    #}
866 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
867 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
868 %%%%%   DYNAMICS
869 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
870 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
873 dynamicsX = #(define-music-function (parser location offset) (number?)
875     \once \override DynamicText #'X-offset = $offset
876     \once \override DynamicLineSpanner #'Y-offset = #0
879 % Move the dynamic sign inside the staff to a fixed staff-relative position 
880 % posY (where 0 means vertically starts at the middle staff line)
881 dynamicsAllInside = #(define-music-function (parser location offsetX posY)
882 (number? number?)
884   % Invalid y-extent -> hidden from skyline calculation and collisions
885   \once \override DynamicLineSpanner #'Y-extent = #(cons +0 -0.01)
886   % move by X offset and to fixed Y-position (use Y-offset of parent!)
887   \once \override DynamicText #'X-offset = $offsetX
888   \once \override DynamicText #'Y-offset =
889     $(lambda (grob)
890        (let* ((head (ly:grob-parent grob Y))
891               (offset (ly:grob-property head 'Y-offset)))
892          (- posY  offset (- 0.6))))
893   \once \override DynamicLineSpanner #'Y-offset = $posY
896 dynamicsUpInside = #(define-music-function (parser location offsetX) (number?)
897   ((ly:music-function-extract dynamicsAllInside) parser location offsetX 1.5)
900 dynamicsDownInside = #(define-music-function (parser location offsetX) (number?)
901   ((ly:music-function-extract dynamicsAllInside) parser location offsetX -3.5)
904 hairpinOffset = #(define-music-function (parser location posY) (number?)
906   \once \override DynamicLineSpanner #'Y-offset = $posY
907   \once \override DynamicLineSpanner #'Y-extent = #(cons +0 -0.01)
910 #(define ((line-break-offset before after) grob)
911   (let* ((orig (ly:grob-original grob))
912          ; All siblings if line-broken:
913          (siblings (if (ly:grob? orig) (ly:spanner-broken-into orig) '() )))
914     (if (>= (length siblings) 2)
915       ; We have been line-broken
916       (if (eq? (car (last-pair siblings)) grob)
917         ; Last sibling:
918         (ly:grob-set-property! grob 'Y-offset after)
919         ; Others get the before value:
920         (ly:grob-set-property! grob 'Y-offset before)
921       )
922     )
923   )
926 ffz = #(make-dynamic-script "ffz")
927 pf = #(make-dynamic-script "pf")
928 sempp = #(make-dynamic-script (markup #:line( #:with-dimensions '(0 . 0) 
929 '(0 . 0) #:right-align #:normal-text #:italic "sempre" #:dynamic "pp")))
930 parenf = #(make-dynamic-script (markup #:line(#:normal-text #:italic #:fontsize 2 "(" #:dynamic "f" #:normal-text #:italic #:fontsize 2 ")" )))
931 parenp = #(make-dynamic-script (markup #:line(#:normal-text #:italic #:fontsize 2 "(" #:dynamic "p" #:normal-text #:italic #:fontsize 2 ")" )))
932 pdolce = #(make-dynamic-script (markup #:line(#:dynamic "p" #:with-dimensions '(0 . 0) '(0 . 0) #:normal-text #:italic "dolce"  )))
933 bracketf = #(make-dynamic-script (markup #:line(#:concat(#:normal-text "[" #:dynamic "f" #:normal-text "]"))))
934 bracketp = #(make-dynamic-script (markup #:line(#:concat(#:normal-text "[" #:dynamic "p" #:normal-text "]"))))
938 % cresc = #(make-music 'CrescendoEvent 'span-direction START 'crescendoSpanner 'text 'crescendoText "cresc.")
939 % endcresc =  #(make-span-event 'CrescendoEvent STOP)
940 % dim = #(make-music 'DecrescendoEvent 'span-direction START 'decrescendoSpanner 'text 'decrescendoText "dim.")
941 % enddim =  #(make-span-event 'DecrescendoEvent STOP)
942 % decresc = #(make-music 'DecrescendoEvent 'span-direction START 'decrescendoSpanner 'text 'decrescendoText "decresc.")
943 % enddecresc =  #(make-span-event 'DecrescendoEvent STOP)
945 % setCresc = {}
946 % setDecresc = {}
947 % setDim = {}
949 newOrOldClef = #(define-music-function (parser location new old ) (string? string?)
950     (if (ly:get-option 'old-clefs) #{ \clef $old #} #{ \clef $new #}) 
955 %%% Thanks to "Gilles THIBAULT" <gilles.thibault@free.fr>, there is a way
956 %   to remove also the fermata from R1-\fermataMarkup: By filtering the music
957 %   and removing the corresponding events.
958 %   Documented as an LSR snippet: http://lsr.dsi.unimi.it/LSR/Item?id=372
959 #(define (filterOneEventsMarkup event)
960 ( let ( (eventname (ly:music-property  event 'name)) )
961  (not
962   (or     ;; add here event name you do NOT want
963    (eq? eventname 'MultiMeasureTextEvent)
964    (eq? eventname 'AbsoluteDynamicEvent)
965    (eq? eventname 'TextScriptEvent)
966    (eq? eventname 'ArticulationEvent)
967    (eq? eventname 'CrescendoEvent)
968    (eq? eventname 'DecrescendoEvent)
969   )
973 filterArticulations = #(define-music-function (parser location music) (ly:music?)
974   Â (music-filter filterOneEventsMarkup music)
981 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
982 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
983 %%%%%   Tempo markings
984 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
985 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
989 rit = \markup {\italic "rit."}
990 pocorit = \markup {\italic "poco rit."}
991 ppmosso = \markup {\italic "poco più mosso"}
992 dolce = \markup {\italic "dolce."}
993 pizz = \markup {\italic "pizz."}
994 arco = \markup {\italic "arco"}
995 perd = \markup {\italic "perdend."}
1000 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1001 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1002 %%%%%   REST COMBINATION
1003 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1004 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1008 %% REST COMBINING, TAKEN FROM http://lsr.dsi.unimi.it/LSR/Item?id=336
1010 %% Usage:
1011 %%   \new Staff \with {
1012 %%     \override RestCollision #'positioning-done = #merge-rests-on-positioning
1013 %%   } << \somevoice \\ \othervoice >>
1014 %% or (globally):
1015 %%   \layout {
1016 %%     \context {
1017 %%       \Staff
1018 %%       \override RestCollision #'positioning-done = #merge-rests-on-positioning
1019 %%     }
1020 %%   } 
1022 %% Limitations:
1023 %% - only handles two voices
1024 %% - does not handle multi-measure/whole-measure rests
1026 #(define (rest-score r)
1027   (let ((score 0)
1028   (yoff (ly:grob-property-data r 'Y-offset))
1029   (sp (ly:grob-property-data r 'staff-position)))
1030     (if (number? yoff)
1031   (set! score (+ score 2))
1032   (if (eq? yoff 'calculation-in-progress)
1033       (set! score (- score 3))))
1034     (and (number? sp)
1035    (<= 0 2 sp)
1036    (set! score (+ score 2))
1037    (set! score (- score (abs (- 1 sp)))))
1038     score))
1040 #(define (merge-rests-on-positioning grob)
1041   (let* ((can-merge #f)
1042    (elts (ly:grob-object grob 'elements))
1043    (num-elts (and (ly:grob-array? elts)
1044       (ly:grob-array-length elts)))
1045    (two-voice? (= num-elts 2)))
1046     (if two-voice?
1047   (let* ((v1-grob (ly:grob-array-ref elts 0))
1048          (v2-grob (ly:grob-array-ref elts 1))
1049          (v1-rest (ly:grob-object v1-grob 'rest))
1050          (v2-rest (ly:grob-object v2-grob 'rest)))
1051     (and
1052      (ly:grob? v1-rest)
1053      (ly:grob? v2-rest)          
1054      (let* ((v1-duration-log (ly:grob-property v1-rest 'duration-log))
1055       (v2-duration-log (ly:grob-property v2-rest 'duration-log))
1056       (v1-dot (ly:grob-object v1-rest 'dot))
1057       (v2-dot (ly:grob-object v2-rest 'dot))
1058       (v1-dot-count (and (ly:grob? v1-dot)
1059              (ly:grob-property v1-dot 'dot-count -1)))
1060       (v2-dot-count (and (ly:grob? v2-dot)
1061              (ly:grob-property v2-dot 'dot-count -1))))
1062        (set! can-merge
1063        (and 
1064         (number? v1-duration-log)
1065         (number? v2-duration-log)
1066         (= v1-duration-log v2-duration-log)
1067         (eq? v1-dot-count v2-dot-count)))
1068        (if can-merge
1069      ;; keep the rest that looks best:
1070      (let* ((keep-v1? (>= (rest-score v1-rest)
1071               (rest-score v2-rest)))
1072       (rest-to-keep (if keep-v1? v1-rest v2-rest))
1073       (dot-to-kill (if keep-v1? v2-dot v1-dot)))
1074        ;; uncomment if you're curious of which rest was chosen:
1075        ;;(ly:grob-set-property! v1-rest 'color green)
1076        ;;(ly:grob-set-property! v2-rest 'color blue)
1077        (ly:grob-suicide! (if keep-v1? v2-rest v1-rest))
1078        (if (ly:grob? dot-to-kill)
1079            (ly:grob-suicide! dot-to-kill))
1080        (ly:grob-set-property! rest-to-keep 'direction 0)
1081        (ly:rest::y-offset-callback rest-to-keep)))))))
1082     (if can-merge
1083   #t
1084   (ly:rest-collision::calc-positioning-done grob))))
1090 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1091 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1092 %%%%%   TABLE OF CONTENTS
1093 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1094 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1097 contentsTitle = "Inhalt / Contents"
1099 \paper {
1100   tocTitleMarkup = \markup \fill-line{ 
1101     \null 
1102     \column {
1103       \override #(cons 'line-width (* 7 cm)) 
1104       \line{ \fill-line {\piece-title {\contentsTitle} \null }}
1105       \hspace #1
1106     }
1107     \null 
1108   }
1109   tocItemMarkup = \markup \fill-line { 
1110     \null 
1111     \column {
1112       \override #(cons 'line-width (* 7 cm )) 
1113       \line { \fill-line{\fromproperty #'toc:text \fromproperty #'toc:page }}
1114     }
1115     \null
1116   }
1120 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1121 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1122 %%%%%   TITLE PAGE / HEADER
1123 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1124 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1126 #(define-markup-command (when-property layout props symbol markp) (symbol? markup?)
1127   (if (chain-assoc-get symbol props)
1128       (interpret-markup layout props markp)
1129       (ly:make-stencil '()  '(1 . -1) '(1 . -1))))
1131 #(define-markup-command (vspace layout props amount) (number?)
1132   "This produces a invisible object taking vertical space."
1133   (let ((amount (* amount 3.0)))
1134     (if (> amount 0)
1135         (ly:make-stencil "" (cons -1 1) (cons 0 amount))
1136         (ly:make-stencil "" (cons -1 1) (cons amount amount)))))
1140 titlePageMarkup = \markup \abs-fontsize #10 \when-property #'header:title \column {
1141     \vspace #4
1142     \fill-line { \fontsize #8 \fromproperty #'header:composer }
1143     \vspace #1
1144     \fill-line { \fontsize #8 \fromproperty #'header:poet }
1145     \vspace #4
1146     \fill-line { \fontsize #10 \bold \fromproperty #'header:titlepagetitle }
1147     \vspace #1
1148     \fontsize #2 \when-property #'header:titlepagesubtitle { 
1149       \fill-line { \fromproperty #'header:titlepagesubtitle }
1150       \vspace #1
1151     }
1152     \fill-line { \postscript #"-20 0 moveto 40 0 rlineto stroke" }
1153     \vspace #8
1154     \fill-line { \fontsize #5 \fromproperty #'header:ensemble }
1155     \vspace #0.02
1156     \fill-line { \fontsize #2 \fromproperty #'header:instruments }
1157     \vspace #9
1158     \fill-line { \fontsize #5 \fromproperty #'header:date }
1159     \vspace #1
1160     \fill-line { \fontsize #5 \fromproperty #'header:scoretype }
1161     \vspace #8
1162     \fontsize #2 \when-property #'header:enteredby { 
1163       \fill-line { "Herausgegeben von: / Edited by:"}
1164       \vspace #0.
1165       \fill-line { \fromproperty #'header:enteredby }
1166     }
1167     \fill-line {
1168       \when-property #'header:arrangement \column {
1169         \vspace #8
1170         \fill-line { \fontsize #3 \fromproperty #'header:arrangement }
1171       }
1172     }
1175 titleHeaderMarkup = \markup {
1176   \override #'(baseline-skip . 3.5)
1177   \column {
1178     \override #'(baseline-skip . 3.5)
1179     \column {
1180       \huge \larger \bold
1181       \fill-line {
1182         \larger \fromproperty #'header:title
1183       }
1184       \fill-line {
1185         \large \smaller \bold
1186         \larger \fromproperty #'header:subtitle
1187       }
1188       \fill-line {
1189         \smaller \bold
1190         \fromproperty #'header:subsubtitle
1191       }
1192       \fill-line {
1193         { \large \bold \fromproperty #'header:instrument }
1194       }
1195       \fill-line {
1196         \fromproperty #'header:poet
1197         \fromproperty #'header:composer
1198       }
1199       \fill-line {
1200         \fromproperty #'header:meter
1201         \fromproperty #'header:arranger
1202       }
1203     }
1204   }
1207 titleScoreMarkup = \markup \piece-title \fromproperty #'header:piece
1209 \paper {
1210   scoreTitleMarkup = \titleScoreMarkup
1211   bookTitleMarkup = \titleHeaderMarkup
1216 %%%%%%%%%%%%%% headers and footers %%%%%%%%%%%%%%%%%%%%%%%%%%
1218 #(define (first-score-page layout props arg)
1219   (let* ((label 'first-score-page)
1220          (table (ly:output-def-lookup layout 'label-page-table))
1221          (label-page (and (list? table) (assoc label table)))
1222          (page-number (and label-page (cdr label-page)))
1223         )
1224     (if (eq? (chain-assoc-get 'page:page-number props -1) page-number)
1225       (interpret-markup layout props arg)
1226       empty-stencil)))
1228 #(define no-header-table '())
1229 thisPageNoHeader = #(define-music-function (parser location) ()
1230   (let* ((label (gensym "header")))
1231     (set! no-header-table (cons label no-header-table))
1232     (make-music 'Music 
1233       'page-marker #t
1234       'page-label label)))
1237 % TODO: Use the no-header-table!
1238 #(define (is-header-page layout props arg)
1239   (let* ((page-number (chain-assoc-get 'page:page-number props -1))
1240         )
1241     ;(if (and (> page-number 2) (!= page-number 7))
1242     (if (> page-number 1)
1243       (interpret-markup layout props arg)
1244       empty-stencil)))
1246 #(define no-footer-table '())
1247 thisPageNoFooter = #(define-music-function (parser location) ()
1248   (let* ((label (gensym "footer")))
1249     (set! no-footer-table (cons label no-footer-table))
1250     (make-music 'Music 
1251       'page-marker #t
1252       'page-label label)))
1254 % TODO: Use the no-footer-table!
1255 #(define (is-footer-page layout props arg)
1256   (let* ((page-number (chain-assoc-get 'page:page-number props -1))
1257          (label 'first-score-page)
1258          (table (ly:output-def-lookup layout 'label-page-table))
1259          (label-page (and (list? table) (assoc label table)))
1260          ;(page-number (and label-page (cdr label-page)))
1261         )
1262     (if (and (> page-number 1))
1263       (interpret-markup layout props arg)
1264       empty-stencil)))
1267 #(define copyright-footer-table '())
1268 thisPageCopyrightFooter = #(define-music-function (parser location) ()
1269   (let* ((label (gensym "copyrightfooter")))
1270     (set! copyright-footer-table (cons label copyright-footer-table))
1271     (make-music 'Music 
1272       'page-marker #t
1273       'page-label label)))
1275 #(define copyright-pg 1)
1276 #(define (set-copyright-page page)
1277   (set! copyright-pg page)
1280 % TODO: Use the copyright-footer-table!
1281 #(define (copyright-page layout props arg)
1282     (if (= (chain-assoc-get 'page:page-number props -1) copyright-pg)
1283       (interpret-markup layout props arg)
1284       empty-stencil))
1287 \paper {
1288   oddHeaderMarkup = \markup \fill-line {
1289     %% force the header to take some space, otherwise the
1290     %% page layout becomes a complete mess.
1291     " "
1292     \on-the-fly #is-header-page \fromproperty #'header:title
1293     \on-the-fly #is-header-page \fromproperty #'page:page-number-string
1294   }
1295   evenHeaderMarkup = \markup \fill-line {
1296     \on-the-fly #is-header-page \fromproperty #'page:page-number-string
1297     \on-the-fly #is-header-page \fromproperty #'header:composer
1298     " "
1299   }
1301   oddFooterMarkup = \markup {
1302     \column {
1303       \fill-line {
1304         %% publisher header field only on title page.
1305         \on-the-fly #first-page \fromproperty #'header:publisher
1306       }
1307       \fill-line {
1308         %% copyright on the first real score page
1309         \on-the-fly #copyright-page \fromproperty #'header:copyright
1310         \on-the-fly #copyright-page \null
1311       }
1312       \fill-line {
1313         %% All other pages get the number of the edition centered
1314         \on-the-fly #is-footer-page \fromproperty #'header:scorenumber
1315       }
1316     }
1317   }
1331 % Interpret the given markup with the header fields added to the props. 
1332 % This way, one can re-use the same functions (using fromproperty 
1333 % #'header:field) in the header block and as top-level markup.
1335 % This function is originally copied from mark-up-title (file scm/titling.scm), 
1336 % which is lilypond's internal function to handle the title markups. I needed 
1337 % to replace the scopes and manually add the $defaultheader (which is internally 
1338 % done in paper-book.cc before calling mark-up-title. Also, I don't extract the 
1339 % markup from the header block, but use the given markup.
1341 % I'm not sure if I really need the page properties in props, too... But I 
1342 % suppose it does not hurt, either.
1343 #(define-markup-command (markupWithHeader layout props markup) (markup?)
1344   "Interpret the given markup with the header fields added to the props. 
1345    This way, one can re-use the same functions (using fromproperty 
1346    #'header:field) in the header block and as top-level markup."
1347   (let* (
1348       ; TODO: If we are inside a score, add the score's local header block, too!
1349       ; Currently, I only use the global header block, stored in $defaultheader
1350       (scopes (list $defaultheader))
1351       (alists (map ly:module->alist scopes))
1352   
1353       (prefixed-alist
1354         (map (lambda (alist)
1355           (map (lambda (entry)
1356             (cons
1357               (string->symbol (string-append "header:" (symbol->string (car entry))))
1358               (cdr entry)))
1359             alist))
1360           alists))
1361       (props (append prefixed-alist
1362               props
1363               (layout-extract-page-properties layout)))
1364     )
1365     (interpret-markup layout props markup)
1366   )
1374 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1375 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1376 %%%%%   Equally spacing multiple columns (e.g. for translations)
1377 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1378 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1380 % Credits: Nicolas Sceaux on the lilypond-user mailinglist
1381 #(define-markup-command (columns layout props args) (markup-list?)
1382    (let ((line-width (/ (chain-assoc-get 'line-width props
1383                          (ly:output-def-lookup layout 'line-width))
1384                         (max (length args) 1))))
1385      (interpret-markup layout props
1386        (make-line-markup (map (lambda (line)
1387                                 (markup #:pad-to-box `(0 . ,line-width) '(0 . 0)
1388                                   #:override `(line-width . ,line-width)
1389                                   line))
1390                                args)))))
1394 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1395 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1396 %%%%%   SCORE (HEADER / LAYOUT) SETTINGS
1397 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1398 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1401 startSlashedGraceMusic =  {
1402   \override Stem  #'stroke-style = #"grace"
1405 stopSlashedGraceMusic =  {
1406   \revert Stem #'stroke-style
1409 slashedGrace =
1410 #(def-grace-function startSlashedGraceMusic stopSlashedGraceMusic
1411    (_i "Create slashed graces (slashes through stems, but no slur)from the following music expression"))
1414 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1415 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1416 %%%%%   SCORE (HEADER / LAYOUT) SETTINGS
1417 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1418 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1420 \paper {
1421   left-margin = 2\cm
1422   right-margin = 1.5\cm
1423   line-width = 17.5\cm
1424 %   bottom-margin = 1.5\cm
1425 %   top-margin = 1.5\cm
1426 %   after-title-space = 0.5\cm
1427   ragged-right = ##f
1428   ragged-last = ##f
1429   ragged-bottom = ##f
1430   ragged-last-bottom = ##f
1432 \layout {
1433   \context {
1434     \ChoirStaff 
1435     % If only one non-empty staff in a system exists, still print the backet
1436     \override SystemStartBracket #'collapse-height = #1
1437     \consists "Instrument_name_engraver"
1438   }
1439   \context {
1440     \StaffGroup
1441     % If only one non-empty staff in a system exists, still print the backet
1442     \override SystemStartBracket #'collapse-height = #1
1443     \consists "Instrument_name_engraver"
1444   }
1445   \context {
1446     \GrandStaff
1447     \override SystemStartBracket #'collapse-height = #1
1448     \consists "Instrument_name_engraver"
1449   }
1450   \context {
1451     \PianoStaff
1452 %     \override VerticalAxisGroup #'keep-fixed-while-stretching = ##t
1453   }
1454   \context {
1455     \FiguredBass
1456 %     \override VerticalAxisGroup #'keep-fixed-while-stretching = ##t
1457     \override VerticalAxisGroup #'minimum-Y-extent  = #'(0 . 1)
1458     \override VerticalAxisGroup #'padding = #0
1459   }
1460   \context {
1461     \Score
1462     % Force multi-measure rests to be written as one span
1463     \override MultiMeasureRest #'expand-limit = #3
1464     skipBars = ##t
1465     autoBeaming = ##f
1466 %     hairpinToBarline = ##f
1467     \override BarNumber #'break-visibility = #end-of-line-invisible
1468     \override BarNumber #'self-alignment-X = #0
1469     \override CombineTextScript #'avoid-slur = #'outside
1470     barNumberVisibility = #(every-nth-bar-number-visible 5)
1471     \override DynamicTextSpanner #'dash-period = #-1.0
1472     \override InstrumentSwitch #'font-size = #-1
1474     % Rest collision
1475     \override RestCollision #'positioning-done = #merge-rests-on-positioning
1476     % Auto-Accidentals: Use modern-cautionary style...
1477     extraNatural = ##f
1478     autoAccidentals = #`(Staff  ,(make-accidental-rule 'same-octave 0)
1479                                 ,(make-accidental-rule 'any-octave 0)
1480                                 ,(make-accidental-rule 'same-octave 1))
1481 %     autoCautionaries = #`(Staff ,(make-accidental-rule 'any-octave 0)
1482 %                                 ,(make-accidental-rule 'same-octave 1))
1483     printKeyCancellation = ##t
1484   }
1485   \context {
1486     \RemoveEmptyStaffContext 
1487   }
1488   \context {
1489     \Lyrics
1490     \override VerticalAxisGroup #'minimum-Y-extent = #'(0.5 . 0.5)
1491   }
1492   \context {
1493     \Staff
1494     \override VerticalAxisGroup #'minimum-Y-extent = #'(-1. . 3)
1495     quotedEventTypes = #'(StreamEvent)
1496     ignoreFiguredBassRest = ##f
1497     implicitBassFigures = #'(0 100)
1498   }
1503 \layout {
1504   \context {
1505     \type "Engraver_group"
1506     \name Dynamics
1507     % So that \cresc works, for example.
1508     \alias Voice
1509     \consists "Output_property_engraver"
1510     
1511     \override VerticalAxisGroup #'minimum-Y-extent = #'(-1 . 1)
1512     pedalSustainStrings = #'("Ped." "*Ped." "*")
1513     pedalUnaCordaStrings = #'("una corda" "" "tre corde")
1514     
1515     \consists "Piano_pedal_engraver"
1516     \consists "Script_engraver"
1517     \consists "Dynamic_engraver"
1518     \consists "Text_engraver"
1519     
1520     \override TextScript #'font-size = #2
1521     \override TextScript #'font-shape = #'italic
1522     \override DynamicText #'extra-offset = #'(0 . 2.5)
1523     \override Hairpin #'extra-offset = #'(0 . 2.5)
1524     
1525     \consists "Skip_event_swallow_translator"
1526     
1527     \consists "Axis_group_engraver"
1528   }
1529   \context {
1530     \PianoStaff
1531     \accepts Dynamics
1532 %     \override VerticalAlignment #'forced-distance = #7
1533   }
1537 ts = ^\markup{"t.s."}
1538 tt = ^\markup{"Tutti"}
1539 solo = ^\markup{"Solo"}
1540 tutti = ^\markup{"Tutti"}
1542 dashedSlur = -\tweak #'dash-definition #'((0 1 0.4 0.75))(
1543 dashedTie = -\tweak #'dash-definition #'((0 1 0.4 0.75))~
1545 divisi = #(define-music-function (parser location vc1 vc2) (ly:music? ly:music?)
1547   << { \voiceOne $vc1 \oneVoice} \new Voice = "divisi2" { \voiceTwo $vc2 } >>
1551 #(define-public (bracket-stencils grob)
1552   (let ((lp (grob-interpret-markup grob (markup #:fontsize 3.5 #:translate (cons -0.3 -0.5) "[")))
1553         (rp (grob-interpret-markup grob (markup #:fontsize 3.5 #:translate (cons -0.3 -0.5) "]"))))
1554     (list lp rp)))
1556 bracketify = #(define-music-function (parser loc arg) (ly:music?)
1557    (_i "Tag @var{arg} to be parenthesized.")
1559   \once \override ParenthesesItem #'stencils = #bracket-stencils
1560   \parenthesize $arg
1565 #(define-markup-command (hat layout props arg) (markup?)
1566   "Draw a hat above the given string @var{arg}."
1567   (interpret-markup layout props (markup #:combine #:raise 1.5 "^" arg)))