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