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