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