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