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