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