]> git.donarmstrong.com Git - lilypond.git/blob - scripts/lilypond-book.py
Turn off sourcefileline, fixes images.
[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 contents
891         # FIXME: translation foo
892         return ('\\sourcefileline %d\n%s'
893                 % (self.line_number - 1, contents))
894
895     def full_ly (self):
896         s = self.ly ()
897         if s:
898             return self.compose_ly (s)
899         return ''
900
901     def do_options (self, option_string, type):
902         self.option_dict = {}
903
904         options = split_options (option_string)
905
906         for i in options:
907             if '=' in i:
908                 (key, value) = re.split ('\s*=\s*', i)
909                 self.option_dict[key] = value
910             else:
911                 if i in no_options.keys ():
912                     if no_options[i] in self.option_dict.keys ():
913                         del self.option_dict[no_options[i]]
914                 else:
915                     self.option_dict[i] = None
916
917         has_line_width = self.option_dict.has_key (LINE_WIDTH)
918         no_line_width_value = 0
919
920         # If LINE_WIDTH is used without parameter, set it to default.
921         if has_line_width and self.option_dict[LINE_WIDTH] == None:
922             no_line_width_value = 1
923             del self.option_dict[LINE_WIDTH]
924
925         for i in default_ly_options.keys ():
926             if i not in self.option_dict.keys ():
927                 self.option_dict[i] = default_ly_options[i]
928
929         if not has_line_width:
930             if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
931                 self.option_dict[RAGGED_RIGHT] = None
932
933             if type == 'lilypond':
934                 if LINE_WIDTH in self.option_dict.keys ():
935                     del self.option_dict[LINE_WIDTH]
936             else:
937                 if RAGGED_RIGHT in self.option_dict.keys ():
938                     if LINE_WIDTH in self.option_dict.keys ():
939                         del self.option_dict[LINE_WIDTH]
940
941             if QUOTE in self.option_dict.keys () or type == 'lilypond':
942                 if LINE_WIDTH in self.option_dict.keys ():
943                     del self.option_dict[LINE_WIDTH]
944
945         if not INDENT in self.option_dict.keys ():
946             self.option_dict[INDENT] = '0\\mm'
947
948         # The QUOTE pattern from ly_options only emits the `line-width'
949         # keyword.
950         if has_line_width and QUOTE in self.option_dict.keys ():
951             if no_line_width_value:
952                 del self.option_dict[LINE_WIDTH]
953             else:
954                 del self.option_dict[QUOTE]
955
956     def compose_ly (self, code):
957         if FRAGMENT in self.option_dict.keys ():
958             body = FRAGMENT_LY
959         else:
960             body = FULL_LY
961
962         # Defaults.
963         relative = 1
964         override = {}
965         # The original concept of the `exampleindent' option is broken.
966         # It is not possible to get a sane value for @exampleindent at all
967         # without processing the document itself.  Saying
968         #
969         #   @exampleindent 0
970         #   @example
971         #   ...
972         #   @end example
973         #   @exampleindent 5
974         #
975         # causes ugly results with the DVI backend of texinfo since the
976         # default value for @exampleindent isn't 5em but 0.4in (or a smaller
977         # value).  Executing the above code changes the environment
978         # indentation to an unknown value because we don't know the amount
979         # of 1em in advance since it is font-dependent.  Modifying
980         # @exampleindent in the middle of a document is simply not
981         # supported within texinfo.
982         #
983         # As a consequence, the only function of @exampleindent is now to
984         # specify the amount of indentation for the `quote' option.
985         #
986         # To set @exampleindent locally to zero, we use the @format
987         # environment for non-quoted snippets.
988         override[EXAMPLEINDENT] = r'0.4\in'
989         override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
990         override.update (default_ly_options)
991
992         option_list = []
993         for (key, value) in self.option_dict.items ():
994             if value == None:
995                 option_list.append (key)
996             else:
997                 option_list.append (key + '=' + value)
998         option_string = string.join (option_list, ',')
999
1000         compose_dict = {}
1001         compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1002         for a in compose_types:
1003             compose_dict[a] = []
1004
1005         for (key, value) in self.option_dict.items ():
1006             (c_key, c_value) = \
1007              classic_lilypond_book_compatibility (key, value)
1008             if c_key:
1009                 if c_value:
1010                     warning \
1011                      (_ ("deprecated ly-option used: %s=%s" \
1012                       % (key, value)))
1013                     warning \
1014                      (_ ("compatibility mode translation: %s=%s" \
1015                       % (c_key, c_value)))
1016                 else:
1017                     warning \
1018                      (_ ("deprecated ly-option used: %s" \
1019                       % key))
1020                     warning \
1021                      (_ ("compatibility mode translation: %s" \
1022                       % c_key))
1023
1024                 (key, value) = (c_key, c_value)
1025
1026             if value:
1027                 override[key] = value
1028             else:
1029                 if not override.has_key (key):
1030                     override[key] = None
1031
1032             found = 0
1033             for type in compose_types:
1034                 if ly_options[type].has_key (key):
1035                     compose_dict[type].append (ly_options[type][key])
1036                     found = 1
1037                     break
1038
1039             if not found and key not in simple_options:
1040                 warning (_ ("ignoring unknown ly option: %s") % key)
1041
1042         # URGS
1043         if RELATIVE in override.keys () and override[RELATIVE]:
1044             relative = int (override[RELATIVE])
1045
1046         relative_quotes = ''
1047
1048         # 1 = central C
1049         if relative < 0:
1050             relative_quotes += ',' * (- relative)
1051         elif relative > 0:
1052             relative_quotes += "'" * relative
1053
1054         paper_string = string.join (compose_dict[PAPER],
1055                       '\n  ') % override
1056         layout_string = string.join (compose_dict[LAYOUT],
1057                       '\n  ') % override
1058         notes_string = string.join (compose_dict[NOTES],
1059                       '\n  ') % vars ()
1060         preamble_string = string.join (compose_dict[PREAMBLE],
1061                        '\n  ') % override
1062         
1063         font_dump_setting = ''
1064         if FONTLOAD in self.option_dict:
1065             font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1066
1067         d = globals().copy()
1068         d.update (locals())
1069         return (PREAMBLE_LY + body) % d
1070
1071     # TODO: Use md5?
1072     def get_hash (self):
1073         if not self.hash:
1074             self.hash = abs (hash (self.full_ly ()))
1075         return self.hash
1076
1077     def basename (self):
1078         if FILENAME in self.option_dict:
1079             return self.option_dict[FILENAME]
1080         if global_options.use_hash:
1081             return 'lily-%d' % self.get_hash ()
1082         raise 'to be done'
1083
1084     def write_ly (self):
1085         outf = open (self.basename () + '.ly', 'w')
1086         outf.write (self.full_ly ())
1087
1088         open (self.basename () + '.txt', 'w').write ('image of music')
1089
1090     def ly_is_outdated (self):
1091         base = self.basename ()
1092
1093         tex_file = '%s.tex' % base
1094         eps_file = '%s.eps' % base
1095         system_file = '%s-systems.tex' % base
1096         ly_file = '%s.ly' % base
1097         ok = os.path.exists (ly_file) \
1098           and os.path.exists (system_file)\
1099           and os.stat (system_file)[stat.ST_SIZE] \
1100           and re.match ('% eof', open (system_file).readlines ()[-1])
1101         if ok and (not global_options.use_hash or FILENAME in self.option_dict):
1102             ok = (self.full_ly () == open (ly_file).read ())
1103         if ok:
1104             # TODO: Do something smart with target formats
1105             #       (ps, png) and m/ctimes.
1106             return None
1107         return self
1108
1109     def png_is_outdated (self):
1110         base = self.basename ()
1111         ok = not self.ly_is_outdated ()
1112         if global_options.format in (HTML, TEXINFO):
1113             ok = ok and os.path.exists (base + '.eps')
1114
1115             page_count = 0
1116             if ok:
1117                 page_count = ps_page_count (base + '.eps')
1118
1119             if page_count <= 1:
1120                 ok = ok and os.path.exists (base + '.png')
1121              
1122             elif page_count > 1:
1123                 for a in range (1, page_count + 1):
1124                         ok = ok and os.path.exists (base + '-page%d.png' % a)
1125                 
1126         return not ok
1127     
1128     def texstr_is_outdated (self):
1129         if backend == 'ps':
1130             return 0
1131
1132         base = self.basename ()
1133         ok = self.ly_is_outdated ()
1134         ok = ok and (os.path.exists (base + '.texstr'))
1135         return not ok
1136
1137     def filter_text (self):
1138         code = self.substring ('code')
1139         s = run_filter (code)
1140         d = {
1141             'code': s,
1142             'options': self.match.group ('options')
1143         }
1144         # TODO
1145         return output[self.format][FILTER] % d
1146
1147     def replacement_text (self):
1148         func = Lilypond_snippet.__dict__['output_' + self.format]
1149         return func (self)
1150
1151     def get_images (self):
1152         base = self.basename ()
1153         # URGUGHUGHUGUGH
1154         single = '%(base)s.png' % vars ()
1155         multiple = '%(base)s-page1.png' % vars ()
1156         images = (single,)
1157         if os.path.exists (multiple) \
1158          and (not os.path.exists (single) \
1159             or (os.stat (multiple)[stat.ST_MTIME] \
1160               > os.stat (single)[stat.ST_MTIME])):
1161             count = ps_page_count ('%(base)s.eps' % vars ())
1162             images = ['%s-page%d.png' % (base, a) for a in range (1, count+1)]
1163             images = tuple (images)
1164         return images
1165
1166     def output_docbook (self):
1167         str = ''
1168         base = self.basename ()
1169         for image in self.get_images ():
1170             (base, ext) = os.path.splitext (image)
1171             str += output[DOCBOOK][OUTPUT] % vars ()
1172             str += self.output_print_filename (DOCBOOK)
1173             if (self.substring('inline') == 'inline'): 
1174                 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1175             else:
1176                 str = '<mediaobject>' + str + '</mediaobject>'
1177         if VERBATIM in self.option_dict:
1178                 verb = verbatim_html (self.substring ('code'))
1179                 str = output[DOCBOOK][VERBATIM] % vars () + str
1180         return str
1181         
1182     def output_html (self):
1183         str = ''
1184         base = self.basename ()
1185         if global_options.format == HTML:
1186             str += self.output_print_filename (HTML)
1187             if VERBATIM in self.option_dict:
1188                 verb = verbatim_html (self.substring ('code'))
1189                 str += output[HTML][VERBATIM] % vars ()
1190             if QUOTE in self.option_dict:
1191                 str = output[HTML][QUOTE] % vars ()
1192
1193         str += output[HTML][BEFORE] % vars ()
1194         for image in self.get_images ():
1195             (base, ext) = os.path.splitext (image)
1196             alt = self.option_dict[ALT]
1197             str += output[HTML][OUTPUT] % vars ()
1198         str += output[HTML][AFTER] % vars ()
1199         return str
1200
1201     def output_info (self):
1202         str = ''
1203         for image in self.get_images ():
1204             (base, ext) = os.path.splitext (image)
1205
1206             # URG, makeinfo implicitly prepends dot to extension.
1207             # Specifying no extension is most robust.
1208             ext = ''
1209             alt = self.option_dict[ALT]
1210             str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1211
1212         base = self.basename ()
1213         str += output[global_options.format][OUTPUT] % vars ()
1214         return str
1215
1216     def output_latex (self):
1217         str = ''
1218         base = self.basename ()
1219         if global_options.format == LATEX:
1220             str += self.output_print_filename (LATEX)
1221             if VERBATIM in self.option_dict:
1222                 verb = self.substring ('code')
1223                 str += (output[LATEX][VERBATIM] % vars ())
1224
1225         str += (output[LATEX][OUTPUT] % vars ())
1226
1227         ## todo: maintain breaks
1228         if 0:
1229             breaks = self.ly ().count ("\n")
1230             str += "".ljust (breaks, "\n").replace ("\n","%\n")
1231         
1232         if QUOTE in self.option_dict:
1233             str = output[LATEX][QUOTE] % vars ()
1234         return str
1235
1236     def output_print_filename (self, format):
1237         str = ''
1238         if PRINTFILENAME in self.option_dict:
1239             base = self.basename ()
1240             filename = self.substring ('filename')
1241             str = output[global_options.format][PRINTFILENAME] % vars ()
1242
1243         return str
1244
1245     def output_texinfo (self):
1246         str = ''
1247         if self.output_print_filename (TEXINFO):
1248             str += ('@html\n'
1249                 + self.output_print_filename (HTML)
1250                 + '\n@end html\n')
1251             str += ('@tex\n'
1252                 + self.output_print_filename (LATEX)
1253                 + '\n@end tex\n')
1254         base = self.basename ()
1255         if TEXIDOC in self.option_dict:
1256             texidoc = base + '.texidoc'
1257             if os.path.exists (texidoc):
1258                 str += '@include %(texidoc)s\n\n' % vars ()
1259
1260         if VERBATIM in self.option_dict:
1261             verb = self.substring ('code')
1262             str += (output[TEXINFO][VERBATIM] % vars ())
1263             if not QUOTE in self.option_dict:
1264                 str = output[TEXINFO][NOQUOTE] % vars ()
1265
1266         str += self.output_info ()
1267
1268 #                str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1269 #                str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1270 #                str += ('@html\n' + self.output_html () + '\n@end html\n')
1271
1272         if QUOTE in self.option_dict:
1273             str = output[TEXINFO][QUOTE] % vars ()
1274
1275         # need par after image
1276         str += '\n'
1277
1278         return str
1279
1280 class Lilypond_file_snippet (Lilypond_snippet):
1281     def ly (self):
1282         name = self.substring ('filename')
1283         contents = open (find_file (name)).read ()
1284
1285         ## strip version string to make automated regtest comparisons
1286         ## across versions easier.
1287         contents = re.sub (r'\\version *"[^"]*"', '', contents)
1288
1289         return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1290                 % (name, contents))
1291
1292 snippet_type_to_class = {
1293     'lilypond_file': Lilypond_file_snippet,
1294     'lilypond_block': Lilypond_snippet,
1295     'lilypond': Lilypond_snippet,
1296     'include': Include_snippet,
1297 }
1298
1299 def find_linestarts (s):
1300     nls = [0]
1301     start = 0
1302     end = len (s)
1303     while 1:
1304         i = s.find ('\n', start)
1305         if i < 0:
1306             break
1307
1308         i = i + 1
1309         nls.append (i)
1310         start = i
1311
1312     nls.append (len (s))
1313     return nls
1314
1315 def find_toplevel_snippets (s, types):
1316     res = {}
1317     for i in types:
1318         res[i] = ly.re.compile (snippet_res[global_options.format][i])
1319
1320     snippets = []
1321     index = 0
1322     found = dict ([(t, None) for t in types])
1323
1324     line_starts = find_linestarts (s)
1325     line_start_idx = 0
1326     # We want to search for multiple regexes, without searching
1327     # the string multiple times for one regex.
1328     # Hence, we use earlier results to limit the string portion
1329     # where we search.
1330     # Since every part of the string is traversed at most once for
1331     # every type of snippet, this is linear.
1332
1333     while 1:
1334         first = None
1335         endex = 1 << 30
1336         for type in types:
1337             if not found[type] or found[type][0] < index:
1338                 found[type] = None
1339                 
1340                 m = res[type].search (s[index:endex])
1341                 if not m:
1342                     continue
1343
1344                 cl = Snippet
1345                 if snippet_type_to_class.has_key (type):
1346                     cl = snippet_type_to_class[type]
1347
1348
1349                 start = index + m.start ('match')
1350                 line_number = line_start_idx
1351                 while (line_starts[line_number] < start):
1352                     line_number += 1
1353
1354                 line_number += 1
1355                 snip = cl (type, m, global_options.format, line_number)
1356
1357                 found[type] = (start, snip)
1358
1359             if found[type] \
1360              and (not first \
1361                 or found[type][0] < found[first][0]):
1362                 first = type
1363
1364                 # FIXME.
1365
1366                 # Limiting the search space is a cute
1367                 # idea, but this *requires* to search
1368                 # for possible containing blocks
1369                 # first, at least as long as we do not
1370                 # search for the start of blocks, but
1371                 # always/directly for the entire
1372                 # @block ... @end block.
1373
1374                 endex = found[first][0]
1375
1376         if not first:
1377             snippets.append (Substring (s, index, len (s), line_start_idx))
1378             break
1379
1380         while (start > line_starts[line_start_idx+1]):
1381             line_start_idx += 1
1382
1383         (start, snip) = found[first]
1384         snippets.append (Substring (s, index, start, line_start_idx + 1))
1385         snippets.append (snip)
1386         found[first] = None
1387         index = start + len (snip.match.group ('match'))
1388
1389     return snippets
1390
1391 def filter_pipe (input, cmd):
1392     if global_options.verbose:
1393         progress (_ ("Opening filter `%s'") % cmd)
1394
1395     (stdin, stdout, stderr) = os.popen3 (cmd)
1396     stdin.write (input)
1397     status = stdin.close ()
1398
1399     if not status:
1400         status = 0
1401         output = stdout.read ()
1402         status = stdout.close ()
1403         error = stderr.read ()
1404
1405     if not status:
1406         status = 0
1407     signal = 0x0f & status
1408     if status or (not output and error):
1409         exit_status = status >> 8
1410         error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1411         error (_ ("The error log is as follows:"))
1412         sys.stderr.write (error)
1413         sys.stderr.write (stderr.read ())
1414         exit (status)
1415
1416     if global_options.verbose:
1417         progress ('\n')
1418
1419     return output
1420
1421 def run_filter (s):
1422     return filter_pipe (s, global_options.filter_cmd)
1423
1424 def is_derived_class (cl, baseclass):
1425     if cl == baseclass:
1426         return 1
1427     for b in cl.__bases__:
1428         if is_derived_class (b, baseclass):
1429             return 1
1430     return 0
1431
1432 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1433     ly_names = filter (lambda x: x,
1434                        map (Lilypond_snippet.basename, ly_snippets))
1435     texstr_names = filter (lambda x: x,
1436                            map (Lilypond_snippet.basename, texstr_snippets))
1437     
1438     png_names = filter (lambda x: x,
1439                         map (Lilypond_snippet.basename, png_snippets))
1440
1441     status = 0
1442     def my_system (cmd):
1443         status = ly.system (cmd,
1444                             be_verbose=global_options.verbose, 
1445                             progress_p=1)
1446
1447     if global_options.format in (HTML, TEXINFO):
1448         cmd += ' --formats=png '
1449     if global_options.format in (DOCBOOK):
1450         cmd += ' --formats=png,pdf '
1451     # UGH
1452     # the --process=CMD switch is a bad idea
1453     # it is too generic for lilypond-book.
1454     if texstr_names:
1455         my_system (string.join ([cmd, '--backend texstr',
1456                                  'snippet-map.ly'] + texstr_names))
1457         for l in texstr_names:
1458             my_system ('latex %s.texstr' % l)
1459
1460     if ly_names:
1461         open ('snippet-names', 'wb').write ('\n'.join (['snippet-map.ly']
1462                                                       + ly_names))
1463         
1464         my_system (string.join ([cmd, 'snippet-names']))
1465
1466
1467 LATEX_INSPECTION_DOCUMENT = r'''
1468 \nonstopmode
1469 %(preamble)s
1470 \begin{document}
1471 \typeout{textwidth=\the\textwidth}
1472 \typeout{columnsep=\the\columnsep}
1473 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1474 \end{document}
1475 '''
1476
1477 # Do we need anything else besides `textwidth'?
1478 def get_latex_textwidth (source):
1479     m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1480     if m == None:
1481         warning (_ ("Can't find \\begin{document} in LaTeX document"))
1482         
1483         ## what's a sensible default?
1484         return 550.0
1485     
1486     preamble = source[:m.start (0)]
1487     latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1488     
1489     (handle, tmpfile) = tempfile.mkstemp('.tex')
1490     logfile = os.path.splitext (tmpfile)[0] + '.log'
1491     logfile = os.path.split (logfile)[1]
1492
1493     tmp_handle = os.fdopen (handle,'w')
1494     tmp_handle.write (latex_document)
1495     tmp_handle.close ()
1496     
1497     ly.system ('latex %s' % tmpfile, be_verbose=global_options.verbose)
1498     parameter_string = open (logfile).read()
1499     
1500     os.unlink (tmpfile)
1501     os.unlink (logfile)
1502
1503     columns = 0
1504     m = re.search ('columns=([0-9.]*)', parameter_string)
1505     if m:
1506         columns = int (m.group (1))
1507
1508     columnsep = 0
1509     m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1510     if m:
1511         columnsep = float (m.group (1))
1512
1513     textwidth = 0
1514     m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1515     if m:
1516         textwidth = float (m.group (1))
1517         if columns:
1518             textwidth = (textwidth - columnsep) / columns
1519
1520     return textwidth
1521
1522 def modify_preamble (chunk):
1523     str = chunk.replacement_text ()
1524     if (re.search (r"\\begin *{document}", str)
1525       and not re.search ("{graphic[sx]", str)):
1526         str = re.sub (r"\\begin{document}",
1527                r"\\usepackage{graphics}" + '\n'
1528                + r"\\begin{document}",
1529                str)
1530         chunk.override_text = str 
1531         
1532     
1533
1534 ext2format = {
1535     '.html': HTML,
1536     '.itely': TEXINFO,
1537     '.latex': LATEX,
1538     '.lytex': LATEX,
1539     '.tely': TEXINFO,
1540     '.tex': LATEX,
1541     '.texi': TEXINFO,
1542     '.texinfo': TEXINFO,
1543     '.xml': HTML,
1544     '.lyxml': DOCBOOK
1545 }
1546
1547 format2ext = {
1548     HTML: '.html',
1549     # TEXINFO: '.texinfo',
1550     TEXINFO: '.texi',
1551     LATEX: '.tex',
1552     DOCBOOK: '.xml'
1553 }
1554
1555 class Compile_error:
1556     pass
1557
1558 def write_file_map (lys, name):
1559     snippet_map = open ('snippet-map.ly', 'w')
1560     snippet_map.write ("""
1561 #(define version-seen #t)
1562 #(ly:add-file-name-alist '(
1563 """)
1564     for ly in lys:
1565         snippet_map.write ('("%s.ly" . "%s")\n'
1566                  % (ly.basename (),
1567                    name))
1568
1569     snippet_map.write ('))\n')
1570
1571 def do_process_cmd (chunks, input_name):
1572     all_lys = filter (lambda x: is_derived_class (x.__class__,
1573                            Lilypond_snippet),
1574              chunks)
1575
1576     write_file_map (all_lys, input_name)
1577     ly_outdated = filter (lambda x: is_derived_class (x.__class__,
1578                                                       Lilypond_snippet)
1579                           and x.ly_is_outdated (), chunks)
1580     texstr_outdated = filter (lambda x: is_derived_class (x.__class__,
1581                                                           Lilypond_snippet)
1582                               and x.texstr_is_outdated (),
1583                               chunks)
1584     png_outdated = filter (lambda x: is_derived_class (x.__class__,
1585                                                         Lilypond_snippet)
1586                            and x.png_is_outdated (),
1587                            chunks)
1588
1589     outdated = png_outdated + texstr_outdated + ly_outdated
1590     
1591     progress (_ ("Writing snippets..."))
1592     map (Lilypond_snippet.write_ly, ly_outdated)
1593     progress ('\n')
1594
1595     if outdated:
1596         progress (_ ("Processing..."))
1597         progress ('\n')
1598         process_snippets (global_options.process_cmd, ly_outdated, texstr_outdated, png_outdated)
1599     else:
1600         progress (_ ("All snippets are up to date..."))
1601     progress ('\n')
1602
1603 def guess_format (input_filename):
1604     format = None
1605     e = os.path.splitext (input_filename)[1]
1606     if e in ext2format.keys ():
1607         # FIXME
1608         format = ext2format[e]
1609     else:
1610         error (_ ("can't determine format for: %s" \
1611               % input_filename))
1612         exit (1)
1613     return format
1614
1615 def write_if_updated (file_name, lines):
1616     try:
1617         f = open (file_name)
1618         oldstr = f.read ()
1619         new_str = string.join (lines, '')
1620         if oldstr == new_str:
1621             progress (_ ("%s is up to date.") % file_name)
1622             progress ('\n')
1623             return
1624     except:
1625         pass
1626
1627     progress (_ ("Writing `%s'...") % file_name)
1628     open (file_name, 'w').writelines (lines)
1629     progress ('\n')
1630
1631 def note_input_file (name, inputs=[]):
1632     ## hack: inputs is mutable!
1633     inputs.append (name)
1634     return inputs
1635
1636 def samefile (f1, f2):
1637     try:
1638         return os.path.samefile (f1, f2)
1639     except AttributeError:                # Windoze
1640         f1 = re.sub ("//*", "/", f1)
1641         f2 = re.sub ("//*", "/", f2)
1642         return f1 == f2
1643
1644 def do_file (input_filename):
1645     # Ugh.
1646     if not input_filename or input_filename == '-':
1647         in_handle = sys.stdin
1648         input_fullname = '<stdin>'
1649     else:
1650         if os.path.exists (input_filename):
1651             input_fullname = input_filename
1652         elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1653             input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1654         else:
1655             input_fullname = find_file (input_filename)
1656
1657         note_input_file (input_fullname)
1658         in_handle = open (input_fullname)
1659
1660     if input_filename == '-':
1661         input_base = 'stdin'
1662     else:
1663         input_base = os.path.basename \
1664                      (os.path.splitext (input_filename)[0])
1665
1666     # Only default to stdout when filtering.
1667     if global_options.output_name == '-' or (not global_options.output_name and global_options.filter_cmd):
1668         output_filename = '-'
1669         output_file = sys.stdout
1670     else:
1671         # don't complain when global_options.output_name is existing
1672         output_filename = input_base + format2ext[global_options.format]
1673         if global_options.output_name:
1674             if not os.path.isdir (global_options.output_name):
1675                 os.mkdir (global_options.output_name, 0777)
1676             os.chdir (global_options.output_name)
1677         else: 
1678             if (os.path.exists (input_filename) 
1679                 and os.path.exists (output_filename) 
1680                 and samefile (output_filename, input_fullname)):
1681              error (
1682              _ ("Output would overwrite input file; use --output."))
1683              exit (2)
1684
1685     try:
1686         progress (_ ("Reading %s...") % input_fullname)
1687         source = in_handle.read ()
1688         progress ('\n')
1689
1690         set_default_options (source)
1691
1692
1693         # FIXME: Containing blocks must be first, see
1694         #        find_toplevel_snippets.
1695         snippet_types = (
1696             'multiline_comment',
1697             'verbatim',
1698             'lilypond_block',
1699     #                'verb',
1700             'singleline_comment',
1701             'lilypond_file',
1702             'include',
1703             'lilypond',
1704         )
1705         progress (_ ("Dissecting..."))
1706         chunks = find_toplevel_snippets (source, snippet_types)
1707
1708         if global_options.format == LATEX:
1709             for c in chunks:
1710                 if (c.is_plain () and
1711                   re.search (r"\\begin *{document}", c.replacement_text())):
1712                     modify_preamble (c)
1713                     break
1714         progress ('\n')
1715
1716         if global_options.filter_cmd:
1717             write_if_updated (output_filename,
1718                      [c.filter_text () for c in chunks])
1719         elif global_options.process_cmd:
1720             do_process_cmd (chunks, input_fullname)
1721             progress (_ ("Compiling %s...") % output_filename)
1722             progress ('\n')
1723             write_if_updated (output_filename,
1724                      [s.replacement_text ()
1725                      for s in chunks])
1726         
1727         def process_include (snippet):
1728             os.chdir (original_dir)
1729             name = snippet.substring ('filename')
1730             progress (_ ("Processing include: %s") % name)
1731             progress ('\n')
1732             return do_file (name)
1733
1734         include_chunks = map (process_include,
1735                    filter (lambda x: is_derived_class (x.__class__,
1736                                      Include_snippet),
1737                        chunks))
1738
1739
1740         return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1741         
1742     except Compile_error:
1743         os.chdir (original_dir)
1744         progress (_ ("Removing `%s'") % output_filename)
1745         progress ('\n')
1746         raise Compile_error
1747
1748 def do_options ():
1749
1750     global global_options
1751
1752     opt_parser = get_option_parser()
1753     (global_options, args) = opt_parser.parse_args ()
1754
1755     if global_options.format in ('texi-html', 'texi'):
1756         global_options.format = TEXINFO
1757     global_options.use_hash = True
1758
1759     global_options.include_path =  map (os.path.abspath, global_options.include_path)
1760     
1761     if global_options.warranty:
1762         warranty ()
1763         exit (0)
1764     if not args or len (args) > 1:
1765         opt_parser.print_help ()
1766         exit (2)
1767         
1768     return args
1769
1770 def main ():
1771     files = do_options ()
1772
1773     file = files[0]
1774
1775     basename = os.path.splitext (file)[0]
1776     basename = os.path.split (basename)[1]
1777     
1778     if not global_options.format:
1779         global_options.format = guess_format (files[0])
1780
1781     formats = 'ps'
1782     if global_options.format in (TEXINFO, HTML, DOCBOOK):
1783         formats += ',png'
1784
1785         
1786     if global_options.process_cmd == '':
1787         global_options.process_cmd = (lilypond_binary 
1788                                       + ' --formats=%s --backend eps ' % formats)
1789
1790     if global_options.process_cmd:
1791         global_options.process_cmd += string.join ([(' -I %s' % ly.mkarg (p))
1792                               for p in global_options.include_path])
1793
1794     if global_options.format in (TEXINFO, LATEX):
1795         ## prevent PDF from being switched on by default.
1796         global_options.process_cmd += ' --formats=eps '
1797         
1798     if (global_options.format in (TEXINFO, LATEX)
1799         and global_options.create_pdf):
1800         global_options.process_cmd += "--pdf  -dinclude-eps-fonts -dgs-load-fonts "
1801
1802         
1803     
1804     if global_options.verbose:
1805         global_options.process_cmd += " --verbose "
1806
1807     global_options.process_cmd += " -dread-file-list -deps-box-padding=-3 "
1808
1809     identify ()
1810
1811     try:
1812         chunks = do_file (file)
1813         if global_options.psfonts:
1814             fontextract.verbose = global_options.verbose
1815             snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1816                                        Lilypond_snippet),
1817                         chunks)
1818
1819             psfonts_file = basename + '.psfonts' 
1820             if not global_options.verbose:
1821                 progress (_ ("Writing fonts to %s...") % psfonts_file)
1822             fontextract.extract_fonts (psfonts_file,
1823                          [x.basename() + '.eps'
1824                           for x in snippet_chunks])
1825             if not global_options.verbose:
1826                 progress ('\n')
1827             
1828     except Compile_error:
1829         exit (1)
1830
1831     if global_options.format in (TEXINFO, LATEX):
1832         psfonts_file = os.path.join (global_options.output_name, basename + '.psfonts')
1833         output = os.path.join (global_options.output_name, basename +  '.dvi' )
1834         
1835         if not global_options.psfonts and not global_options.create_pdf:
1836             warning (_ ("option --psfonts not used"))
1837             warning (_ ("processing with dvips will have no fonts"))
1838         else:
1839             progress ('\n')
1840             progress (_ ("DVIPS usage:"))
1841             progress ('\n')
1842             progress ("    dvips -h %(psfonts_file)s %(output)s" % vars ())
1843             progress ('\n')
1844
1845     inputs = note_input_file ('')
1846     inputs.pop ()
1847
1848     base_file_name = os.path.splitext (os.path.basename (file))[0]
1849     dep_file = os.path.join (global_options.output_name, base_file_name + '.dep')
1850     final_output_file = os.path.join (global_options.output_name,
1851                      base_file_name
1852                      + '.%s' % global_options.format)
1853     
1854     os.chdir (original_dir)
1855     open (dep_file, 'w').write ('%s: %s' % (final_output_file, ' '.join (inputs)))
1856
1857 if __name__ == '__main__':
1858     main ()