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