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