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