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