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