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