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