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