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