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