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