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