]> git.donarmstrong.com Git - lilypond.git/blob - scripts/lilypond-book.py
Optionally preserve input path.
[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         cs = self.get_checksum ()
1111
1112         # TODO: use xx/xxxxx directory layout.
1113         name = 'lily-%s' % cs[:10]
1114         return name
1115
1116     def write_ly (self):
1117         base = self.basename ()
1118         path = os.path.join (global_options.lily_output_dir, base)
1119
1120         out = file (path + '.ly', 'w')
1121         out.write (self.full_ly ())
1122         file (path + '.txt', 'w').write ('image of music')
1123
1124     def relevant_contents (self, ly):
1125         return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
1126
1127     def link_all_output_files (self, output_dir, output_dir_files, destination):
1128         existing, missing = self.all_output_files (output_dir, output_dir_files)
1129         if missing:
1130             print '\nMissing', missing
1131             raise CompileError(self.basename())
1132         for name in existing:
1133             try:
1134                 os.unlink (os.path.join (destination, name))
1135             except OSError:
1136                 pass
1137
1138             src = os.path.join (output_dir, name)
1139             dst = os.path.join (destination, name)
1140             os.link (src, dst)
1141
1142         
1143     def all_output_files (self, output_dir, output_dir_files):
1144         """Return all files generated in lily_output_dir, a set.
1145
1146         output_dir_files is the list of files in the output directory.
1147         """
1148         result = set ()
1149         missing = set ()
1150         base = self.basename()
1151         full = os.path.join (output_dir, base)
1152         def consider_file (name):
1153             if name in output_dir_files:
1154                 result.add (name)
1155              
1156         def require_file (name):
1157             if name in output_dir_files:
1158                 result.add (name)
1159             else:
1160                 missing.add (name)
1161
1162         # UGH - junk global_options
1163         skip_lily = global_options.skip_lilypond_run
1164         for required in [base + '.ly',
1165                          base + '.txt']:
1166             require_file (required)
1167         if not skip_lily:
1168             require_file (base + '-systems.count')
1169
1170         map (consider_file, [base + '.tex',
1171                              base + '.eps',
1172                              base + '.texidoc',
1173                              base + '-systems.texi',
1174                              base + '-systems.tex',
1175                              base + '-systems.pdftexi'])
1176
1177         # UGH - junk global_options
1178         if (base + '.eps' in result and self.format in (HTML, TEXINFO)
1179             and not global_options.skip_png_check):
1180             page_count = ps_page_count (full + '.eps')
1181             if page_count <= 1:
1182                 require_file (base + '.png')
1183             else:
1184                 for page in range (1, page_count + 1):
1185                     require_file (base + '-page%d.png' % page)
1186
1187         system_count = 0
1188         if not skip_lily and not missing:
1189             system_count = int(file (full + '-systems.count').read())
1190         for number in range(1, system_count + 1):
1191             systemfile = '%s-%d' % (base, number)
1192             require_file (systemfile + '.eps')
1193             consider_file (systemfile + '.pdf')
1194         
1195         return (result, missing)
1196     
1197     def is_outdated (self, output_dir, current_files):
1198         found, missing = self.all_output_files (output_dir, current_files)
1199         return missing
1200     
1201     def filter_text (self):
1202         """Run snippet bodies through a command (say: convert-ly).
1203
1204         This functionality is rarely used, and this code must have bitrot.
1205         """
1206         code = self.substring ('code')
1207         s = filter_pipe (code, global_options.filter_cmd)
1208         d = {
1209             'code': s,
1210             'options': self.match.group ('options')
1211         }
1212         # TODO
1213         return output[self.format][FILTER] % d
1214
1215     def replacement_text (self):
1216         func = LilypondSnippet.__dict__['output_' + self.format]
1217         return func (self)
1218
1219     def get_images (self):
1220         base = self.basename ()
1221
1222         single = '%(base)s.png' % vars ()
1223         multiple = '%(base)s-page1.png' % vars ()
1224         images = (single,)
1225         if (os.path.exists (multiple) 
1226             and (not os.path.exists (single)
1227                  or (os.stat (multiple)[stat.ST_MTIME]
1228                      > os.stat (single)[stat.ST_MTIME]))):
1229             count = ps_page_count ('%(base)s.eps' % vars ())
1230             images = ['%s-page%d.png' % (base, page) for page in range (1, count+1)]
1231             images = tuple (images)
1232             
1233         return images
1234
1235     def output_docbook (self):
1236         str = ''
1237         base = self.basename ()
1238         for image in self.get_images ():
1239             (base, ext) = os.path.splitext (image)
1240             str += output[DOCBOOK][OUTPUT] % vars ()
1241             str += self.output_print_filename (DOCBOOK)
1242             if (self.substring('inline') == 'inline'): 
1243                 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1244             else:
1245                 str = '<mediaobject>' + str + '</mediaobject>'
1246         if VERBATIM in self.option_dict:
1247                 verb = verbatim_html (self.verb_ly ())
1248                 str = output[DOCBOOK][VERBATIM] % vars () + str
1249         return str
1250         
1251     def output_html (self):
1252         str = ''
1253         base = self.basename ()
1254         if self.format == HTML:
1255             str += self.output_print_filename (HTML)
1256             if VERBATIM in self.option_dict:
1257                 verb = verbatim_html (self.verb_ly ())
1258                 str += output[HTML][VERBATIM] % vars ()
1259             if QUOTE in self.option_dict:
1260                 str = output[HTML][QUOTE] % vars ()
1261
1262         str += output[HTML][BEFORE] % vars ()
1263         for image in self.get_images ():
1264             (base, ext) = os.path.splitext (image)
1265             alt = self.option_dict[ALT]
1266             str += output[HTML][OUTPUT] % vars ()
1267         str += output[HTML][AFTER] % vars ()
1268         return str
1269
1270     def output_info (self):
1271         str = ''
1272         for image in self.get_images ():
1273             (base, ext) = os.path.splitext (image)
1274
1275             # URG, makeinfo implicitly prepends dot to extension.
1276             # Specifying no extension is most robust.
1277             ext = ''
1278             alt = self.option_dict[ALT]
1279             info_image_path = os.path.join (global_options.info_images_dir, base)
1280             str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1281
1282         base = self.basename ()
1283         str += output[self.format][OUTPUT] % vars ()
1284         return str
1285
1286     def output_latex (self):
1287         str = ''
1288         base = self.basename ()
1289         if self.format == LATEX:
1290             str += self.output_print_filename (LATEX)
1291             if VERBATIM in self.option_dict:
1292                 verb = self.verb_ly ()
1293                 str += (output[LATEX][VERBATIM] % vars ())
1294
1295         str += (output[LATEX][OUTPUT] % vars ())
1296
1297         ## todo: maintain breaks
1298         if 0:
1299             breaks = self.ly ().count ("\n")
1300             str += "".ljust (breaks, "\n").replace ("\n","%\n")
1301         
1302         if QUOTE in self.option_dict:
1303             str = output[LATEX][QUOTE] % vars ()
1304         return str
1305
1306     def output_print_filename (self, format):
1307         str = ''
1308         if PRINTFILENAME in self.option_dict:
1309             base = self.basename ()
1310             filename = os.path.basename (self.substring ('filename'))
1311             str = output[format][PRINTFILENAME] % vars ()
1312
1313         return str
1314
1315     def output_texinfo (self):
1316         str = self.output_print_filename (TEXINFO)
1317         base = self.basename ()
1318         if TEXIDOC in self.option_dict:
1319             texidoc = base + '.texidoc'
1320             translated_texidoc = texidoc + default_ly_options[LANG]
1321             if os.path.exists (translated_texidoc):
1322                 str += '@include %(translated_texidoc)s\n\n' % vars ()
1323             elif os.path.exists (texidoc):
1324                 str += '@include %(texidoc)s\n\n' % vars ()
1325
1326         substr = ''
1327         if VERBATIM in self.option_dict:
1328             version = ''
1329             if ADDVERSION in self.option_dict:
1330                 version = output[TEXINFO][ADDVERSION]
1331             verb = self.verb_ly ()
1332             substr = output[TEXINFO][VERBATIM] % vars ()
1333         substr += self.output_info ()
1334         if LILYQUOTE in self.option_dict:
1335             substr = output[TEXINFO][QUOTE] % {'str':substr}
1336         str += substr
1337
1338 #                str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1339 #                str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1340 #                str += ('@html\n' + self.output_html () + '\n@end html\n')
1341
1342         if QUOTE in self.option_dict:
1343             str = output[TEXINFO][QUOTE] % vars ()
1344
1345         # need par after image
1346         str += '\n'
1347
1348         return str
1349
1350 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1351 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1352
1353 class LilypondFileSnippet (LilypondSnippet):
1354     def __init__ (self, type, match, format, line_number):
1355         LilypondSnippet.__init__ (self, type, match, format, line_number)
1356         self.contents = file (find_file (self.substring ('filename'))).read ()
1357
1358     def verb_ly (self):
1359         s = self.contents
1360         s = re_begin_verbatim.split (s)[-1]
1361         s = re_end_verbatim.split (s)[0]
1362         return s
1363
1364     def ly (self):
1365         name = self.substring ('filename')
1366         return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1367                 % (name, self.contents))
1368
1369
1370 snippet_type_to_class = {
1371     'lilypond_file': LilypondFileSnippet,
1372     'lilypond_block': LilypondSnippet,
1373     'lilypond': LilypondSnippet,
1374     'include': IncludeSnippet,
1375 }
1376
1377 def find_linestarts (s):
1378     nls = [0]
1379     start = 0
1380     end = len (s)
1381     while 1:
1382         i = s.find ('\n', start)
1383         if i < 0:
1384             break
1385
1386         i = i + 1
1387         nls.append (i)
1388         start = i
1389
1390     nls.append (len (s))
1391     return nls
1392
1393 def find_toplevel_snippets (input_string, format, types):
1394     res = {}
1395     for t in types:
1396         res[t] = re.compile (snippet_res[format][t])
1397
1398     snippets = []
1399     index = 0
1400     found = dict ([(t, None) for t in types])
1401
1402     line_starts = find_linestarts (input_string)
1403     line_start_idx = 0
1404     # We want to search for multiple regexes, without searching
1405     # the string multiple times for one regex.
1406     # Hence, we use earlier results to limit the string portion
1407     # where we search.
1408     # Since every part of the string is traversed at most once for
1409     # every type of snippet, this is linear.
1410
1411     while 1:
1412         first = None
1413         endex = 1 << 30
1414         for type in types:
1415             if not found[type] or found[type][0] < index:
1416                 found[type] = None
1417                 
1418                 m = res[type].search (input_string[index:endex])
1419                 if not m:
1420                     continue
1421
1422                 klass = Snippet
1423                 if type in snippet_type_to_class:
1424                     klass = snippet_type_to_class[type]
1425
1426                 start = index + m.start ('match')
1427                 line_number = line_start_idx
1428                 while (line_starts[line_number] < start):
1429                     line_number += 1
1430
1431                 line_number += 1
1432                 snip = klass (type, m, format, line_number)
1433
1434                 found[type] = (start, snip)
1435
1436             if (found[type] 
1437                 and (not first 
1438                      or found[type][0] < found[first][0])):
1439                 first = type
1440
1441                 # FIXME.
1442
1443                 # Limiting the search space is a cute
1444                 # idea, but this *requires* to search
1445                 # for possible containing blocks
1446                 # first, at least as long as we do not
1447                 # search for the start of blocks, but
1448                 # always/directly for the entire
1449                 # @block ... @end block.
1450
1451                 endex = found[first][0]
1452
1453         if not first:
1454             snippets.append (Substring (input_string, index, len (input_string), line_start_idx))
1455             break
1456
1457         while (start > line_starts[line_start_idx+1]):
1458             line_start_idx += 1
1459
1460         (start, snip) = found[first]
1461         snippets.append (Substring (input_string, index, start, line_start_idx + 1))
1462         snippets.append (snip)
1463         found[first] = None
1464         index = start + len (snip.match.group ('match'))
1465
1466     return snippets
1467
1468 def filter_pipe (input, cmd):
1469     """Pass input through cmd, and return the result."""
1470     
1471     if global_options.verbose:
1472         progress (_ ("Opening filter `%s'") % cmd)
1473
1474     (stdin, stdout, stderr) = os.popen3 (cmd)
1475     stdin.write (input)
1476     status = stdin.close ()
1477
1478     if not status:
1479         status = 0
1480         output = stdout.read ()
1481         status = stdout.close ()
1482         error = stderr.read ()
1483
1484     if not status:
1485         status = 0
1486     signal = 0x0f & status
1487     if status or (not output and error):
1488         exit_status = status >> 8
1489         error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1490         error (_ ("The error log is as follows:"))
1491         ly.stderr_write (error)
1492         ly.stderr_write (stderr.read ())
1493         exit (status)
1494
1495     if global_options.verbose:
1496         progress ('\n')
1497
1498     return output
1499
1500 def system_in_directory (cmd, directory):
1501     """Execute a command in a different directory.
1502
1503     Because of win32 compatibility, we can't simply use subprocess.
1504     """
1505     
1506     current = os.getcwd()
1507     os.chdir (directory)
1508     ly.system(cmd, be_verbose=global_options.verbose, 
1509               progress_p=1)
1510     os.chdir (current)
1511     
1512
1513 def process_snippets (cmd, snippets,
1514                       format, lily_output_dir):
1515     """Run cmd on all of the .ly files from snippets."""
1516
1517     if not snippets:
1518         return
1519     
1520     if format in (HTML, TEXINFO) and '--formats' not in cmd:
1521         cmd += ' --formats=png '
1522     elif format in (DOCBOOK) and '--formats' not in cmd:
1523         cmd += ' --formats=png,pdf '
1524
1525     checksum = snippet_list_checksum (snippets)
1526     contents = '\n'.join (['snippet-map-%d.ly' % checksum] 
1527                           + [snip.basename() for snip in snippets])
1528     name = os.path.join (lily_output_dir,
1529                          'snippet-names-%d' % checksum)
1530     file (name, 'wb').write (contents)
1531
1532     system_in_directory (' '.join ([cmd, name]),
1533                          lily_output_dir)
1534             
1535         
1536 ###
1537 # Retrieve dimensions from LaTeX
1538 LATEX_INSPECTION_DOCUMENT = r'''
1539 \nonstopmode
1540 %(preamble)s
1541 \begin{document}
1542 \typeout{textwidth=\the\textwidth}
1543 \typeout{columnsep=\the\columnsep}
1544 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1545 \end{document}
1546 '''
1547
1548 # Do we need anything else besides `textwidth'?
1549 def get_latex_textwidth (source):
1550     m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1551     if m == None:
1552         warning (_ ("cannot find \\begin{document} in LaTeX document"))
1553         
1554         ## what's a sensible default?
1555         return 550.0
1556     
1557     preamble = source[:m.start (0)]
1558     latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1559     
1560     (handle, tmpfile) = tempfile.mkstemp('.tex')
1561     logfile = os.path.splitext (tmpfile)[0] + '.log'
1562     logfile = os.path.split (logfile)[1]
1563
1564     tmp_handle = os.fdopen (handle,'w')
1565     tmp_handle.write (latex_document)
1566     tmp_handle.close ()
1567     
1568     ly.system ('latex %s' % tmpfile, be_verbose=global_options.verbose)
1569     parameter_string = file (logfile).read()
1570     
1571     os.unlink (tmpfile)
1572     os.unlink (logfile)
1573
1574     columns = 0
1575     m = re.search ('columns=([0-9.]*)', parameter_string)
1576     if m:
1577         columns = int (m.group (1))
1578
1579     columnsep = 0
1580     m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1581     if m:
1582         columnsep = float (m.group (1))
1583
1584     textwidth = 0
1585     m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1586     if m:
1587         textwidth = float (m.group (1))
1588         if columns:
1589             textwidth = (textwidth - columnsep) / columns
1590
1591     return textwidth
1592
1593 def modify_preamble (chunk):
1594     str = chunk.replacement_text ()
1595     if (re.search (r"\\begin *{document}", str)
1596       and not re.search ("{graphic[sx]", str)):
1597         str = re.sub (r"\\begin{document}",
1598                r"\\usepackage{graphics}" + '\n'
1599                + r"\\begin{document}",
1600                str)
1601         chunk.override_text = str 
1602
1603
1604 format2ext = {
1605     HTML: '.html',
1606     # TEXINFO: '.texinfo',
1607     TEXINFO: '.texi',
1608     LATEX: '.tex',
1609     DOCBOOK: '.xml'
1610 }
1611
1612 class CompileError(Exception):
1613     pass
1614
1615 def snippet_list_checksum (snippets):
1616     return hash (' '.join([l.basename() for l in snippets]))
1617
1618 def write_file_map (lys, name):
1619     snippet_map = file (os.path.join (
1620         global_options.lily_output_dir,
1621         'snippet-map-%d.ly' % snippet_list_checksum (lys)), 'w')
1622
1623     snippet_map.write ("""
1624 #(define version-seen #t)
1625 #(define output-empty-score-list #f)
1626 #(ly:add-file-name-alist '(%s
1627     ))\n
1628 """ % '\n'.join(['("%s.ly" . "%s")\n' % (ly.basename (), name)
1629                  for ly in lys]))
1630
1631 def do_process_cmd (chunks, input_name, options):
1632     snippets = [c for c in chunks if isinstance (c, LilypondSnippet)]
1633
1634
1635     output_files = set(os.listdir(options.lily_output_dir))
1636     outdated = [c for c in snippets if c.is_outdated (options.lily_output_dir, output_files)]
1637     
1638     write_file_map (outdated, input_name)    
1639     progress (_ ("Writing snippets..."))
1640     for snippet in outdated:
1641         snippet.write_ly()
1642     progress ('\n')
1643
1644     if outdated:
1645         progress (_ ("Processing..."))
1646         progress ('\n')
1647         process_snippets (options.process_cmd, outdated,
1648                           options.format, options.lily_output_dir)
1649
1650     else:
1651         progress (_ ("All snippets are up to date..."))
1652
1653     if options.lily_output_dir != options.output_dir:
1654         output_files = set(os.listdir(options.lily_output_dir))
1655         for snippet in snippets:
1656             snippet.link_all_output_files (options.lily_output_dir,
1657                                            output_files,
1658                                            options.output_dir)
1659
1660     progress ('\n')
1661
1662
1663 ###
1664 # Format guessing data
1665 ext2format = {
1666     '.html': HTML,
1667     '.itely': TEXINFO,
1668     '.latex': LATEX,
1669     '.lytex': LATEX,
1670     '.tely': TEXINFO,
1671     '.tex': LATEX,
1672     '.texi': TEXINFO,
1673     '.texinfo': TEXINFO,
1674     '.xml': HTML,
1675     '.lyxml': DOCBOOK
1676 }
1677
1678 def guess_format (input_filename):
1679     format = None
1680     e = os.path.splitext (input_filename)[1]
1681     if e in ext2format:
1682         # FIXME
1683         format = ext2format[e]
1684     else:
1685         error (_ ("cannot determine format for: %s"
1686                   % input_filename))
1687         exit (1)
1688     return format
1689
1690 def write_if_updated (file_name, lines):
1691     try:
1692         f = file (file_name)
1693         oldstr = f.read ()
1694         new_str = ''.join (lines)
1695         if oldstr == new_str:
1696             progress (_ ("%s is up to date.") % file_name)
1697             progress ('\n')
1698
1699             # this prevents make from always rerunning lilypond-book:
1700             # output file must be touched in order to be up to date
1701             os.utime (file_name, None)
1702     except:
1703         pass
1704
1705     progress (_ ("Writing `%s'...") % file_name)
1706     file (file_name, 'w').writelines (lines)
1707     progress ('\n')
1708
1709
1710 def note_input_file (name, inputs=[]):
1711     ## hack: inputs is mutable!
1712     inputs.append (name)
1713     return inputs
1714
1715 def samefile (f1, f2):
1716     try:
1717         return os.path.samefile (f1, f2)
1718     except AttributeError:                # Windoze
1719         f1 = re.sub ("//*", "/", f1)
1720         f2 = re.sub ("//*", "/", f2)
1721         return f1 == f2
1722
1723 def do_file (input_filename):
1724     # Ugh.
1725     if not input_filename or input_filename == '-':
1726         in_handle = sys.stdin
1727         input_fullname = '<stdin>'
1728     else:
1729         if os.path.exists (input_filename):
1730             input_fullname = input_filename
1731         elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1732             input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1733         else:
1734             input_fullname = find_file (input_filename)
1735
1736         note_input_file (input_fullname)
1737         in_handle = file (input_fullname)
1738
1739     if input_filename == '-':
1740         input_base = 'stdin'
1741     else:
1742         input_base = os.path.basename (
1743             os.path.splitext (input_filename)[0])
1744
1745     # don't complain when global_options.output_dir is existing
1746     if not global_options.output_dir:
1747         global_options.output_dir = os.getcwd()
1748     else:
1749         global_options.output_dir = os.path.abspath(global_options.output_dir)
1750         
1751         if not os.path.isdir (global_options.output_dir):
1752             os.mkdir (global_options.output_dir, 0777)
1753         os.chdir (global_options.output_dir)
1754
1755     output_filename = os.path.join(global_options.output_dir,
1756                                    input_base + format2ext[global_options.format])
1757     if (os.path.exists (input_filename) 
1758         and os.path.exists (output_filename) 
1759         and samefile (output_filename, input_fullname)):
1760      error (
1761      _ ("Output would overwrite input file; use --output."))
1762      exit (2)
1763
1764     try:
1765         progress (_ ("Reading %s...") % input_fullname)
1766         source = in_handle.read ()
1767         progress ('\n')
1768
1769         set_default_options (source, default_ly_options, global_options.format)
1770
1771
1772         # FIXME: Containing blocks must be first, see
1773         #        find_toplevel_snippets.
1774         snippet_types = (
1775             'multiline_comment',
1776             'verbatim',
1777             'lilypond_block',
1778     #                'verb',
1779             'singleline_comment',
1780             'lilypond_file',
1781             'include',
1782             'lilypond',
1783         )
1784         progress (_ ("Dissecting..."))
1785         chunks = find_toplevel_snippets (source, global_options.format, snippet_types)
1786
1787         if global_options.format == LATEX:
1788             for c in chunks:
1789                 if (c.is_plain () and
1790                   re.search (r"\\begin *{document}", c.replacement_text())):
1791                     modify_preamble (c)
1792                     break
1793         progress ('\n')
1794
1795         if global_options.filter_cmd:
1796             write_if_updated (output_filename,
1797                      [c.filter_text () for c in chunks])
1798         elif global_options.process_cmd:
1799             do_process_cmd (chunks, input_fullname, global_options)
1800             progress (_ ("Compiling %s...") % output_filename)
1801             progress ('\n')
1802             write_if_updated (output_filename,
1803                      [s.replacement_text ()
1804                      for s in chunks])
1805         
1806         def process_include (snippet):
1807             os.chdir (original_dir)
1808             name = snippet.substring ('filename')
1809             progress (_ ("Processing include: %s") % name)
1810             progress ('\n')
1811             return do_file (name)
1812
1813         include_chunks = map (process_include,
1814                               filter (lambda x: isinstance (x, IncludeSnippet),
1815                                       chunks))
1816
1817         return chunks + reduce (lambda x, y: x + y, include_chunks, [])
1818         
1819     except CompileError:
1820         os.chdir (original_dir)
1821         progress (_ ("Removing `%s'") % output_filename)
1822         progress ('\n')
1823         raise CompileError
1824
1825 def do_options ():
1826     global global_options
1827
1828     opt_parser = get_option_parser()
1829     (global_options, args) = opt_parser.parse_args ()
1830     if global_options.format in ('texi-html', 'texi'):
1831         global_options.format = TEXINFO
1832
1833     global_options.include_path =  map (os.path.abspath, global_options.include_path)
1834     
1835     if global_options.warranty:
1836         warranty ()
1837         exit (0)
1838     if not args or len (args) > 1:
1839         opt_parser.print_help ()
1840         exit (2)
1841         
1842     return args
1843
1844 def main ():
1845     # FIXME: 85 lines of `main' macramee??
1846     files = do_options ()
1847
1848     basename = os.path.splitext (files[0])[0]
1849     basename = os.path.split (basename)[1]
1850     
1851     if not global_options.format:
1852         global_options.format = guess_format (files[0])
1853
1854     formats = 'ps'
1855     if global_options.format in (TEXINFO, HTML, DOCBOOK):
1856         formats += ',png'
1857
1858     if global_options.process_cmd == '':
1859         global_options.process_cmd = (lilypond_binary 
1860                                       + ' --formats=%s -dbackend=eps ' % formats)
1861
1862     if global_options.process_cmd:
1863         global_options.process_cmd += ' '.join ([(' -I %s' % ly.mkarg (p))
1864                                                  for p in global_options.include_path])
1865
1866     if global_options.format in (TEXINFO, LATEX):
1867         ## prevent PDF from being switched on by default.
1868         global_options.process_cmd += ' --formats=eps '
1869         if global_options.create_pdf:
1870             global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
1871     
1872     if global_options.verbose:
1873         global_options.process_cmd += " --verbose "
1874
1875     if global_options.padding_mm:
1876         global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
1877         
1878     global_options.process_cmd += " -dread-file-list "
1879
1880     if global_options.lily_output_dir:
1881         global_options.lily_output_dir = os.path.abspath(global_options.lily_output_dir)
1882         if not os.path.isdir (global_options.lily_output_dir):
1883             os.makedirs (global_options.lily_output_dir)
1884     else:
1885         global_options.lily_output_dir = os.path.abspath(global_options.output_dir)
1886         
1887
1888     identify ()
1889     try:
1890         chunks = do_file (files[0])
1891     except CompileError:
1892         exit (1)
1893
1894     inputs = note_input_file ('')
1895     inputs.pop ()
1896
1897     base_file_name = os.path.splitext (os.path.basename (files[0]))[0]
1898     dep_file = os.path.join (global_options.output_dir, base_file_name + '.dep')
1899     final_output_file = os.path.join (global_options.output_dir,
1900                      base_file_name
1901                      + '.%s' % global_options.format)
1902     
1903     os.chdir (original_dir)
1904     file (dep_file, 'w').write ('%s: %s'
1905                                 % (final_output_file, ' '.join (inputs)))
1906
1907 if __name__ == '__main__':
1908     main ()