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