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