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