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