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