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