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