]> git.donarmstrong.com Git - lilypond.git/blob - scripts/lilypond-book.py
2d76b3c7bbbe30d0d71da0c61ecd04bab479b3cb
[lilypond.git] / scripts / lilypond-book.py
1 #!@PYTHON@
2
3 '''
4 Example usage:
5
6 test:
7      lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
8           
9 convert-ly on book:
10      lilypond-book --filter="convert-ly --no-version --from=1.6.11 -" BOOK
11
12 classic lilypond-book:
13      lilypond-book --process="lilypond" BOOK.tely
14
15 TODO:
16     *  ly-options: intertext ?
17     *  --linewidth?
18     *  eps in latex / eps by lilypond -fps ?
19     *  check latex parameters, twocolumn, multicolumn?
20       
21     *  Converting from lilypond-book source, substitute:
22        @mbinclude foo.itely -> @include foo.itely
23        \mbinput -> \input
24
25 '''
26
27 import __main__
28 import glob
29 import stat
30 import string
31
32 #
33 # TODO:
34 #
35 #  * use --png --ps --pdf for making images? 
36 #
37
38 ################################################################
39 # Users of python modules should include this snippet
40 # and customize variables below.
41
42 # We'll suffer this path init stuff as long as we don't install our
43 # python packages in <prefix>/lib/pythonx.y (and don't kludge around
44 # it as we do with teTeX on Red Hat Linux: set some environment var
45 # (PYTHONPATH) in profile)
46
47 # If set, LILYPONDPREFIX must take prevalence
48 # if datadir is not set, we're doing a build and LILYPONDPREFIX
49 import getopt, os, sys
50 datadir = '@local_lilypond_datadir@'
51 if not os.path.isdir (datadir):
52         datadir = '@lilypond_datadir@'
53 if os.environ.has_key ('LILYPONDPREFIX') :
54         datadir = os.environ['LILYPONDPREFIX']
55         while datadir[-1] == os.sep:
56                 datadir= datadir[:-1]
57
58 sys.path.insert (0, os.path.join (datadir, 'python'))
59
60 # Customize these
61 #if __name__ == '__main__':
62
63 import lilylib as ly
64 global _;_=ly._
65 global re;re = ly.re
66
67
68 # lilylib globals
69 program_version = '@TOPLEVEL_VERSION@'
70 program_name = 'lilypond-book'
71 verbose_p = 0
72 pseudo_filter_p = 0
73 original_dir = os.getcwd ()
74
75
76 help_summary = _ ("""Process LilyPond snippets in hybrid HTML, LaTeX or texinfo document.
77 Example usage:
78
79    lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
80    lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" BOOK
81    lilypond-book --process='lilypond -I include' BOOK
82
83 """)
84
85 copyright = ('Jan Nieuwenhuizen <janneke@gnu.org>',
86              'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
87
88 option_definitions = [
89         (_ ("EXT"), 'f', 'format', _ ("use output format EXT (texi [default], texi-html, latex, html)")),
90         (_ ("FILTER"), 'F', 'filter', _ ("pipe snippets through FILTER [convert-ly -n -]")),
91         ('', 'h', 'help', _ ("print this help")),
92         (_ ("DIR"), 'I', 'include', _ ("add DIR to include path")),
93         (_ ("COMMAND"), 'P', 'process', _ ("process ly_files using COMMAND FILE...")),
94         (_ ("DIR"), 'o', 'output', _ ("write output to DIR")),
95         ('', 'V', 'verbose', _ ("be verbose")),
96         ('', 'v', 'version', _ ("print version information")),
97         ('', 'w', 'warranty', _ ("show warranty and copyright")),
98         ]
99
100 include_path = [ly.abspath (os.getcwd ())]
101 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
102
103 # only use installed binary  when we're installed too.
104 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
105         lilypond_binary = 'lilypond'
106
107
108 use_hash_p = 1
109 format = 0
110 output_name = 0
111 latex_filter_cmd = 'latex "\\nonstopmode \input /dev/stdin"'
112 filter_cmd = 0
113 process_cmd = ''
114 default_ly_options = {}
115
116 #
117 # is this pythonic? Personally, I find this rather #define-nesque. --hwn
118 #
119 AFTER = 'after'
120 BEFORE = 'before'
121 BOOKPAPER = 'bookpaper'
122 EXAMPLEINDENT = 'exampleindent'
123 FILTER = 'filter'
124 FRAGMENT = 'fragment'
125 HTML = 'html'
126 INDENT = 'indent'
127 LATEX = 'latex'
128 LINEWIDTH = 'linewidth'
129 NOFRAGMENT = 'nofragment'
130 NOINDENT = 'noindent'
131 NOTES = 'body'
132 NOTIME = 'notime'
133 OUTPUT = 'output'
134 PAPER = 'paper'
135 PREAMBLE = 'preamble'
136 PRINTFILENAME = 'printfilename'
137 QUOTE = 'quote'
138 RAGGEDRIGHT = 'raggedright'
139 RELATIVE = 'relative'
140 STAFFSIZE = 'staffsize'
141 TEXIDOC = 'texidoc'
142 TEXINFO = 'texinfo'
143 VERBATIM = 'verbatim'
144
145 # Recognize special sequences in the input 
146 #
147 # (?P<name>regex) -- assign result of REGEX to NAME
148 # *? -- match non-greedily.
149 # (?m) -- multiline regex: make ^ and $ match at each line
150 # (?s) -- make the dot match all characters including newline
151 no_match = 'a\ba'
152 snippet_res = {
153         HTML: {
154         'include':  no_match,
155         'lilypond' : '(?m)(?P<match><lilypond((?P<options>[^:]*):)(?P<code>.*?)/>)',
156         'lilypond_block': r'''(?ms)(?P<match><lilypond(?P<options>[^>]+)?>(?P<code>.*?)</lilypond>)''',
157         'lilypond_file': r'(?m)(?P<match><lilypondfile(?P<options>[^>]+)?>\s*(?P<filename>[^<]+)\s*</lilypondfile>)',
158         'multiline_comment': r"(?sm)\s*(?!@c\s+)(?P<code><!--\s.*?!-->)\s",
159         'singleline_comment': no_match,
160         'verb': r'''(?P<code><pre>.*?</pre>)''',
161         'verbatim': r'''(?s)(?P<code><pre>\s.*?</pre>\s)''',
162         },
163
164         LATEX: {
165         'include': r'(?m)^[^%\n]*?(?P<match>\\input{(?P<filename>[^}]+)})',
166         'lilypond' : r'(?m)^[^%\n]*?(?P<match>\\lilypond\s*(\[(?P<options>.*?)\])?\s*{(?P<code>.*?)})',
167         'lilypond_block': r"(?sm)^[^%\n]*?(?P<match>\\begin\s*(\[(?P<options>.*?)\])?\s*{lilypond}(?P<code>.*?)\\end{lilypond})",
168         'lilypond_file': r'(?m)^[^%\n]*?(?P<match>\\lilypondfile\s*(\[(?P<options>.*?)\])?\s*\{(?P<filename>.+)})',
169         'multiline_comment': no_match,
170         'singleline_comment': r"(?m)^.*?(?P<match>(?P<code>^%.*$\n+))",
171         'verb': r"(?P<code>\\verb(?P<del>.).*?(?P=del))",
172         'verbatim': r"(?s)(?P<code>\\begin\s*{verbatim}.*?\\end{verbatim})",
173         },
174
175         TEXINFO: {
176         'include':  '(?m)^[^%\n]*?(?P<match>@include\s+(?P<filename>\S+))',
177         'lilypond' : '(?m)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?{(?P<code>.*?)})',
178         'lilypond_block': r'''(?ms)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?\s(?P<code>.*?)@end lilypond)\s''',
179         'lilypond_file': '(?m)^(?P<match>@lilypondfile(\[(?P<options>[^]]*)\])?{(?P<filename>[^}]+)})',
180         'multiline_comment': r'(?sm)^\s*(?!@c\s+)(?P<code>@ignore\s.*?@end\s+ignore)\s',
181         'singleline_comment': r'(?m)^.*(?P<match>(?P<code>@c([ \t][^\n]*|)\n))',
182
183 # don't do this: fucks up with @code{@{}
184 #       'verb': r'''(?P<code>@code{.*?})''',
185         'verbatim': r'''(?s)(?P<code>@example\s.*?@end\s+example\s)''',
186         },
187         }
188
189 format_res = {
190         HTML: {
191         'option-sep' : '\s*',
192         'intertext': r',?\s*intertext=\".*?\"',
193         },
194         LATEX: {
195         'intertext': r',?\s*intertext=\".*?\"',
196         'option-sep' : ',\s*',
197         },
198         TEXINFO: {
199         'intertext': r',?\s*intertext=\".*?\"',
200         'option-sep' : ',\s*',
201         },
202         }
203
204 ly_options = {
205         NOTES: {
206                 RELATIVE: r'''\relative c%(relative_quotes)s''',
207         },
208         BOOKPAPER: {
209                 INDENT : r'''
210     indent = %(indent)s''',
211         'linewidth' : r'''
212     linewidth = %(linewidth)s''',
213                 NOINDENT : r'''
214     indent = 0.0\mm''', 
215                 QUOTE : r'''
216     linewidth = %(linewidth)s - 2.0 * %(exampleindent)s
217 ''',    
218                 RAGGEDRIGHT : r'''
219     indent = 0.0\mm
220     raggedright = ##t''',
221         },
222
223         ##
224         PAPER: {
225                 EXAMPLEINDENT : '',
226
227                 NOTIME : r'''
228     \context {
229         \Staff
230         \remove Time_signature_engraver
231     }''',
232         },
233
234         ##
235         PREAMBLE: {
236                 STAFFSIZE: r'''
237 #(set-global-staff-size %(staffsize)s)''',
238                 },
239         }
240
241 output = {
242         HTML : {
243         FILTER: r'''<lilypond %(options)s>
244 %(code)s
245 </lilypond>
246 ''',
247         
248         AFTER: r'''
249   </a>
250 </p>''',
251         BEFORE: r'''
252 <p>
253   <a href="%(base)s.ly">''',
254         OUTPUT: r'''
255     <img align="center" valign="center"
256          border="0" src="%(image)s" alt="[image of music]">''',
257         PRINTFILENAME:'<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
258         QUOTE: r'''<blockquote>
259 %(str)s
260 </blockquote>
261 ''',    
262         VERBATIM: r'''<pre>
263 %(verb)s</pre>''',
264         },
265
266         LATEX : {
267         AFTER: '',
268         BEFORE: '',
269         OUTPUT: r'''{\parindent 0pt
270 \catcode`\@=12
271 \ifx\preLilyPondExample\undefined\relax\else\preLilyPondExample\fi
272 \def\lilypondbook{}
273 \input %(base)s.tex
274 \ifx\postLilyPondExample\undefined\relax\else\postLilyPondExample\fi
275 \catcode`\@=0}''',
276         PRINTFILENAME: '''\\texttt{%(filename)s}
277
278         ''',
279         QUOTE: r'''\begin{quotation}
280 %(str)s
281 \end{quotation}
282 ''',    
283         VERBATIM: r'''\noindent
284 \begin{verbatim}
285 %(verb)s\end{verbatim}
286 ''',
287         FILTER: r'''\begin{lilypond}[%(options)s]
288 %(code)s
289 \end{lilypond}''',
290         },
291
292         TEXINFO : {
293         FILTER: r'''@lilypond[%(options)s]
294 %(code)s
295 @lilypond''',
296         AFTER: '',
297         BEFORE: '',
298         OUTPUT: r'''@noindent
299 @image{%(base)s,,,[image of music],%(ext)s}
300 ''',    
301         PRINTFILENAME: '''@file{%(filename)s}
302
303         ''',
304         QUOTE: r'''@quotation
305 %(str)s
306 @end quotation
307 ''',
308         # FIXME: @exampleindent 5  is the default...
309         VERBATIM: r'''@exampleindent 0
310 @example
311 %(verb)s@end example
312 @exampleindent 5
313 ''',
314         },
315         }
316
317 PREAMBLE_LY = r'''%%%% Generated by %(program_name)s
318 %%%% Options: [%(option_string)s]
319 #(set! toplevel-score-handler ly:parser-print-score)
320 #(set! toplevel-music-handler (lambda (p m)
321                                (ly:parser-print-score
322                                 p (ly:music-scorify m))
323                             ))
324 %(preamble_string)s
325 \bookpaper {%(bookpaper_string)s
326 }
327 \paper { %(paper_string)s
328 }
329
330 ''' 
331
332 FRAGMENT_LY = r'''
333     %(notes_string)s{
334         %(code)s    }
335 '''
336 FULL_LY = '%(code)s'
337
338 texinfo_linewidths = {
339         '@afourpaper': '160 \\mm',
340         '@afourwide': '6.5 \\in',
341         '@afourlatex': '150 \\mm',
342         '@smallbook': '5 \\in' ,
343         '@letterpaper': '6\\in',
344         }
345
346 def classic_lilypond_book_compatibility (o):
347         if o == 'singleline':
348                 return RAGGEDRIGHT
349         m = re.search ('relative\s*([-0-9])', o)
350         if m:
351                 return 'relative=%s' % m.group (1)
352         m = re.match ('([0-9]+)pt', o)
353         if m:
354                 return 'staffsize=%s' % m.group (1)
355         m = re.match ('indent=([-.0-9]+)(cm|in|mm|pt|staffspace)', o)
356         if m:
357                 f = float (m.group (1))
358                 return 'indent=%f\\%s' % (f, m.group (2))
359         m = re.match ('linewidth=([-.0-9]+)(cm|in|mm|pt|staffspace)', o)
360         if m:
361                 f = float (m.group (1))
362                 return 'linewidth=%f\\%s' % (f, m.group (2))
363         return None
364
365 def compose_ly (code, options):
366         #Hmm
367         for i in default_ly_options.keys ():
368                 if i not in options:
369                         options.append (i)
370         
371         #Hmm
372         if QUOTE in options and LINEWIDTH in options:
373                 options.remove (LINEWIDTH)
374
375         if FRAGMENT in options:
376                 if RAGGEDRIGHT not in options:
377                         options.append (RAGGEDRIGHT)
378                 body = FRAGMENT_LY
379         else:
380                 body = FULL_LY
381
382         # defaults
383         relative = 1
384         staffsize = 16
385         override = {}
386         override.update (default_ly_options)
387         #FIXME: where to get sane value for exampleindent?
388         override[EXAMPLEINDENT] = r'9.0 \mm'
389
390         option_string = string.join (options, ',')
391
392         options_dict = {}
393         option_types = [NOTES, PREAMBLE, PAPER, BOOKPAPER]
394         for a in option_types:
395                 options_dict[a] = []
396                 
397         for i in options:
398                 c = classic_lilypond_book_compatibility (i)
399                 if c:
400                         ly.warning (_ ("deprecated ly-option used: %s" % i))
401                         ly.warning (_ ("compatibility mode translation: %s" \
402                                        % c))
403                         i = c
404                 
405                 if string.find (i, '=') > 0:
406                         key, value = string.split (i, '=')
407                         override[key] = value
408                 else:
409                         key = i
410                         if not override.has_key (i):
411                                 override[i] = None
412
413                 found = 0
414                 for type in option_types:
415                         if ly_options[type].has_key (key):
416                                 
417                                 options_dict[type].append (ly_options[type][key])
418                                 found = 1
419                                 break
420
421                 if not found and key not in (FRAGMENT, NOFRAGMENT, PRINTFILENAME,
422                                              RELATIVE, VERBATIM, TEXIDOC):
423                         ly.warning (_("ignoring unknown ly option: %s") % i)
424
425         #URGS
426         if RELATIVE in override.keys () and override[RELATIVE]:
427                 relative = string.atoi (override[RELATIVE])
428
429         relative_quotes = ''
430
431         # 1 = central C
432         if relative < 0:
433                 relative_quotes += ',' * (- relative)
434         elif relative > 0:
435                 relative_quotes += "'" * relative
436                 
437         program_name = __main__.program_name
438         
439         paper_string = string.join (options_dict[PAPER], '\n    ') % override
440         bookpaper_string = string.join (options_dict[BOOKPAPER], '\n    ') % override
441         notes_string = string.join (options_dict[NOTES], '\n    ') % vars ()
442         preamble_string = string.join (options_dict[PREAMBLE], '\n    ') % override
443         return (PREAMBLE_LY + body) % vars ()
444
445
446 # BARF
447 # use lilypond for latex (.lytex) books,
448 # and lilypond --preview for html, texinfo books?
449 def to_eps (file):
450         cmd = r'latex "\nonstopmode \input %s"' % file
451         # Ugh.  (La)TeX writes progress and error messages on stdout
452         # Redirect to stderr
453         cmd = '(( %s  >&2 ) >&- )' % cmd
454         ly.system (cmd)
455         ly.system ('dvips -Ppdf -u+ec-mftrace.map -u+lilypond.map -E -o %s.eps %s' \
456                    % (file, file))
457
458
459         # check if it really is EPS.
460         # Otherwise music glyphs disappear from 2nd and following pages.
461
462         # TODO: should run dvips -pp -E per page, then we get proper
463         # cropping as well.
464         
465         f = open ('%s.eps' % file)
466         for x in range(0,10) :
467                 if re.search ("^%%Pages: ", f.readline ()):
468
469                         # make non EPS.
470                         ly.system ('dvips -Ppdf -u+ec-mftrace.map -u+lilypond.map -o %s.eps %s' \
471                                    % (file, file))
472                         break
473         
474
475 def find_file (name):
476         for i in include_path:
477                 full = os.path.join (i, name)
478                 if os.path.exists (full):
479                         return full
480         ly.error (_ ('file not found: %s') % name + '\n')
481         ly.exit (1)
482         return ''
483         
484 def verbatim_html (s):
485         return re.sub ('>', '&gt;',
486                        re.sub ('<', '&lt;',
487                                re.sub ('&', '&amp;', s)))
488
489 def verbatim_texinfo (s):
490         return re.sub ('{', '@{',
491                        re.sub ('}', '@}',
492                                re.sub ('@', '@@', s)))
493
494 def split_options (option_string):
495         return re.split (format_res[format]['option-sep'], option_string)
496
497
498 class Chunk:
499         def replacement_text (self):
500                 return ''
501         
502         def filter_text (self):
503                 return self.replacement_text ()
504
505
506         def is_outdated (self):
507                 return 0
508
509 class Substring (Chunk):
510         def __init__ (self, source, start, end):
511                 self.source = source
512                 self.start = start
513                 self.end = end
514
515         def replacement_text (self):
516                 return self.source [self.start:self.end]
517         
518 class Snippet (Chunk):
519         def __init__ (self, type, match, format):
520                 self.type = type
521                 self.match = match
522                 self.hash = 0
523                 self.options = []
524                 self.format = format
525
526         def replacement_text (self):
527                 return self.match.group (0)
528         
529         def substring (self, s):
530                 return self.match.group (s)
531
532         def __repr__ (self):
533                 return `self.__class__`  +  " type =  " + self.type
534
535 class Include_snippet (Snippet):
536         def processed_filename (self):
537                 f = self.substring ('filename')
538                 return os.path.splitext (f)[0] + format2ext[format]
539
540         def replacement_text (self):
541                 s = self.match.group (0)
542                 f = self.substring ('filename')
543         
544                 return re.sub (f, self.processed_filename (), s)
545
546 class Lilypond_snippet (Snippet):
547         def __init__ (self, type, match, format):
548                 Snippet.__init__ (self, type, match, format)
549                 os = match.group ('options')
550                 if os:
551                         self.options = split_options (os)
552
553         def ly (self):
554                 return self.substring ('code')
555                 
556         def full_ly (self):
557                 s = self.ly ()
558                 if s:
559                         return compose_ly (s, self.options)
560                 return ''
561
562         # todo: use md5?
563         def get_hash (self):
564                 if not self.hash:
565                         self.hash = abs (hash (self.full_ly ()))
566                 return self.hash
567
568         def basename (self):
569                 if use_hash_p:
570                         return 'lily-%d' % self.get_hash ()
571                 raise 'to be done'
572
573         def write_ly (self):
574                 outf = open (self.basename () + '.ly', 'w')
575                 outf.write (self.full_ly ())
576                 
577                 open (self.basename() + '.txt', 'w').write("image of music")
578                 
579
580         def is_outdated (self):
581                 base = self.basename ()
582
583                 tex_file = '%s.tex' % base
584                 ly_file = '%s.ly' % base
585                 ok = os.path.exists (ly_file) and os.path.exists (tex_file)\
586                      and os.stat (tex_file)[stat.ST_SIZE] \
587                      and open (tex_file).readlines ()[-1][1:-1] \
588                      == 'lilypondend'
589
590                 if format == HTML or format == TEXINFO:
591                         ok = ok and (os.path.exists (base + '.png')
592                                      or glob.glob (base + '-page*.png'))
593                         
594                 if ok and (use_hash_p or self.ly () == open (ly_file).read ()):
595                         # TODO: something smart with target formats
596                         # (ps, png) and m/ctimes
597                         return None
598                 return self
599         
600         def filter_text (self):
601                 code  = self.substring ('code')
602                 s = run_filter (code)
603                 d = {'code' : s,
604                      'options': self.match.group ('options')
605                      }
606                 # TODO
607                 return output[self.format][FILTER] % d
608         
609         def replacement_text (self):
610                 func = Lilypond_snippet.__dict__ ['output_' + self.format]
611                 return func (self)
612         
613         def get_images (self):
614                 base = self.basename ()
615                 # URGUGHUGHUGUGHU
616                 single = '%(base)s.png' % vars ()
617                 multiple = '%(base)s-page1.png' % vars ()
618                 images = (single,)
619                 if os.path.exists (multiple) \
620                    and (not os.path.exists (single)\
621                         or (os.stat (multiple)[stat.ST_MTIME] \
622                             > os.stat (single)[stat.ST_MTIME])):
623                         images = glob.glob ('%(base)s-page*.png' % vars ())
624                 return images
625                 
626         def output_html (self):
627                 str = ''
628                 base = self.basename ()
629                 if format == HTML:
630                         str += self.output_print_filename (HTML)
631                         if VERBATIM in self.options:
632                                 verb = verbatim_html (self.substring ('code'))
633                                 str += write (output[HTML][VERBATIM] % vars ())
634                         if QUOTE in self.options:
635                                 str = output[HTML][QUOTE] % vars ()
636
637                 str += output[HTML][BEFORE] % vars ()
638                 for image in self.get_images ():
639                         base, ext = os.path.splitext (image)
640                         str += output[HTML][OUTPUT] % vars ()
641                 str += output[HTML][AFTER] % vars ()
642                 return str
643
644         def output_info (self):
645                 str = self.output_print_filename (HTML)
646                 str = output[TEXINFO][BEFORE] % vars ()
647                 for image in self.get_images ():
648                         base, ext = os.path.splitext (image)
649                         
650                         # URG, makeinfo implicitely prepends dot to ext
651                         # specifying no extension is most robust
652                         ext = ''
653                         str += output[TEXINFO][OUTPUT] % vars ()
654                 str += output[TEXINFO][AFTER] % vars ()
655                 return str
656
657         def output_latex (self):
658                 str = ''
659                 base = self.basename ()
660                 if format == LATEX:
661                         str += self.output_print_filename (LATEX)
662                         if  VERBATIM in self.options:
663                                 verb = self.substring ('code')
664                                 str += (output[LATEX][VERBATIM] % vars ())
665                         if QUOTE in self.options:
666                                 str = output[LATEX][QUOTE] % vars ()
667
668                 str +=  (output[LATEX][BEFORE]
669                          + (output[LATEX][OUTPUT] % vars ())
670                          + output[LATEX][AFTER])
671                 return str
672
673         def output_print_filename (self,format):
674                 str = ''
675                 if  PRINTFILENAME in self.options:
676                         base = self.basename ()
677                         filename = self.substring ('filename')
678                         str = output[format][PRINTFILENAME] % vars ()
679                 return str
680
681         def output_texinfo (self):
682                 str = ''
683                 # self.output_print_filename (TEXINFO)
684                 str += ('@html\n' + self.output_print_filename (HTML)
685                         + '\n@end html\n')
686                 str += ('@tex\n' + self.output_print_filename (LATEX)
687                         + '\n@end tex\n')
688                 base = self.basename ()
689                 if TEXIDOC in self.options:
690                         texidoc = base + '.texidoc'
691                         if os.path.exists (texidoc):
692                                 str += '@include %(texidoc)s\n\n' % vars ()
693
694                 if VERBATIM in self.options:
695                         verb = verbatim_texinfo (self.substring ('code'))
696                         str +=  (output[TEXINFO][VERBATIM] % vars ())
697
698                 str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
699                 str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
700                 str += ('@html\n' + self.output_html () + '\n@end html\n')
701
702                 if QUOTE in self.options:
703                         str = output[TEXINFO][QUOTE] % vars ()
704
705                 # need par after image
706                 str += '\n'
707
708                 return str
709
710 class Lilypond_file_snippet (Lilypond_snippet):
711         def ly (self):
712                 name = self.substring ('filename')
713                 return open (find_file (name)).read ()
714                         
715 snippet_type_to_class = {
716         'lilypond_file' : Lilypond_file_snippet,
717         'lilypond_block' : Lilypond_snippet,
718         'lilypond' : Lilypond_snippet,
719         'include' : Include_snippet,
720         }
721
722 def find_toplevel_snippets (s, types):
723         res = {}
724         for i in types:
725                 res[i] = ly.re.compile (snippet_res[format][i])
726
727         snippets = []
728         index = 0
729         ##  found = dict (map (lambda x: (x, None), types))
730         ## urg python2.1
731         found = {}
732         map (lambda x, f=found: f.setdefault (x, None), types)
733
734         # We want to search for multiple regexes, without searching
735         # the string multiple times for one regex.
736         # Hence, we use earlier results to limit the string portion
737         # where we search.
738         # Since every part of the string is traversed at most once for
739         # every type of snippet, this is linear.
740
741         while 1:
742                 first = None
743                 endex = 1 << 30
744                 for type in types:
745                         if not found[type] or found[type][0] < index:
746                                 found[type] = None
747                                 m = res[type].search (s[index:endex])
748                                 if not m:
749                                         continue
750
751                                 cl = Snippet
752                                 if snippet_type_to_class.has_key (type):
753                                         cl = snippet_type_to_class[type]
754                                 snip = cl (type, m, format)
755                                 start = index + m.start (0)
756                                 found[type] = (start, snip)
757
758                         if found[type] \
759                            and (not first or found[type][0] < found[first][0]):
760                                 first = type
761
762                                 # FIXME.
763
764                                 # Limiting the search space is a cute
765                                 # idea, but this *requires* to search
766                                 # for possible containing blocks
767                                 # first, at least long as we do not
768                                 # search for the start of blocks, but
769                                 # always/directly for the entire
770                                 # @block ... @end block.
771                                 
772                                 endex = found[first][0]
773
774                 if not first:
775                         snippets.append (Substring (s, index, len (s)))
776                         break
777
778                 (start , snip) = found[first]
779                 snippets.append (Substring (s, index, start))
780                 snippets.append (snip)
781                 found[first] = None
782                 index = start + len (snip.match.group (0))
783
784         return snippets
785
786 def filter_pipe (input, cmd):
787         if verbose_p:
788                 ly.progress (_ ("Opening filter `%s\'") % cmd)
789                 
790         stdin, stdout, stderr = os.popen3 (cmd)
791         stdin.write (input)
792         status = stdin.close ()
793
794         if not status:
795                 status = 0
796                 output = stdout.read ()
797                 status = stdout.close ()
798                 error = stderr.read ()
799                 
800         if not status:
801                 status = 0
802         signal = 0x0f & status
803         if status or (not output and error):
804                 exit_status = status >> 8
805                 ly.error (_ ("`%s\' failed (%d)") % (cmd, exit_status))
806                 ly.error (_ ("The error log is as follows:"))
807                 sys.stderr.write (error)
808                 sys.stderr.write (stderr.read ())
809                 ly.exit (status)
810         
811         if verbose_p:
812                 ly.progress ('\n')
813
814         return output
815         
816 def run_filter (s):
817         return filter_pipe (s, filter_cmd)
818
819 def is_derived_class (cl,  baseclass):
820         if cl == baseclass:
821                 return 1
822         for b in cl.__bases__:
823                 if is_derived_class (b, baseclass):
824                         return 1
825         return 0
826
827
828 def process_snippets (cmd, snippets):
829         names = filter (lambda x: x, map (Lilypond_snippet.basename, snippets))
830         if names:
831                 ly.system (string.join ([cmd] + names))
832
833         if format == HTML or format == TEXINFO:
834                 for i in names:
835                         if not os.path.exists (i + '.eps') and os.path.exists (i + '.tex'):
836                                 to_eps (i)
837                                 ly.make_ps_images (i + '.eps', resolution=110)
838                                 
839 #                       elif os.path.exists (i + '.ps'):
840 #                               ly.make_ps_images (i + '.ps', resolution=110)
841
842
843 LATEX_DOCUMENT = r'''
844 %(preamble)s
845 \begin{document}
846 \typeout{textwidth=\the\textwidth}
847 \typeout{columnsep=\the\columnsep}
848 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
849 \end{document}
850 '''
851 #need anything else besides textwidth?
852 def get_latex_textwidth (source):
853         m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
854         preamble = source[:m.start (0)]
855         latex_document = LATEX_DOCUMENT % vars ()
856         parameter_string = filter_pipe (latex_document, latex_filter_cmd)
857
858         columns = 0
859         m = re.search ('columns=([0-9.]*)', parameter_string)
860         if m:
861                 columns = string.atoi (m.group (1))
862
863         columnsep = 0
864         m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
865         if m:
866                 columnsep = string.atof (m.group (1))
867
868         textwidth = 0
869         m = re.search('textwidth=([0-9.]*)pt', parameter_string)
870         if m:
871                 textwidth = string.atof (m.group (1))
872                 if columns:
873                         textwidth = (textwidth - columnsep) / columns
874
875         return textwidth
876
877 ext2format = {
878         '.html' : HTML,
879         '.itely' : TEXINFO,
880         '.lytex' : LATEX,
881         '.tely' : TEXINFO,
882         '.tex': LATEX,
883         '.texi' : TEXINFO,
884         '.texinfo' : TEXINFO,
885         '.xml' : HTML,
886         }
887                                
888 format2ext = {
889         HTML: '.html',
890         #TEXINFO: '.texinfo',
891         TEXINFO: '.texi',
892         LATEX: '.tex',
893         }
894         
895 def do_file (input_filename):
896         #ugh
897         global format
898         if not format:
899                 e = os.path.splitext (input_filename)[1]
900                 if e in ext2format.keys ():
901                         #FIXME
902                         format = ext2format[e]
903                 else:
904                         ly.error (_ ("cannot determine format for: %s" \
905                                      % input_filename))
906
907         if not input_filename or input_filename == '-':
908                 in_handle = sys.stdin
909                 input_fullname = '<stdin>'
910         else:
911                 if os.path.exists (input_filename):
912                         input_fullname = input_filename
913                 elif format == LATEX:
914                         # urg python interface to libkpathsea?
915                         input_fullname = ly.read_pipe ('kpsewhich '
916                                                        + input_filename)[:-1]
917                 else:
918                         input_fullname = find_file (input_filename)
919                 in_handle = open (input_fullname)
920                 
921         if input_filename == '-':
922                 input_base = 'stdin'
923         else:
924                 input_base = os.path.basename \
925                              (os.path.splitext (input_filename)[0])
926
927         # only default to stdout when filtering 
928         if output_name == '-' or (not output_name and filter_cmd):
929                 output_filename = '-'
930                 output_file = sys.stdout
931         else:
932                 if not output_name:
933                         output_filename = input_base + format2ext[format]
934                 else:
935                         if not os.path.isdir (output_name):
936                                 os.mkdir (output_name, 0777)
937                         output_filename = (output_name
938                                            + '/' + input_base
939                                            + format2ext[format])
940
941
942                 if (os.path.exists (input_filename) and 
943                     os.path.exists (output_filename) and 
944                     os.path.samefile (output_filename, input_fullname)):
945                         ly.error (_("Output would overwrite input file; use --output."))
946                         sys.exit (2)
947
948                 output_file = open (output_filename, 'w')
949                 if output_name:
950                         os.chdir (output_name)
951
952         ly.progress (_ ("Reading %s...") % input_fullname)
953         source = in_handle.read ()
954         ly.progress ('\n')
955
956         # FIXME: containing blocks must be first, see find_toplevel_snippets
957         snippet_types = (
958                 'multiline_comment',
959                 'verbatim',
960                 'lilypond_block',
961 #               'verb',
962                 'singleline_comment',
963                 'lilypond_file',
964                 'include',
965                 'lilypond', )
966         ly.progress (_ ("Dissecting..."))
967         chunks = find_toplevel_snippets (source, snippet_types)
968         ly.progress ('\n')
969
970         global default_ly_options
971         textwidth = 0
972         if not default_ly_options.has_key (LINEWIDTH):
973                 if format == LATEX:
974                         textwidth = get_latex_textwidth (source)
975                         default_ly_options[LINEWIDTH] = '''%.0f\\pt''' \
976                                                         % textwidth
977                 elif format == TEXINFO:
978                         for (k, v) in texinfo_linewidths.items ():
979                                 # FIXME: @paper is usually not in chunk #0:
980                                 #        \input texinfo @c -*-texinfo-*-
981                                 # bluntly search first K of source
982                                 # s = chunks[0].replacement_text ()
983                                 if re.search (k, source[:1024]):
984                                         default_ly_options[LINEWIDTH] = v
985                                         break
986
987         if filter_cmd:
988                 output_file.writelines ([c.filter_text () for c in chunks])
989                 
990                 
991         elif process_cmd:
992                 outdated = filter (lambda x: is_derived_class (x.__class__, Lilypond_snippet) \
993                                    and x.is_outdated (), chunks)
994                 ly.progress (_ ("Writing snippets..."))
995                 map (Lilypond_snippet.write_ly, outdated)
996                 ly.progress ('\n')
997
998                 if outdated:
999                         ly.progress (_ ("Processing..."))
1000                         process_snippets (process_cmd, outdated)
1001                 else:
1002                         ly.progress (_ ("All snippets are up to date..."))
1003                 ly.progress ('\n')
1004
1005                 ly.progress (_ ("Compiling %s...") % output_filename)
1006                 output_file.writelines ([s.replacement_text () \
1007                                          for s in chunks])
1008                 ly.progress ('\n')
1009
1010         def process_include (snippet):
1011                 os.chdir (original_dir)
1012                 name = snippet.substring ('filename')
1013                 ly.progress (_ ('Processing include: %s') % name)
1014                 ly.progress ('\n')
1015                 do_file (name)
1016                 
1017         map (process_include,
1018              filter (lambda x: is_derived_class (x.__class__, Include_snippet), chunks))
1019
1020 def do_options ():
1021         global format, output_name
1022         global filter_cmd, process_cmd, verbose_p
1023         
1024         (sh, long) = ly.getopt_args (option_definitions)
1025         try:
1026                 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1027         except getopt.error, s:
1028                 sys.stderr.write ('\n')
1029                 ly.error (_ ("getopt says: `%s\'" % s))
1030                 sys.stderr.write ('\n')
1031                 ly.help ()
1032                 ly.exit (2)
1033
1034         for opt in options:
1035                 o = opt[0]
1036                 a = opt[1]
1037
1038                 if 0:
1039                         pass
1040                 elif o == '--filter' or o == '-F':
1041                         filter_cmd = a
1042                         process_cmd = 0
1043                 elif o == '--format' or o == '-f':
1044                         format = a
1045                         if a == 'texi-html' or a == 'texi':
1046                                 format = TEXINFO
1047                 elif o == '--help' or o == '-h':
1048                         ly.help ()
1049                         sys.exit (0)
1050                 elif o == '--include' or o == '-I':
1051                         include_path.append (os.path.join (original_dir,
1052                                                            ly.abspath (a)))
1053                 elif o == '--output' or o == '-o':
1054                         output_name = a
1055                 elif o == '--outdir':
1056                         output_name = a
1057                 elif o == '--process' or o == '-P':
1058                         process_cmd = a
1059                         filter_cmd = 0
1060                 elif o == '--version' or o == '-v':
1061                         ly.identify (sys.stdout)
1062                         sys.exit (0)
1063                 elif o == '--verbose' or o == '-V':
1064                         verbose_p = 1
1065                 elif o == '--warranty' or o == '-w':
1066                         if 1 or status:
1067                                 ly.warranty ()
1068                         sys.exit (0)
1069         return files
1070
1071 def main ():
1072         files = do_options ()
1073         global process_cmd
1074         if process_cmd == '':
1075                 process_cmd = lilypond_binary + " -f tex "
1076         
1077         if process_cmd:
1078                 process_cmd += string.join ([(' -I %s' % p)
1079                                              for p in include_path])
1080
1081         ly.identify (sys.stderr)
1082         ly.setup_environment ()
1083         if files:
1084                 do_file (files[0])
1085
1086 if __name__ == '__main__':
1087         main ()