]> git.donarmstrong.com Git - lilypond.git/blob - scripts/lilypond-book.py
7667d4c30231849f9e267c6dae6d4dd0f4c520d6
[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     *  --line-width?
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 LINE_WIDTH = 'line-width'
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 RAGGED_RIGHT = 'ragged-right'
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                 LINE_WIDTH: r'''line-width = %(line-width)s''',
419
420                 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
421
422                 RAGGED_RIGHT: r'''ragged-right = ##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 = '''%%%% 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
558   (lambda (p m)
559    (if (not (eq? (ly:music-property m \'void) #t))
560         (print-score-with-defaults
561          p (scorify-music m p)))))
562
563 #(ly:set-option (quote no-point-and-click))
564 #(define inside-lilypond-book #t)
565 #(define version-seen? #t)
566 %(preamble_string)s
567
568
569
570
571
572
573 %% ****************************************************************
574 %% Start cut-&-pastable-section 
575 %% ****************************************************************
576
577 \paper {
578   #(define dump-extents #t)
579   %(font_dump_setting)s
580   %(paper_string)s
581 }
582
583 \layout {
584   %(layout_string)s
585 }
586 '''
587
588 FRAGMENT_LY = r'''
589 %(notes_string)s
590 {
591
592
593 %% ****************************************************************
594 %% ly snippet contents follows:
595 %% ****************************************************************
596 %(code)s
597
598
599 %% ****************************************************************
600 %% end ly snippet
601 %% ****************************************************************
602 }
603 '''
604
605 FULL_LY = '''
606
607
608 %% ****************************************************************
609 %% ly snippet:
610 %% ****************************************************************
611 %(code)s
612
613
614 %% ****************************************************************
615 %% end ly snippet
616 %% ****************************************************************
617 '''
618
619 texinfo_line_widths = {
620         '@afourpaper': '160\\mm',
621         '@afourwide': '6.5\\in',
622         '@afourlatex': '150\\mm',
623         '@smallbook': '5\\in',
624         '@letterpaper': '6\\in',
625 }
626
627 def classic_lilypond_book_compatibility (key, value):
628         if key == 'singleline' and value == None:
629                 return (RAGGED_RIGHT, None)
630
631         m = re.search ('relative\s*([-0-9])', key)
632         if m:
633                 return ('relative', m.group (1))
634
635         m = re.match ('([0-9]+)pt', key)
636         if m:
637                 return ('staffsize', m.group (1))
638
639         if key == 'indent' or key == 'line-width':
640                 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
641                 if m:
642                         f = float (m.group (1))
643                         return (key, '%f\\%s' % (f, m.group (2)))
644
645         return (None, None)
646
647 def find_file (name):
648         for i in include_path:
649                 full = os.path.join (i, name)
650                 if os.path.exists (full):
651                         return full
652         ly.error (_ ("file not found: %s") % name + '\n')
653         ly.exit (1)
654         return ''
655
656 def verbatim_html (s):
657         return re.sub ('>', '&gt;',
658                        re.sub ('<', '&lt;',
659                                re.sub ('&', '&amp;', s)))
660
661 def verbatim_texinfo (s):
662         return re.sub ('{', '@{',
663                        re.sub ('}', '@}',
664                                re.sub ('@', '@@', s)))
665
666 def split_options (option_string):
667         if option_string:
668                 if format == HTML:
669                         options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
670                         for i in range(len(options)):
671                                 options[i] = re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
672                         return options
673                 else:
674                         return re.split (format_res[format]['option_sep'],
675                                          option_string)
676         return []
677
678 def set_default_options (source):
679         global default_ly_options
680         if not default_ly_options.has_key (LINE_WIDTH):
681                 if format == LATEX:
682                         textwidth = get_latex_textwidth (source)
683                         default_ly_options[LINE_WIDTH] = \
684                           '''%.0f\\pt''' % textwidth
685                 elif format == TEXINFO:
686                         for (k, v) in texinfo_line_widths.items ():
687                                 # FIXME: @layout is usually not in
688                                 # chunk #0:
689                                 #
690                                 #  \input texinfo @c -*-texinfo-*-
691                                 #
692                                 # Bluntly search first K items of
693                                 # source.
694                                 # s = chunks[0].replacement_text ()
695                                 if re.search (k, source[:1024]):
696                                         default_ly_options[LINE_WIDTH] = v
697                                         break
698
699 class Chunk:
700         def replacement_text (self):
701                 return ''
702
703         def filter_text (self):
704                 return self.replacement_text ()
705
706         def ly_is_outdated (self):
707                 return 0
708
709         def png_is_outdated (self):
710                 return 0
711
712         def is_plain (self):
713                 return False
714         
715 class Substring (Chunk):
716         def __init__ (self, source, start, end, line_number):
717                 self.source = source
718                 self.start = start
719                 self.end = end
720                 self.line_number = line_number
721                 self.override_text = None
722                 
723         def is_plain (self):
724                 return True
725
726         def replacement_text (self):
727                 if self.override_text:
728                         return self.override_text
729                 else:
730                         return self.source[self.start:self.end]
731
732 class Snippet (Chunk):
733         def __init__ (self, type, match, format, line_number):
734                 self.type = type
735                 self.match = match
736                 self.hash = 0
737                 self.option_dict = {}
738                 self.format = format
739                 self.line_number = line_number
740
741         def replacement_text (self):
742                 return self.match.group ('match')
743
744         def substring (self, s):
745                 return self.match.group (s)
746
747         def __repr__ (self):
748                 return `self.__class__` + ' type = ' + self.type
749
750 class Include_snippet (Snippet):
751         def processed_filename (self):
752                 f = self.substring ('filename')
753                 return os.path.splitext (f)[0] + format2ext[format]
754
755         def replacement_text (self):
756                 s = self.match.group ('match')
757                 f = self.substring ('filename')
758
759                 return re.sub (f, self.processed_filename (), s)
760
761 class Lilypond_snippet (Snippet):
762         def __init__ (self, type, match, format, line_number):
763                 Snippet.__init__ (self, type, match, format, line_number)
764                 os = match.group ('options')
765                 self.do_options (os, self.type)
766
767         def ly (self):
768                 return self.substring ('code')
769
770         def full_ly (self):
771                 s = self.ly ()
772                 if s:
773                         return self.compose_ly (s)
774                 return ''
775
776         def do_options (self, option_string, type):
777                 self.option_dict = {}
778
779                 options = split_options (option_string)
780
781                 for i in options:
782                         if string.find (i, '=') > 0:
783                                 (key, value) = re.split ('\s*=\s*', i)
784                                 self.option_dict[key] = value
785                         else:
786                                 if i in no_options.keys ():
787                                         if no_options[i] in self.option_dict.keys ():
788                                                 del self.option_dict[no_options[i]]
789                                 else:
790                                         self.option_dict[i] = None
791
792                 has_line_width = self.option_dict.has_key (LINE_WIDTH)
793                 no_line_width_value = 0
794
795                 # If LINE_WIDTH is used without parameter, set it to default.
796                 if has_line_width and self.option_dict[LINE_WIDTH] == None:
797                         no_line_width_value = 1
798                         del self.option_dict[LINE_WIDTH]
799
800                 for i in default_ly_options.keys ():
801                         if i not in self.option_dict.keys ():
802                                 self.option_dict[i] = default_ly_options[i]
803
804                 if not has_line_width:
805                         if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
806                                 self.option_dict[RAGGED_RIGHT] = None
807
808                         if type == 'lilypond':
809                                 if LINE_WIDTH in self.option_dict.keys ():
810                                         del self.option_dict[LINE_WIDTH]
811                         else:
812                                 if RAGGED_RIGHT in self.option_dict.keys ():
813                                         if LINE_WIDTH in self.option_dict.keys ():
814                                                 del self.option_dict[LINE_WIDTH]
815
816                         if QUOTE in self.option_dict.keys () or type == 'lilypond':
817                                 if LINE_WIDTH in self.option_dict.keys ():
818                                         del self.option_dict[LINE_WIDTH]
819
820                 if not INDENT in self.option_dict.keys ():
821                         self.option_dict[INDENT] = '0\\mm'
822
823                 # The QUOTE pattern from ly_options only emits the `line-width'
824                 # keyword.
825                 if has_line_width and QUOTE in self.option_dict.keys ():
826                         if no_line_width_value:
827                                 del self.option_dict[LINE_WIDTH]
828                         else:
829                                 del self.option_dict[QUOTE]
830
831         def compose_ly (self, code):
832                 if FRAGMENT in self.option_dict.keys ():
833                         body = FRAGMENT_LY
834                 else:
835                         body = FULL_LY
836
837                 # Defaults.
838                 relative = 1
839                 override = {}
840                 # The original concept of the `exampleindent' option is broken.
841                 # It is not possible to get a sane value for @exampleindent at all
842                 # without processing the document itself.  Saying
843                 #
844                 #   @exampleindent 0
845                 #   @example
846                 #   ...
847                 #   @end example
848                 #   @exampleindent 5
849                 #
850                 # causes ugly results with the DVI backend of texinfo since the
851                 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
852                 # value).  Executing the above code changes the environment
853                 # indentation to an unknown value because we don't know the amount
854                 # of 1em in advance since it is font-dependent.  Modifying
855                 # @exampleindent in the middle of a document is simply not
856                 # supported within texinfo.
857                 #
858                 # As a consequence, the only function of @exampleindent is now to
859                 # specify the amount of indentation for the `quote' option.
860                 #
861                 # To set @exampleindent locally to zero, we use the @format
862                 # environment for non-quoted snippets.
863                 override[EXAMPLEINDENT] = r'0.4\in'
864                 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
865                 override.update (default_ly_options)
866
867                 option_list = []
868                 for (key, value) in self.option_dict.items ():
869                         if value == None:
870                                 option_list.append (key)
871                         else:
872                                 option_list.append (key + '=' + value)
873                 option_string = string.join (option_list, ',')
874
875                 compose_dict = {}
876                 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
877                 for a in compose_types:
878                         compose_dict[a] = []
879
880                 for (key, value) in self.option_dict.items ():
881                         (c_key, c_value) = \
882                           classic_lilypond_book_compatibility (key, value)
883                         if c_key:
884                                 if c_value:
885                                         ly.warning \
886                                           (_ ("deprecated ly-option used: %s=%s" \
887                                             % (key, value)))
888                                         ly.warning \
889                                           (_ ("compatibility mode translation: %s=%s" \
890                                             % (c_key, c_value)))
891                                 else:
892                                         ly.warning \
893                                           (_ ("deprecated ly-option used: %s" \
894                                             % key))
895                                         ly.warning \
896                                           (_ ("compatibility mode translation: %s" \
897                                             % c_key))
898
899                                 (key, value) = (c_key, c_value)
900
901                         if value:
902                                 override[key] = value
903                         else:
904                                 if not override.has_key (key):
905                                         override[key] = None
906
907                         found = 0
908                         for type in compose_types:
909                                 if ly_options[type].has_key (key):
910                                         compose_dict[type].append (ly_options[type][key])
911                                         found = 1
912                                         break
913
914                         if not found and key not in simple_options:
915                                 ly.warning (_ ("ignoring unknown ly option: %s") % key)
916
917                 # URGS
918                 if RELATIVE in override.keys () and override[RELATIVE]:
919                         relative = string.atoi (override[RELATIVE])
920
921                 relative_quotes = ''
922
923                 # 1 = central C
924                 if relative < 0:
925                         relative_quotes += ',' * (- relative)
926                 elif relative > 0:
927                         relative_quotes += "'" * relative
928
929                 program_name = __main__.program_name
930
931                 paper_string = string.join (compose_dict[PAPER],
932                                             '\n  ') % override
933                 layout_string = string.join (compose_dict[LAYOUT],
934                                              '\n  ') % override
935                 notes_string = string.join (compose_dict[NOTES],
936                                             '\n  ') % vars ()
937                 preamble_string = string.join (compose_dict[PREAMBLE],
938                                                '\n  ') % override
939
940                 font_dump_setting = ''
941                 if FONTLOAD in self.option_dict:
942                         font_dump_setting = '#(define-public force-eps-font-include #t)\n'
943
944                 return (PREAMBLE_LY + body) % vars ()
945
946         # TODO: Use md5?
947         def get_hash (self):
948                 if not self.hash:
949                         self.hash = abs (hash (self.full_ly ()))
950                 return self.hash
951
952         def basename (self):
953                 if FILENAME in self.option_dict:
954                         return self.option_dict[FILENAME]
955                 if use_hash_p:
956                         return 'lily-%d' % self.get_hash ()
957                 raise 'to be done'
958
959         def write_ly (self):
960                 outf = open (self.basename () + '.ly', 'w')
961                 outf.write (self.full_ly ())
962
963                 open (self.basename () + '.txt', 'w').write ('image of music')
964
965         def ly_is_outdated (self):
966                 base = self.basename ()
967
968                 tex_file = '%s.tex' % base
969                 eps_file = '%s.eps' % base
970                 system_file = '%s-systems.tex' % base
971                 ly_file = '%s.ly' % base
972                 ok = os.path.exists (ly_file) \
973                      and os.path.exists (system_file)\
974                      and os.stat (system_file)[stat.ST_SIZE] \
975                      and re.match ('% eof', open (system_file).readlines ()[-1])
976                 if ok and (not use_hash_p or FILENAME in self.option_dict):
977                         ok = (self.full_ly () == open (ly_file).read ())
978                 if ok:
979                         # TODO: Do something smart with target formats
980                         #       (ps, png) and m/ctimes.
981                         return None
982                 return self
983
984         def png_is_outdated (self):
985                 base = self.basename ()
986                 ok = self.ly_is_outdated ()
987                 if format == HTML or format == TEXINFO:
988                         ok = ok and os.path.exists (base + '.eps')
989
990                         page_count = 0
991                         if ok:
992                                 page_count = ly.ps_page_count (base + '.eps')
993                         
994                         if page_count == 1:
995                                 ok = ok and os.path.exists (base + '.png')
996                         elif page_count > 1:
997                                 for a in range (1, page_count + 1):
998                                                 ok = ok and os.path.exists (base + '-page%d.png' % a)
999                                 
1000                 return not ok
1001         
1002         def texstr_is_outdated (self):
1003                 if backend == 'ps':
1004                         return 0
1005
1006                 base = self.basename ()
1007                 ok = self.ly_is_outdated ()
1008                 ok = ok and (os.path.exists (base + '.texstr'))
1009                 return not ok
1010
1011         def filter_text (self):
1012                 code = self.substring ('code')
1013                 s = run_filter (code)
1014                 d = {
1015                         'code': s,
1016                         'options': self.match.group ('options')
1017                 }
1018                 # TODO
1019                 return output[self.format][FILTER] % d
1020
1021         def replacement_text (self):
1022                 func = Lilypond_snippet.__dict__['output_' + self.format]
1023                 return func (self)
1024
1025         def get_images (self):
1026                 base = self.basename ()
1027                 # URGUGHUGHUGUGH
1028                 single = '%(base)s.png' % vars ()
1029                 multiple = '%(base)s-page1.png' % vars ()
1030                 images = (single,)
1031                 if os.path.exists (multiple) \
1032                    and (not os.path.exists (single) \
1033                         or (os.stat (multiple)[stat.ST_MTIME] \
1034                             > os.stat (single)[stat.ST_MTIME])):
1035                         count = ly.ps_page_count ('%(base)s.eps' % vars ())
1036                         images = ['%s-page%d.png' % (base, a) for a in range (1, count+1)]
1037                         images = tuple (images)
1038                 return images
1039
1040         def output_html (self):
1041                 str = ''
1042                 base = self.basename ()
1043                 if format == HTML:
1044                         str += self.output_print_filename (HTML)
1045                         if VERBATIM in self.option_dict:
1046                                 verb = verbatim_html (self.substring ('code'))
1047                                 str += write (output[HTML][VERBATIM] % vars ())
1048                         if QUOTE in self.option_dict:
1049                                 str = output[HTML][QUOTE] % vars ()
1050
1051                 str += output[HTML][BEFORE] % vars ()
1052                 for image in self.get_images ():
1053                         (base, ext) = os.path.splitext (image)
1054                         alt = self.option_dict[ALT]
1055                         str += output[HTML][OUTPUT] % vars ()
1056                 str += output[HTML][AFTER] % vars ()
1057                 return str
1058
1059         def output_info (self):
1060                 str = ''
1061                 for image in self.get_images ():
1062                         (base, ext) = os.path.splitext (image)
1063
1064                         # URG, makeinfo implicitly prepends dot to extension.
1065                         # Specifying no extension is most robust.
1066                         ext = ''
1067                         alt = self.option_dict[ALT]
1068                         str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1069
1070                 base = self.basename ()
1071                 str += output[format][OUTPUT] % vars ()
1072                 return str
1073
1074         def output_latex (self):
1075                 str = ''
1076                 base = self.basename ()
1077                 if format == LATEX:
1078                         str += self.output_print_filename (LATEX)
1079                         if VERBATIM in self.option_dict:
1080                                 verb = self.substring ('code')
1081                                 str += (output[LATEX][VERBATIM] % vars ())
1082                         elif srcltx_p:
1083                                 breaks = self.ly ().count ("\n")
1084                                 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1085                 str += (output[LATEX][OUTPUT] % vars ())
1086                 if QUOTE in self.option_dict:
1087                         str = output[LATEX][QUOTE] % vars ()
1088                 return str
1089
1090         def output_print_filename (self, format):
1091                 str = ''
1092                 if PRINTFILENAME in self.option_dict:
1093                         base = self.basename ()
1094                         filename = self.substring ('filename')
1095                         str = output[format][PRINTFILENAME] % vars ()
1096
1097                 return str
1098
1099         def output_texinfo (self):
1100                 str = ''
1101                 if self.output_print_filename (TEXINFO):
1102                         str += ('@html\n'
1103                                 + self.output_print_filename (HTML)
1104                                 + '\n@end html\n')
1105                         str += ('@tex\n'
1106                                 + self.output_print_filename (LATEX)
1107                                 + '\n@end tex\n')
1108                 base = self.basename ()
1109                 if TEXIDOC in self.option_dict:
1110                         texidoc = base + '.texidoc'
1111                         if os.path.exists (texidoc):
1112                                 str += '@include %(texidoc)s\n\n' % vars ()
1113
1114                 if VERBATIM in self.option_dict:
1115                         verb = verbatim_texinfo (self.substring ('code'))
1116                         str += (output[TEXINFO][VERBATIM] % vars ())
1117                         if not QUOTE in self.option_dict:
1118                                 str = output[TEXINFO][NOQUOTE] % vars ()
1119
1120                 str += self.output_info ()
1121
1122 #               str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1123 #               str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1124 #               str += ('@html\n' + self.output_html () + '\n@end html\n')
1125
1126                 if QUOTE in self.option_dict:
1127                         str = output[TEXINFO][QUOTE] % vars ()
1128
1129                 # need par after image
1130                 str += '\n'
1131
1132                 return str
1133
1134 class Lilypond_file_snippet (Lilypond_snippet):
1135         def ly (self):
1136                 name = self.substring ('filename')
1137                 return '\\sourcefilename \"%s\"\n%s' \
1138                          % (name, open (find_file (name)).read ())
1139
1140 snippet_type_to_class = {
1141         'lilypond_file': Lilypond_file_snippet,
1142         'lilypond_block': Lilypond_snippet,
1143         'lilypond': Lilypond_snippet,
1144         'include': Include_snippet,
1145 }
1146
1147 def find_linestarts (s):
1148         nls = [0]
1149         start = 0
1150         end = len (s)
1151         while 1:
1152                 i = s.find ('\n', start)
1153                 if i < 0:
1154                         break
1155
1156                 i = i + 1
1157                 nls.append (i)
1158                 start = i
1159
1160         nls.append (len (s))
1161         return nls
1162
1163 def find_toplevel_snippets (s, types):
1164         res = {}
1165         for i in types:
1166                 res[i] = ly.re.compile (snippet_res[format][i])
1167
1168         snippets = []
1169         index = 0
1170         ## found = dict (map (lambda x: (x, None),
1171         ##                    types))
1172         ## urg python2.1
1173         found = {}
1174         map (lambda x, f = found: f.setdefault (x, None),
1175              types)
1176
1177         line_starts = find_linestarts (s)
1178         line_start_idx = 0
1179         # We want to search for multiple regexes, without searching
1180         # the string multiple times for one regex.
1181         # Hence, we use earlier results to limit the string portion
1182         # where we search.
1183         # Since every part of the string is traversed at most once for
1184         # every type of snippet, this is linear.
1185
1186         while 1:
1187                 first = None
1188                 endex = 1 << 30
1189                 for type in types:
1190                         if not found[type] or found[type][0] < index:
1191                                 found[type] = None
1192                                 m = res[type].search (s[index:endex])
1193                                 if not m:
1194                                         continue
1195
1196                                 cl = Snippet
1197                                 if snippet_type_to_class.has_key (type):
1198                                         cl = snippet_type_to_class[type]
1199
1200
1201                                 start = index + m.start ('match')
1202                                 line_number = line_start_idx
1203                                 while (line_starts[line_number] < start):
1204                                         line_number += 1
1205
1206                                 line_number += 1
1207                                 snip = cl (type, m, format, line_number)
1208                                 found[type] = (start, snip)
1209
1210                         if found[type] \
1211                            and (not first \
1212                                 or found[type][0] < found[first][0]):
1213                                 first = type
1214
1215                                 # FIXME.
1216
1217                                 # Limiting the search space is a cute
1218                                 # idea, but this *requires* to search
1219                                 # for possible containing blocks
1220                                 # first, at least as long as we do not
1221                                 # search for the start of blocks, but
1222                                 # always/directly for the entire
1223                                 # @block ... @end block.
1224
1225                                 endex = found[first][0]
1226
1227                 if not first:
1228                         snippets.append (Substring (s, index, len (s), line_start_idx))
1229                         break
1230
1231                 while (start > line_starts[line_start_idx+1]):
1232                         line_start_idx += 1
1233
1234                 (start, snip) = found[first]
1235                 snippets.append (Substring (s, index, start, line_start_idx + 1))
1236                 snippets.append (snip)
1237                 found[first] = None
1238                 index = start + len (snip.match.group ('match'))
1239
1240         return snippets
1241
1242 def filter_pipe (input, cmd):
1243         if verbose_p:
1244                 ly.progress (_ ("Opening filter `%s'") % cmd)
1245
1246         (stdin, stdout, stderr) = os.popen3 (cmd)
1247         stdin.write (input)
1248         status = stdin.close ()
1249
1250         if not status:
1251                 status = 0
1252                 output = stdout.read ()
1253                 status = stdout.close ()
1254                 error = stderr.read ()
1255
1256         if not status:
1257                 status = 0
1258         signal = 0x0f & status
1259         if status or (not output and error):
1260                 exit_status = status >> 8
1261                 ly.error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1262                 ly.error (_ ("The error log is as follows:"))
1263                 sys.stderr.write (error)
1264                 sys.stderr.write (stderr.read ())
1265                 ly.exit (status)
1266
1267         if verbose_p:
1268                 ly.progress ('\n')
1269
1270         return output
1271
1272 def run_filter (s):
1273         return filter_pipe (s, filter_cmd)
1274
1275 def is_derived_class (cl, baseclass):
1276         if cl == baseclass:
1277                 return 1
1278         for b in cl.__bases__:
1279                 if is_derived_class (b, baseclass):
1280                         return 1
1281         return 0
1282
1283 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1284         ly_names = filter (lambda x: x,
1285                            map (Lilypond_snippet.basename, ly_snippets))
1286         texstr_names = filter (lambda x: x,
1287                            map (Lilypond_snippet.basename, texstr_snippets))
1288         png_names = filter (lambda x: x,
1289                             map (Lilypond_snippet.basename, png_snippets))
1290
1291         status = 0
1292         def my_system (cmd):
1293                 status = ly.system (cmd,
1294                                     ignore_error = 1, progress_p = 1)
1295
1296                 if status:
1297                         ly.error ('Process %s exited unsuccessfully.' % cmd)
1298                         raise Compile_error
1299
1300         # UGH
1301         # the --process=CMD switch is a bad idea
1302         # it is too generic for lilypond-book.
1303         if texstr_names:
1304                 my_system (string.join ([cmd, '--backend texstr',
1305                                          'snippet-map.ly'] + texstr_names))
1306                 for l in texstr_names:
1307                         my_system ('latex %s.texstr' % l)
1308
1309         if ly_names:
1310                 my_system (string.join ([cmd, 'snippet-map.ly'] + ly_names))
1311
1312 LATEX_INSPECTION_DOCUMENT = r'''
1313 \nonstopmode
1314 %(preamble)s
1315 \begin{document}
1316 \typeout{textwidth=\the\textwidth}
1317 \typeout{columnsep=\the\columnsep}
1318 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1319 \end{document}
1320 '''
1321
1322 # Do we need anything else besides `textwidth'?
1323 def get_latex_textwidth (source):
1324         m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1325         preamble = source[:m.start (0)]
1326         latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1327         # Workaround problems with unusable $TMP on Cygwin:
1328         tempfile.tempdir = ''
1329         tmpfile = tempfile.mktemp('.tex')
1330         logfile = os.path.splitext (tmpfile)[0] + '.log'
1331         open (tmpfile,'w').write (latex_document)
1332         ly.system ('latex %s' % tmpfile)
1333         parameter_string = open (logfile).read()
1334         os.unlink (tmpfile)
1335         os.unlink (logfile)
1336
1337         columns = 0
1338         m = re.search ('columns=([0-9.]*)', parameter_string)
1339         if m:
1340                 columns = string.atoi (m.group (1))
1341
1342         columnsep = 0
1343         m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1344         if m:
1345                 columnsep = string.atof (m.group (1))
1346
1347         textwidth = 0
1348         m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1349         if m:
1350                 textwidth = string.atof (m.group (1))
1351                 if columns:
1352                         textwidth = (textwidth - columnsep) / columns
1353
1354         return textwidth
1355
1356 def modify_preamble (chunk):
1357         str = chunk.replacement_text ()
1358         if (re.search (r"\\begin *{document}", str)
1359             and not re.search ("{graphic[sx]", str)):
1360                 str = re.sub (r"\\begin{document}",
1361                               r"\\usepackage{graphics}" + '\n'
1362                               + r"\\begin{document}",
1363                               str)
1364                 chunk.override_text = str 
1365                 
1366         
1367
1368 ext2format = {
1369         '.html': HTML,
1370         '.itely': TEXINFO,
1371         '.latex': LATEX,
1372         '.lytex': LATEX,
1373         '.tely': TEXINFO,
1374         '.tex': LATEX,
1375         '.texi': TEXINFO,
1376         '.texinfo': TEXINFO,
1377         '.xml': HTML,
1378 }
1379
1380 format2ext = {
1381         HTML: '.html',
1382         # TEXINFO: '.texinfo',
1383         TEXINFO: '.texi',
1384         LATEX: '.tex',
1385 }
1386
1387 class Compile_error:
1388         pass
1389
1390 def write_file_map (lys, name):
1391         snippet_map = open ('snippet-map.ly', 'w')
1392         snippet_map.write ("""
1393 #(define version-seen? #t)
1394 #(ly:add-file-name-alist '(
1395 """)
1396         for ly in lys:
1397                 snippet_map.write ('("%s.ly" . "%s:%d (%s.ly)")\n'
1398                                    % (ly.basename (),
1399                                       name,
1400                                       ly.line_number,
1401                                       ly.basename ()))
1402
1403         snippet_map.write ('))\n')
1404
1405 def do_process_cmd (chunks, input_name):
1406         all_lys = filter (lambda x: is_derived_class (x.__class__,
1407                                                       Lilypond_snippet),
1408                           chunks)
1409
1410         write_file_map (all_lys, input_name)
1411         ly_outdated = \
1412           filter (lambda x: is_derived_class (x.__class__,
1413                                               Lilypond_snippet)
1414                             and x.ly_is_outdated (),
1415                   chunks)
1416         texstr_outdated = \
1417           filter (lambda x: is_derived_class (x.__class__,
1418                                               Lilypond_snippet)
1419                             and x.texstr_is_outdated (),
1420                   chunks)
1421         png_outdated = \
1422           filter (lambda x: is_derived_class (x.__class__,
1423                                               Lilypond_snippet)
1424                             and x.png_is_outdated (),
1425                   chunks)
1426
1427         ly.progress (_ ("Writing snippets..."))
1428         map (Lilypond_snippet.write_ly, ly_outdated)
1429         ly.progress ('\n')
1430
1431         if ly_outdated:
1432                 ly.progress (_ ("Processing..."))
1433                 ly.progress ('\n')
1434                 process_snippets (process_cmd, ly_outdated, texstr_outdated, png_outdated)
1435         else:
1436                 ly.progress (_ ("All snippets are up to date..."))
1437         ly.progress ('\n')
1438
1439 def guess_format (input_filename):
1440         format = None
1441         e = os.path.splitext (input_filename)[1]
1442         if e in ext2format.keys ():
1443                 # FIXME
1444                 format = ext2format[e]
1445         else:
1446                 ly.error (_ ("can't determine format for: %s" \
1447                              % input_filename))
1448                 ly.exit (1)
1449         return format
1450
1451 def write_if_updated (file_name, lines):
1452         try:
1453                 f = open (file_name)
1454                 oldstr = f.read ()
1455                 new_str = string.join (lines, '')
1456                 if oldstr == new_str:
1457                         ly.progress (_ ("%s is up to date.") % file_name)
1458                         ly.progress ('\n')
1459                         return
1460         except:
1461                 pass
1462
1463         ly.progress (_ ("Writing `%s'...") % file_name)
1464         open (file_name, 'w').writelines (lines)
1465         ly.progress ('\n')
1466
1467 def note_input_file (name, inputs=[]):
1468         inputs.append (name)
1469         return inputs
1470
1471 def do_file (input_filename):
1472         # Ugh.
1473         if not input_filename or input_filename == '-':
1474                 in_handle = sys.stdin
1475                 input_fullname = '<stdin>'
1476         else:
1477                 if os.path.exists (input_filename):
1478                         input_fullname = input_filename
1479                 elif format == LATEX and ly.search_exe_path ('kpsewhich'): 
1480                         # urg python interface to libkpathsea?
1481                         input_fullname = ly.read_pipe ('kpsewhich '
1482                                                        + input_filename)[:-1]
1483                 else:
1484                         input_fullname = find_file (input_filename)
1485
1486                 note_input_file (input_fullname)
1487                 in_handle = open (input_fullname)
1488
1489         if input_filename == '-':
1490                 input_base = 'stdin'
1491         else:
1492                 input_base = os.path.basename \
1493                              (os.path.splitext (input_filename)[0])
1494
1495         # Only default to stdout when filtering.
1496         if output_name == '-' or (not output_name and filter_cmd):
1497                 output_filename = '-'
1498                 output_file = sys.stdout
1499         else:
1500                 # don't complain when output_name is existing
1501                 output_filename = input_base + format2ext[format]
1502                 if output_name:
1503                         if not os.path.isdir (output_name):
1504                                 os.mkdir (output_name, 0777)
1505                         os.chdir (output_name)
1506                 else: 
1507                         if os.path.exists (input_filename) \
1508                            and os.path.exists (output_filename) \
1509                            and os.path.samefile (output_filename, input_fullname):
1510                            ly.error (
1511                            _ ("Output would overwrite input file; use --output."))
1512                            ly.exit (2)
1513
1514         try:
1515                 ly.progress (_ ("Reading %s...") % input_fullname)
1516                 source = in_handle.read ()
1517                 ly.progress ('\n')
1518
1519                 set_default_options (source)
1520
1521
1522                 # FIXME: Containing blocks must be first, see
1523                 #        find_toplevel_snippets.
1524                 snippet_types = (
1525                         'multiline_comment',
1526                         'verbatim',
1527                         'lilypond_block',
1528         #               'verb',
1529                         'singleline_comment',
1530                         'lilypond_file',
1531                         'include',
1532                         'lilypond',
1533                 )
1534                 ly.progress (_ ("Dissecting..."))
1535                 chunks = find_toplevel_snippets (source, snippet_types)
1536
1537                 if format == LATEX:
1538                         for c in chunks:
1539                                 if (c.is_plain () and
1540                                     re.search (r"\\begin *{document}", c.replacement_text())):
1541                                         modify_preamble (c)
1542                                         break
1543                 ly.progress ('\n')
1544
1545                 if filter_cmd:
1546                         write_if_updated (output_filename,
1547                                           [c.filter_text () for c in chunks])
1548                 elif process_cmd:
1549                         do_process_cmd (chunks, input_fullname)
1550                         ly.progress (_ ("Compiling %s...") % output_filename)
1551                         ly.progress ('\n')
1552                         write_if_updated (output_filename,
1553                                           [s.replacement_text ()
1554                                            for s in chunks])
1555                 
1556                 def process_include (snippet):
1557                         os.chdir (original_dir)
1558                         name = snippet.substring ('filename')
1559                         ly.progress (_ ("Processing include: %s") % name)
1560                         ly.progress ('\n')
1561                         return do_file (name)
1562
1563                 include_chunks = map (process_include,
1564                                       filter (lambda x: is_derived_class (x.__class__,
1565                                                                           Include_snippet),
1566                                               chunks))
1567
1568
1569                 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1570                 
1571         except Compile_error:
1572                 os.chdir (original_dir)
1573                 ly.progress (_ ("Removing `%s'") % output_filename)
1574                 ly.progress ('\n')
1575                 raise Compile_error
1576
1577 def do_options ():
1578         global format, output_name, psfonts_p, srcltx_p
1579         global filter_cmd, process_cmd, verbose_p
1580
1581         (sh, long) = ly.getopt_args (option_definitions)
1582         try:
1583                 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1584         except getopt.error, s:
1585                 sys.stderr.write ('\n')
1586                 ly.error (_ ("getopt says: `%s'" % s))
1587                 sys.stderr.write ('\n')
1588                 ly.help ()
1589                 ly.exit (2)
1590
1591         for opt in options:
1592                 o = opt[0]
1593                 a = opt[1]
1594
1595                 if 0:
1596                         pass
1597                 elif o == '--filter' or o == '-F':
1598                         filter_cmd = a
1599                         process_cmd = 0
1600                 elif o == '--format' or o == '-f':
1601                         format = a
1602                         if a == 'texi-html' or a == 'texi':
1603                                 format = TEXINFO
1604                 elif o == '--tex-backend ':
1605                         backend = 'tex'
1606                 elif o == '--help' or o == '-h':
1607                         ly.help ()
1608                         sys.exit (0)
1609                 elif o == '--include' or o == '-I':
1610                         include_path.append (os.path.join (original_dir,
1611                                                            os.path.abspath (a)))
1612                 elif o == '--output' or o == '-o':
1613                         output_name = a
1614                 elif o == '--process' or o == '-P':
1615                         process_cmd = a
1616                         filter_cmd = 0
1617                 elif o == '--version' or o == '-v':
1618                         ly.identify (sys.stdout)
1619                         sys.exit (0)
1620                 elif o == '--verbose' or o == '-V':
1621                         verbose_p = 1
1622                 elif o == '--psfonts':
1623                         psfonts_p = 1 
1624                 elif o == '--keep-line-breaks':
1625                         srcltx_p = 1 
1626                         for s in (OUTPUT, QUOTE, VERBATIM):
1627                                 output[LATEX][s] = output[LATEX][s].replace("\n"," ")
1628                 elif o == '--warranty' or o == '-w':
1629                         if 1 or status:
1630                                 ly.warranty ()
1631                         sys.exit (0)
1632         return files
1633
1634 def main ():
1635         files = do_options ()
1636         if not files or len (files) > 1:
1637                 ly.help ()
1638                 ly.exit (2)
1639
1640         file = files[0]
1641
1642         basename = os.path.splitext (file)[0]
1643         basename = os.path.split (basename)[1]
1644         
1645         global process_cmd, format
1646         if not format:
1647                 format = guess_format (files[0])
1648
1649         formats = 'ps'
1650         if format == TEXINFO or format == HTML:
1651                 formats += ',png'
1652         if process_cmd == '':
1653                 process_cmd = lilypond_binary \
1654                               + ' --formats=%s --backend eps ' % formats
1655
1656         if process_cmd:
1657                 process_cmd += string.join ([(' -I %s' % commands.mkarg (p))
1658                                              for p in include_path])
1659
1660         ly.identify (sys.stderr)
1661
1662         try:
1663                 chunks = do_file (file)
1664                 if psfonts_p:
1665                         fontextract.verbose = verbose_p
1666                         snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1667                                                                               Lilypond_snippet),
1668                                                  chunks)
1669
1670                         psfonts_file = basename + '.psfonts' 
1671                         if not verbose_p:
1672                                 ly.progress (_ ("Writing fonts to %s...") % psfonts_file)
1673                         fontextract.extract_fonts (psfonts_file,
1674                                                    [x.basename() + '.eps'
1675                                                     for x in snippet_chunks])
1676                         if not verbose_p:
1677                                 ly.progress ('\n')
1678                         
1679         except Compile_error:
1680                 ly.exit (1)
1681
1682         if format == TEXINFO or format == LATEX:
1683                 if not psfonts_p:
1684                         ly.warning (_ ("option --psfonts not used"))
1685                         ly.warning (_ ("processing with dvips will have no fonts"))
1686
1687                 psfonts_file = os.path.join (output_name, basename + '.psfonts')
1688                 output = os.path.join (output_name, basename +  '.dvi' )
1689                 
1690                 ly.progress ('\n')
1691                 ly.progress (_ ("DVIPS usage:"))
1692                 ly.progress ('\n')
1693                 ly.progress ("    dvips -h %(psfonts_file)s %(output)s" % vars ())
1694                 ly.progress ('\n')
1695
1696         inputs = note_input_file ('')
1697         inputs.pop ()
1698         dep_file = os.path.join (output_name, os.path.splitext (file)[0] + '.dep')
1699         final_output_file = os.path.join (output_name,
1700                                           os.path.splitext (os.path.basename (file))[0]
1701                                           + '.%s' % format)
1702         
1703         os.chdir (original_dir)
1704         open (dep_file, 'w').write ('%s: %s' % (final_output_file, ' '.join (inputs)))
1705
1706 if __name__ == '__main__':
1707         main ()