]> git.donarmstrong.com Git - lilypond.git/blob - scripts/lilypond-book.py
03ae87d43fe4d87a705adbf52ccac023b00e0337
[lilypond.git] / scripts / lilypond-book.py
1 #!@TARGET_PYTHON@
2
3 '''
4 Example usage:
5
6 test:
7   lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
8
9 convert-ly on book:
10   lilypond-book --filter="convert-ly --no-version --from=1.6.11 -" BOOK
11
12 classic lilypond-book:
13   lilypond-book --process="lilypond" BOOK.tely
14
15 TODO:
16
17   *  this script is too complex. Modularize.
18   
19   *  ly-options: intertext?
20   *  --line-width?
21   *  eps in latex / eps by lilypond -b ps?
22   *  check latex parameters, twocolumn, multicolumn?
23   *  use --png --ps --pdf for making images?
24
25   *  Converting from lilypond-book source, substitute:
26    @mbinclude foo.itely -> @include foo.itely
27    \mbinput -> \input
28
29 '''
30
31 import md5
32 import os
33 import re
34 import stat
35 import sys
36 import tempfile
37
38 """
39 @relocate-preamble@
40 """
41
42 import lilylib as ly
43 import fontextract
44 global _;_=ly._
45
46
47 # Lilylib globals.
48 program_version = '@TOPLEVEL_VERSION@'
49 program_name = os.path.basename (sys.argv[0])
50
51 original_dir = os.getcwd ()
52 backend = 'ps'
53
54 help_summary = (
55 _ ("Process LilyPond snippets in hybrid HTML, LaTeX, texinfo or DocBook document.")
56 + '\n\n'
57 + _ ("Examples:")
58 + '''
59  lilypond-book --filter="tr '[a-z]' '[A-Z]'" %(BOOK)s
60  lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" %(BOOK)s
61  lilypond-book --process='lilypond -I include' %(BOOK)s
62 ''' % {'BOOK': _ ("BOOK")})
63
64 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
65            'Han-Wen Nienhuys <hanwen@xs4all.nl>')
66
67 ################################################################
68 def exit (i):
69     if global_options.verbose:
70         raise Exception (_ ('Exiting (%d)...') % i)
71     else:
72         sys.exit (i)
73
74 def identify ():
75     ly.encoded_write (sys.stdout, '%s (GNU LilyPond) %s\n' % (program_name, program_version))
76
77 progress = ly.progress
78
79 def warning (s):
80     ly.stderr_write (program_name + ": " + _ ("warning: %s") % s + '\n')
81
82 def error (s):
83     ly.stderr_write (program_name + ": " + _ ("error: %s") % s + '\n')
84
85 def ps_page_count (ps_name):
86     header = file (ps_name).read (1024)
87     m = re.search ('\n%%Pages: ([0-9]+)', header)
88     if m:
89         return int (m.group (1))
90     return 0
91
92 def warranty ():
93     identify ()
94     ly.encoded_write (sys.stdout, '''
95 %s
96
97 %s
98
99 %s
100 %s
101 ''' % ( _ ('Copyright (c) %s by') % '2001--2007',
102         ' '.join (authors),
103         _ ("Distributed under terms of the GNU General Public License."),
104         _ ("It comes with NO WARRANTY.")))
105
106 def get_option_parser ():
107     p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'lilypond-book',
108                               description=help_summary,
109                               add_help_option=False)
110
111     p.add_option ('-F', '--filter', metavar=_ ("FILTER"),
112                   action="store",
113                   dest="filter_cmd",
114                   help=_ ("pipe snippets through FILTER [convert-ly -n -]"),
115                   default=None)
116
117     p.add_option ('-f', '--format',
118                   help=_ ("use output format FORMAT (texi [default], texi-html, latex, html, docbook)"),
119                   action='store')
120
121     p.add_option("-h", "--help",
122                  action="help",
123                  help=_ ("show this help and exit"))
124
125     p.add_option ("-I", '--include', help=_ ("add DIR to include path"),
126                   metavar=_ ("DIR"),
127                   action='append', dest='include_path',
128                   default=[os.path.abspath (os.getcwd ())])
129
130     p.add_option ('--info-images-dir',
131                   help=_ ("format Texinfo output so that Info will "
132                           "look for images of music in DIR"),
133                   metavar=_ ("DIR"),
134                   action='store', dest='info_images_dir',
135                   default='')
136
137     p.add_option ('--left-padding', 
138                   metavar=_ ("PAD"),
139                   dest="padding_mm",
140                   help=_ ("pad left side of music to align music inspite of uneven bar numbers (in mm)"),
141                   type="float",
142                   default=3.0)
143     
144     p.add_option ("-o", '--output', help=_ ("write output to DIR"),
145                   metavar=_ ("DIR"),
146                   action='store', dest='output_dir',
147                   default='')
148     
149     p.add_option ('--lily-output-dir',
150                   help=_ ("write lily-XXX files to DIR, link into --output dir."),
151                   metavar=_ ("DIR"),
152                   action='store', dest='lily_output_dir',
153                   default=None)
154     
155     p.add_option ('-P', '--process', metavar=_ ("COMMAND"),
156                   help = _ ("process ly_files using COMMAND FILE..."),
157                   action='store', 
158                   dest='process_cmd', default='')
159
160     p.add_option ('--pdf',
161                   action="store_true",
162                   dest="create_pdf",
163                   help=_ ("create PDF files for use with PDFTeX"),
164                   default=False)
165
166     p.add_option ('', '--psfonts', action="store_true", dest="psfonts",
167                   help=_ ('''extract all PostScript fonts into INPUT.psfonts for LaTeX
168 must use this with dvips -h INPUT.psfonts'''),
169                   default=None)
170
171     p.add_option ('-V', '--verbose', help=_ ("be verbose"),
172                   action="store_true",
173                   default=False,
174                   dest="verbose")
175
176     p.version = "@TOPLEVEL_VERSION@"
177     p.add_option("--version",
178                  action="version",
179                  help=_ ("show version number and exit"))
180
181     p.add_option ('-w', '--warranty',
182                   help=_ ("show warranty and copyright"),
183                   action='store_true')
184     p.add_option_group (ly.display_encode (_ ('Bugs')),
185                         description=(
186         _ ("Report bugs via")
187         + ' http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs\n'))
188     return p
189
190 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
191
192 # Only use installed binary when we are installed too.
193 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
194     lilypond_binary = 'lilypond'
195
196 global_options = None
197
198
199 default_ly_options = { 'alt': "[image of music]" }
200
201 #
202 # Is this pythonic?  Personally, I find this rather #define-nesque. --hwn
203 #
204 ADDVERSION = 'addversion'
205 AFTER = 'after'
206 BEFORE = 'before'
207 DOCBOOK = 'docbook'
208 EXAMPLEINDENT = 'exampleindent'
209 FILTER = 'filter'
210 FRAGMENT = 'fragment'
211 HTML = 'html'
212 INDENT = 'indent'
213 LANG = 'lang'
214 LATEX = 'latex'
215 LAYOUT = 'layout'
216 LINE_WIDTH = 'line-width'
217 LILYQUOTE = 'lilyquote'
218 NOFRAGMENT = 'nofragment'
219 NOINDENT = 'noindent'
220 NOQUOTE = 'noquote'
221 NOTES = 'body'
222 NOTIME = 'notime'
223 OUTPUT = 'output'
224 OUTPUTIMAGE = 'outputimage'
225 PACKED = 'packed'
226 PAPER = 'paper'
227 PREAMBLE = 'preamble'
228 PRINTFILENAME = 'printfilename'
229 QUOTE = 'quote'
230 RAGGED_RIGHT = 'ragged-right'
231 RELATIVE = 'relative'
232 STAFFSIZE = 'staffsize'
233 TEXIDOC = 'texidoc'
234 TEXINFO = 'texinfo'
235 VERBATIM = 'verbatim'
236 FONTLOAD = 'fontload'
237 FILENAME = 'filename'
238 ALT = 'alt'
239
240
241 # NOTIME has no opposite so it isn't part of this dictionary.
242 # NOQUOTE is used internally only.
243 no_options = {
244     NOFRAGMENT: FRAGMENT,
245     NOINDENT: INDENT,
246 }
247
248
249 # Recognize special sequences in the input.
250 #
251 #   (?P<name>regex) -- Assign result of REGEX to NAME.
252 #   *? -- Match non-greedily.
253 #   (?m) -- Multiline regex: Make ^ and $ match at each line.
254 #   (?s) -- Make the dot match all characters including newline.
255 #   (?x) -- Ignore whitespace in patterns.
256 no_match = 'a\ba'
257 snippet_res = {
258  ##
259     DOCBOOK: {
260         'include':
261          no_match,
262
263         'lilypond':
264          r'''(?smx)
265           (?P<match>
266           <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
267
268         'lilypond_block':
269          r'''(?smx)
270           (?P<match>
271           <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
272
273         'lilypond_file':
274          r'''(?smx)
275           (?P<match>
276           <(?P<inline>(inline)?)mediaobject>\s*<imageobject.*?>\s*<imagedata\s+fileref="(?P<filename>.*?\.ly)"\s*(role="(?P<options>.*?)")?\s*(/>|>\s*</imagedata>)\s*</imageobject>\s*</(inline)?mediaobject>)''',
277
278         'multiline_comment':
279          r'''(?smx)
280           (?P<match>
281           \s*(?!@c\s+)
282           (?P<code><!--\s.*?!-->)
283           \s)''',
284
285         'singleline_comment':
286          no_match,
287
288         'verb':
289          no_match,
290
291         'verbatim':
292         no_match,
293         
294     }, 
295     ##
296     HTML: {
297         'include':
298          no_match,
299
300         'lilypond':
301          r'''(?mx)
302           (?P<match>
303           <lilypond
304            (\s*(?P<options>.*?)\s*:)?\s*
305            (?P<code>.*?)
306           />)''',
307
308         'lilypond_block':
309          r'''(?msx)
310           (?P<match>
311           <lilypond
312            \s*(?P<options>.*?)\s*
313           >
314           (?P<code>.*?)
315           </lilypond>)''',
316
317         'lilypond_file':
318          r'''(?mx)
319           (?P<match>
320           <lilypondfile
321            \s*(?P<options>.*?)\s*
322           >
323           \s*(?P<filename>.*?)\s*
324           </lilypondfile>)''',
325
326         'multiline_comment':
327          r'''(?smx)
328           (?P<match>
329           \s*(?!@c\s+)
330           (?P<code><!--\s.*?!-->)
331           \s)''',
332
333         'singleline_comment':
334          no_match,
335
336         'verb':
337          r'''(?x)
338           (?P<match>
339            (?P<code><pre>.*?</pre>))''',
340
341         'verbatim':
342          r'''(?x)
343           (?s)
344           (?P<match>
345            (?P<code><pre>\s.*?</pre>\s))''',
346     },
347
348     ##
349     LATEX: {
350         'include':
351          r'''(?smx)
352           ^[^%\n]*?
353           (?P<match>
354           \\input\s*{
355            (?P<filename>\S+?)
356           })''',
357
358         'lilypond':
359          r'''(?smx)
360           ^[^%\n]*?
361           (?P<match>
362           \\lilypond\s*(
363           \[
364            \s*(?P<options>.*?)\s*
365           \])?\s*{
366            (?P<code>.*?)
367           })''',
368
369         'lilypond_block':
370          r'''(?smx)
371           ^[^%\n]*?
372           (?P<match>
373           \\begin\s*(
374           \[
375            \s*(?P<options>.*?)\s*
376           \])?\s*{lilypond}
377            (?P<code>.*?)
378           ^[^%\n]*?
379           \\end\s*{lilypond})''',
380
381         'lilypond_file':
382          r'''(?smx)
383           ^[^%\n]*?
384           (?P<match>
385           \\lilypondfile\s*(
386           \[
387            \s*(?P<options>.*?)\s*
388           \])?\s*\{
389            (?P<filename>\S+?)
390           })''',
391
392         'multiline_comment':
393          no_match,
394
395         'singleline_comment':
396          r'''(?mx)
397           ^.*?
398           (?P<match>
399            (?P<code>
400            %.*$\n+))''',
401
402         'verb':
403          r'''(?mx)
404           ^[^%\n]*?
405           (?P<match>
406            (?P<code>
407            \\verb(?P<del>.)
408             .*?
409            (?P=del)))''',
410
411         'verbatim':
412          r'''(?msx)
413           ^[^%\n]*?
414           (?P<match>
415            (?P<code>
416            \\begin\s*{verbatim}
417             .*?
418            \\end\s*{verbatim}))''',
419     },
420
421     ##
422     TEXINFO: {
423         'include':
424          r'''(?mx)
425           ^(?P<match>
426           @include\s+
427            (?P<filename>\S+))''',
428
429         'lilypond':
430          r'''(?smx)
431           ^[^\n]*?(?!@c\s+)[^\n]*?
432           (?P<match>
433           @lilypond\s*(
434           \[
435            \s*(?P<options>.*?)\s*
436           \])?\s*{
437            (?P<code>.*?)
438           })''',
439
440         'lilypond_block':
441          r'''(?msx)
442           ^(?P<match>
443           @lilypond\s*(
444           \[
445            \s*(?P<options>.*?)\s*
446           \])?\s+?
447           ^(?P<code>.*?)
448           ^@end\s+lilypond)\s''',
449
450         'lilypond_file':
451          r'''(?mx)
452           ^(?P<match>
453           @lilypondfile\s*(
454           \[
455            \s*(?P<options>.*?)\s*
456           \])?\s*{
457            (?P<filename>\S+)
458           })''',
459
460         'multiline_comment':
461          r'''(?smx)
462           ^(?P<match>
463            (?P<code>
464            @ignore\s
465             .*?
466            @end\s+ignore))\s''',
467
468         'singleline_comment':
469          r'''(?mx)
470           ^.*
471           (?P<match>
472            (?P<code>
473            @c([ \t][^\n]*|)\n))''',
474
475     # Don't do this: It interferes with @code{@{}.
476     #        'verb': r'''(?P<code>@code{.*?})''',
477
478         'verbatim':
479          r'''(?sx)
480           (?P<match>
481            (?P<code>
482            @example
483             \s.*?
484            @end\s+example\s))''',
485     },
486 }
487
488
489
490
491 format_res = {
492     DOCBOOK: {        
493         'intertext': r',?\s*intertext=\".*?\"',
494         'option_sep': '\s*',
495     }, 
496     HTML: {
497         'intertext': r',?\s*intertext=\".*?\"',
498         'option_sep': '\s*',
499     },
500
501     LATEX: {
502         'intertext': r',?\s*intertext=\".*?\"',
503         'option_sep': '\s*,\s*',
504     },
505
506     TEXINFO: {
507         'intertext': r',?\s*intertext=\".*?\"',
508         'option_sep': '\s*,\s*',
509     },
510 }
511
512 # Options without a pattern in ly_options.
513 simple_options = [
514     EXAMPLEINDENT,
515     FRAGMENT,
516     NOFRAGMENT,
517     NOINDENT,
518     PRINTFILENAME,
519     TEXIDOC,
520     LANG,
521     VERBATIM,
522     FONTLOAD,
523     FILENAME,
524     ALT,
525     ADDVERSION
526 ]
527
528 ly_options = {
529     ##
530     NOTES: {
531         RELATIVE: r'''\relative c%(relative_quotes)s''',
532     },
533
534     ##
535     PAPER: {
536         INDENT: r'''indent = %(indent)s''',
537
538         LINE_WIDTH: r'''line-width = %(line-width)s''',
539
540         QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
541
542         LILYQUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
543
544         RAGGED_RIGHT: r'''ragged-right = ##t''',
545
546         PACKED: r'''packed = ##t''',
547     },
548
549     ##
550     LAYOUT: {
551         NOTIME: r'''
552  \context {
553   \Score
554   timing = ##f
555  }
556  \context {
557   \Staff
558   \remove Time_signature_engraver
559  }''',
560     },
561
562     ##
563     PREAMBLE: {
564         STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
565     },
566 }
567
568 output = {
569     ##
570     DOCBOOK: {                 
571         FILTER: r'''<mediaobject><textobject><programlisting language="lilypond" role="%(options)s">%(code)s</programlisting></textobject></mediaobject>''', 
572     
573         OUTPUT: r'''
574         <imageobject role="latex">
575                 <imagedata fileref="%(base)s.pdf" format="PDF"/>
576                 </imageobject>
577                 <imageobject role="html">
578                 <imagedata fileref="%(base)s.png" format="PNG"/></imageobject>''',
579     
580         VERBATIM: r'''<programlisting>%(verb)s</programlisting>''',
581     
582         PRINTFILENAME: '<textobject><simpara><ulink url="%(base)s.ly"><filename>%(filename)s</filename></ulink></simpara></textobject>'
583     },
584     ##
585     HTML: {
586         FILTER: r'''<lilypond %(options)s>
587 %(code)s
588 </lilypond>
589 ''',
590
591         AFTER: r'''
592  </a>
593 </p>''',
594
595         BEFORE: r'''<p>
596  <a href="%(base)s.ly">''',
597
598         OUTPUT: r'''
599   <img align="middle" 
600     border="0" src="%(image)s" alt="%(alt)s">''',
601
602         PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
603
604         QUOTE: r'''<blockquote>
605 %(str)s
606 </blockquote>
607 ''',
608
609         VERBATIM: r'''<pre>
610 %(verb)s</pre>''',
611     },
612
613     ##
614     LATEX: {
615         OUTPUT: r'''{%%
616 \parindent 0pt%%
617 \ifx\preLilyPondExample \undefined%%
618  \relax%%
619 \else%%
620  \preLilyPondExample%%
621 \fi%%
622 \def\lilypondbook{}%%
623 \input %(base)s-systems.tex%%
624 \ifx\postLilyPondExample \undefined%%
625  \relax%%
626 \else%%
627  \postLilyPondExample%%
628 \fi%%
629 }''',
630
631         PRINTFILENAME: '''\\texttt{%(filename)s}
632     ''',
633
634         QUOTE: r'''\begin{quotation}%(str)s
635 \end{quotation}''',
636
637         VERBATIM: r'''\noindent
638 \begin{verbatim}%(verb)s\end{verbatim}''',
639
640         FILTER: r'''\begin{lilypond}[%(options)s]
641 %(code)s
642 \end{lilypond}''',
643     },
644
645     ##
646     TEXINFO: {
647         FILTER: r'''@lilypond[%(options)s]
648 %(code)s
649 @lilypond''',
650
651         OUTPUT: r'''
652 @iftex
653 @include %(base)s-systems.texi
654 @end iftex
655 ''',
656
657         OUTPUTIMAGE: r'''@noindent
658 @ifinfo
659 @image{%(info_image_path)s,,,%(alt)s,%(ext)s}
660 @end ifinfo
661 @html
662 <p>
663  <a href="%(base)s.ly">
664   <img align="middle"
665     border="0" src="%(image)s" alt="%(alt)s">
666  </a>
667 </p>
668 @end html
669 ''',
670
671         PRINTFILENAME: '''
672 @html
673 <a href="%(base)s.ly">
674 @end html
675 @file{%(filename)s}
676 @html
677 </a>
678 @end html
679     ''',
680
681         QUOTE: r'''@quotation
682 %(str)s@end quotation
683 ''',
684
685         NOQUOTE: r'''@format
686 %(str)s@end format
687 ''',
688
689         VERBATIM: r'''@exampleindent 0
690 %(version)s@verbatim
691 %(verb)s@end verbatim
692 ''',
693
694         ADDVERSION: r'''@example
695 \version @w{"@version{}"}
696 @end example
697 '''
698     },
699 }
700
701 #
702 # Maintain line numbers.
703 #
704
705 ## TODO
706 if 0:
707     for f in [HTML, LATEX]:
708         for s in (QUOTE, VERBATIM):
709             output[f][s] = output[f][s].replace("\n"," ")
710
711
712 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
713 %%%% Options: [%(option_string)s]
714 \\include "lilypond-book-preamble.ly"
715
716
717 %% ****************************************************************
718 %% Start cut-&-pastable-section 
719 %% ****************************************************************
720
721 %(preamble_string)s
722
723 \paper {
724   #(define dump-extents #t)
725   %(font_dump_setting)s
726   %(paper_string)s
727   force-assignment = #""
728   line-width = #(- line-width (* mm  %(padding_mm)f))
729 }
730
731 \layout {
732   %(layout_string)s
733 }
734 '''
735
736 FRAGMENT_LY = r'''
737 %(notes_string)s
738 {
739
740
741 %% ****************************************************************
742 %% ly snippet contents follows:
743 %% ****************************************************************
744 %(code)s
745
746
747 %% ****************************************************************
748 %% end ly snippet
749 %% ****************************************************************
750 }
751 '''
752
753 FULL_LY = '''
754
755
756 %% ****************************************************************
757 %% ly snippet:
758 %% ****************************************************************
759 %(code)s
760
761
762 %% ****************************************************************
763 %% end ly snippet
764 %% ****************************************************************
765 '''
766
767 texinfo_line_widths = {
768     '@afourpaper': '160\\mm',
769     '@afourwide': '6.5\\in',
770     '@afourlatex': '150\\mm',
771     '@smallbook': '5\\in',
772     '@letterpaper': '6\\in',
773 }
774
775 def classic_lilypond_book_compatibility (key, value):
776     if key == 'singleline' and value == None:
777         return (RAGGED_RIGHT, None)
778
779     m = re.search ('relative\s*([-0-9])', key)
780     if m:
781         return ('relative', m.group (1))
782
783     m = re.match ('([0-9]+)pt', key)
784     if m:
785         return ('staffsize', m.group (1))
786
787     if key == 'indent' or key == 'line-width':
788         m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
789         if m:
790             f = float (m.group (1))
791             return (key, '%f\\%s' % (f, m.group (2)))
792
793     return (None, None)
794
795 def find_file (name, raise_error=True):
796     for i in global_options.include_path:
797         full = os.path.join (i, name)
798         if os.path.exists (full):
799             return full
800         
801     if raise_error:
802         error (_ ("file not found: %s") % name + '\n')
803         exit (1)
804     return ''
805
806 def verbatim_html (s):
807     return re.sub ('>', '&gt;',
808            re.sub ('<', '&lt;',
809                re.sub ('&', '&amp;', s)))
810
811
812 texinfo_lang_re = re.compile ('(?m)^@documentlanguage (.*?)( |$)')
813 def set_default_options (source, default_ly_options, format):
814     if LINE_WIDTH not in default_ly_options:
815         if format == LATEX:
816             textwidth = get_latex_textwidth (source)
817             default_ly_options[LINE_WIDTH] = '%.0f\\pt' % textwidth
818         elif format == TEXINFO:
819             m = texinfo_lang_re.search (source)
820             if m and not m.group (1).startswith ('en'):
821                 default_ly_options[LANG] = m.group (1)
822             else:
823                 default_ly_options[LANG] = ''
824             for regex in texinfo_line_widths:
825                 # FIXME: @layout is usually not in
826                 # chunk #0:
827                 #
828                 #  \input texinfo @c -*-texinfo-*-
829                 #
830                 # Bluntly search first K items of
831                 # source.
832                 # s = chunks[0].replacement_text ()
833                 if re.search (regex, source[:1024]):
834                     default_ly_options[LINE_WIDTH] = texinfo_line_widths[regex]
835                     break
836
837 class Chunk:
838     def replacement_text (self):
839         return ''
840
841     def filter_text (self):
842         return self.replacement_text ()
843
844     def is_outdated (self):
845         return False
846
847     def is_plain (self):
848         return False
849     
850 class Substring (Chunk):
851     """A string that does not require extra memory."""
852     def __init__ (self, source, start, end, line_number):
853         self.source = source
854         self.start = start
855         self.end = end
856         self.line_number = line_number
857         self.override_text = None
858         
859     def is_plain (self):
860         return True
861
862     def replacement_text (self):
863         if self.override_text:
864             return self.override_text
865         else:
866             return self.source[self.start:self.end]
867
868 class Snippet (Chunk):
869     def __init__ (self, type, match, format, line_number):
870         self.type = type
871         self.match = match
872         self.checksum = 0
873         self.option_dict = {}
874         self.format = format
875         self.line_number = line_number
876
877     def replacement_text (self):
878         return self.match.group ('match')
879
880     def substring (self, s):
881         return self.match.group (s)
882
883     def __repr__ (self):
884         return `self.__class__` + ' type = ' + self.type
885
886 class IncludeSnippet (Snippet):
887     def processed_filename (self):
888         f = self.substring ('filename')
889         return os.path.splitext (f)[0] + format2ext[self.format]
890
891     def replacement_text (self):
892         s = self.match.group ('match')
893         f = self.substring ('filename')
894
895         return re.sub (f, self.processed_filename (), s)
896
897 class LilypondSnippet (Snippet):
898     def __init__ (self, type, match, format, line_number):
899         Snippet.__init__ (self, type, match, format, line_number)
900         os = match.group ('options')
901         self.do_options (os, self.type)
902
903     def verb_ly (self):
904         return self.substring ('code')
905
906     def ly (self):
907         contents = self.substring ('code')
908         return ('\\sourcefileline %d\n%s'
909                 % (self.line_number - 1, contents))
910
911     def full_ly (self):
912         s = self.ly ()
913         if s:
914             return self.compose_ly (s)
915         return ''
916
917     def split_options (self, option_string):
918         if option_string:
919             if self.format == HTML:
920                 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',
921                                      option_string)
922                 options = [re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)', '\g<1>\g<3>', opt)
923                            for opt in options]
924                 return options
925             else:
926                 return re.split (format_res[self.format]['option_sep'],
927                                  option_string)
928         return []
929
930     def do_options (self, option_string, type):
931         self.option_dict = {}
932
933         options = self.split_options (option_string)
934
935         for option in options:
936             if '=' in option:
937                 (key, value) = re.split ('\s*=\s*', option)
938                 self.option_dict[key] = value
939             else:
940                 if option in no_options:
941                     if no_options[option] in self.option_dict:
942                         del self.option_dict[no_options[option]]
943                 else:
944                     self.option_dict[option] = None
945
946         has_line_width = self.option_dict.has_key (LINE_WIDTH)
947         no_line_width_value = 0
948
949         # If LINE_WIDTH is used without parameter, set it to default.
950         if has_line_width and self.option_dict[LINE_WIDTH] == None:
951             no_line_width_value = 1
952             del self.option_dict[LINE_WIDTH]
953
954         for k in default_ly_options:
955             if k not in self.option_dict:
956                 self.option_dict[k] = default_ly_options[k]
957
958         if not has_line_width:
959             if type == 'lilypond' or FRAGMENT in self.option_dict:
960                 self.option_dict[RAGGED_RIGHT] = None
961
962             if type == 'lilypond':
963                 if LINE_WIDTH in self.option_dict:
964                     del self.option_dict[LINE_WIDTH]
965             else:
966                 if RAGGED_RIGHT in self.option_dict:
967                     if LINE_WIDTH in self.option_dict:
968                         del self.option_dict[LINE_WIDTH]
969
970             if QUOTE in self.option_dict or type == 'lilypond':
971                 if LINE_WIDTH in self.option_dict:
972                     del self.option_dict[LINE_WIDTH]
973
974         if not INDENT in self.option_dict:
975             self.option_dict[INDENT] = '0\\mm'
976
977         # The QUOTE pattern from ly_options only emits the `line-width'
978         # keyword.
979         if has_line_width and QUOTE in self.option_dict:
980             if no_line_width_value:
981                 del self.option_dict[LINE_WIDTH]
982             else:
983                 del self.option_dict[QUOTE]
984
985     def compose_ly (self, code):
986         if FRAGMENT in self.option_dict:
987             body = FRAGMENT_LY
988         else:
989             body = FULL_LY
990
991         # Defaults.
992         relative = 1
993         override = {}
994         # The original concept of the `exampleindent' option is broken.
995         # It is not possible to get a sane value for @exampleindent at all
996         # without processing the document itself.  Saying
997         #
998         #   @exampleindent 0
999         #   @example
1000         #   ...
1001         #   @end example
1002         #   @exampleindent 5
1003         #
1004         # causes ugly results with the DVI backend of texinfo since the
1005         # default value for @exampleindent isn't 5em but 0.4in (or a smaller
1006         # value).  Executing the above code changes the environment
1007         # indentation to an unknown value because we don't know the amount
1008         # of 1em in advance since it is font-dependent.  Modifying
1009         # @exampleindent in the middle of a document is simply not
1010         # supported within texinfo.
1011         #
1012         # As a consequence, the only function of @exampleindent is now to
1013         # specify the amount of indentation for the `quote' option.
1014         #
1015         # To set @exampleindent locally to zero, we use the @format
1016         # environment for non-quoted snippets.
1017         override[EXAMPLEINDENT] = r'0.4\in'
1018         override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1019         override.update (default_ly_options)
1020
1021         option_list = []
1022         for (key, value) in self.option_dict.items ():
1023             if value == None:
1024                 option_list.append (key)
1025             else:
1026                 option_list.append (key + '=' + value)
1027         option_string = ','.join (option_list)
1028
1029         compose_dict = {}
1030         compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1031         for a in compose_types:
1032             compose_dict[a] = []
1033
1034         for (key, value) in self.option_dict.items ():
1035             (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
1036             if c_key:
1037                 if c_value:
1038                     warning (
1039                         _ ("deprecated ly-option used: %s=%s"
1040                            % (key, value)))
1041                     warning (
1042                         _ ("compatibility mode translation: %s=%s"
1043                            % (c_key, c_value)))
1044                 else:
1045                     warning (
1046                         _ ("deprecated ly-option used: %s"
1047                            % key))
1048                     warning (
1049                         _ ("compatibility mode translation: %s"
1050                            % c_key))
1051
1052                 (key, value) = (c_key, c_value)
1053
1054             if value:
1055                 override[key] = value
1056             else:
1057                 if not override.has_key (key):
1058                     override[key] = None
1059
1060             found = 0
1061             for type in compose_types:
1062                 if ly_options[type].has_key (key):
1063                     compose_dict[type].append (ly_options[type][key])
1064                     found = 1
1065                     break
1066
1067             if not found and key not in simple_options:
1068                 warning (_ ("ignoring unknown ly option: %s") % key)
1069
1070         # URGS
1071         if RELATIVE in override and override[RELATIVE]:
1072             relative = int (override[RELATIVE])
1073
1074         relative_quotes = ''
1075
1076         # 1 = central C
1077         if relative < 0:
1078             relative_quotes += ',' * (- relative)
1079         elif relative > 0:
1080             relative_quotes += "'" * relative
1081
1082         paper_string = '\n  '.join (compose_dict[PAPER]) % override
1083         layout_string = '\n  '.join (compose_dict[LAYOUT]) % override
1084         notes_string = '\n  '.join (compose_dict[NOTES]) % vars ()
1085         preamble_string = '\n  '.join (compose_dict[PREAMBLE]) % override
1086         padding_mm = global_options.padding_mm
1087         font_dump_setting = ''
1088         if FONTLOAD in self.option_dict:
1089             font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1090
1091         d = globals().copy()
1092         d.update (locals())
1093         return (PREAMBLE_LY + body) % d
1094
1095     def get_checksum (self):
1096         if not self.checksum:
1097             hash = md5.md5 (self.relevant_contents (self.full_ly ()))
1098
1099             ## let's not create too long names.
1100             self.checksum = hash.hexdigest ()[:10]
1101             
1102         return self.checksum
1103
1104     def basename (self):
1105         if FILENAME in self.option_dict:
1106             return self.option_dict[FILENAME]
1107
1108         cs = self.get_checksum ()
1109
1110         # TODO: use xx/xxxxx directory layout.
1111         name = 'lily-%s' % cs[:10]
1112         if global_options.lily_output_dir:
1113             name = os.path.join (global_options.lily_output_dir, name)
1114         return name
1115
1116     def write_ly (self):
1117         out = file (self.basename () + '.ly', 'w')
1118         out.write (self.full_ly ())
1119         file (self.basename () + '.txt', 'w').write ('image of music')
1120
1121     def relevant_contents (self, ly):
1122         return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
1123
1124     def link_all_output_files (self, output_dir, output_dir_files, destination):
1125         existing = self.all_output_files (output_dir_files)
1126         for name in existing:
1127             try:
1128                 os.unlink (os.path.join (destination, name))
1129             except OSError:
1130                 pass
1131
1132             src = os.path.join (output_dir, name)
1133             dst = os.path.join (destination, name)
1134             os.link (src, dst)
1135
1136         
1137     def all_output_files (self, output_dir_files):
1138         """Return all files generated in lily_output_dir, a set.
1139
1140         output_dir_files is the list of files in the output directory.
1141         """
1142         class Missing(Exception):
1143             pass
1144         
1145         result = set()
1146         base = os.path.basename(self.basename())
1147         def consider_file (name):
1148             if name in output_dir_files:
1149                 result.add (name)
1150
1151         def require_file (name):
1152             if name not in output_dir_files:
1153                 raise Missing
1154             result.add (name)
1155
1156         try:
1157             for required in [base + '.ly',
1158                              base + '.txt',
1159                              base + '-systems.count']:
1160                 require_file (required)
1161
1162             map (consider_file, [base + '.tex',
1163                                  base + '.eps',
1164                                  base + '-systems.texi',
1165                                  base + '-systems.tex',
1166                                  base + '-systems.pdftexi'])
1167
1168             if base + '.eps' in result and self.format in (HTML, TEXINFO):
1169                 page_count = ps_page_count (self.basename() + '.eps')
1170                 if page_count <= 1:
1171                     require_file (base + '.png')
1172                 else:
1173                     for page in range (1, page_count + 1):
1174                         require_file (base + '-page%d.png' % page)
1175
1176             system_count = int(file (self.basename () + '-systems.count').read())
1177             for number in range(1, system_count + 1):
1178                 systemfile = '%s-%d' % (base, number)
1179                 require_file (systemfile + '.eps')
1180                 consider_file (systemfile + '.pdf')
1181         except Missing:
1182             return None
1183         
1184         return result
1185     
1186     def is_outdated (self, current_files):
1187         return self.all_output_files (current_files) is None
1188     
1189     def filter_text (self):
1190         """Run snippet bodies through a command (say: convert-ly).
1191
1192         This functionality is rarely used, and this code must have bitrot.
1193         """
1194         
1195         code = self.substring ('code')
1196         s = filter_pipe (code, global_options.filter_cmd)
1197         d = {
1198             'code': s,
1199             'options': self.match.group ('options')
1200         }
1201         # TODO
1202         return output[self.format][FILTER] % d
1203
1204     def replacement_text (self):
1205         func = LilypondSnippet.__dict__['output_' + self.format]
1206         return func (self)
1207
1208     def get_images (self):
1209         base = self.basename ()
1210
1211         single = '%(base)s.png' % vars ()
1212         multiple = '%(base)s-page1.png' % vars ()
1213         images = (single,)
1214         if (os.path.exists (multiple) 
1215             and (not os.path.exists (single)
1216                  or (os.stat (multiple)[stat.ST_MTIME]
1217                      > os.stat (single)[stat.ST_MTIME]))):
1218             count = ps_page_count ('%(base)s.eps' % vars ())
1219             images = ['%s-page%d.png' % (base, page) for page in range (1, count+1)]
1220             images = tuple (images)
1221             
1222         return images
1223
1224     def output_docbook (self):
1225         str = ''
1226         base = self.basename ()
1227         for image in self.get_images ():
1228             (base, ext) = os.path.splitext (image)
1229             str += output[DOCBOOK][OUTPUT] % vars ()
1230             str += self.output_print_filename (DOCBOOK)
1231             if (self.substring('inline') == 'inline'): 
1232                 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1233             else:
1234                 str = '<mediaobject>' + str + '</mediaobject>'
1235         if VERBATIM in self.option_dict:
1236                 verb = verbatim_html (self.verb_ly ())
1237                 str = output[DOCBOOK][VERBATIM] % vars () + str
1238         return str
1239         
1240     def output_html (self):
1241         str = ''
1242         base = self.basename ()
1243         if self.format == HTML:
1244             str += self.output_print_filename (HTML)
1245             if VERBATIM in self.option_dict:
1246                 verb = verbatim_html (self.verb_ly ())
1247                 str += output[HTML][VERBATIM] % vars ()
1248             if QUOTE in self.option_dict:
1249                 str = output[HTML][QUOTE] % vars ()
1250
1251         str += output[HTML][BEFORE] % vars ()
1252         for image in self.get_images ():
1253             (base, ext) = os.path.splitext (image)
1254             alt = self.option_dict[ALT]
1255             str += output[HTML][OUTPUT] % vars ()
1256         str += output[HTML][AFTER] % vars ()
1257         return str
1258
1259     def output_info (self):
1260         str = ''
1261         for image in self.get_images ():
1262             (base, ext) = os.path.splitext (image)
1263
1264             # URG, makeinfo implicitly prepends dot to extension.
1265             # Specifying no extension is most robust.
1266             ext = ''
1267             alt = self.option_dict[ALT]
1268             info_image_path = os.path.join (global_options.info_images_dir, base)
1269             str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1270
1271         base = self.basename ()
1272         str += output[self.format][OUTPUT] % vars ()
1273         return str
1274
1275     def output_latex (self):
1276         str = ''
1277         base = self.basename ()
1278         if self.format == LATEX:
1279             str += self.output_print_filename (LATEX)
1280             if VERBATIM in self.option_dict:
1281                 verb = self.verb_ly ()
1282                 str += (output[LATEX][VERBATIM] % vars ())
1283
1284         str += (output[LATEX][OUTPUT] % vars ())
1285
1286         ## todo: maintain breaks
1287         if 0:
1288             breaks = self.ly ().count ("\n")
1289             str += "".ljust (breaks, "\n").replace ("\n","%\n")
1290         
1291         if QUOTE in self.option_dict:
1292             str = output[LATEX][QUOTE] % vars ()
1293         return str
1294
1295     def output_print_filename (self, format):
1296         str = ''
1297         if PRINTFILENAME in self.option_dict:
1298             base = self.basename ()
1299             filename = os.path.basename (self.substring ('filename'))
1300             str = output[format][PRINTFILENAME] % vars ()
1301
1302         return str
1303
1304     def output_texinfo (self):
1305         str = self.output_print_filename (TEXINFO)
1306         base = self.basename ()
1307         if TEXIDOC in self.option_dict:
1308             texidoc = base + '.texidoc'
1309             translated_texidoc = texidoc + default_ly_options[LANG]
1310             if os.path.exists (translated_texidoc):
1311                 str += '@include %(translated_texidoc)s\n\n' % vars ()
1312             elif os.path.exists (texidoc):
1313                 str += '@include %(texidoc)s\n\n' % vars ()
1314
1315         substr = ''
1316         if VERBATIM in self.option_dict:
1317             version = ''
1318             if ADDVERSION in self.option_dict:
1319                 version = output[TEXINFO][ADDVERSION]
1320             verb = self.verb_ly ()
1321             substr = output[TEXINFO][VERBATIM] % vars ()
1322         substr += self.output_info ()
1323         if LILYQUOTE in self.option_dict:
1324             substr = output[TEXINFO][QUOTE] % {'str':substr}
1325         str += substr
1326
1327 #                str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1328 #                str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1329 #                str += ('@html\n' + self.output_html () + '\n@end html\n')
1330
1331         if QUOTE in self.option_dict:
1332             str = output[TEXINFO][QUOTE] % vars ()
1333
1334         # need par after image
1335         str += '\n'
1336
1337         return str
1338
1339 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1340 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1341
1342 class LilypondFileSnippet (LilypondSnippet):
1343     def __init__ (self, type, match, format, line_number):
1344         LilypondSnippet.__init__ (self, type, match, format, line_number)
1345         self.contents = file (find_file (self.substring ('filename'))).read ()
1346
1347     def verb_ly (self):
1348         s = self.contents
1349         s = re_begin_verbatim.split (s)[-1]
1350         s = re_end_verbatim.split (s)[0]
1351         return s
1352
1353     def ly (self):
1354         name = self.substring ('filename')
1355         return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1356                 % (name, self.contents))
1357
1358
1359 snippet_type_to_class = {
1360     'lilypond_file': LilypondFileSnippet,
1361     'lilypond_block': LilypondSnippet,
1362     'lilypond': LilypondSnippet,
1363     'include': IncludeSnippet,
1364 }
1365
1366 def find_linestarts (s):
1367     nls = [0]
1368     start = 0
1369     end = len (s)
1370     while 1:
1371         i = s.find ('\n', start)
1372         if i < 0:
1373             break
1374
1375         i = i + 1
1376         nls.append (i)
1377         start = i
1378
1379     nls.append (len (s))
1380     return nls
1381
1382 def find_toplevel_snippets (input_string, format, types):
1383     res = {}
1384     for t in types:
1385         res[t] = ly.re.compile (snippet_res[format][t])
1386
1387     snippets = []
1388     index = 0
1389     found = dict ([(t, None) for t in types])
1390
1391     line_starts = find_linestarts (input_string)
1392     line_start_idx = 0
1393     # We want to search for multiple regexes, without searching
1394     # the string multiple times for one regex.
1395     # Hence, we use earlier results to limit the string portion
1396     # where we search.
1397     # Since every part of the string is traversed at most once for
1398     # every type of snippet, this is linear.
1399
1400     while 1:
1401         first = None
1402         endex = 1 << 30
1403         for type in types:
1404             if not found[type] or found[type][0] < index:
1405                 found[type] = None
1406                 
1407                 m = res[type].search (input_string[index:endex])
1408                 if not m:
1409                     continue
1410
1411                 klass = Snippet
1412                 if type in snippet_type_to_class:
1413                     klass = snippet_type_to_class[type]
1414
1415                 start = index + m.start ('match')
1416                 line_number = line_start_idx
1417                 while (line_starts[line_number] < start):
1418                     line_number += 1
1419
1420                 line_number += 1
1421                 snip = klass (type, m, format, line_number)
1422
1423                 found[type] = (start, snip)
1424
1425             if (found[type] 
1426                 and (not first 
1427                      or found[type][0] < found[first][0])):
1428                 first = type
1429
1430                 # FIXME.
1431
1432                 # Limiting the search space is a cute
1433                 # idea, but this *requires* to search
1434                 # for possible containing blocks
1435                 # first, at least as long as we do not
1436                 # search for the start of blocks, but
1437                 # always/directly for the entire
1438                 # @block ... @end block.
1439
1440                 endex = found[first][0]
1441
1442         if not first:
1443             snippets.append (Substring (input_string, index, len (input_string), line_start_idx))
1444             break
1445
1446         while (start > line_starts[line_start_idx+1]):
1447             line_start_idx += 1
1448
1449         (start, snip) = found[first]
1450         snippets.append (Substring (input_string, index, start, line_start_idx + 1))
1451         snippets.append (snip)
1452         found[first] = None
1453         index = start + len (snip.match.group ('match'))
1454
1455     return snippets
1456
1457 def filter_pipe (input, cmd):
1458     """Pass input through cmd, and return the result."""
1459     
1460     if global_options.verbose:
1461         progress (_ ("Opening filter `%s'") % cmd)
1462
1463     (stdin, stdout, stderr) = os.popen3 (cmd)
1464     stdin.write (input)
1465     status = stdin.close ()
1466
1467     if not status:
1468         status = 0
1469         output = stdout.read ()
1470         status = stdout.close ()
1471         error = stderr.read ()
1472
1473     if not status:
1474         status = 0
1475     signal = 0x0f & status
1476     if status or (not output and error):
1477         exit_status = status >> 8
1478         error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1479         error (_ ("The error log is as follows:"))
1480         ly.stderr_write (error)
1481         ly.stderr_write (stderr.read ())
1482         exit (status)
1483
1484     if global_options.verbose:
1485         progress ('\n')
1486
1487     return output
1488
1489 def system_in_directory (cmd, directory):
1490     """Execute a command in a different directory.
1491
1492     Because of win32 compatibility, we can't simply use subprocess.
1493     """
1494     
1495     current = os.getcwd()
1496     os.chdir (directory)
1497     ly.system(cmd, be_verbose=global_options.verbose, 
1498               progress_p=1)
1499     os.chdir (current)
1500     
1501
1502 def process_snippets (cmd, snippets,
1503                       format, lily_output_dir):
1504     """Run cmd on all of the .ly files from snippets."""
1505
1506     if not snippets:
1507         return
1508     
1509     if format in (HTML, TEXINFO) and '--formats' not in cmd:
1510         cmd += ' --formats=png '
1511     elif format in (DOCBOOK) and '--formats' not in cmd:
1512         cmd += ' --formats=png,pdf '
1513
1514     checksum = snippet_list_checksum (snippets)
1515     contents = '\n'.join (['snippet-map-%d.ly' % checksum] 
1516                           + [snip.basename() for snip in snippets])
1517     name = os.path.join (lily_output_dir,
1518                          'snippet-names-%d' % checksum)
1519     file (name, 'wb').write (contents)
1520
1521     system_in_directory (' '.join ([cmd, name]),
1522                          lily_output_dir)
1523             
1524         
1525 ###
1526 # Retrieve dimensions from LaTeX
1527 LATEX_INSPECTION_DOCUMENT = r'''
1528 \nonstopmode
1529 %(preamble)s
1530 \begin{document}
1531 \typeout{textwidth=\the\textwidth}
1532 \typeout{columnsep=\the\columnsep}
1533 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1534 \end{document}
1535 '''
1536
1537 # Do we need anything else besides `textwidth'?
1538 def get_latex_textwidth (source):
1539     m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1540     if m == None:
1541         warning (_ ("cannot find \\begin{document} in LaTeX document"))
1542         
1543         ## what's a sensible default?
1544         return 550.0
1545     
1546     preamble = source[:m.start (0)]
1547     latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1548     
1549     (handle, tmpfile) = tempfile.mkstemp('.tex')
1550     logfile = os.path.splitext (tmpfile)[0] + '.log'
1551     logfile = os.path.split (logfile)[1]
1552
1553     tmp_handle = os.fdopen (handle,'w')
1554     tmp_handle.write (latex_document)
1555     tmp_handle.close ()
1556     
1557     ly.system ('latex %s' % tmpfile, be_verbose=global_options.verbose)
1558     parameter_string = file (logfile).read()
1559     
1560     os.unlink (tmpfile)
1561     os.unlink (logfile)
1562
1563     columns = 0
1564     m = re.search ('columns=([0-9.]*)', parameter_string)
1565     if m:
1566         columns = int (m.group (1))
1567
1568     columnsep = 0
1569     m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1570     if m:
1571         columnsep = float (m.group (1))
1572
1573     textwidth = 0
1574     m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1575     if m:
1576         textwidth = float (m.group (1))
1577         if columns:
1578             textwidth = (textwidth - columnsep) / columns
1579
1580     return textwidth
1581
1582 def modify_preamble (chunk):
1583     str = chunk.replacement_text ()
1584     if (re.search (r"\\begin *{document}", str)
1585       and not re.search ("{graphic[sx]", str)):
1586         str = re.sub (r"\\begin{document}",
1587                r"\\usepackage{graphics}" + '\n'
1588                + r"\\begin{document}",
1589                str)
1590         chunk.override_text = str 
1591
1592
1593 format2ext = {
1594     HTML: '.html',
1595     # TEXINFO: '.texinfo',
1596     TEXINFO: '.texi',
1597     LATEX: '.tex',
1598     DOCBOOK: '.xml'
1599 }
1600
1601 class CompileError(Exception):
1602     pass
1603
1604 def snippet_list_checksum (snippets):
1605     return hash (' '.join([l.basename() for l in snippets]))
1606
1607 def write_file_map (lys, name):
1608     snippet_map = file (os.path.join (
1609         global_options.lily_output_dir,
1610         'snippet-map-%d.ly' % snippet_list_checksum (lys)), 'w')
1611
1612     snippet_map.write ("""
1613 #(define version-seen #t)
1614 #(define output-empty-score-list #f)
1615 #(ly:add-file-name-alist '(%s
1616     ))\n
1617 """ % '\n'.join('("%s.ly" . "%s")\n' % (ly.basename (), name)
1618                 for ly in lys))
1619
1620 def do_process_cmd (chunks, input_name, options):
1621     snippets = [c for c in chunks if isinstance (c, LilypondSnippet)]
1622
1623
1624     output_files = set(os.listdir(options.lily_output_dir))
1625     outdated = [c for c in snippets if c.is_outdated (output_files)]
1626     
1627     write_file_map (outdated, input_name)    
1628     progress (_ ("Writing snippets..."))
1629     for snippet in outdated:
1630         snippet.write_ly()
1631     progress ('\n')
1632
1633     if outdated:
1634         progress (_ ("Processing..."))
1635         progress ('\n')
1636         process_snippets (options.process_cmd, outdated,
1637                           options.format, options.lily_output_dir)
1638
1639     else:
1640         progress (_ ("All snippets are up to date..."))
1641
1642     if options.lily_output_dir != options.output_dir:
1643         output_files = set(os.listdir(options.lily_output_dir))
1644         for snippet in snippets:
1645             snippet.link_all_output_files (options.lily_output_dir,
1646                                            output_files,
1647                                            options.output_dir)
1648
1649     progress ('\n')
1650
1651
1652 ###
1653 # Format guessing data
1654 ext2format = {
1655     '.html': HTML,
1656     '.itely': TEXINFO,
1657     '.latex': LATEX,
1658     '.lytex': LATEX,
1659     '.tely': TEXINFO,
1660     '.tex': LATEX,
1661     '.texi': TEXINFO,
1662     '.texinfo': TEXINFO,
1663     '.xml': HTML,
1664     '.lyxml': DOCBOOK
1665 }
1666
1667 def guess_format (input_filename):
1668     format = None
1669     e = os.path.splitext (input_filename)[1]
1670     if e in ext2format:
1671         # FIXME
1672         format = ext2format[e]
1673     else:
1674         error (_ ("cannot determine format for: %s"
1675                   % input_filename))
1676         exit (1)
1677     return format
1678
1679 def write_if_updated (file_name, lines):
1680     try:
1681         f = file (file_name)
1682         oldstr = f.read ()
1683         new_str = ''.join (lines)
1684         if oldstr == new_str:
1685             progress (_ ("%s is up to date.") % file_name)
1686             progress ('\n')
1687
1688             # this prevents make from always rerunning lilypond-book:
1689             # output file must be touched in order to be up to date
1690             os.utime (file_name, None)
1691     except:
1692         pass
1693
1694     progress (_ ("Writing `%s'...") % file_name)
1695     file (file_name, 'w').writelines (lines)
1696     progress ('\n')
1697
1698
1699 def note_input_file (name, inputs=[]):
1700     ## hack: inputs is mutable!
1701     inputs.append (name)
1702     return inputs
1703
1704 def samefile (f1, f2):
1705     try:
1706         return os.path.samefile (f1, f2)
1707     except AttributeError:                # Windoze
1708         f1 = re.sub ("//*", "/", f1)
1709         f2 = re.sub ("//*", "/", f2)
1710         return f1 == f2
1711
1712 def do_file (input_filename):
1713     # Ugh.
1714     if not input_filename or input_filename == '-':
1715         in_handle = sys.stdin
1716         input_fullname = '<stdin>'
1717     else:
1718         if os.path.exists (input_filename):
1719             input_fullname = input_filename
1720         elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1721             input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1722         else:
1723             input_fullname = find_file (input_filename)
1724
1725         note_input_file (input_fullname)
1726         in_handle = file (input_fullname)
1727
1728     if input_filename == '-':
1729         input_base = 'stdin'
1730     else:
1731         input_base = os.path.basename (
1732             os.path.splitext (input_filename)[0])
1733
1734     # don't complain when global_options.output_dir is existing
1735     if not global_options.output_dir:
1736         global_options.output_dir = os.getcwd()
1737     else:
1738         global_options.output_dir = os.path.abspath(global_options.output_dir)
1739         
1740         if not os.path.isdir (global_options.output_dir):
1741             os.mkdir (global_options.output_dir, 0777)
1742         os.chdir (global_options.output_dir)
1743
1744     output_filename = os.path.join(global_options.output_dir,
1745                                    input_base + format2ext[global_options.format])
1746     if (os.path.exists (input_filename) 
1747         and os.path.exists (output_filename) 
1748         and samefile (output_filename, input_fullname)):
1749      error (
1750      _ ("Output would overwrite input file; use --output."))
1751      exit (2)
1752
1753     try:
1754         progress (_ ("Reading %s...") % input_fullname)
1755         source = in_handle.read ()
1756         progress ('\n')
1757
1758         set_default_options (source, default_ly_options, global_options.format)
1759
1760
1761         # FIXME: Containing blocks must be first, see
1762         #        find_toplevel_snippets.
1763         snippet_types = (
1764             'multiline_comment',
1765             'verbatim',
1766             'lilypond_block',
1767     #                'verb',
1768             'singleline_comment',
1769             'lilypond_file',
1770             'include',
1771             'lilypond',
1772         )
1773         progress (_ ("Dissecting..."))
1774         chunks = find_toplevel_snippets (source, global_options.format, snippet_types)
1775
1776         if global_options.format == LATEX:
1777             for c in chunks:
1778                 if (c.is_plain () and
1779                   re.search (r"\\begin *{document}", c.replacement_text())):
1780                     modify_preamble (c)
1781                     break
1782         progress ('\n')
1783
1784         if global_options.filter_cmd:
1785             write_if_updated (output_filename,
1786                      [c.filter_text () for c in chunks])
1787         elif global_options.process_cmd:
1788             do_process_cmd (chunks, input_fullname, global_options)
1789             progress (_ ("Compiling %s...") % output_filename)
1790             progress ('\n')
1791             write_if_updated (output_filename,
1792                      [s.replacement_text ()
1793                      for s in chunks])
1794         
1795         def process_include (snippet):
1796             os.chdir (original_dir)
1797             name = snippet.substring ('filename')
1798             progress (_ ("Processing include: %s") % name)
1799             progress ('\n')
1800             return do_file (name)
1801
1802         include_chunks = map (process_include,
1803                               filter (lambda x: isinstance (x, IncludeSnippet),
1804                                       chunks))
1805
1806         return chunks + reduce (lambda x, y: x + y, include_chunks, [])
1807         
1808     except CompileError:
1809         os.chdir (original_dir)
1810         progress (_ ("Removing `%s'") % output_filename)
1811         progress ('\n')
1812         raise CompileError
1813
1814 def do_options ():
1815     global global_options
1816
1817     opt_parser = get_option_parser()
1818     (global_options, args) = opt_parser.parse_args ()
1819     if global_options.format in ('texi-html', 'texi'):
1820         global_options.format = TEXINFO
1821
1822     global_options.include_path =  map (os.path.abspath, global_options.include_path)
1823     
1824     if global_options.warranty:
1825         warranty ()
1826         exit (0)
1827     if not args or len (args) > 1:
1828         opt_parser.print_help ()
1829         exit (2)
1830         
1831     return args
1832
1833 def main ():
1834     # FIXME: 85 lines of `main' macramee??
1835     files = do_options ()
1836
1837     basename = os.path.splitext (files[0])[0]
1838     basename = os.path.split (basename)[1]
1839     
1840     if not global_options.format:
1841         global_options.format = guess_format (files[0])
1842
1843     formats = 'ps'
1844     if global_options.format in (TEXINFO, HTML, DOCBOOK):
1845         formats += ',png'
1846
1847     if global_options.process_cmd == '':
1848         global_options.process_cmd = (lilypond_binary 
1849                                       + ' --formats=%s -dbackend=eps ' % formats)
1850
1851     if global_options.process_cmd:
1852         global_options.process_cmd += ' '.join ([(' -I %s' % ly.mkarg (p))
1853                                                  for p in global_options.include_path])
1854
1855     if global_options.format in (TEXINFO, LATEX):
1856         ## prevent PDF from being switched on by default.
1857         global_options.process_cmd += ' --formats=eps '
1858         if global_options.create_pdf:
1859             global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
1860     
1861     if global_options.verbose:
1862         global_options.process_cmd += " --verbose "
1863
1864     if global_options.padding_mm:
1865         global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
1866         
1867     global_options.process_cmd += " -dread-file-list "
1868
1869     if global_options.lily_output_dir:
1870         global_options.lily_output_dir = os.path.abspath(global_options.lily_output_dir)
1871         if not os.path.isdir (global_options.lily_output_dir):
1872             os.makedirs (global_options.lily_output_dir)
1873     else:
1874         global_options.lily_output_dir = os.path.abspath(global_options.output_dir)
1875         
1876
1877     identify ()
1878     try:
1879         chunks = do_file (files[0])
1880     except CompileError:
1881         exit (1)
1882
1883     inputs = note_input_file ('')
1884     inputs.pop ()
1885
1886     base_file_name = os.path.splitext (os.path.basename (files[0]))[0]
1887     dep_file = os.path.join (global_options.output_dir, base_file_name + '.dep')
1888     final_output_file = os.path.join (global_options.output_dir,
1889                      base_file_name
1890                      + '.%s' % global_options.format)
1891     
1892     os.chdir (original_dir)
1893     file (dep_file, 'w').write ('%s: %s'
1894                                 % (final_output_file, ' '.join (inputs)))
1895
1896 if __name__ == '__main__':
1897     main ()