]> git.donarmstrong.com Git - lilypond.git/blob - scripts/lilypond-book.py
* scripts/lilypond-book.py (ly_options): set timing to #f for
[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 class Chunk:
646         def replacement_text (self):
647                 return ''
648
649         def filter_text (self):
650                 return self.replacement_text ()
651
652         def ly_is_outdated (self):
653                 return 0
654
655         def png_is_outdated (self):
656                 return 0
657
658 class Substring (Chunk):
659         def __init__ (self, source, start, end, line_number):
660                 self.source = source
661                 self.start = start
662                 self.end = end
663                 self.line_number = line_number
664
665         def replacement_text (self):
666                 return self.source[self.start:self.end]
667
668 class Snippet (Chunk):
669         def __init__ (self, type, match, format, line_number):
670                 self.type = type
671                 self.match = match
672                 self.hash = 0
673                 self.option_dict = {}
674                 self.format = format
675                 self.line_number = line_number
676
677         def replacement_text (self):
678                 return self.match.group ('match')
679
680         def substring (self, s):
681                 return self.match.group (s)
682
683         def __repr__ (self):
684                 return `self.__class__` + ' type = ' + self.type
685
686 class Include_snippet (Snippet):
687         def processed_filename (self):
688                 f = self.substring ('filename')
689                 return os.path.splitext (f)[0] + format2ext[format]
690
691         def replacement_text (self):
692                 s = self.match.group ('match')
693                 f = self.substring ('filename')
694
695                 return re.sub (f, self.processed_filename (), s)
696
697 class Lilypond_snippet (Snippet):
698         def __init__ (self, type, match, format, line_number):
699                 Snippet.__init__ (self, type, match, format, line_number)
700                 os = match.group ('options')
701                 self.do_options (os, self.type)
702
703         def ly (self):
704                 return self.substring ('code')
705
706         def full_ly (self):
707                 s = self.ly ()
708                 if s:
709                         return self.compose_ly (s)
710                 return ''
711
712         def do_options (self, option_string, type):
713                 self.option_dict = {}
714
715                 options = split_options (option_string)
716
717                 for i in options:
718                         if string.find (i, '=') > 0:
719                                 (key, value) = re.split ('\s*=\s*', i)
720                                 self.option_dict[key] = value
721                         else:
722                                 if i in no_options.keys ():
723                                         if no_options[i] in self.option_dict.keys ():
724                                                 del self.option_dict[no_options[i]]
725                                 else:
726                                         self.option_dict[i] = None
727
728                 has_linewidth = self.option_dict.has_key (LINEWIDTH)
729                 no_linewidth_value = 0
730
731                 # If LINEWIDTH is used without parameter, set it to default.
732                 if has_linewidth and self.option_dict[LINEWIDTH] == None:
733                         no_linewidth_value = 1
734                         del self.option_dict[LINEWIDTH]
735
736                 for i in default_ly_options.keys ():
737                         if i not in self.option_dict.keys ():
738                                 self.option_dict[i] = default_ly_options[i]
739
740                 if not has_linewidth:
741                         if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
742                                 self.option_dict[RAGGEDRIGHT] = None
743
744                         if type == 'lilypond':
745                                 if LINEWIDTH in self.option_dict.keys ():
746                                         del self.option_dict[LINEWIDTH]
747                         else:
748                                 if RAGGEDRIGHT in self.option_dict.keys ():
749                                         if LINEWIDTH in self.option_dict.keys ():
750                                                 del self.option_dict[LINEWIDTH]
751
752                         if QUOTE in self.option_dict.keys () or type == 'lilypond':
753                                 if LINEWIDTH in self.option_dict.keys ():
754                                         del self.option_dict[LINEWIDTH]
755
756                 if not INDENT in self.option_dict.keys ():
757                         self.option_dict[INDENT] = '0\\mm'
758
759                 # The QUOTE pattern from ly_options only emits the `linewidth'
760                 # keyword.
761                 if has_linewidth and QUOTE in self.option_dict.keys ():
762                         if no_linewidth_value:
763                                 del self.option_dict[LINEWIDTH]
764                         else:
765                                 del self.option_dict[QUOTE]
766
767         def compose_ly (self, code):
768                 if FRAGMENT in self.option_dict.keys ():
769                         body = FRAGMENT_LY
770                 else:
771                         body = FULL_LY
772
773                 # Defaults.
774                 relative = 1
775                 override = {}
776                 # The original concept of the `exampleindent' option is broken.
777                 # It is not possible to get a sane value for @exampleindent at all
778                 # without processing the document itself.  Saying
779                 #
780                 #   @exampleindent 0
781                 #   @example
782                 #   ...
783                 #   @end example
784                 #   @exampleindent 5
785                 #
786                 # causes ugly results with the DVI backend of texinfo since the
787                 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
788                 # value).  Executing the above code changes the environment
789                 # indentation to an unknown value because we don't know the amount
790                 # of 1em in advance since it is font-dependent.  Modifying
791                 # @exampleindent in the middle of a document is simply not
792                 # supported within texinfo.
793                 #
794                 # As a consequence, the only function of @exampleindent is now to
795                 # specify the amount of indentation for the `quote' option.
796                 #
797                 # To set @exampleindent locally to zero, we use the @format
798                 # environment for non-quoted snippets.
799                 override[EXAMPLEINDENT] = r'0.4\in'
800                 override[LINEWIDTH] = texinfo_linewidths['@smallbook']
801                 override.update (default_ly_options)
802
803                 option_list = []
804                 for (key, value) in self.option_dict.items ():
805                         if value == None:
806                                 option_list.append (key)
807                         else:
808                                 option_list.append (key + '=' + value)
809                 option_string = string.join (option_list, ',')
810
811                 compose_dict = {}
812                 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
813                 for a in compose_types:
814                         compose_dict[a] = []
815
816                 for (key, value) in self.option_dict.items ():
817                         (c_key, c_value) = \
818                           classic_lilypond_book_compatibility (key, value)
819                         if c_key:
820                                 if c_value:
821                                         ly.warning \
822                                           (_ ("deprecated ly-option used: %s=%s" \
823                                             % (key, value)))
824                                         ly.warning \
825                                           (_ ("compatibility mode translation: %s=%s" \
826                                             % (c_key, c_value)))
827                                 else:
828                                         ly.warning \
829                                           (_ ("deprecated ly-option used: %s" \
830                                             % key))
831                                         ly.warning \
832                                           (_ ("compatibility mode translation: %s" \
833                                             % c_key))
834
835                                 (key, value) = (c_key, c_value)
836
837                         if value:
838                                 override[key] = value
839                         else:
840                                 if not override.has_key (key):
841                                         override[key] = None
842
843                         found = 0
844                         for type in compose_types:
845                                 if ly_options[type].has_key (key):
846                                         compose_dict[type].append (ly_options[type][key])
847                                         found = 1
848                                         break
849
850                         if not found and key not in simple_options:
851                                 ly.warning (_ ("ignoring unknown ly option: %s") % key)
852
853                 # URGS
854                 if RELATIVE in override.keys () and override[RELATIVE]:
855                         relative = string.atoi (override[RELATIVE])
856
857                 relative_quotes = ''
858
859                 # 1 = central C
860                 if relative < 0:
861                         relative_quotes += ',' * (- relative)
862                 elif relative > 0:
863                         relative_quotes += "'" * relative
864
865                 program_name = __main__.program_name
866
867                 paper_string = string.join (compose_dict[PAPER],
868                                             '\n  ') % override
869                 layout_string = string.join (compose_dict[LAYOUT],
870                                              '\n  ') % override
871                 notes_string = string.join (compose_dict[NOTES],
872                                             '\n  ') % vars ()
873                 preamble_string = string.join (compose_dict[PREAMBLE],
874                                                '\n  ') % override
875
876                 font_dump_setting = ''
877                 if FONTLOAD in self.option_dict:
878                         font_dump_setting = '#(define-public force-eps-font-include #t)\n'
879
880                 return (PREAMBLE_LY + body) % vars ()
881
882         # TODO: Use md5?
883         def get_hash (self):
884                 if not self.hash:
885                         self.hash = abs (hash (self.full_ly ()))
886                 return self.hash
887
888         def basename (self):
889                 if FILENAME in self.option_dict:
890                         return self.option_dict[FILENAME]
891                 if use_hash_p:
892                         return 'lily-%d' % self.get_hash ()
893                 raise 'to be done'
894
895         def write_ly (self):
896                 outf = open (self.basename () + '.ly', 'w')
897                 outf.write (self.full_ly ())
898
899                 open (self.basename () + '.txt', 'w').write ('image of music')
900
901         def ly_is_outdated (self):
902                 base = self.basename ()
903
904                 tex_file = '%s.tex' % base
905                 eps_file = '%s.eps' % base
906                 system_file = '%s-systems.tex' % base
907                 ly_file = '%s.ly' % base
908                 ok = os.path.exists (ly_file) \
909                      and os.path.exists (system_file)\
910                      and os.stat (system_file)[stat.ST_SIZE] \
911                      and re.match ('% eof', open (system_file).readlines ()[-1])
912                 if ok and (not use_hash_p or FILENAME in self.option_dict):
913                         ok = (self.full_ly () == open (ly_file).read ())
914                 if ok:
915                         # TODO: Do something smart with target formats
916                         #       (ps, png) and m/ctimes.
917                         return None
918                 return self
919
920         def png_is_outdated (self):
921                 base = self.basename ()
922                 ok = self.ly_is_outdated ()
923                 if format == HTML or format == TEXINFO:
924                         ok = ok and (os.path.exists (base + '.png')
925                                      or glob.glob (base + '-page*.png'))
926                 return not ok
927         def texstr_is_outdated (self):
928                 if backend == 'ps':
929                         return 0
930
931                 base = self.basename ()
932                 ok = self.ly_is_outdated ()
933                 ok = ok and (os.path.exists (base + '.texstr'))
934                 return not ok
935
936         def filter_text (self):
937                 code = self.substring ('code')
938                 s = run_filter (code)
939                 d = {
940                         'code': s,
941                         'options': self.match.group ('options')
942                 }
943                 # TODO
944                 return output[self.format][FILTER] % d
945
946         def replacement_text (self):
947                 func = Lilypond_snippet.__dict__['output_' + self.format]
948                 return func (self)
949
950         def get_images (self):
951                 base = self.basename ()
952                 # URGUGHUGHUGUGH
953                 single = '%(base)s.png' % vars ()
954                 multiple = '%(base)s-page1.png' % vars ()
955                 images = (single,)
956                 if os.path.exists (multiple) \
957                    and (not os.path.exists (single) \
958                         or (os.stat (multiple)[stat.ST_MTIME] \
959                             > os.stat (single)[stat.ST_MTIME])):
960                         images = glob.glob ('%(base)s-page*.png' % vars ())
961                 return images
962
963         def output_html (self):
964                 str = ''
965                 base = self.basename ()
966                 if format == HTML:
967                         str += self.output_print_filename (HTML)
968                         if VERBATIM in self.option_dict:
969                                 verb = verbatim_html (self.substring ('code'))
970                                 str += write (output[HTML][VERBATIM] % vars ())
971                         if QUOTE in self.option_dict:
972                                 str = output[HTML][QUOTE] % vars ()
973
974                 str += output[HTML][BEFORE] % vars ()
975                 for image in self.get_images ():
976                         (base, ext) = os.path.splitext (image)
977                         alt = self.option_dict[ALT]
978                         str += output[HTML][OUTPUT] % vars ()
979                 str += output[HTML][AFTER] % vars ()
980                 return str
981
982         def output_info (self):
983                 str = ''
984                 for image in self.get_images ():
985                         (base, ext) = os.path.splitext (image)
986
987                         # URG, makeinfo implicitly prepends dot to extension.
988                         # Specifying no extension is most robust.
989                         ext = ''
990                         alt = self.option_dict[ALT]
991                         str += output[TEXINFO][OUTPUTIMAGE] % vars ()
992
993                 base = self.basename ()
994                 str += output[format][OUTPUT] % vars ()
995                 return str
996
997         def output_latex (self):
998                 str = ''
999                 base = self.basename ()
1000                 if format == LATEX:
1001                         str += self.output_print_filename (LATEX)
1002                         if VERBATIM in self.option_dict:
1003                                 verb = self.substring ('code')
1004                                 str += (output[LATEX][VERBATIM] % vars ())
1005                         if QUOTE in self.option_dict:
1006                                 str = output[LATEX][QUOTE] % vars ()
1007
1008                 str += (output[LATEX][OUTPUT] % vars ())
1009                 return str
1010
1011         def output_print_filename (self, format):
1012                 str = ''
1013                 if PRINTFILENAME in self.option_dict:
1014                         base = self.basename ()
1015                         filename = self.substring ('filename')
1016                         str = output[format][PRINTFILENAME] % vars ()
1017
1018                 return str
1019
1020         def output_texinfo (self):
1021                 str = ''
1022                 if self.output_print_filename (TEXINFO):
1023                         str += ('@html\n'
1024                                 + self.output_print_filename (HTML)
1025                                 + '\n@end html\n')
1026                         str += ('@tex\n'
1027                                 + self.output_print_filename (LATEX)
1028                                 + '\n@end tex\n')
1029                 base = self.basename ()
1030                 if TEXIDOC in self.option_dict:
1031                         texidoc = base + '.texidoc'
1032                         if os.path.exists (texidoc):
1033                                 str += '@include %(texidoc)s\n\n' % vars ()
1034
1035                 if VERBATIM in self.option_dict:
1036                         verb = verbatim_texinfo (self.substring ('code'))
1037                         str += (output[TEXINFO][VERBATIM] % vars ())
1038                         if not QUOTE in self.option_dict:
1039                                 str = output[TEXINFO][NOQUOTE] % vars ()
1040
1041                 str += self.output_info ()
1042
1043 #               str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1044 #               str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1045 #               str += ('@html\n' + self.output_html () + '\n@end html\n')
1046
1047                 if QUOTE in self.option_dict:
1048                         str = output[TEXINFO][QUOTE] % vars ()
1049
1050                 # need par after image
1051                 str += '\n'
1052
1053                 return str
1054
1055 class Lilypond_file_snippet (Lilypond_snippet):
1056         def ly (self):
1057                 name = self.substring ('filename')
1058                 return '\\renameinput \"%s\"\n%s' \
1059                          % (name, open (find_file (name)).read ())
1060
1061 snippet_type_to_class = {
1062         'lilypond_file': Lilypond_file_snippet,
1063         'lilypond_block': Lilypond_snippet,
1064         'lilypond': Lilypond_snippet,
1065         'include': Include_snippet,
1066 }
1067
1068 def find_linestarts (s):
1069         nls = [0]
1070         start = 0
1071         end = len (s)
1072         while 1:
1073                 i = s.find ('\n', start)
1074                 if i < 0:
1075                         break
1076
1077                 i = i + 1
1078                 nls.append (i)
1079                 start = i
1080
1081         nls.append (len (s))
1082         return nls
1083
1084 def find_toplevel_snippets (s, types):
1085         res = {}
1086         for i in types:
1087                 res[i] = ly.re.compile (snippet_res[format][i])
1088
1089         snippets = []
1090         index = 0
1091         ## found = dict (map (lambda x: (x, None),
1092         ##                    types))
1093         ## urg python2.1
1094         found = {}
1095         map (lambda x, f = found: f.setdefault (x, None),
1096              types)
1097
1098         line_starts = find_linestarts (s)
1099         line_start_idx = 0
1100         # We want to search for multiple regexes, without searching
1101         # the string multiple times for one regex.
1102         # Hence, we use earlier results to limit the string portion
1103         # where we search.
1104         # Since every part of the string is traversed at most once for
1105         # every type of snippet, this is linear.
1106
1107         while 1:
1108                 first = None
1109                 endex = 1 << 30
1110                 for type in types:
1111                         if not found[type] or found[type][0] < index:
1112                                 found[type] = None
1113                                 m = res[type].search (s[index:endex])
1114                                 if not m:
1115                                         continue
1116
1117                                 cl = Snippet
1118                                 if snippet_type_to_class.has_key (type):
1119                                         cl = snippet_type_to_class[type]
1120
1121
1122                                 start = index + m.start ('match')
1123                                 line_number = line_start_idx
1124                                 while (line_starts[line_number] < start):
1125                                         line_number += 1
1126
1127                                 line_number += 1
1128                                 snip = cl (type, m, format, line_number)
1129                                 found[type] = (start, snip)
1130
1131                         if found[type] \
1132                            and (not first \
1133                                 or found[type][0] < found[first][0]):
1134                                 first = type
1135
1136                                 # FIXME.
1137
1138                                 # Limiting the search space is a cute
1139                                 # idea, but this *requires* to search
1140                                 # for possible containing blocks
1141                                 # first, at least as long as we do not
1142                                 # search for the start of blocks, but
1143                                 # always/directly for the entire
1144                                 # @block ... @end block.
1145
1146                                 endex = found[first][0]
1147
1148                 if not first:
1149                         snippets.append (Substring (s, index, len (s), line_start_idx))
1150                         break
1151
1152                 while (start > line_starts[line_start_idx+1]):
1153                         line_start_idx += 1
1154
1155                 (start, snip) = found[first]
1156                 snippets.append (Substring (s, index, start, line_start_idx + 1))
1157                 snippets.append (snip)
1158                 found[first] = None
1159                 index = start + len (snip.match.group ('match'))
1160
1161         return snippets
1162
1163 def filter_pipe (input, cmd):
1164         if verbose_p:
1165                 ly.progress (_ ("Opening filter `%s'") % cmd)
1166
1167         (stdin, stdout, stderr) = os.popen3 (cmd)
1168         stdin.write (input)
1169         status = stdin.close ()
1170
1171         if not status:
1172                 status = 0
1173                 output = stdout.read ()
1174                 status = stdout.close ()
1175                 error = stderr.read ()
1176
1177         if not status:
1178                 status = 0
1179         signal = 0x0f & status
1180         if status or (not output and error):
1181                 exit_status = status >> 8
1182                 ly.error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1183                 ly.error (_ ("The error log is as follows:"))
1184                 sys.stderr.write (error)
1185                 sys.stderr.write (stderr.read ())
1186                 ly.exit (status)
1187
1188         if verbose_p:
1189                 ly.progress ('\n')
1190
1191         return output
1192
1193 def run_filter (s):
1194         return filter_pipe (s, filter_cmd)
1195
1196 def is_derived_class (cl, baseclass):
1197         if cl == baseclass:
1198                 return 1
1199         for b in cl.__bases__:
1200                 if is_derived_class (b, baseclass):
1201                         return 1
1202         return 0
1203
1204 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1205         ly_names = filter (lambda x: x,
1206                            map (Lilypond_snippet.basename, ly_snippets))
1207         texstr_names = filter (lambda x: x,
1208                            map (Lilypond_snippet.basename, texstr_snippets))
1209         png_names = filter (lambda x: x,
1210                             map (Lilypond_snippet.basename, png_snippets))
1211
1212         status = 0
1213         def my_system (cmd):
1214                 status = ly.system (cmd,
1215                                     ignore_error = 1, progress_p = 1)
1216
1217                 if status:
1218                         ly.error ('Process %s exited unsuccessfully.' % cmd)
1219                         raise Compile_error
1220
1221         # UGH
1222         # the --process=CMD switch is a bad idea
1223         # it is too generic for lilypond-book.
1224         if texstr_names and re.search ('^[0-9A-Za-z/]*lilypond', cmd):
1225
1226                 my_system (string.join ([cmd, '--backend texstr',
1227                                          'snippet-map.ly'] + texstr_names))
1228                 for l in texstr_names:
1229                         my_system ('latex %s.texstr' % l)
1230
1231         if ly_names:
1232                 my_system (string.join ([cmd, 'snippet-map.ly'] + ly_names))
1233
1234 LATEX_DOCUMENT = r'''
1235 %(preamble)s
1236 \begin{document}
1237 \typeout{textwidth=\the\textwidth}
1238 \typeout{columnsep=\the\columnsep}
1239 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1240 \end{document}
1241 '''
1242
1243 # Do we need anything else besides `textwidth'?
1244 def get_latex_textwidth (source):
1245         m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1246         preamble = source[:m.start (0)]
1247         latex_document = LATEX_DOCUMENT % vars ()
1248         parameter_string = filter_pipe (latex_document, latex_filter_cmd)
1249
1250         columns = 0
1251         m = re.search ('columns=([0-9.]*)', parameter_string)
1252         if m:
1253                 columns = string.atoi (m.group (1))
1254
1255         columnsep = 0
1256         m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1257         if m:
1258                 columnsep = string.atof (m.group (1))
1259
1260         textwidth = 0
1261         m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1262         if m:
1263                 textwidth = string.atof (m.group (1))
1264                 if columns:
1265                         textwidth = (textwidth - columnsep) / columns
1266
1267         return textwidth
1268
1269 ext2format = {
1270         '.html': HTML,
1271         '.itely': TEXINFO,
1272         '.latex': LATEX,
1273         '.lytex': LATEX,
1274         '.tely': TEXINFO,
1275         '.tex': LATEX,
1276         '.texi': TEXINFO,
1277         '.texinfo': TEXINFO,
1278         '.xml': HTML,
1279 }
1280
1281 format2ext = {
1282         HTML: '.html',
1283         # TEXINFO: '.texinfo',
1284         TEXINFO: '.texi',
1285         LATEX: '.tex',
1286 }
1287
1288 class Compile_error:
1289         pass
1290
1291 def write_file_map (lys, name):
1292         snippet_map = open ('snippet-map.ly', 'w')
1293         snippet_map.write ("""
1294 #(define version-seen? #t)
1295 #(ly:add-file-name-alist '(
1296 """)
1297         for ly in lys:
1298                 snippet_map.write ('("%s.ly" . "%s:%d (%s.ly)")\n'
1299                                    % (ly.basename (),
1300                                       name,
1301                                       ly.line_number,
1302                                       ly.basename ()))
1303
1304         snippet_map.write ('))\n')
1305
1306 def do_process_cmd (chunks, input_name):
1307         all_lys = filter (lambda x: is_derived_class (x.__class__,
1308                                                       Lilypond_snippet),
1309                           chunks)
1310
1311         write_file_map (all_lys, input_name)
1312         ly_outdated = \
1313           filter (lambda x: is_derived_class (x.__class__,
1314                                               Lilypond_snippet)
1315                             and x.ly_is_outdated (),
1316                   chunks)
1317         texstr_outdated = \
1318           filter (lambda x: is_derived_class (x.__class__,
1319                                               Lilypond_snippet)
1320                             and x.texstr_is_outdated (),
1321                   chunks)
1322         png_outdated = \
1323           filter (lambda x: is_derived_class (x.__class__,
1324                                               Lilypond_snippet)
1325                             and x.png_is_outdated (),
1326                   chunks)
1327
1328         ly.progress (_ ("Writing snippets..."))
1329         map (Lilypond_snippet.write_ly, ly_outdated)
1330         ly.progress ('\n')
1331
1332         if ly_outdated:
1333                 ly.progress (_ ("Processing..."))
1334                 ly.progress ('\n')
1335                 process_snippets (process_cmd, ly_outdated, texstr_outdated, png_outdated)
1336         else:
1337                 ly.progress (_ ("All snippets are up to date..."))
1338         ly.progress ('\n')
1339
1340 def guess_format (input_filename):
1341         format = None
1342         e = os.path.splitext (input_filename)[1]
1343         if e in ext2format.keys ():
1344                 # FIXME
1345                 format = ext2format[e]
1346         else:
1347                 ly.error (_ ("can't determine format for: %s" \
1348                              % input_filename))
1349                 ly.exit (1)
1350         return format
1351
1352 def write_if_updated (file_name, lines):
1353         try:
1354                 f = open (file_name)
1355                 oldstr = f.read ()
1356                 new_str = string.join (lines, '')
1357                 if oldstr == new_str:
1358                         ly.progress (_ ("%s is up to date."))
1359                         ly.progress ('\n')
1360                         return
1361         except:
1362                 pass
1363
1364         ly.progress (_ ("Writing `%s'...") % file_name)
1365         open (file_name, 'w').writelines (lines)
1366         ly.progress ('\n')
1367
1368 def do_file (input_filename):
1369         # Ugh.
1370         if not input_filename or input_filename == '-':
1371                 in_handle = sys.stdin
1372                 input_fullname = '<stdin>'
1373         else:
1374                 if os.path.exists (input_filename):
1375                         input_fullname = input_filename
1376                 elif format == LATEX:
1377                         # urg python interface to libkpathsea?
1378                         input_fullname = ly.read_pipe ('kpsewhich '
1379                                                        + input_filename)[:-1]
1380                 else:
1381                         input_fullname = find_file (input_filename)
1382                 in_handle = open (input_fullname)
1383
1384         if input_filename == '-':
1385                 input_base = 'stdin'
1386         else:
1387                 input_base = os.path.basename \
1388                              (os.path.splitext (input_filename)[0])
1389
1390         # Only default to stdout when filtering.
1391         if output_name == '-' or (not output_name and filter_cmd):
1392                 output_filename = '-'
1393                 output_file = sys.stdout
1394         else:
1395                 if output_name:
1396                         if not os.path.isdir (output_name):
1397                                 os.mkdir (output_name, 0777)
1398                         os.chdir (output_name)
1399
1400                 output_filename = input_base + format2ext[format]
1401                 if os.path.exists (input_filename) \
1402                    and os.path.exists (output_filename) \
1403                    and os.path.samefile (output_filename, input_fullname):
1404                         ly.error (
1405                           _ ("Output would overwrite input file; use --output."))
1406                         ly.exit (2)
1407
1408         try:
1409                 ly.progress (_ ("Reading %s...") % input_fullname)
1410                 source = in_handle.read ()
1411                 ly.progress ('\n')
1412
1413                 # FIXME: Containing blocks must be first, see
1414                 #        find_toplevel_snippets.
1415                 snippet_types = (
1416                         'multiline_comment',
1417                         'verbatim',
1418                         'lilypond_block',
1419         #               'verb',
1420                         'singleline_comment',
1421                         'lilypond_file',
1422                         'include',
1423                         'lilypond',
1424                 )
1425                 ly.progress (_ ("Dissecting..."))
1426                 chunks = find_toplevel_snippets (source, snippet_types)
1427                 ly.progress ('\n')
1428
1429                 global default_ly_options
1430                 textwidth = 0
1431                 if not default_ly_options.has_key (LINEWIDTH):
1432                         if format == LATEX:
1433                                 textwidth = get_latex_textwidth (source)
1434                                 default_ly_options[LINEWIDTH] = \
1435                                   '''%.0f\\pt''' % textwidth
1436                         elif format == TEXINFO:
1437                                 for (k, v) in texinfo_linewidths.items ():
1438                                         # FIXME: @layout is usually not in
1439                                         # chunk #0:
1440                                         #
1441                                         #  \input texinfo @c -*-texinfo-*-
1442                                         #
1443                                         # Bluntly search first K items of
1444                                         # source.
1445                                         # s = chunks[0].replacement_text ()
1446                                         if re.search (k, source[:1024]):
1447                                                 default_ly_options[LINEWIDTH] = v
1448                                                 break
1449
1450                 if filter_cmd:
1451                         write_if_updated (output_filename,
1452                                           [c.filter_text () for c in chunks])
1453                 elif process_cmd:
1454                         do_process_cmd (chunks, input_fullname)
1455                         ly.progress (_ ("Compiling %s...") % output_filename)
1456                         ly.progress ('\n')
1457                         write_if_updated (output_filename,
1458                                           [s.replacement_text ()
1459                                            for s in chunks])
1460                 
1461                 def process_include (snippet):
1462                         os.chdir (original_dir)
1463                         name = snippet.substring ('filename')
1464                         ly.progress (_ ("Processing include: %s") % name)
1465                         ly.progress ('\n')
1466                         return do_file (name)
1467
1468                 include_chunks = map (process_include,
1469                                       filter (lambda x: is_derived_class (x.__class__,
1470                                                                           Include_snippet),
1471                                               chunks))
1472
1473
1474                 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1475                 
1476         except Compile_error:
1477                 os.chdir (original_dir)
1478                 ly.progress (_ ("Removing `%s'") % output_filename)
1479                 ly.progress ('\n')
1480                 raise Compile_error
1481
1482 def do_options ():
1483         global format, output_name, psfonts_file
1484         global filter_cmd, process_cmd, verbose_p
1485
1486         (sh, long) = ly.getopt_args (option_definitions)
1487         try:
1488                 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1489         except getopt.error, s:
1490                 sys.stderr.write ('\n')
1491                 ly.error (_ ("getopt says: `%s'" % s))
1492                 sys.stderr.write ('\n')
1493                 ly.help ()
1494                 ly.exit (2)
1495
1496         for opt in options:
1497                 o = opt[0]
1498                 a = opt[1]
1499
1500                 if 0:
1501                         pass
1502                 elif o == '--filter' or o == '-F':
1503                         filter_cmd = a
1504                         process_cmd = 0
1505                 elif o == '--format' or o == '-f':
1506                         format = a
1507                         if a == 'texi-html' or a == 'texi':
1508                                 format = TEXINFO
1509                 elif o == '--tex-backend ':
1510                         backend = 'tex'
1511                 elif o == '--help' or o == '-h':
1512                         ly.help ()
1513                         sys.exit (0)
1514                 elif o == '--include' or o == '-I':
1515                         include_path.append (os.path.join (original_dir,
1516                                                            ly.abspath (a)))
1517                 elif o == '--output' or o == '-o':
1518                         output_name = a
1519                 elif o == '--process' or o == '-P':
1520                         process_cmd = a
1521                         filter_cmd = 0
1522                 elif o == '--version' or o == '-v':
1523                         ly.identify (sys.stdout)
1524                         sys.exit (0)
1525                 elif o == '--verbose' or o == '-V':
1526                         verbose_p = 1
1527                 elif o == '--psfonts':
1528                         psfonts_file = a
1529                 elif o == '--warranty' or o == '-w':
1530                         if 1 or status:
1531                                 ly.warranty ()
1532                         sys.exit (0)
1533         return files
1534
1535 def main ():
1536         files = do_options ()
1537         if not files or len (files) > 1:
1538                 ly.help ()
1539                 ly.exit (2)
1540
1541         file = files[0]
1542         global process_cmd, format
1543         if not format:
1544                 format = guess_format (files[0])
1545
1546         formats = 'ps'
1547         if format == TEXINFO or format == HTML:
1548                 formats += ',png'
1549         if process_cmd == '':
1550                 process_cmd = lilypond_binary \
1551                               + ' --formats=%s --backend eps ' % formats
1552
1553         if process_cmd:
1554                 process_cmd += string.join ([(' -I %s' % p)
1555                                              for p in include_path])
1556
1557         ly.identify (sys.stderr)
1558         ly.setup_environment ()
1559
1560         try:
1561                 chunks = do_file (file)
1562                 if psfonts_file:
1563                         fontextract.verbose = verbose_p
1564                         snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1565                                                                               Lilypond_snippet),
1566                                                  chunks)
1567                         if not verbose_p:
1568                                 ly.progress (_ ("Writing fonts to %s...") % psfonts_file)
1569                         fontextract.extract_fonts (psfonts_file,
1570                                                    [x.basename() + '.eps'
1571                                                     for x in snippet_chunks])
1572                         if not verbose_p:
1573                                 ly.progress ('\n')
1574                         
1575         except Compile_error:
1576                 ly.exit (1)
1577
1578         if format == TEXINFO or format == LATEX:
1579                 psfonts = os.path.join (output_name, psfonts_file)
1580                 output = os.path.join (output_name,
1581                                        os.path.splitext (os.path.basename
1582                                                          (file))[0]) + '.dvi'
1583                 if not psfonts:
1584                         ly.warning (_ ("option --psfonts=FILE not used"))
1585                         ly.warning (_ ("processing with dvips will have no fonts"))
1586                         psfonts = 'PSFONTS-FILE'
1587                 ly.progress ('\n')
1588                 ly.progress (_ ("DVIPS usage:"))
1589                 ly.progress ('\n')
1590                 ly.progress ("    dvips -h %(psfonts)s %(output)s" % vars ())
1591                 ly.progress ('\n')
1592
1593 if __name__ == '__main__':
1594         main ()