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