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