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