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