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