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