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