]> git.donarmstrong.com Git - lilypond.git/blob - scripts/lilypond-book.py
Changed scripts/* to use sys.argv[0]
[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 = sys.argv[0]
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 p))
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 ly_is_outdated (self):
507                 return 0
508
509         def png_is_outdated (self):
510                 return 0
511
512 class Substring (Chunk):
513         def __init__ (self, source, start, end):
514                 self.source = source
515                 self.start = start
516                 self.end = end
517
518         def replacement_text (self):
519                 return self.source [self.start:self.end]
520         
521 class Snippet (Chunk):
522         def __init__ (self, type, match, format):
523                 self.type = type
524                 self.match = match
525                 self.hash = 0
526                 self.options = []
527                 self.format = format
528
529         def replacement_text (self):
530                 return self.match.group (0)
531         
532         def substring (self, s):
533                 return self.match.group (s)
534
535         def __repr__ (self):
536                 return `self.__class__`  +  " type =  " + self.type
537
538 class Include_snippet (Snippet):
539         def processed_filename (self):
540                 f = self.substring ('filename')
541                 return os.path.splitext (f)[0] + format2ext[format]
542
543         def replacement_text (self):
544                 s = self.match.group (0)
545                 f = self.substring ('filename')
546         
547                 return re.sub (f, self.processed_filename (), s)
548
549 class Lilypond_snippet (Snippet):
550         def __init__ (self, type, match, format):
551                 Snippet.__init__ (self, type, match, format)
552                 os = match.group ('options')
553                 if os:
554                         self.options = split_options (os)
555
556         def ly (self):
557                 return self.substring ('code')
558                 
559         def full_ly (self):
560                 s = self.ly ()
561                 if s:
562                         return compose_ly (s, self.options)
563                 return ''
564
565         # todo: use md5?
566         def get_hash (self):
567                 if not self.hash:
568                         self.hash = abs (hash (self.full_ly ()))
569                 return self.hash
570
571         def basename (self):
572                 if use_hash_p:
573                         return 'lily-%d' % self.get_hash ()
574                 raise 'to be done'
575
576         def write_ly (self):
577                 outf = open (self.basename () + '.ly', 'w')
578                 outf.write (self.full_ly ())
579                 
580                 open (self.basename() + '.txt', 'w').write("image of music")
581                 
582
583         def ly_is_outdated (self):
584                 base = self.basename ()
585
586                 tex_file = '%s.tex' % base
587                 ly_file = '%s.ly' % base
588                 ok = os.path.exists (ly_file) and os.path.exists (tex_file)\
589                      and os.stat (tex_file)[stat.ST_SIZE] \
590                      and open (tex_file).readlines ()[-1][1:-1] \
591                      == 'lilypondend'
592                         
593                 if ok and (use_hash_p or self.ly () == open (ly_file).read ()):
594                         # TODO: something smart with target formats
595                         # (ps, png) and m/ctimes
596                         return None
597                 return self
598         
599         def png_is_outdated (self):
600                 base = self.basename ()
601                 ok = self.ly_is_outdated ()
602                 if format == HTML or format == TEXINFO:
603                         ok = ok and (os.path.exists (base + '.png')
604                                      or glob.glob (base + '-page*.png'))
605                 return not ok
606         
607         def filter_text (self):
608                 code  = self.substring ('code')
609                 s = run_filter (code)
610                 d = {'code' : s,
611                      'options': self.match.group ('options')
612                      }
613                 # TODO
614                 return output[self.format][FILTER] % d
615         
616         def replacement_text (self):
617                 func = Lilypond_snippet.__dict__ ['output_' + self.format]
618                 return func (self)
619         
620         def get_images (self):
621                 base = self.basename ()
622                 # URGUGHUGHUGUGHU
623                 single = '%(base)s.png' % vars ()
624                 multiple = '%(base)s-page1.png' % vars ()
625                 images = (single,)
626                 if os.path.exists (multiple) \
627                    and (not os.path.exists (single)\
628                         or (os.stat (multiple)[stat.ST_MTIME] \
629                             > os.stat (single)[stat.ST_MTIME])):
630                         images = glob.glob ('%(base)s-page*.png' % vars ())
631                 return images
632                 
633         def output_html (self):
634                 str = ''
635                 base = self.basename ()
636                 if format == HTML:
637                         str += self.output_print_filename (HTML)
638                         if VERBATIM in self.options:
639                                 verb = verbatim_html (self.substring ('code'))
640                                 str += write (output[HTML][VERBATIM] % vars ())
641                         if QUOTE in self.options:
642                                 str = output[HTML][QUOTE] % vars ()
643
644                 str += output[HTML][BEFORE] % vars ()
645                 for image in self.get_images ():
646                         base, ext = os.path.splitext (image)
647                         str += output[HTML][OUTPUT] % vars ()
648                 str += output[HTML][AFTER] % vars ()
649                 return str
650
651         def output_info (self):
652                 str = self.output_print_filename (HTML)
653                 str = output[TEXINFO][BEFORE] % vars ()
654                 for image in self.get_images ():
655                         base, ext = os.path.splitext (image)
656                         
657                         # URG, makeinfo implicitely prepends dot to ext
658                         # specifying no extension is most robust
659                         ext = ''
660                         str += output[TEXINFO][OUTPUT] % vars ()
661                 str += output[TEXINFO][AFTER] % vars ()
662                 return str
663
664         def output_latex (self):
665                 str = ''
666                 base = self.basename ()
667                 if format == LATEX:
668                         str += self.output_print_filename (LATEX)
669                         if  VERBATIM in self.options:
670                                 verb = self.substring ('code')
671                                 str += (output[LATEX][VERBATIM] % vars ())
672                         if QUOTE in self.options:
673                                 str = output[LATEX][QUOTE] % vars ()
674
675                 str +=  (output[LATEX][BEFORE]
676                          + (output[LATEX][OUTPUT] % vars ())
677                          + output[LATEX][AFTER])
678                 return str
679
680         def output_print_filename (self,format):
681                 str = ''
682                 if  PRINTFILENAME in self.options:
683                         base = self.basename ()
684                         filename = self.substring ('filename')
685                         str = output[format][PRINTFILENAME] % vars ()
686                 return str
687
688         def output_texinfo (self):
689                 str = ''
690                 # self.output_print_filename (TEXINFO)
691                 str += ('@html\n' + self.output_print_filename (HTML)
692                         + '\n@end html\n')
693                 str += ('@tex\n' + self.output_print_filename (LATEX)
694                         + '\n@end tex\n')
695                 base = self.basename ()
696                 if TEXIDOC in self.options:
697                         texidoc = base + '.texidoc'
698                         if os.path.exists (texidoc):
699                                 str += '@include %(texidoc)s\n\n' % vars ()
700
701                 if VERBATIM in self.options:
702                         verb = verbatim_texinfo (self.substring ('code'))
703                         str +=  (output[TEXINFO][VERBATIM] % vars ())
704
705                 str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
706                 str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
707                 str += ('@html\n' + self.output_html () + '\n@end html\n')
708
709                 if QUOTE in self.options:
710                         str = output[TEXINFO][QUOTE] % vars ()
711
712                 # need par after image
713                 str += '\n'
714
715                 return str
716
717 class Lilypond_file_snippet (Lilypond_snippet):
718         def ly (self):
719                 name = self.substring ('filename')
720                 return '\\renameinput \"%s\"\n%s' % (name, open (find_file (name)).read ())
721                         
722 snippet_type_to_class = {
723         'lilypond_file' : Lilypond_file_snippet,
724         'lilypond_block' : Lilypond_snippet,
725         'lilypond' : Lilypond_snippet,
726         'include' : Include_snippet,
727         }
728
729 def find_toplevel_snippets (s, types):
730         res = {}
731         for i in types:
732                 res[i] = ly.re.compile (snippet_res[format][i])
733
734         snippets = []
735         index = 0
736         ##  found = dict (map (lambda x: (x, None), types))
737         ## urg python2.1
738         found = {}
739         map (lambda x, f=found: f.setdefault (x, None), types)
740
741         # We want to search for multiple regexes, without searching
742         # the string multiple times for one regex.
743         # Hence, we use earlier results to limit the string portion
744         # where we search.
745         # Since every part of the string is traversed at most once for
746         # every type of snippet, this is linear.
747
748         while 1:
749                 first = None
750                 endex = 1 << 30
751                 for type in types:
752                         if not found[type] or found[type][0] < index:
753                                 found[type] = None
754                                 m = res[type].search (s[index:endex])
755                                 if not m:
756                                         continue
757
758                                 cl = Snippet
759                                 if snippet_type_to_class.has_key (type):
760                                         cl = snippet_type_to_class[type]
761                                 snip = cl (type, m, format)
762                                 start = index + m.start (0)
763                                 found[type] = (start, snip)
764
765                         if found[type] \
766                            and (not first or found[type][0] < found[first][0]):
767                                 first = type
768
769                                 # FIXME.
770
771                                 # Limiting the search space is a cute
772                                 # idea, but this *requires* to search
773                                 # for possible containing blocks
774                                 # first, at least long as we do not
775                                 # search for the start of blocks, but
776                                 # always/directly for the entire
777                                 # @block ... @end block.
778                                 
779                                 endex = found[first][0]
780
781                 if not first:
782                         snippets.append (Substring (s, index, len (s)))
783                         break
784
785                 (start , snip) = found[first]
786                 snippets.append (Substring (s, index, start))
787                 snippets.append (snip)
788                 found[first] = None
789                 index = start + len (snip.match.group (0))
790
791         return snippets
792
793 def filter_pipe (input, cmd):
794         if verbose_p:
795                 ly.progress (_ ("Opening filter `%s\'") % cmd)
796                 
797         stdin, stdout, stderr = os.popen3 (cmd)
798         stdin.write (input)
799         status = stdin.close ()
800
801         if not status:
802                 status = 0
803                 output = stdout.read ()
804                 status = stdout.close ()
805                 error = stderr.read ()
806                 
807         if not status:
808                 status = 0
809         signal = 0x0f & status
810         if status or (not output and error):
811                 exit_status = status >> 8
812                 ly.error (_ ("`%s\' failed (%d)") % (cmd, exit_status))
813                 ly.error (_ ("The error log is as follows:"))
814                 sys.stderr.write (error)
815                 sys.stderr.write (stderr.read ())
816                 ly.exit (status)
817         
818         if verbose_p:
819                 ly.progress ('\n')
820
821         return output
822         
823 def run_filter (s):
824         return filter_pipe (s, filter_cmd)
825
826 def is_derived_class (cl,  baseclass):
827         if cl == baseclass:
828                 return 1
829         for b in cl.__bases__:
830                 if is_derived_class (b, baseclass):
831                         return 1
832         return 0
833
834
835 def process_snippets (cmd, ly_snippets, png_snippets):
836         ly_names = filter (lambda x: x, map (Lilypond_snippet.basename, ly_snippets))
837         png_names = filter (lambda x: x, map (Lilypond_snippet.basename, png_snippets))
838         
839         if ly_names:
840                 ly.system (string.join ([cmd] + ly_names), progress_p = 1)
841
842         if format == HTML or format == TEXINFO:
843                 for i in png_names:
844                         if not os.path.exists (i + '.eps') and os.path.exists (i + '.tex'):
845                                 to_eps (i)
846                                 ly.make_ps_images (i + '.eps', resolution=110)
847                                 
848 #                       elif os.path.exists (i + '.ps'):
849 #                               ly.make_ps_images (i + '.ps', resolution=110)
850
851
852 LATEX_DOCUMENT = r'''
853 %(preamble)s
854 \begin{document}
855 \typeout{textwidth=\the\textwidth}
856 \typeout{columnsep=\the\columnsep}
857 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
858 \end{document}
859 '''
860 #need anything else besides textwidth?
861 def get_latex_textwidth (source):
862         m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
863         preamble = source[:m.start (0)]
864         latex_document = LATEX_DOCUMENT % vars ()
865         parameter_string = filter_pipe (latex_document, latex_filter_cmd)
866
867         columns = 0
868         m = re.search ('columns=([0-9.]*)', parameter_string)
869         if m:
870                 columns = string.atoi (m.group (1))
871
872         columnsep = 0
873         m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
874         if m:
875                 columnsep = string.atof (m.group (1))
876
877         textwidth = 0
878         m = re.search('textwidth=([0-9.]*)pt', parameter_string)
879         if m:
880                 textwidth = string.atof (m.group (1))
881                 if columns:
882                         textwidth = (textwidth - columnsep) / columns
883
884         return textwidth
885
886 ext2format = {
887         '.html' : HTML,
888         '.itely' : TEXINFO,
889         '.lytex' : LATEX,
890         '.tely' : TEXINFO,
891         '.tex': LATEX,
892         '.texi' : TEXINFO,
893         '.texinfo' : TEXINFO,
894         '.xml' : HTML,
895         }
896                                
897 format2ext = {
898         HTML: '.html',
899         #TEXINFO: '.texinfo',
900         TEXINFO: '.texi',
901         LATEX: '.tex',
902         }
903         
904 def do_file (input_filename):
905         #ugh
906         global format
907         if not format:
908                 e = os.path.splitext (input_filename)[1]
909                 if e in ext2format.keys ():
910                         #FIXME
911                         format = ext2format[e]
912                 else:
913                         ly.error (_ ("cannot determine format for: %s" \
914                                      % input_filename))
915
916         if not input_filename or input_filename == '-':
917                 in_handle = sys.stdin
918                 input_fullname = '<stdin>'
919         else:
920                 if os.path.exists (input_filename):
921                         input_fullname = input_filename
922                 elif format == LATEX:
923                         # urg python interface to libkpathsea?
924                         input_fullname = ly.read_pipe ('kpsewhich '
925                                                        + input_filename)[:-1]
926                 else:
927                         input_fullname = find_file (input_filename)
928                 in_handle = open (input_fullname)
929                 
930         if input_filename == '-':
931                 input_base = 'stdin'
932         else:
933                 input_base = os.path.basename \
934                              (os.path.splitext (input_filename)[0])
935
936         # only default to stdout when filtering 
937         if output_name == '-' or (not output_name and filter_cmd):
938                 output_filename = '-'
939                 output_file = sys.stdout
940         else:
941                 if not output_name:
942                         output_filename = input_base + format2ext[format]
943                 else:
944                         if not os.path.isdir (output_name):
945                                 os.mkdir (output_name, 0777)
946                         output_filename = (output_name
947                                            + '/' + input_base
948                                            + format2ext[format])
949
950
951                 if (os.path.exists (input_filename) and 
952                     os.path.exists (output_filename) and 
953                     os.path.samefile (output_filename, input_fullname)):
954                         ly.error (_("Output would overwrite input file; use --output."))
955                         sys.exit (2)
956
957                 output_file = open (output_filename, 'w')
958                 if output_name:
959                         os.chdir (output_name)
960
961         ly.progress (_ ("Reading %s...") % input_fullname)
962         source = in_handle.read ()
963         ly.progress ('\n')
964
965         # FIXME: containing blocks must be first, see find_toplevel_snippets
966         snippet_types = (
967                 'multiline_comment',
968                 'verbatim',
969                 'lilypond_block',
970 #               'verb',
971                 'singleline_comment',
972                 'lilypond_file',
973                 'include',
974                 'lilypond', )
975         ly.progress (_ ("Dissecting..."))
976         chunks = find_toplevel_snippets (source, snippet_types)
977         ly.progress ('\n')
978
979         global default_ly_options
980         textwidth = 0
981         if not default_ly_options.has_key (LINEWIDTH):
982                 if format == LATEX:
983                         textwidth = get_latex_textwidth (source)
984                         default_ly_options[LINEWIDTH] = '''%.0f\\pt''' \
985                                                         % textwidth
986                 elif format == TEXINFO:
987                         for (k, v) in texinfo_linewidths.items ():
988                                 # FIXME: @paper is usually not in chunk #0:
989                                 #        \input texinfo @c -*-texinfo-*-
990                                 # bluntly search first K of source
991                                 # s = chunks[0].replacement_text ()
992                                 if re.search (k, source[:1024]):
993                                         default_ly_options[LINEWIDTH] = v
994                                         break
995
996         if filter_cmd:
997                 output_file.writelines ([c.filter_text () for c in chunks])
998                 
999                 
1000         elif process_cmd:
1001                 ly_outdated = filter (lambda x: is_derived_class (x.__class__, Lilypond_snippet) \
1002                                    and x.ly_is_outdated (), chunks)
1003                 png_outdated = filter (lambda x: is_derived_class (x.__class__, Lilypond_snippet) \
1004                                    and x.png_is_outdated (), chunks)
1005                 
1006                 ly.progress (_ ("Writing snippets..."))
1007                 map (Lilypond_snippet.write_ly, ly_outdated)
1008                 ly.progress ('\n')
1009
1010                 if ly_outdated:
1011                         ly.progress (_ ("Processing..."))
1012                         process_snippets (process_cmd, ly_outdated, png_outdated)
1013                 else:
1014                         ly.progress (_ ("All snippets are up to date..."))
1015                 ly.progress ('\n')
1016
1017                 ly.progress (_ ("Compiling %s...") % output_filename)
1018                 output_file.writelines ([s.replacement_text () \
1019                                          for s in chunks])
1020                 ly.progress ('\n')
1021
1022         def process_include (snippet):
1023                 os.chdir (original_dir)
1024                 name = snippet.substring ('filename')
1025                 ly.progress (_ ('Processing include: %s') % name)
1026                 ly.progress ('\n')
1027                 do_file (name)
1028                 
1029         map (process_include,
1030              filter (lambda x: is_derived_class (x.__class__, Include_snippet), chunks))
1031
1032 def do_options ():
1033         global format, output_name
1034         global filter_cmd, process_cmd, verbose_p
1035         
1036         (sh, long) = ly.getopt_args (option_definitions)
1037         try:
1038                 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1039         except getopt.error, s:
1040                 sys.stderr.write ('\n')
1041                 ly.error (_ ("getopt says: `%s\'" % s))
1042                 sys.stderr.write ('\n')
1043                 ly.help ()
1044                 ly.exit (2)
1045
1046         for opt in options:
1047                 o = opt[0]
1048                 a = opt[1]
1049
1050                 if 0:
1051                         pass
1052                 elif o == '--filter' or o == '-F':
1053                         filter_cmd = a
1054                         process_cmd = 0
1055                 elif o == '--format' or o == '-f':
1056                         format = a
1057                         if a == 'texi-html' or a == 'texi':
1058                                 format = TEXINFO
1059                 elif o == '--help' or o == '-h':
1060                         ly.help ()
1061                         sys.exit (0)
1062                 elif o == '--include' or o == '-I':
1063                         include_path.append (os.path.join (original_dir,
1064                                                            ly.abspath (a)))
1065                 elif o == '--output' or o == '-o':
1066                         output_name = a
1067                 elif o == '--outdir':
1068                         output_name = a
1069                 elif o == '--process' or o == '-P':
1070                         process_cmd = a
1071                         filter_cmd = 0
1072                 elif o == '--version' or o == '-v':
1073                         ly.identify (sys.stdout)
1074                         sys.exit (0)
1075                 elif o == '--verbose' or o == '-V':
1076                         verbose_p = 1
1077                 elif o == '--warranty' or o == '-w':
1078                         if 1 or status:
1079                                 ly.warranty ()
1080                         sys.exit (0)
1081         return files
1082
1083 def main ():
1084         files = do_options ()
1085         global process_cmd
1086         if process_cmd == '':
1087                 process_cmd = lilypond_binary + " -f tex "
1088         
1089         if process_cmd:
1090                 process_cmd += string.join ([(' -I %s' % p)
1091                                              for p in include_path])
1092
1093         ly.identify (sys.stderr)
1094         ly.setup_environment ()
1095         if files:
1096                 do_file (files[0])
1097
1098 if __name__ == '__main__':
1099         main ()