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