]> git.donarmstrong.com Git - lilypond.git/blob - scripts/lilypond-book.py
The grand \paper -> \layout, \bookpaper -> \paper renaming.
[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 EXAMPLEINDENT = 'exampleindent'
122 FILTER = 'filter'
123 FRAGMENT = 'fragment'
124 HTML = 'html'
125 INDENT = 'indent'
126 LATEX = 'latex'
127 LAYOUT = 'layout'
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         PAPER: {
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         LAYOUT: {
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 \paper {
326   #(define dump-extents #t)
327   %(paper_string)s
328 }
329 \layout { %(layout_string)s
330 }
331
332 """
333
334 FRAGMENT_LY = r'''
335     %(notes_string)s{
336         %(code)s    }
337 '''
338 FULL_LY = '%(code)s'
339
340 texinfo_linewidths = {
341         '@afourpaper': '160 \\mm',
342         '@afourwide': '6.5 \\in',
343         '@afourlatex': '150 \\mm',
344         '@smallbook': '5 \\in' ,
345         '@letterpaper': '6\\in',
346         }
347
348 def classic_lilypond_book_compatibility (o):
349         if o == 'singleline':
350                 return RAGGEDRIGHT
351         m = re.search ('relative\s*([-0-9])', o)
352         if m:
353                 return 'relative=%s' % m.group (1)
354         m = re.match ('([0-9]+)pt', o)
355         if m:
356                 return 'staffsize=%s' % m.group (1)
357         m = re.match ('indent=([-.0-9]+)(cm|in|mm|pt|staffspace)', o)
358         if m:
359                 f = float (m.group (1))
360                 return 'indent=%f\\%s' % (f, m.group (2))
361         m = re.match ('linewidth=([-.0-9]+)(cm|in|mm|pt|staffspace)', o)
362         if m:
363                 f = float (m.group (1))
364                 return 'linewidth=%f\\%s' % (f, m.group (2))
365         return None
366
367 def compose_ly (code, options):
368         #Hmm
369         for i in default_ly_options.keys ():
370                 if i not in options:
371                         options.append (i)
372         
373         #Hmm
374         if QUOTE in options and LINEWIDTH in options:
375                 options.remove (LINEWIDTH)
376
377         if FRAGMENT in options:
378                 if RAGGEDRIGHT not in options:
379                         options.append (RAGGEDRIGHT)
380                 body = FRAGMENT_LY
381         else:
382                 body = FULL_LY
383
384         # defaults
385         relative = 1
386         staffsize = 16
387         override = {}
388         #FIXME: where to get sane value for exampleindent?
389         override[EXAMPLEINDENT] = r'9.0 \mm'
390         override[LINEWIDTH] = None
391         override.update (default_ly_options)
392
393         option_string = string.join (options, ',')
394
395         options_dict = {}
396         option_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
397         for a in option_types:
398                 options_dict[a] = []
399                 
400         for i in options:
401                 c = classic_lilypond_book_compatibility (i)
402                 if c:
403                         ly.warning (_ ("deprecated ly-option used: %s" % i))
404                         ly.warning (_ ("compatibility mode translation: %s" \
405                                        % c))
406                         i = c
407                 
408                 if string.find (i, '=') > 0:
409                         key, value = string.split (i, '=')
410                         override[key] = value
411                 else:
412                         key = i
413                         if not override.has_key (i):
414                                 override[i] = None
415
416                 found = 0
417                 for type in option_types:
418                         if ly_options[type].has_key (key):
419                                 
420                                 options_dict[type].append (ly_options[type][key])
421                                 found = 1
422                                 break
423
424                 if not found and key not in (FRAGMENT, NOFRAGMENT, PRINTFILENAME,
425                                              RELATIVE, VERBATIM, TEXIDOC):
426                         ly.warning (_("ignoring unknown ly option: %s") % i)
427
428         #URGS
429         if RELATIVE in override.keys () and override[RELATIVE]:
430                 relative = string.atoi (override[RELATIVE])
431
432         relative_quotes = ''
433
434         # 1 = central C
435         if relative < 0:
436                 relative_quotes += ',' * (- relative)
437         elif relative > 0:
438                 relative_quotes += "'" * relative
439                 
440         program_name = __main__.program_name
441
442         paper_string = string.join (options_dict[PAPER], '\n    ') % override
443         layout_string = string.join (options_dict[LAYOUT], '\n    ') % override
444         notes_string = string.join (options_dict[NOTES], '\n    ') % vars ()
445         preamble_string = string.join (options_dict[PREAMBLE], '\n    ') % override
446         return (PREAMBLE_LY + body) % vars ()
447
448
449 # BARF
450 # use lilypond for latex (.lytex) books,
451 # and lilypond --preview for html, texinfo books?
452 def to_eps (file):
453         cmd = r'latex "\nonstopmode \input %s"' % file
454         # Ugh.  (La)TeX writes progress and error messages on stdout
455         # Redirect to stderr
456         cmd = '(( %s  >&2 ) >&- )' % cmd
457         ly.system (cmd)
458         ly.system ('dvips -Ppdf -u+ec-mftrace.map -u+lilypond.map -E -o %s.eps %s' \
459                    % (file, file))
460
461
462         # check if it really is EPS.
463         # Otherwise music glyphs disappear from 2nd and following pages.
464
465         # TODO: should run dvips -pp -E per page, then we get proper
466         # cropping as well.
467         
468         f = open ('%s.eps' % file)
469         for x in range(0,10) :
470                 if re.search ("^%%Pages: ", f.readline ()):
471
472                         # make non EPS.
473                         ly.system ('dvips -Ppdf -u+ec-mftrace.map -u+lilypond.map -o %s.eps %s' \
474                                    % (file, file))
475                         break
476         
477
478 def find_file (name):
479         for i in include_path:
480                 full = os.path.join (i, name)
481                 if os.path.exists (full):
482                         return full
483         ly.error (_ ('file not found: %s') % name + '\n')
484         ly.exit (1)
485         return ''
486         
487 def verbatim_html (s):
488         return re.sub ('>', '&gt;',
489                        re.sub ('<', '&lt;',
490                                re.sub ('&', '&amp;', s)))
491
492 def verbatim_texinfo (s):
493         return re.sub ('{', '@{',
494                        re.sub ('}', '@}',
495                                re.sub ('@', '@@', s)))
496
497 def split_options (option_string):
498         return re.split (format_res[format]['option-sep'], option_string)
499
500
501 class Chunk:
502         def replacement_text (self):
503                 return ''
504         
505         def filter_text (self):
506                 return self.replacement_text ()
507
508
509         def ly_is_outdated (self):
510                 return 0
511
512         def png_is_outdated (self):
513                 return 0
514
515 class Substring (Chunk):
516         def __init__ (self, source, start, end):
517                 self.source = source
518                 self.start = start
519                 self.end = end
520
521         def replacement_text (self):
522                 return self.source [self.start:self.end]
523         
524 class Snippet (Chunk):
525         def __init__ (self, type, match, format):
526                 self.type = type
527                 self.match = match
528                 self.hash = 0
529                 self.options = []
530                 self.format = format
531
532         def replacement_text (self):
533                 return self.match.group (0)
534         
535         def substring (self, s):
536                 return self.match.group (s)
537
538         def __repr__ (self):
539                 return `self.__class__`  +  " type =  " + self.type
540
541 class Include_snippet (Snippet):
542         def processed_filename (self):
543                 f = self.substring ('filename')
544                 return os.path.splitext (f)[0] + format2ext[format]
545
546         def replacement_text (self):
547                 s = self.match.group (0)
548                 f = self.substring ('filename')
549         
550                 return re.sub (f, self.processed_filename (), s)
551
552 class Lilypond_snippet (Snippet):
553         def __init__ (self, type, match, format):
554                 Snippet.__init__ (self, type, match, format)
555                 os = match.group ('options')
556                 if os:
557                         self.options = split_options (os)
558
559         def ly (self):
560                 return self.substring ('code')
561                 
562         def full_ly (self):
563                 s = self.ly ()
564                 if s:
565                         return compose_ly (s, self.options)
566                 return ''
567
568         # todo: use md5?
569         def get_hash (self):
570                 if not self.hash:
571                         self.hash = abs (hash (self.full_ly ()))
572                 return self.hash
573
574         def basename (self):
575                 if use_hash_p:
576                         return 'lily-%d' % self.get_hash ()
577                 raise 'to be done'
578
579         def write_ly (self):
580                 outf = open (self.basename () + '.ly', 'w')
581                 outf.write (self.full_ly ())
582                 
583                 open (self.basename() + '.txt', 'w').write("image of music")
584                 
585
586         def ly_is_outdated (self):
587                 base = self.basename ()
588
589                 tex_file = '%s.tex' % base
590                 ly_file = '%s.ly' % base
591                 ok = os.path.exists (ly_file) and os.path.exists (tex_file)\
592                      and os.stat (tex_file)[stat.ST_SIZE] \
593                      and open (tex_file).readlines ()[-1][1:-1] \
594                      == 'lilypondend'
595                         
596                 if ok and (use_hash_p or self.ly () == open (ly_file).read ()):
597                         # TODO: something smart with target formats
598                         # (ps, png) and m/ctimes
599                         return None
600                 return self
601         
602         def png_is_outdated (self):
603                 base = self.basename ()
604                 ok = self.ly_is_outdated ()
605                 if format == HTML or format == TEXINFO:
606                         ok = ok and (os.path.exists (base + '.png')
607                                      or glob.glob (base + '-page*.png'))
608                 return not ok
609         
610         def filter_text (self):
611                 code  = self.substring ('code')
612                 s = run_filter (code)
613                 d = {'code' : s,
614                      'options': self.match.group ('options')
615                      }
616                 # TODO
617                 return output[self.format][FILTER] % d
618         
619         def replacement_text (self):
620                 func = Lilypond_snippet.__dict__ ['output_' + self.format]
621                 return func (self)
622         
623         def get_images (self):
624                 base = self.basename ()
625                 # URGUGHUGHUGUGHU
626                 single = '%(base)s.png' % vars ()
627                 multiple = '%(base)s-page1.png' % vars ()
628                 images = (single,)
629                 if os.path.exists (multiple) \
630                    and (not os.path.exists (single)\
631                         or (os.stat (multiple)[stat.ST_MTIME] \
632                             > os.stat (single)[stat.ST_MTIME])):
633                         images = glob.glob ('%(base)s-page*.png' % vars ())
634                 return images
635                 
636         def output_html (self):
637                 str = ''
638                 base = self.basename ()
639                 if format == HTML:
640                         str += self.output_print_filename (HTML)
641                         if VERBATIM in self.options:
642                                 verb = verbatim_html (self.substring ('code'))
643                                 str += write (output[HTML][VERBATIM] % vars ())
644                         if QUOTE in self.options:
645                                 str = output[HTML][QUOTE] % vars ()
646
647                 str += output[HTML][BEFORE] % vars ()
648                 for image in self.get_images ():
649                         base, ext = os.path.splitext (image)
650                         str += output[HTML][OUTPUT] % vars ()
651                 str += output[HTML][AFTER] % vars ()
652                 return str
653
654         def output_info (self):
655                 str = self.output_print_filename (HTML)
656                 str = output[TEXINFO][BEFORE] % vars ()
657                 for image in self.get_images ():
658                         base, ext = os.path.splitext (image)
659                         
660                         # URG, makeinfo implicitely prepends dot to ext
661                         # specifying no extension is most robust
662                         ext = ''
663                         str += output[TEXINFO][OUTPUT] % vars ()
664                 str += output[TEXINFO][AFTER] % vars ()
665                 return str
666
667         def output_latex (self):
668                 str = ''
669                 base = self.basename ()
670                 if format == LATEX:
671                         str += self.output_print_filename (LATEX)
672                         if  VERBATIM in self.options:
673                                 verb = self.substring ('code')
674                                 str += (output[LATEX][VERBATIM] % vars ())
675                         if QUOTE in self.options:
676                                 str = output[LATEX][QUOTE] % vars ()
677
678                 str +=  (output[LATEX][BEFORE]
679                          + (output[LATEX][OUTPUT] % vars ())
680                          + output[LATEX][AFTER])
681                 return str
682
683         def output_print_filename (self,format):
684                 str = ''
685                 if  PRINTFILENAME in self.options:
686                         base = self.basename ()
687                         filename = self.substring ('filename')
688                         str = output[format][PRINTFILENAME] % vars ()
689                 return str
690
691         def output_texinfo (self):
692                 str = ''
693                 # self.output_print_filename (TEXINFO)
694                 str += ('@html\n' + self.output_print_filename (HTML)
695                         + '\n@end html\n')
696                 str += ('@tex\n' + self.output_print_filename (LATEX)
697                         + '\n@end tex\n')
698                 base = self.basename ()
699                 if TEXIDOC in self.options:
700                         texidoc = base + '.texidoc'
701                         if os.path.exists (texidoc):
702                                 str += '@include %(texidoc)s\n\n' % vars ()
703
704                 if VERBATIM in self.options:
705                         verb = verbatim_texinfo (self.substring ('code'))
706                         str +=  (output[TEXINFO][VERBATIM] % vars ())
707
708                 str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
709                 str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
710                 str += ('@html\n' + self.output_html () + '\n@end html\n')
711
712                 if QUOTE in self.options:
713                         str = output[TEXINFO][QUOTE] % vars ()
714
715                 # need par after image
716                 str += '\n'
717
718                 return str
719
720 class Lilypond_file_snippet (Lilypond_snippet):
721         def ly (self):
722                 name = self.substring ('filename')
723                 return '\\renameinput \"%s\"\n%s' % (name, open (find_file (name)).read ())
724                         
725 snippet_type_to_class = {
726         'lilypond_file' : Lilypond_file_snippet,
727         'lilypond_block' : Lilypond_snippet,
728         'lilypond' : Lilypond_snippet,
729         'include' : Include_snippet,
730         }
731
732 def find_toplevel_snippets (s, types):
733         res = {}
734         for i in types:
735                 res[i] = ly.re.compile (snippet_res[format][i])
736
737         snippets = []
738         index = 0
739         ##  found = dict (map (lambda x: (x, None), types))
740         ## urg python2.1
741         found = {}
742         map (lambda x, f=found: f.setdefault (x, None), types)
743
744         # We want to search for multiple regexes, without searching
745         # the string multiple times for one regex.
746         # Hence, we use earlier results to limit the string portion
747         # where we search.
748         # Since every part of the string is traversed at most once for
749         # every type of snippet, this is linear.
750
751         while 1:
752                 first = None
753                 endex = 1 << 30
754                 for type in types:
755                         if not found[type] or found[type][0] < index:
756                                 found[type] = None
757                                 m = res[type].search (s[index:endex])
758                                 if not m:
759                                         continue
760
761                                 cl = Snippet
762                                 if snippet_type_to_class.has_key (type):
763                                         cl = snippet_type_to_class[type]
764                                 snip = cl (type, m, format)
765                                 start = index + m.start (0)
766                                 found[type] = (start, snip)
767
768                         if found[type] \
769                            and (not first or found[type][0] < found[first][0]):
770                                 first = type
771
772                                 # FIXME.
773
774                                 # Limiting the search space is a cute
775                                 # idea, but this *requires* to search
776                                 # for possible containing blocks
777                                 # first, at least long as we do not
778                                 # search for the start of blocks, but
779                                 # always/directly for the entire
780                                 # @block ... @end block.
781                                 
782                                 endex = found[first][0]
783
784                 if not first:
785                         snippets.append (Substring (s, index, len (s)))
786                         break
787
788                 (start , snip) = found[first]
789                 snippets.append (Substring (s, index, start))
790                 snippets.append (snip)
791                 found[first] = None
792                 index = start + len (snip.match.group (0))
793
794         return snippets
795
796 def filter_pipe (input, cmd):
797         if verbose_p:
798                 ly.progress (_ ("Opening filter `%s\'") % cmd)
799                 
800         stdin, stdout, stderr = os.popen3 (cmd)
801         stdin.write (input)
802         status = stdin.close ()
803
804         if not status:
805                 status = 0
806                 output = stdout.read ()
807                 status = stdout.close ()
808                 error = stderr.read ()
809                 
810         if not status:
811                 status = 0
812         signal = 0x0f & status
813         if status or (not output and error):
814                 exit_status = status >> 8
815                 ly.error (_ ("`%s\' failed (%d)") % (cmd, exit_status))
816                 ly.error (_ ("The error log is as follows:"))
817                 sys.stderr.write (error)
818                 sys.stderr.write (stderr.read ())
819                 ly.exit (status)
820         
821         if verbose_p:
822                 ly.progress ('\n')
823
824         return output
825         
826 def run_filter (s):
827         return filter_pipe (s, filter_cmd)
828
829 def is_derived_class (cl,  baseclass):
830         if cl == baseclass:
831                 return 1
832         for b in cl.__bases__:
833                 if is_derived_class (b, baseclass):
834                         return 1
835         return 0
836
837
838 def process_snippets (cmd, ly_snippets, png_snippets):
839         ly_names = filter (lambda x: x, map (Lilypond_snippet.basename, ly_snippets))
840         png_names = filter (lambda x: x, map (Lilypond_snippet.basename, png_snippets))
841
842         
843         status = 0
844         if ly_names:
845                 status = ly.system (string.join ([cmd] + ly_names),
846                                     ignore_error = 1, progress_p = 1)
847
848
849         if status:
850                 ly.error( 'Process %s exited unsuccessfully.' % cmd )
851                 raise Compile_error
852                 
853         if format == HTML or format == TEXINFO:
854                 for i in png_names:
855                         if not os.path.exists (i + '.eps') and os.path.exists (i + '.tex'):
856                                 to_eps (i)
857                                 ly.make_ps_images (i + '.eps', resolution=110)
858                                 
859 #                       elif os.path.exists (i + '.ps'):
860 #                               ly.make_ps_images (i + '.ps', resolution=110)
861
862
863 LATEX_DOCUMENT = r'''
864 %(preamble)s
865 \begin{document}
866 \typeout{textwidth=\the\textwidth}
867 \typeout{columnsep=\the\columnsep}
868 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
869 \end{document}
870 '''
871 #need anything else besides textwidth?
872 def get_latex_textwidth (source):
873         m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
874         preamble = source[:m.start (0)]
875         latex_document = LATEX_DOCUMENT % vars ()
876         parameter_string = filter_pipe (latex_document, latex_filter_cmd)
877
878         columns = 0
879         m = re.search ('columns=([0-9.]*)', parameter_string)
880         if m:
881                 columns = string.atoi (m.group (1))
882
883         columnsep = 0
884         m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
885         if m:
886                 columnsep = string.atof (m.group (1))
887
888         textwidth = 0
889         m = re.search('textwidth=([0-9.]*)pt', parameter_string)
890         if m:
891                 textwidth = string.atof (m.group (1))
892                 if columns:
893                         textwidth = (textwidth - columnsep) / columns
894
895         return textwidth
896
897 ext2format = {
898         '.html' : HTML,
899         '.itely' : TEXINFO,
900         '.latex' : LATEX,
901         '.lytex' : LATEX,
902         '.tely' : TEXINFO,
903         '.tex': LATEX,
904         '.texi' : TEXINFO,
905         '.texinfo' : TEXINFO,
906         '.xml' : HTML,
907         }
908                                
909 format2ext = {
910         HTML: '.html',
911         #TEXINFO: '.texinfo',
912         TEXINFO: '.texi',
913         LATEX: '.tex',
914         }
915         
916 class Compile_error:
917         pass
918
919 def do_process_cmd (chunks):
920         ly_outdated = filter (lambda x: is_derived_class (x.__class__, Lilypond_snippet) \
921                            and x.ly_is_outdated (), chunks)
922         png_outdated = filter (lambda x: is_derived_class (x.__class__, Lilypond_snippet) \
923                            and x.png_is_outdated (), chunks)
924
925         ly.progress (_ ("Writing snippets..."))
926         map (Lilypond_snippet.write_ly, ly_outdated)
927         ly.progress ('\n')
928
929         if ly_outdated:
930                 ly.progress (_ ("Processing..."))
931                 process_snippets (process_cmd, ly_outdated, png_outdated)
932         else:
933                 ly.progress (_ ("All snippets are up to date..."))
934         ly.progress ('\n')
935
936
937 def do_file (input_filename):
938         #ugh
939         global format
940         if not format:
941                 e = os.path.splitext (input_filename)[1]
942                 if e in ext2format.keys ():
943                         #FIXME
944                         format = ext2format[e]
945                 else:
946                         ly.error (_ ("cannot determine format for: %s" \
947                                      % input_filename))
948                         ly.exit (1) 
949                 
950         if not input_filename or input_filename == '-':
951                 in_handle = sys.stdin
952                 input_fullname = '<stdin>'
953         else:
954                 if os.path.exists (input_filename):
955                         input_fullname = input_filename
956                 elif format == LATEX:
957                         # urg python interface to libkpathsea?
958                         input_fullname = ly.read_pipe ('kpsewhich '
959                                                        + input_filename)[:-1]
960                 else:
961                         input_fullname = find_file (input_filename)
962                 in_handle = open (input_fullname)
963                 
964         if input_filename == '-':
965                 input_base = 'stdin'
966         else:
967                 input_base = os.path.basename \
968                              (os.path.splitext (input_filename)[0])
969
970         # only default to stdout when filtering 
971         if output_name == '-' or (not output_name and filter_cmd):
972                 output_filename = '-'
973                 output_file = sys.stdout
974         else:
975                 if not output_name:
976                         output_filename = input_base + format2ext[format]
977                 else:
978                         if not os.path.isdir (output_name):
979                                 os.mkdir (output_name, 0777)
980                         output_filename = (output_name
981                                            + '/' + input_base
982                                            + format2ext[format])
983
984
985                 if (os.path.exists (input_filename) and 
986                     os.path.exists (output_filename) and 
987                     os.path.samefile (output_filename, input_fullname)):
988                         ly.error (_("Output would overwrite input file; use --output."))
989                         ly.exit (2)
990
991                 output_file = open (output_filename, 'w')
992                 if output_name:
993                         os.chdir (output_name)
994         try:
995                 ly.progress (_ ("Reading %s...") % input_fullname)
996                 source = in_handle.read ()
997                 ly.progress ('\n')
998
999                 # FIXME: containing blocks must be first, see find_toplevel_snippets
1000                 snippet_types = (
1001                         'multiline_comment',
1002                         'verbatim',
1003                         'lilypond_block',
1004         #               'verb',
1005                         'singleline_comment',
1006                         'lilypond_file',
1007                         'include',
1008                         'lilypond', )
1009                 ly.progress (_ ("Dissecting..."))
1010                 chunks = find_toplevel_snippets (source, snippet_types)
1011                 ly.progress ('\n')
1012
1013                 global default_ly_options
1014                 textwidth = 0
1015                 if not default_ly_options.has_key (LINEWIDTH):
1016                         if format == LATEX:
1017                                 textwidth = get_latex_textwidth (source)
1018                                 default_ly_options[LINEWIDTH] = '''%.0f\\pt''' \
1019                                                                 % textwidth
1020                         elif format == TEXINFO:
1021                                 for (k, v) in texinfo_linewidths.items ():
1022                                         # FIXME: @layout is usually not in chunk #0:
1023                                         #        \input texinfo @c -*-texinfo-*-
1024                                         # bluntly search first K of source
1025                                         # s = chunks[0].replacement_text ()
1026                                         if re.search (k, source[:1024]):
1027                                                 default_ly_options[LINEWIDTH] = v
1028                                                 break
1029
1030                 if filter_cmd:
1031                         output_file.writelines ([c.filter_text () for c in chunks])
1032
1033
1034                 elif process_cmd:
1035                         do_process_cmd (chunks)
1036                         ly.progress (_ ("Compiling %s...") % output_filename)
1037                         output_file.writelines ([s.replacement_text () \
1038                                                  for s in chunks])
1039                         ly.progress ('\n')
1040
1041                 def process_include (snippet):
1042                         os.chdir (original_dir)
1043                         name = snippet.substring ('filename')
1044                         ly.progress (_ ('Processing include: %s') % name)
1045                         ly.progress ('\n')
1046                         do_file (name)
1047
1048                 map (process_include,
1049                      filter (lambda x: is_derived_class (x.__class__, Include_snippet), chunks))
1050         except Compile_error:
1051                 os.chdir (original_dir)
1052                 ly.progress (_('Removing `%s\'') % output_filename)
1053                 ly.progress ('\n')
1054                 
1055                 os.unlink (output_filename)
1056                 raise Compile_error
1057         
1058
1059 def do_options ():
1060         global format, output_name
1061         global filter_cmd, process_cmd, verbose_p
1062         
1063         (sh, long) = ly.getopt_args (option_definitions)
1064         try:
1065                 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1066         except getopt.error, s:
1067                 sys.stderr.write ('\n')
1068                 ly.error (_ ("getopt says: `%s\'" % s))
1069                 sys.stderr.write ('\n')
1070                 ly.help ()
1071                 ly.exit (2)
1072
1073         for opt in options:
1074                 o = opt[0]
1075                 a = opt[1]
1076
1077                 if 0:
1078                         pass
1079                 elif o == '--filter' or o == '-F':
1080                         filter_cmd = a
1081                         process_cmd = 0
1082                 elif o == '--format' or o == '-f':
1083                         format = a
1084                         if a == 'texi-html' or a == 'texi':
1085                                 format = TEXINFO
1086                 elif o == '--help' or o == '-h':
1087                         ly.help ()
1088                         sys.exit (0)
1089                 elif o == '--include' or o == '-I':
1090                         include_path.append (os.path.join (original_dir,
1091                                                            ly.abspath (a)))
1092                 elif o == '--output' or o == '-o':
1093                         output_name = a
1094                 elif o == '--outdir':
1095                         output_name = a
1096                 elif o == '--process' or o == '-P':
1097                         process_cmd = a
1098                         filter_cmd = 0
1099                 elif o == '--version' or o == '-v':
1100                         ly.identify (sys.stdout)
1101                         sys.exit (0)
1102                 elif o == '--verbose' or o == '-V':
1103                         verbose_p = 1
1104                 elif o == '--warranty' or o == '-w':
1105                         if 1 or status:
1106                                 ly.warranty ()
1107                         sys.exit (0)
1108         return files
1109
1110 def main ():
1111         files = do_options ()
1112         global process_cmd
1113         if process_cmd == '':
1114                 process_cmd = lilypond_binary + " -f tex "
1115         
1116         if process_cmd:
1117                 process_cmd += string.join ([(' -I %s' % p)
1118                                              for p in include_path])
1119
1120         ly.identify (sys.stderr)
1121         ly.setup_environment ()
1122         if files:
1123                 try:
1124                         do_file (files[0])
1125                 except Compile_error:
1126                         ly.exit (1)
1127                         
1128 if __name__ == '__main__':
1129         main ()