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