]> git.donarmstrong.com Git - lilypond.git/blob - scripts/lilypond-book.py
495c3683a7685aa4751f01c3c3811dea4bb61545
[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_name',
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=(_ ("Report bugs via")
187                                      + ''' http://post.gmane.org/post.php'''
188                                      '''?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 def split_options (option_string):
811     if option_string:
812         if global_options.format == HTML:
813             options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
814             for i in range(len(options)):
815                 options[i] = re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
816             return options
817         else:
818             return re.split (format_res[global_options.format]['option_sep'],
819                     option_string)
820     return []
821
822 def set_default_options (source):
823     global default_ly_options
824     if not default_ly_options.has_key (LINE_WIDTH):
825         if global_options.format == LATEX:
826             textwidth = get_latex_textwidth (source)
827             default_ly_options[LINE_WIDTH] = '%.0f\\pt' % textwidth
828         elif global_options.format == TEXINFO:
829             for (k, v) in texinfo_line_widths.items ():
830                 # FIXME: @layout is usually not in
831                 # chunk #0:
832                 #
833                 #  \input texinfo @c -*-texinfo-*-
834                 #
835                 # Bluntly search first K items of
836                 # source.
837                 # s = chunks[0].replacement_text ()
838                 if re.search (k, source[:1024]):
839                     default_ly_options[LINE_WIDTH] = v
840                     break
841
842 class Chunk:
843     def replacement_text (self):
844         return ''
845
846     def filter_text (self):
847         return self.replacement_text ()
848
849     def ly_is_outdated (self):
850         return False
851
852     def png_is_outdated (self):
853         return False
854
855     def is_plain (self):
856         return False
857     
858 class Substring (Chunk):
859     """A string that does not require extra memory."""
860     def __init__ (self, source, start, end, line_number):
861         self.source = source
862         self.start = start
863         self.end = end
864         self.line_number = line_number
865         self.override_text = None
866         
867     def is_plain (self):
868         return True
869
870     def replacement_text (self):
871         if self.override_text:
872             return self.override_text
873         else:
874             return self.source[self.start:self.end]
875
876 class Snippet (Chunk):
877     def __init__ (self, type, match, format, line_number):
878         self.type = type
879         self.match = match
880         self.checksum = 0
881         self.option_dict = {}
882         self.format = format
883         self.line_number = line_number
884
885     def replacement_text (self):
886         return self.match.group ('match')
887
888     def substring (self, s):
889         return self.match.group (s)
890
891     def __repr__ (self):
892         return `self.__class__` + ' type = ' + self.type
893
894 class IncludeSnippet (Snippet):
895     def processed_filename (self):
896         f = self.substring ('filename')
897         return os.path.splitext (f)[0] + format2ext[global_options.format]
898
899     def replacement_text (self):
900         s = self.match.group ('match')
901         f = self.substring ('filename')
902
903         return re.sub (f, self.processed_filename (), s)
904
905 class LilypondSnippet (Snippet):
906     def __init__ (self, type, match, format, line_number):
907         Snippet.__init__ (self, type, match, format, line_number)
908         os = match.group ('options')
909         self.do_options (os, self.type)
910
911     def verb_ly (self):
912         return self.substring ('code')
913
914     def ly (self):
915         contents = self.substring ('code')
916         return ('\\sourcefileline %d\n%s'
917                 % (self.line_number - 1, contents))
918
919     def full_ly (self):
920         s = self.ly ()
921         if s:
922             return self.compose_ly (s)
923         return ''
924
925     def do_options (self, option_string, type):
926         self.option_dict = {}
927
928         options = split_options (option_string)
929
930         for i in options:
931             if '=' in i:
932                 (key, value) = re.split ('\s*=\s*', i)
933                 self.option_dict[key] = value
934             else:
935                 if i in no_options.keys ():
936                     if no_options[i] in self.option_dict.keys ():
937                         del self.option_dict[no_options[i]]
938                 else:
939                     self.option_dict[i] = None
940
941         has_line_width = self.option_dict.has_key (LINE_WIDTH)
942         no_line_width_value = 0
943
944         # If LINE_WIDTH is used without parameter, set it to default.
945         if has_line_width and self.option_dict[LINE_WIDTH] == None:
946             no_line_width_value = 1
947             del self.option_dict[LINE_WIDTH]
948
949         for i in default_ly_options.keys ():
950             if i not in self.option_dict.keys ():
951                 self.option_dict[i] = default_ly_options[i]
952
953         if not has_line_width:
954             if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
955                 self.option_dict[RAGGED_RIGHT] = None
956
957             if type == 'lilypond':
958                 if LINE_WIDTH in self.option_dict.keys ():
959                     del self.option_dict[LINE_WIDTH]
960             else:
961                 if RAGGED_RIGHT in self.option_dict.keys ():
962                     if LINE_WIDTH in self.option_dict.keys ():
963                         del self.option_dict[LINE_WIDTH]
964
965             if QUOTE in self.option_dict.keys () or type == 'lilypond':
966                 if LINE_WIDTH in self.option_dict.keys ():
967                     del self.option_dict[LINE_WIDTH]
968
969         if not INDENT in self.option_dict.keys ():
970             self.option_dict[INDENT] = '0\\mm'
971
972         # The QUOTE pattern from ly_options only emits the `line-width'
973         # keyword.
974         if has_line_width and QUOTE in self.option_dict.keys ():
975             if no_line_width_value:
976                 del self.option_dict[LINE_WIDTH]
977             else:
978                 del self.option_dict[QUOTE]
979
980     def compose_ly (self, code):
981         if FRAGMENT in self.option_dict.keys ():
982             body = FRAGMENT_LY
983         else:
984             body = FULL_LY
985
986         # Defaults.
987         relative = 1
988         override = {}
989         # The original concept of the `exampleindent' option is broken.
990         # It is not possible to get a sane value for @exampleindent at all
991         # without processing the document itself.  Saying
992         #
993         #   @exampleindent 0
994         #   @example
995         #   ...
996         #   @end example
997         #   @exampleindent 5
998         #
999         # causes ugly results with the DVI backend of texinfo since the
1000         # default value for @exampleindent isn't 5em but 0.4in (or a smaller
1001         # value).  Executing the above code changes the environment
1002         # indentation to an unknown value because we don't know the amount
1003         # of 1em in advance since it is font-dependent.  Modifying
1004         # @exampleindent in the middle of a document is simply not
1005         # supported within texinfo.
1006         #
1007         # As a consequence, the only function of @exampleindent is now to
1008         # specify the amount of indentation for the `quote' option.
1009         #
1010         # To set @exampleindent locally to zero, we use the @format
1011         # environment for non-quoted snippets.
1012         override[EXAMPLEINDENT] = r'0.4\in'
1013         override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1014         override.update (default_ly_options)
1015
1016         option_list = []
1017         for (key, value) in self.option_dict.items ():
1018             if value == None:
1019                 option_list.append (key)
1020             else:
1021                 option_list.append (key + '=' + value)
1022         option_string = ','.join (option_list)
1023
1024         compose_dict = {}
1025         compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1026         for a in compose_types:
1027             compose_dict[a] = []
1028
1029         for (key, value) in self.option_dict.items ():
1030             (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
1031             if c_key:
1032                 if c_value:
1033                     warning (
1034                         _ ("deprecated ly-option used: %s=%s"
1035                            % (key, value)))
1036                     warning (
1037                         _ ("compatibility mode translation: %s=%s"
1038                            % (c_key, c_value)))
1039                 else:
1040                     warning (
1041                         _ ("deprecated ly-option used: %s"
1042                            % key))
1043                     warning (
1044                         _ ("compatibility mode translation: %s"
1045                            % c_key))
1046
1047                 (key, value) = (c_key, c_value)
1048
1049             if value:
1050                 override[key] = value
1051             else:
1052                 if not override.has_key (key):
1053                     override[key] = None
1054
1055             found = 0
1056             for type in compose_types:
1057                 if ly_options[type].has_key (key):
1058                     compose_dict[type].append (ly_options[type][key])
1059                     found = 1
1060                     break
1061
1062             if not found and key not in simple_options:
1063                 warning (_ ("ignoring unknown ly option: %s") % key)
1064
1065         # URGS
1066         if RELATIVE in override.keys () and override[RELATIVE]:
1067             relative = int (override[RELATIVE])
1068
1069         relative_quotes = ''
1070
1071         # 1 = central C
1072         if relative < 0:
1073             relative_quotes += ',' * (- relative)
1074         elif relative > 0:
1075             relative_quotes += "'" * relative
1076
1077         paper_string = '\n  '.join (compose_dict[PAPER]) % override
1078         layout_string = '\n  '.join (compose_dict[LAYOUT]) % override
1079         notes_string = '\n  '.join (compose_dict[NOTES]) % vars ()
1080         preamble_string = '\n  '.join (compose_dict[PREAMBLE]) % override
1081         padding_mm = global_options.padding_mm
1082         font_dump_setting = ''
1083         if FONTLOAD in self.option_dict:
1084             font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1085
1086         d = globals().copy()
1087         d.update (locals())
1088         return (PREAMBLE_LY + body) % d
1089
1090     def get_checksum (self):
1091         if not self.checksum:
1092             hash = md5.md5 (self.relevant_contents (self.full_ly ()))
1093
1094             ## let's not create too long names.
1095             self.checksum = hash.hexdigest ()[:10]
1096             
1097         return self.checksum
1098
1099     def basename (self):
1100         if FILENAME in self.option_dict:
1101             return self.option_dict[FILENAME]
1102
1103         cs = self.get_checksum ()
1104
1105         # TODO: use xx/xxxxx directory layout.
1106         name = 'lily-%s' % (cs[:2], cs[2:])
1107         if global_options.lily_output_dir:
1108             name = os.path.join (global_options.lily_output_dir, name)
1109         return name
1110
1111     def write_ly (self):
1112         out = file (self.basename () + '.ly', 'w')
1113         out.write (self.full_ly ())
1114         file (self.basename () + '.txt', 'w').write ('image of music')
1115
1116     def relevant_contents (self, ly):
1117         return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
1118              
1119     def ly_is_outdated (self):
1120         base = self.basename ()
1121         ly_file = find_file (base + '.ly', raise_error=False)
1122         tex_file = find_file (base + '.tex', raise_error=False)
1123         systems_file = find_file (base + '-systems.tex', raise_error=False)
1124
1125         if (not os.path.exists (ly_file)
1126             or not os.path.exists (systems_file)):
1127             return True
1128
1129         lines = file (systems_file).readlines ()
1130         if not lines:
1131             return True
1132
1133         if not re.match ('% eof', lines[-1]):
1134             return true
1135         
1136         # and FILENAME in self.option_dict
1137         #huh?
1138
1139         if (self.relevant_contents (self.full_ly ())
1140             != self.relevant_contents (file (ly_file).read ())):
1141             return True
1142         
1143         return False
1144
1145     def png_is_outdated (self):
1146         base = self.basename ()
1147         eps_file = find_file (base + '.eps', raise_error=False)
1148         png_file = find_file (base + '.png', raise_error=False)
1149         if self.ly_is_outdated ():
1150             return True
1151         
1152         if (global_options.format in (HTML, TEXINFO)
1153             and os.path.exists (eps_file)):
1154             page_count = ps_page_count (eps_file)
1155             if page_count <= 1:
1156                 return not os.path.exists (png_file)
1157             else:
1158                 for a in range (1, page_count + 1):
1159                     if not find_file (base + '-page%d.png' % a,
1160                                       raise_error=False):
1161                         return True
1162                 
1163         return False
1164     
1165     def filter_text (self):
1166         """Run snippet bodies through a command (say: convert-ly).
1167
1168         This functionality is rarely used, and this code must have bitrot.
1169         """
1170         
1171         code = self.substring ('code')
1172         s = filter_pipe (code, global_options.filter_cmd)
1173         d = {
1174             'code': s,
1175             'options': self.match.group ('options')
1176         }
1177         # TODO
1178         return output[self.format][FILTER] % d
1179
1180     def replacement_text (self):
1181         func = LilypondSnippet.__dict__['output_' + self.format]
1182         return func (self)
1183
1184     def get_images (self):
1185         base = self.basename ()
1186
1187         single = '%(base)s.png' % vars ()
1188         multiple = '%(base)s-page1.png' % vars ()
1189         images = (single,)
1190         if (os.path.exists (multiple) 
1191             and (not os.path.exists (single)
1192                  or (os.stat (multiple)[stat.ST_MTIME]
1193                      > os.stat (single)[stat.ST_MTIME]))):
1194             count = ps_page_count ('%(base)s.eps' % vars ())
1195             images = ['%s-page%d.png' % (base, a) for a in range (1, count+1)]
1196             images = tuple (images)
1197         return images
1198
1199     def output_docbook (self):
1200         str = ''
1201         base = self.basename ()
1202         for image in self.get_images ():
1203             (base, ext) = os.path.splitext (image)
1204             str += output[DOCBOOK][OUTPUT] % vars ()
1205             str += self.output_print_filename (DOCBOOK)
1206             if (self.substring('inline') == 'inline'): 
1207                 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1208             else:
1209                 str = '<mediaobject>' + str + '</mediaobject>'
1210         if VERBATIM in self.option_dict:
1211                 verb = verbatim_html (self.verb_ly ())
1212                 str = output[DOCBOOK][VERBATIM] % vars () + str
1213         return str
1214         
1215     def output_html (self):
1216         str = ''
1217         base = self.basename ()
1218         if global_options.format == HTML:
1219             str += self.output_print_filename (HTML)
1220             if VERBATIM in self.option_dict:
1221                 verb = verbatim_html (self.verb_ly ())
1222                 str += output[HTML][VERBATIM] % vars ()
1223             if QUOTE in self.option_dict:
1224                 str = output[HTML][QUOTE] % vars ()
1225
1226         str += output[HTML][BEFORE] % vars ()
1227         for image in self.get_images ():
1228             (base, ext) = os.path.splitext (image)
1229             alt = self.option_dict[ALT]
1230             str += output[HTML][OUTPUT] % vars ()
1231         str += output[HTML][AFTER] % vars ()
1232         return str
1233
1234     def output_info (self):
1235         str = ''
1236         for image in self.get_images ():
1237             (base, ext) = os.path.splitext (image)
1238
1239             # URG, makeinfo implicitly prepends dot to extension.
1240             # Specifying no extension is most robust.
1241             ext = ''
1242             alt = self.option_dict[ALT]
1243             info_image_path = os.path.join (global_options.info_images_dir, base)
1244             str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1245
1246         base = self.basename ()
1247         str += output[global_options.format][OUTPUT] % vars ()
1248         return str
1249
1250     def output_latex (self):
1251         str = ''
1252         base = self.basename ()
1253         if global_options.format == LATEX:
1254             str += self.output_print_filename (LATEX)
1255             if VERBATIM in self.option_dict:
1256                 verb = self.verb_ly ()
1257                 str += (output[LATEX][VERBATIM] % vars ())
1258
1259         str += (output[LATEX][OUTPUT] % vars ())
1260
1261         ## todo: maintain breaks
1262         if 0:
1263             breaks = self.ly ().count ("\n")
1264             str += "".ljust (breaks, "\n").replace ("\n","%\n")
1265         
1266         if QUOTE in self.option_dict:
1267             str = output[LATEX][QUOTE] % vars ()
1268         return str
1269
1270     def output_print_filename (self, format):
1271         str = ''
1272         if PRINTFILENAME in self.option_dict:
1273             base = self.basename ()
1274             filename = os.path.basename (self.substring ('filename'))
1275             str = output[format][PRINTFILENAME] % vars ()
1276
1277         return str
1278
1279     def output_texinfo (self):
1280         str = self.output_print_filename (TEXINFO)
1281         base = self.basename ()
1282         if TEXIDOC in self.option_dict:
1283             texidoc = base + '.texidoc'
1284             if os.path.exists (texidoc):
1285                 str += '@include %(texidoc)s\n\n' % vars ()
1286
1287         substr = ''
1288         if VERBATIM in self.option_dict:
1289             version = ''
1290             if ADDVERSION in self.option_dict:
1291                 version = output[TEXINFO][ADDVERSION]
1292             verb = self.verb_ly ()
1293             substr = output[TEXINFO][VERBATIM] % vars ()
1294         substr += self.output_info ()
1295         if LILYQUOTE in self.option_dict:
1296             substr = output[TEXINFO][QUOTE] % {'str':substr}
1297         str += substr
1298
1299 #                str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1300 #                str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1301 #                str += ('@html\n' + self.output_html () + '\n@end html\n')
1302
1303         if QUOTE in self.option_dict:
1304             str = output[TEXINFO][QUOTE] % vars ()
1305
1306         # need par after image
1307         str += '\n'
1308
1309         return str
1310
1311 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1312 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1313
1314 class LilypondFileSnippet (LilypondSnippet):
1315     def __init__ (self, type, match, format, line_number):
1316         LilypondSnippet.__init__ (self, type, match, format, line_number)
1317         self.contents = file (find_file (self.substring ('filename'))).read ()
1318
1319     def verb_ly (self):
1320         s = self.contents
1321         s = re_begin_verbatim.split (s)[-1]
1322         s = re_end_verbatim.split (s)[0]
1323         return s
1324
1325     def ly (self):
1326         name = self.substring ('filename')
1327         return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1328                 % (name, self.contents))
1329
1330
1331 snippet_type_to_class = {
1332     'lilypond_file': LilypondFileSnippet,
1333     'lilypond_block': LilypondSnippet,
1334     'lilypond': LilypondSnippet,
1335     'include': IncludeSnippet,
1336 }
1337
1338 def find_linestarts (s):
1339     nls = [0]
1340     start = 0
1341     end = len (s)
1342     while 1:
1343         i = s.find ('\n', start)
1344         if i < 0:
1345             break
1346
1347         i = i + 1
1348         nls.append (i)
1349         start = i
1350
1351     nls.append (len (s))
1352     return nls
1353
1354 def find_toplevel_snippets (s, types):
1355     res = {}
1356     for i in types:
1357         res[i] = ly.re.compile (snippet_res[global_options.format][i])
1358
1359     snippets = []
1360     index = 0
1361     found = dict ([(t, None) for t in types])
1362
1363     line_starts = find_linestarts (s)
1364     line_start_idx = 0
1365     # We want to search for multiple regexes, without searching
1366     # the string multiple times for one regex.
1367     # Hence, we use earlier results to limit the string portion
1368     # where we search.
1369     # Since every part of the string is traversed at most once for
1370     # every type of snippet, this is linear.
1371
1372     while 1:
1373         first = None
1374         endex = 1 << 30
1375         for type in types:
1376             if not found[type] or found[type][0] < index:
1377                 found[type] = None
1378                 
1379                 m = res[type].search (s[index:endex])
1380                 if not m:
1381                     continue
1382
1383                 cl = Snippet
1384                 if snippet_type_to_class.has_key (type):
1385                     cl = snippet_type_to_class[type]
1386
1387
1388                 start = index + m.start ('match')
1389                 line_number = line_start_idx
1390                 while (line_starts[line_number] < start):
1391                     line_number += 1
1392
1393                 line_number += 1
1394                 snip = cl (type, m, global_options.format, line_number)
1395
1396                 found[type] = (start, snip)
1397
1398             if (found[type] 
1399                 and (not first 
1400                      or found[type][0] < found[first][0])):
1401                 first = type
1402
1403                 # FIXME.
1404
1405                 # Limiting the search space is a cute
1406                 # idea, but this *requires* to search
1407                 # for possible containing blocks
1408                 # first, at least as long as we do not
1409                 # search for the start of blocks, but
1410                 # always/directly for the entire
1411                 # @block ... @end block.
1412
1413                 endex = found[first][0]
1414
1415         if not first:
1416             snippets.append (Substring (s, index, len (s), line_start_idx))
1417             break
1418
1419         while (start > line_starts[line_start_idx+1]):
1420             line_start_idx += 1
1421
1422         (start, snip) = found[first]
1423         snippets.append (Substring (s, index, start, line_start_idx + 1))
1424         snippets.append (snip)
1425         found[first] = None
1426         index = start + len (snip.match.group ('match'))
1427
1428     return snippets
1429
1430 def filter_pipe (input, cmd):
1431     """Pass input through cmd, and return the result."""
1432     
1433     if global_options.verbose:
1434         progress (_ ("Opening filter `%s'") % cmd)
1435
1436     (stdin, stdout, stderr) = os.popen3 (cmd)
1437     stdin.write (input)
1438     status = stdin.close ()
1439
1440     if not status:
1441         status = 0
1442         output = stdout.read ()
1443         status = stdout.close ()
1444         error = stderr.read ()
1445
1446     if not status:
1447         status = 0
1448     signal = 0x0f & status
1449     if status or (not output and error):
1450         exit_status = status >> 8
1451         error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1452         error (_ ("The error log is as follows:"))
1453         ly.stderr_write (error)
1454         ly.stderr_write (stderr.read ())
1455         exit (status)
1456
1457     if global_options.verbose:
1458         progress ('\n')
1459
1460     return output
1461
1462 def system_in_directory (cmd, directory):
1463     """Execute a command in a different directory.
1464
1465     Because of win32 compatibility, we can't simply use subprocess.
1466     """
1467     
1468     current = os.getcwd()
1469     os.chdir (directory)
1470     ly.system(cmd, be_verbose=global_options.verbose, 
1471               progress_p=1)
1472     os.chdir (current)
1473     
1474
1475 def process_snippets (cmd, snippets):
1476     """Run cmd on all of the .ly files from snippets."""
1477     if not snippets:
1478         return
1479     
1480     if global_options.format in (HTML, TEXINFO) and '--formats' not in cmd:
1481         cmd += ' --formats=png '
1482     elif global_options.format in (DOCBOOK) and '--formats' not in cmd:
1483         cmd += ' --formats=png,pdf '
1484
1485     checksum = snippet_list_checksum (snippets)
1486     contents = '\n'.join (['snippet-map-%d.ly' % checksum] 
1487                           + [snip.basename() for snip in snippets])
1488     name = os.path.join (global_options.lily_output_dir,
1489                          'snippet-names-%d' % checksum)
1490     file (name, 'wb').write (contents)
1491
1492     system_in_directory (' '.join ([cmd, name]),
1493                          global_options.lily_output_dir)
1494
1495 ###
1496 # Retrieve dimensions from LaTeX
1497 LATEX_INSPECTION_DOCUMENT = r'''
1498 \nonstopmode
1499 %(preamble)s
1500 \begin{document}
1501 \typeout{textwidth=\the\textwidth}
1502 \typeout{columnsep=\the\columnsep}
1503 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1504 \end{document}
1505 '''
1506
1507 # Do we need anything else besides `textwidth'?
1508 def get_latex_textwidth (source):
1509     m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1510     if m == None:
1511         warning (_ ("cannot find \\begin{document} in LaTeX document"))
1512         
1513         ## what's a sensible default?
1514         return 550.0
1515     
1516     preamble = source[:m.start (0)]
1517     latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1518     
1519     (handle, tmpfile) = tempfile.mkstemp('.tex')
1520     logfile = os.path.splitext (tmpfile)[0] + '.log'
1521     logfile = os.path.split (logfile)[1]
1522
1523     tmp_handle = os.fdopen (handle,'w')
1524     tmp_handle.write (latex_document)
1525     tmp_handle.close ()
1526     
1527     ly.system ('latex %s' % tmpfile, be_verbose=global_options.verbose)
1528     parameter_string = file (logfile).read()
1529     
1530     os.unlink (tmpfile)
1531     os.unlink (logfile)
1532
1533     columns = 0
1534     m = re.search ('columns=([0-9.]*)', parameter_string)
1535     if m:
1536         columns = int (m.group (1))
1537
1538     columnsep = 0
1539     m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1540     if m:
1541         columnsep = float (m.group (1))
1542
1543     textwidth = 0
1544     m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1545     if m:
1546         textwidth = float (m.group (1))
1547         if columns:
1548             textwidth = (textwidth - columnsep) / columns
1549
1550     return textwidth
1551
1552 def modify_preamble (chunk):
1553     str = chunk.replacement_text ()
1554     if (re.search (r"\\begin *{document}", str)
1555       and not re.search ("{graphic[sx]", str)):
1556         str = re.sub (r"\\begin{document}",
1557                r"\\usepackage{graphics}" + '\n'
1558                + r"\\begin{document}",
1559                str)
1560         chunk.override_text = str 
1561
1562
1563 format2ext = {
1564     HTML: '.html',
1565     # TEXINFO: '.texinfo',
1566     TEXINFO: '.texi',
1567     LATEX: '.tex',
1568     DOCBOOK: '.xml'
1569 }
1570
1571 class CompileError(Exception):
1572     pass
1573
1574 def snippet_list_checksum (snippets):
1575     return hash (' '.join([l.basename() for l in snippets]))
1576
1577 def write_file_map (lys, name):
1578     snippet_map = file (os.path.join (
1579         global_options.lily_output_dir,
1580         'snippet-map-%d.ly' % snippet_list_checksum (lys)), 'w')
1581     snippet_map.write ("""
1582 #(define version-seen #t)
1583 #(define output-empty-score-list #f)
1584 #(ly:add-file-name-alist '(
1585 """)
1586     
1587     for ly in lys:
1588         snippet_map.write ('("%s.ly" . "%s")\n'
1589                            % (ly.basename (), name))
1590
1591     snippet_map.write ('))\n')
1592
1593 def do_process_cmd (chunks, input_name):
1594     outdated = [c for c in chunks
1595                 if (isinstance (c, LilypondSnippet)
1596                     and (c.ly_is_outdated () or c.png_is_outdated ()))]
1597     write_file_map (outdated, input_name)    
1598     progress (_ ("Writing snippets..."))
1599     for snippet in outdated:
1600         snippet.write_ly()
1601     progress ('\n')
1602
1603     if outdated:
1604         progress (_ ("Processing..."))
1605         progress ('\n')
1606         process_snippets (global_options.process_cmd, outdated)
1607     else:
1608         progress (_ ("All snippets are up to date..."))
1609     progress ('\n')
1610
1611
1612 ###
1613 # Format guessing data
1614 ext2format = {
1615     '.html': HTML,
1616     '.itely': TEXINFO,
1617     '.latex': LATEX,
1618     '.lytex': LATEX,
1619     '.tely': TEXINFO,
1620     '.tex': LATEX,
1621     '.texi': TEXINFO,
1622     '.texinfo': TEXINFO,
1623     '.xml': HTML,
1624     '.lyxml': DOCBOOK
1625 }
1626
1627 def guess_format (input_filename):
1628     format = None
1629     e = os.path.splitext (input_filename)[1]
1630     if e in ext2format.keys ():
1631         # FIXME
1632         format = ext2format[e]
1633     else:
1634         error (_ ("cannot determine format for: %s"
1635                   % input_filename))
1636         exit (1)
1637     return format
1638
1639 def write_if_updated (file_name, lines):
1640     try:
1641         f = file (file_name)
1642         oldstr = f.read ()
1643         new_str = ''.join (lines)
1644         if oldstr == new_str:
1645             progress (_ ("%s is up to date.") % file_name)
1646             progress ('\n')
1647
1648             # this prevents make from always rerunning lilypond-book:
1649             # output file must be touched in order to be up to date
1650             os.utime (file_name, None)
1651     except:
1652         pass
1653
1654     progress (_ ("Writing `%s'...") % file_name)
1655     file (file_name, 'w').writelines (lines)
1656     progress ('\n')
1657
1658
1659 def note_input_file (name, inputs=[]):
1660     ## hack: inputs is mutable!
1661     inputs.append (name)
1662     return inputs
1663
1664 def samefile (f1, f2):
1665     try:
1666         return os.path.samefile (f1, f2)
1667     except AttributeError:                # Windoze
1668         f1 = re.sub ("//*", "/", f1)
1669         f2 = re.sub ("//*", "/", f2)
1670         return f1 == f2
1671
1672 def do_file (input_filename):
1673     # Ugh.
1674     if not input_filename or input_filename == '-':
1675         in_handle = sys.stdin
1676         input_fullname = '<stdin>'
1677     else:
1678         if os.path.exists (input_filename):
1679             input_fullname = input_filename
1680         elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1681             input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1682         else:
1683             input_fullname = find_file (input_filename)
1684
1685         note_input_file (input_fullname)
1686         in_handle = file (input_fullname)
1687
1688     if input_filename == '-':
1689         input_base = 'stdin'
1690     else:
1691         input_base = os.path.basename (
1692             os.path.splitext (input_filename)[0])
1693
1694     # Only default to stdout when filtering.
1695     if global_options.output_name == '-' or (not global_options.output_name and global_options.filter_cmd):
1696         output_filename = '-'
1697         output_file = sys.stdout
1698     else:
1699         # don't complain when global_options.output_name is existing
1700         output_filename = input_base + format2ext[global_options.format]
1701         if global_options.output_name:
1702             if not os.path.isdir (global_options.output_name):
1703                 os.mkdir (global_options.output_name, 0777)
1704             os.chdir (global_options.output_name)
1705         else: 
1706             if (os.path.exists (input_filename) 
1707                 and os.path.exists (output_filename) 
1708                 and samefile (output_filename, input_fullname)):
1709              error (
1710              _ ("Output would overwrite input file; use --output."))
1711              exit (2)
1712
1713     try:
1714         progress (_ ("Reading %s...") % input_fullname)
1715         source = in_handle.read ()
1716         progress ('\n')
1717
1718         set_default_options (source)
1719
1720
1721         # FIXME: Containing blocks must be first, see
1722         #        find_toplevel_snippets.
1723         snippet_types = (
1724             'multiline_comment',
1725             'verbatim',
1726             'lilypond_block',
1727     #                'verb',
1728             'singleline_comment',
1729             'lilypond_file',
1730             'include',
1731             'lilypond',
1732         )
1733         progress (_ ("Dissecting..."))
1734         chunks = find_toplevel_snippets (source, snippet_types)
1735
1736         if global_options.format == LATEX:
1737             for c in chunks:
1738                 if (c.is_plain () and
1739                   re.search (r"\\begin *{document}", c.replacement_text())):
1740                     modify_preamble (c)
1741                     break
1742         progress ('\n')
1743
1744         if global_options.filter_cmd:
1745             write_if_updated (output_filename,
1746                      [c.filter_text () for c in chunks])
1747         elif global_options.process_cmd:
1748             do_process_cmd (chunks, input_fullname)
1749             progress (_ ("Compiling %s...") % output_filename)
1750             progress ('\n')
1751             write_if_updated (output_filename,
1752                      [s.replacement_text ()
1753                      for s in chunks])
1754         
1755         def process_include (snippet):
1756             os.chdir (original_dir)
1757             name = snippet.substring ('filename')
1758             progress (_ ("Processing include: %s") % name)
1759             progress ('\n')
1760             return do_file (name)
1761
1762         include_chunks = map (process_include,
1763                    filter (lambda x: isinstance (x, IncludeSnippet),
1764                        chunks))
1765
1766         return chunks + reduce (lambda x, y: x + y, include_chunks, [])
1767         
1768     except CompileError:
1769         os.chdir (original_dir)
1770         progress (_ ("Removing `%s'") % output_filename)
1771         progress ('\n')
1772         raise CompileError
1773
1774 def do_options ():
1775     global global_options
1776
1777     opt_parser = get_option_parser()
1778     (global_options, args) = opt_parser.parse_args ()
1779
1780     if global_options.format in ('texi-html', 'texi'):
1781         global_options.format = TEXINFO
1782
1783     global_options.include_path =  map (os.path.abspath, global_options.include_path)
1784     
1785     if global_options.warranty:
1786         warranty ()
1787         exit (0)
1788     if not args or len (args) > 1:
1789         opt_parser.print_help ()
1790         exit (2)
1791         
1792     return args
1793
1794 def psfonts_warning (options, basename):
1795     if options.format in (TEXINFO, LATEX):
1796         psfonts_file = os.path.join (options.output_name, basename + '.psfonts')
1797         output = os.path.join (options.output_name, basename +  '.dvi' )
1798
1799         if not options.create_pdf:
1800             if not options.psfonts:
1801                 warning (_ ("option --psfonts not used"))
1802                 warning (_ ("processing with dvips will have no fonts"))
1803             else:
1804                 progress ('\n')
1805                 progress (_ ("DVIPS usage:"))
1806                 progress ('\n')
1807                 progress ("    dvips -h %(psfonts_file)s %(output)s" % vars ())
1808                 progress ('\n')
1809
1810 def main ():
1811     # FIXME: 85 lines of `main' macramee??
1812     files = do_options ()
1813
1814     basename = os.path.splitext (files[0])[0]
1815     basename = os.path.split (basename)[1]
1816     
1817     if not global_options.format:
1818         global_options.format = guess_format (files[0])
1819
1820     formats = 'ps'
1821     if global_options.format in (TEXINFO, HTML, DOCBOOK):
1822         formats += ',png'
1823
1824     if global_options.process_cmd == '':
1825         global_options.process_cmd = (lilypond_binary 
1826                                       + ' --formats=%s -dbackend=eps ' % formats)
1827
1828     if global_options.process_cmd:
1829         global_options.process_cmd += ' '.join ([(' -I %s' % ly.mkarg (p))
1830                               for p in global_options.include_path])
1831
1832     if global_options.format in (TEXINFO, LATEX):
1833         ## prevent PDF from being switched on by default.
1834         global_options.process_cmd += ' --formats=eps '
1835         if global_options.create_pdf:
1836             global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
1837     
1838     if global_options.verbose:
1839         global_options.process_cmd += " --verbose "
1840
1841     if global_options.padding_mm:
1842         global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
1843         
1844     global_options.process_cmd += " -dread-file-list "
1845
1846     if global_options.lily_output_dir:
1847         global_options.lily_output_dir = os.path.abspath(global_options.lily_output_dir)
1848         if not os.path.isdir (global_options.lily_output_dir):
1849             os.makedirs (global_options.lily_output_dir)
1850     else:
1851         global_options.lily_output_dir = os.path.abspath(global_options.output_name)
1852         
1853
1854     identify ()
1855     try:
1856         chunks = do_file (files[0])
1857         if global_options.psfonts:
1858             fontextract.verbose = global_options.verbose
1859             snippet_chunks = filter (
1860                 lambda x: isinstance (x, LilypondSnippet),
1861                 chunks)
1862
1863             psfonts_file = basename + '.psfonts' 
1864             if not global_options.verbose:
1865                 progress (_ ("Writing fonts to %s...") % psfonts_file)
1866             fontextract.extract_fonts (
1867                 psfonts_file,
1868                 [x.basename() + '.eps' for x in snippet_chunks])
1869             if not global_options.verbose:
1870                 progress ('\n')
1871             
1872     except CompileError:
1873         exit (1)
1874
1875     psfonts_warning (global_options, basename)
1876
1877     inputs = note_input_file ('')
1878     inputs.pop ()
1879
1880     base_file_name = os.path.splitext (os.path.basename (files[0]))[0]
1881     dep_file = os.path.join (global_options.output_name, base_file_name + '.dep')
1882     final_output_file = os.path.join (global_options.output_name,
1883                      base_file_name
1884                      + '.%s' % global_options.format)
1885     
1886     os.chdir (original_dir)
1887     file (dep_file, 'w').write ('%s: %s'
1888                                 % (final_output_file, ' '.join (inputs)))
1889
1890 if __name__ == '__main__':
1891     main ()