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