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