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