]> git.donarmstrong.com Git - lilypond.git/blob - scripts/lilypond-book.py
* scripts/lilypond-book.py (Snippet, Include_snippet)
[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 # (?x) -- ignore whitespace in patterns
152 no_match = 'a\ba'
153 snippet_res = {
154         HTML: {
155         'include':
156           no_match,
157         'lilypond':
158           r'''(?mx)
159             (?P<match>
160             <lilypond
161               ((?P<options>[^:]*):)
162               (?P<code>.*?)
163             />)''',
164         'lilypond_block':
165           r'''(?msx)
166             (?P<match>
167             <lilypond
168               (?P<options>[^>]+)?
169             >
170             (?P<code>.*?)
171             </lilypond>)''',
172         'lilypond_file':
173           r'''(?mx)
174             (?P<match>
175             <lilypondfile
176               (?P<options>[^>]+)?
177             >\s*
178               (?P<filename>[^<]+)\s*
179             </lilypondfile>)''',
180         'multiline_comment':
181           r'''(?smx)
182             (?P<match>
183             \s*(?!@c\s+)
184             (?P<code><!--\s.*?!-->)
185             \s)''',
186         'singleline_comment':
187           no_match,
188         'verb':
189           r'''(?x)
190             (?P<match>
191               (?P<code><pre>.*?</pre>))''',
192         'verbatim':
193           r'''(?x)
194             (?s)
195             (?P<match>
196               (?P<code><pre>\s.*?</pre>\s))''',
197         },
198
199         LATEX: {
200         'include':
201           r'''(?smx)
202             ^[^%\n]*?
203             (?P<match>
204             \\input\s*{
205               (?P<filename>\S+?)
206             })''',
207         'lilypond':
208           r'''(?smx)
209             ^[^%\n]*?
210             (?P<match>
211             \\lilypond\s*(
212             \[
213               (?P<options>.*?)
214             \])?\s*{
215               (?P<code>.*?)
216             })''',
217         'lilypond_block':
218           r'''(?smx)
219             ^[^%\n]*?
220             (?P<match>
221             \\begin\s*(
222             \[
223               (?P<options>.*?)
224             \])?\s*{lilypond}
225               (?P<code>.*?)
226             ^[^%\n]*?
227             \\end\s*{lilypond})''',
228         'lilypond_file':
229           r'''(?smx)
230             ^[^%\n]*?
231             (?P<match>
232             \\lilypondfile\s*(
233             \[
234               (?P<options>.*?)
235             \])?\s*\{
236               (?P<filename>\S+?)
237             })''',
238         'multiline_comment':
239           no_match,
240         'singleline_comment':
241           r'''(?mx)
242             ^.*?
243             (?P<match>
244               (?P<code>
245               %.*$\n+))''',
246         'verb':
247           r'''(?mx)
248             ^[^%\n]*?
249             (?P<match>
250               (?P<code>
251               \\verb(?P<del>.)
252                 .*?
253               (?P=del)))''',
254         'verbatim':
255           r'''(?msx)
256             ^[^%\n]*?
257             (?P<match>
258               (?P<code>
259               \\begin\s*{verbatim}
260                 .*?
261               \\end\s*{verbatim}))''',
262         },
263
264         TEXINFO: {
265         'include':
266           r'''(?mx)
267             ^(?P<match>
268             @include\s+
269               (?P<filename>\S+))''',
270         'lilypond':
271           r'''(?smx)
272             ^[^\n]*?(?!@c\s+)[^\n]*?
273             (?P<match>
274             @lilypond\s*(
275             \[
276               (?P<options>.*?)
277             \])?\s*{
278               (?P<code>.*?)
279             })''',
280         'lilypond_block':
281           r'''(?msx)
282             ^(?P<match>
283             @lilypond\s*(
284             \[
285               (?P<options>.*?)
286             \])?\s+?
287             ^(?P<code>.*?)
288             ^@end\s+lilypond)\s''',
289         'lilypond_file':
290           r'''(?mx)
291             ^(?P<match>
292             @lilypondfile\s*(
293             \[
294               (?P<options>.*?)
295             \])?\s*{
296               (?P<filename>\S+)
297             })''',
298         'multiline_comment':
299           r'''(?smx)
300             ^(?P<match>
301               (?P<code>
302               @ignore\s
303                 .*?
304               @end\s+ignore))\s''',
305         'singleline_comment':
306           r'''(?mx)
307             ^.*
308             (?P<match>
309               (?P<code>
310               @c([ \t][^\n]*|)\n))''',
311
312 # don't do this: fucks up with @code{@{}
313 #       'verb': r'''(?P<code>@code{.*?})''',
314         'verbatim':
315           r'''(?sx)
316             (?P<match>
317               (?P<code>
318               @example
319                 \s.*?
320               @end\s+example\s))''',
321         },
322 }
323
324 format_res = {
325         HTML: {
326         'option-sep': '\s*',
327         'intertext': r',?\s*intertext=\".*?\"',
328         },
329         LATEX: {
330         'intertext': r',?\s*intertext=\".*?\"',
331         'option-sep': ',\s*',
332         },
333         TEXINFO: {
334         'intertext': r',?\s*intertext=\".*?\"',
335         'option-sep': ',\s*',
336         },
337 }
338
339 ly_options = {
340         NOTES: {
341                 RELATIVE: r'''\relative c%(relative_quotes)s''',
342         },
343         PAPER: {
344                 INDENT: r'''
345     indent = %(indent)s''',
346         'linewidth': r'''
347     linewidth = %(linewidth)s''',
348                 NOINDENT: r'''
349     indent = 0.0\mm''',
350                 QUOTE: r'''
351     linewidth = %(linewidth)s - 2.0 * %(exampleindent)s
352 ''',
353                 RAGGEDRIGHT: r'''
354     indent = 0.0\mm
355     raggedright = ##t''',
356         },
357
358         ##
359         LAYOUT: {
360                 EXAMPLEINDENT: '',
361
362                 NOTIME: r'''
363     \context {
364         \Staff
365         \remove Time_signature_engraver
366     }''',
367         },
368
369         ##
370         PREAMBLE: {
371                 STAFFSIZE: r'''
372 #(set-global-staff-size %(staffsize)s)''',
373         },
374 }
375
376 output = {
377         HTML: {
378         FILTER: r'''<lilypond %(options)s>
379 %(code)s
380 </lilypond>
381 ''',
382
383         AFTER: r'''
384   </a>
385 </p>''',
386         BEFORE: r'''<p>
387   <a href="%(base)s.ly">''',
388         OUTPUT: r'''
389     <img align="center" valign="center"
390          border="0" src="%(image)s" alt="[image of music]">''',
391         PRINTFILENAME:'<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
392         QUOTE: r'''<blockquote>
393 %(str)s
394 </blockquote>
395 ''',
396         VERBATIM: r'''<pre>
397 %(verb)s</pre>''',
398         },
399
400         LATEX:  {
401         AFTER: '',
402         BEFORE: '',
403         OUTPUT: r'''{\parindent 0pt
404 \catcode`\@=12
405 \ifx\preLilyPondExample\undefined\relax\else\preLilyPondExample\fi
406 \def\lilypondbook{}%%
407 \input %(base)s.tex
408 \ifx\postLilyPondExample\undefined\relax\else\postLilyPondExample\fi
409 \catcode`\@=0}''',
410         PRINTFILENAME: '''\\texttt{%(filename)s}
411         ''',
412         QUOTE: r'''\begin{quotation}
413 %(str)s
414 \end{quotation}
415 ''',
416         VERBATIM: r'''\noindent
417 \begin{verbatim}
418 %(verb)s\end{verbatim}
419 ''',
420         FILTER: r'''\begin{lilypond}[%(options)s]
421 %(code)s
422 \end{lilypond}''',
423         },
424
425         TEXINFO: {
426         FILTER: r'''@lilypond[%(options)s]
427 %(code)s
428 @lilypond''',
429         AFTER: '',
430         BEFORE: '',
431         OUTPUT: r'''@noindent
432 @image{%(base)s,,,[image of music],%(ext)s}''',
433         PRINTFILENAME: '''@file{%(filename)s}
434         ''',
435         QUOTE: r'''@quotation
436 %(str)s
437 @end quotation
438 ''',
439         # FIXME: @exampleindent 5  is the default...
440         VERBATIM: r'''@exampleindent 0
441 @example
442 %(verb)s@end example
443 @exampleindent 5
444 ''',
445         },
446 }
447
448 PREAMBLE_LY = r"""%%%% Generated by %(program_name)s
449 %%%% Options: [%(option_string)s]
450 #(set! toplevel-score-handler ly:parser-print-score)
451 #(set! toplevel-music-handler (lambda (p m)
452                                (ly:parser-print-score
453                                 p (ly:music-scorify m p))
454                             ))
455 %(preamble_string)s
456 \paper {
457   #(define dump-extents #t)
458   %(paper_string)s
459 }
460 \layout { %(layout_string)s
461 }
462
463 """
464
465 FRAGMENT_LY = r'''
466     %(notes_string)s{
467         %(code)s    }
468 '''
469 FULL_LY = '%(code)s'
470
471 texinfo_linewidths = {
472         '@afourpaper': '160 \\mm',
473         '@afourwide': '6.5 \\in',
474         '@afourlatex': '150 \\mm',
475         '@smallbook': '5 \\in' ,
476         '@letterpaper': '6\\in',
477 }
478
479 def classic_lilypond_book_compatibility (o):
480         if o == 'singleline':
481                 return RAGGEDRIGHT
482         m = re.search ('relative\s*([-0-9])', o)
483         if m:
484                 return 'relative=%s' % m.group (1)
485         m = re.match ('([0-9]+)pt', o)
486         if m:
487                 return 'staffsize=%s' % m.group (1)
488         m = re.match ('indent=([-.0-9]+)(cm|in|mm|pt|staffspace)', o)
489         if m:
490                 f = float (m.group (1))
491                 return 'indent=%f\\%s' % (f, m.group (2))
492         m = re.match ('linewidth=([-.0-9]+)(cm|in|mm|pt|staffspace)', o)
493         if m:
494                 f = float (m.group (1))
495                 return 'linewidth=%f\\%s' % (f, m.group (2))
496         return None
497
498 def compose_ly (code, options):
499         #Hmm
500         for i in default_ly_options.keys ():
501                 if i not in options:
502                         options.append (i)
503
504         #Hmm
505         if QUOTE in options and LINEWIDTH in options:
506                 options.remove (LINEWIDTH)
507
508         if FRAGMENT in options:
509                 if RAGGEDRIGHT not in options:
510                         options.append (RAGGEDRIGHT)
511                 body = FRAGMENT_LY
512         else:
513                 body = FULL_LY
514
515         # defaults
516         relative = 1
517         staffsize = 16
518         override = {}
519         #FIXME: where to get sane value for exampleindent?
520         override[EXAMPLEINDENT] = r'9.0 \mm'
521         override[LINEWIDTH] = None
522         override.update (default_ly_options)
523
524         option_string = string.join (options, ',')
525
526         options_dict = {}
527         option_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
528         for a in option_types:
529                 options_dict[a] = []
530
531         for i in options:
532                 c = classic_lilypond_book_compatibility (i)
533                 if c:
534                         ly.warning (_ ("deprecated ly-option used: %s" % i))
535                         ly.warning (_ ("compatibility mode translation: %s" \
536                                        % c))
537                         i = c
538
539                 if string.find (i, '=') > 0:
540                         key, value = string.split (i, '=')
541                         override[key] = value
542                 else:
543                         key = i
544                         if not override.has_key (i):
545                                 override[i] = None
546
547                 found = 0
548                 for type in option_types:
549                         if ly_options[type].has_key (key):
550
551                                 options_dict[type].append (ly_options[type][key])
552                                 found = 1
553                                 break
554
555                 if not found and key not in (FRAGMENT, NOFRAGMENT, PRINTFILENAME,
556                                              RELATIVE, VERBATIM, TEXIDOC):
557                         ly.warning (_("ignoring unknown ly option: %s") % i)
558
559         #URGS
560         if RELATIVE in override.keys () and override[RELATIVE]:
561                 relative = string.atoi (override[RELATIVE])
562
563         relative_quotes = ''
564
565         # 1 = central C
566         if relative < 0:
567                 relative_quotes += ',' * (- relative)
568         elif relative > 0:
569                 relative_quotes += "'" * relative
570
571         program_name = __main__.program_name
572
573         paper_string = string.join (options_dict[PAPER], '\n    ') % override
574         layout_string = string.join (options_dict[LAYOUT], '\n    ') % override
575         notes_string = string.join (options_dict[NOTES], '\n    ') % vars ()
576         preamble_string = string.join (options_dict[PREAMBLE], '\n    ') % override
577         return (PREAMBLE_LY + body) % vars ()
578
579
580 # BARF
581 # use lilypond for latex (.lytex) books,
582 # and lilypond --preview for html, texinfo books?
583 def to_eps (file):
584         cmd = r'latex "\nonstopmode \input %s"' % file
585         # Ugh.  (La)TeX writes progress and error messages on stdout
586         # Redirect to stderr
587         cmd = '(( %s >&2 ) >&- )' % cmd
588         ly.system (cmd)
589         ly.system ('dvips -Ppdf -u+ec-mftrace.map -u+lilypond.map -E -o %s.eps %s' \
590                    % (file, file))
591
592
593         # check if it really is EPS.
594         # Otherwise music glyphs disappear from 2nd and following pages.
595
596         # TODO: should run dvips -pp -E per page, then we get proper
597         # cropping as well.
598
599         f = open ('%s.eps' % file)
600         for x in range(0,10):
601                 if re.search ("^%%Pages: ", f.readline ()):
602
603                         # make non EPS.
604                         ly.system ('dvips -Ppdf -u+ec-mftrace.map -u+lilypond.map -o %s.eps %s' \
605                                    % (file, file))
606                         break
607
608
609 def find_file (name):
610         for i in include_path:
611                 full = os.path.join (i, name)
612                 if os.path.exists (full):
613                         return full
614         ly.error (_ ('file not found: %s') % name + '\n')
615         ly.exit (1)
616         return ''
617
618 def verbatim_html (s):
619         return re.sub ('>', '&gt;',
620                        re.sub ('<', '&lt;',
621                                re.sub ('&', '&amp;', s)))
622
623 def verbatim_texinfo (s):
624         return re.sub ('{', '@{',
625                        re.sub ('}', '@}',
626                                re.sub ('@', '@@', s)))
627
628 def split_options (option_string):
629         return re.split (format_res[format]['option-sep'], option_string)
630
631
632 class Chunk:
633         def replacement_text (self):
634                 return ''
635
636         def filter_text (self):
637                 return self.replacement_text ()
638
639
640         def ly_is_outdated (self):
641                 return 0
642
643         def png_is_outdated (self):
644                 return 0
645
646 class Substring (Chunk):
647         def __init__ (self, source, start, end):
648                 self.source = source
649                 self.start = start
650                 self.end = end
651
652         def replacement_text (self):
653                 return self.source [self.start:self.end]
654
655 class Snippet (Chunk):
656         def __init__ (self, type, match, format):
657                 self.type = type
658                 self.match = match
659                 self.hash = 0
660                 self.options = []
661                 self.format = format
662
663         def replacement_text (self):
664                 return self.match.group ('match')
665
666         def substring (self, s):
667                 return self.match.group (s)
668
669         def __repr__ (self):
670                 return `self.__class__` + " type = " + self.type
671
672 class Include_snippet (Snippet):
673         def processed_filename (self):
674                 f = self.substring ('filename')
675                 return os.path.splitext (f)[0] + format2ext[format]
676
677         def replacement_text (self):
678                 s = self.match.group ('match')
679                 f = self.substring ('filename')
680
681                 return re.sub (f, self.processed_filename (), s)
682
683 class Lilypond_snippet (Snippet):
684         def __init__ (self, type, match, format):
685                 Snippet.__init__ (self, type, match, format)
686                 os = match.group ('options')
687                 if os:
688                         self.options = split_options (os)
689
690         def ly (self):
691                 return self.substring ('code')
692
693         def full_ly (self):
694                 s = self.ly ()
695                 if s:
696                         return compose_ly (s, self.options)
697                 return ''
698
699         # todo: use md5?
700         def get_hash (self):
701                 if not self.hash:
702                         self.hash = abs (hash (self.full_ly ()))
703                 return self.hash
704
705         def basename (self):
706                 if use_hash_p:
707                         return 'lily-%d' % self.get_hash ()
708                 raise 'to be done'
709
710         def write_ly (self):
711                 outf = open (self.basename () + '.ly', 'w')
712                 outf.write (self.full_ly ())
713
714                 open (self.basename() + '.txt', 'w').write("image of music")
715
716
717         def ly_is_outdated (self):
718                 base = self.basename ()
719
720                 tex_file = '%s.tex' % base
721                 ly_file = '%s.ly' % base
722                 ok = os.path.exists (ly_file) and os.path.exists (tex_file)\
723                      and os.stat (tex_file)[stat.ST_SIZE] \
724                      and open (tex_file).readlines ()[-1][1:-1] \
725                      == 'lilypondend'
726
727                 if ok and (use_hash_p or self.ly () == open (ly_file).read ()):
728                         # TODO: something smart with target formats
729                         # (ps, png) and m/ctimes
730                         return None
731                 return self
732
733         def png_is_outdated (self):
734                 base = self.basename ()
735                 ok = self.ly_is_outdated ()
736                 if format == HTML or format == TEXINFO:
737                         ok = ok and (os.path.exists (base + '.png')
738                                      or glob.glob (base + '-page*.png'))
739                 return not ok
740
741         def filter_text (self):
742                 code = self.substring ('code')
743                 s = run_filter (code)
744                 d = {
745                   'code': s,
746                   'options': self.match.group ('options')
747                 }
748                 # TODO
749                 return output[self.format][FILTER] % d
750
751         def replacement_text (self):
752                 func = Lilypond_snippet.__dict__ ['output_' + self.format]
753                 return func (self)
754
755         def get_images (self):
756                 base = self.basename ()
757                 # URGUGHUGHUGUGHU
758                 single = '%(base)s.png' % vars ()
759                 multiple = '%(base)s-page1.png' % vars ()
760                 images = (single,)
761                 if os.path.exists (multiple) \
762                    and (not os.path.exists (single)\
763                         or (os.stat (multiple)[stat.ST_MTIME] \
764                             > os.stat (single)[stat.ST_MTIME])):
765                         images = glob.glob ('%(base)s-page*.png' % vars ())
766                 return images
767
768         def output_html (self):
769                 str = ''
770                 base = self.basename ()
771                 if format == HTML:
772                         str += self.output_print_filename (HTML)
773                         if VERBATIM in self.options:
774                                 verb = verbatim_html (self.substring ('code'))
775                                 str += write (output[HTML][VERBATIM] % vars ())
776                         if QUOTE in self.options:
777                                 str = output[HTML][QUOTE] % vars ()
778
779                 str += output[HTML][BEFORE] % vars ()
780                 for image in self.get_images ():
781                         base, ext = os.path.splitext (image)
782                         str += output[HTML][OUTPUT] % vars ()
783                 str += output[HTML][AFTER] % vars ()
784                 return str
785
786         def output_info (self):
787                 str = self.output_print_filename (HTML)
788                 str = output[TEXINFO][BEFORE] % vars ()
789                 for image in self.get_images ():
790                         base, ext = os.path.splitext (image)
791
792                         # URG, makeinfo implicitely prepends dot to ext
793                         # specifying no extension is most robust
794                         ext = ''
795                         str += output[TEXINFO][OUTPUT] % vars ()
796                 str += output[TEXINFO][AFTER] % vars ()
797                 return str
798
799         def output_latex (self):
800                 str = ''
801                 base = self.basename ()
802                 if format == LATEX:
803                         str += self.output_print_filename (LATEX)
804                         if VERBATIM in self.options:
805                                 verb = self.substring ('code')
806                                 str += (output[LATEX][VERBATIM] % vars ())
807                         if QUOTE in self.options:
808                                 str = output[LATEX][QUOTE] % vars ()
809
810                 str += (output[LATEX][BEFORE]
811                         + (output[LATEX][OUTPUT] % vars ())
812                         + output[LATEX][AFTER])
813                 return str
814
815         def output_print_filename (self,format):
816                 str = ''
817                 if PRINTFILENAME in self.options:
818                         base = self.basename ()
819                         filename = self.substring ('filename')
820                         str = output[format][PRINTFILENAME] % vars ()
821                 return str
822
823         def output_texinfo (self):
824                 str = ''
825                 # self.output_print_filename (TEXINFO)
826                 if self.output_print_filename (0):
827                         str += ('@html\n' + self.output_print_filename (HTML)
828                                 + '\n@end html\n')
829                         str += ('@tex\n' + self.output_print_filename (LATEX)
830                                 + '\n@end tex\n')
831                 base = self.basename ()
832                 if TEXIDOC in self.options:
833                         texidoc = base + '.texidoc'
834                         if os.path.exists (texidoc):
835                                 str += '@include %(texidoc)s\n\n' % vars ()
836
837                 if VERBATIM in self.options:
838                         verb = verbatim_texinfo (self.substring ('code'))
839                         str += (output[TEXINFO][VERBATIM] % vars ())
840
841                 str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
842                 str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
843                 str += ('@html\n' + self.output_html () + '\n@end html\n')
844
845                 if QUOTE in self.options:
846                         str = output[TEXINFO][QUOTE] % vars ()
847
848                 # need par after image
849                 str += '\n'
850
851                 return str
852
853 class Lilypond_file_snippet (Lilypond_snippet):
854         def ly (self):
855                 name = self.substring ('filename')
856                 return '\\renameinput \"%s\"\n%s' % (name, open (find_file (name)).read ())
857
858 snippet_type_to_class = {
859         'lilypond_file': Lilypond_file_snippet,
860         'lilypond_block': Lilypond_snippet,
861         'lilypond': Lilypond_snippet,
862         'include': Include_snippet,
863 }
864
865 def find_toplevel_snippets (s, types):
866         res = {}
867         for i in types:
868                 res[i] = ly.re.compile (snippet_res[format][i])
869
870         snippets = []
871         index = 0
872         ## found = dict (map (lambda x: (x, None), types))
873         ## urg python2.1
874         found = {}
875         map (lambda x, f=found: f.setdefault (x, None), types)
876
877         # We want to search for multiple regexes, without searching
878         # the string multiple times for one regex.
879         # Hence, we use earlier results to limit the string portion
880         # where we search.
881         # Since every part of the string is traversed at most once for
882         # every type of snippet, this is linear.
883
884         while 1:
885                 first = None
886                 endex = 1 << 30
887                 for type in types:
888                         if not found[type] or found[type][0] < index:
889                                 found[type] = None
890                                 m = res[type].search (s[index:endex])
891                                 if not m:
892                                         continue
893
894                                 cl = Snippet
895                                 if snippet_type_to_class.has_key (type):
896                                         cl = snippet_type_to_class[type]
897                                 snip = cl (type, m, format)
898                                 start = index + m.start ('match')
899                                 found[type] = (start, snip)
900
901                         if found[type] \
902                            and (not first or found[type][0] < found[first][0]):
903                                 first = type
904
905                                 # FIXME.
906
907                                 # Limiting the search space is a cute
908                                 # idea, but this *requires* to search
909                                 # for possible containing blocks
910                                 # first, at least as long as we do not
911                                 # search for the start of blocks, but
912                                 # always/directly for the entire
913                                 # @block ... @end block.
914
915                                 endex = found[first][0]
916
917                 if not first:
918                         snippets.append (Substring (s, index, len (s)))
919                         break
920
921                 (start, snip) = found[first]
922                 snippets.append (Substring (s, index, start))
923                 snippets.append (snip)
924                 found[first] = None
925                 index = start + len (snip.match.group ('match'))
926
927         return snippets
928
929 def filter_pipe (input, cmd):
930         if verbose_p:
931                 ly.progress (_ ("Opening filter `%s\'") % cmd)
932
933         stdin, stdout, stderr = os.popen3 (cmd)
934         stdin.write (input)
935         status = stdin.close ()
936
937         if not status:
938                 status = 0
939                 output = stdout.read ()
940                 status = stdout.close ()
941                 error = stderr.read ()
942
943         if not status:
944                 status = 0
945         signal = 0x0f & status
946         if status or (not output and error):
947                 exit_status = status >> 8
948                 ly.error (_ ("`%s\' failed (%d)") % (cmd, exit_status))
949                 ly.error (_ ("The error log is as follows:"))
950                 sys.stderr.write (error)
951                 sys.stderr.write (stderr.read ())
952                 ly.exit (status)
953
954         if verbose_p:
955                 ly.progress ('\n')
956
957         return output
958
959 def run_filter (s):
960         return filter_pipe (s, filter_cmd)
961
962 def is_derived_class (cl, baseclass):
963         if cl == baseclass:
964                 return 1
965         for b in cl.__bases__:
966                 if is_derived_class (b, baseclass):
967                         return 1
968         return 0
969
970
971 def process_snippets (cmd, ly_snippets, png_snippets):
972         ly_names = filter (lambda x: x, map (Lilypond_snippet.basename, ly_snippets))
973         png_names = filter (lambda x: x, map (Lilypond_snippet.basename, png_snippets))
974
975
976         status = 0
977         if ly_names:
978                 status = ly.system (string.join ([cmd] + ly_names),
979                                     ignore_error = 1, progress_p = 1)
980
981
982         if status:
983                 ly.error( 'Process %s exited unsuccessfully.' % cmd )
984                 raise Compile_error
985
986         if format == HTML or format == TEXINFO:
987                 for i in png_names:
988                         if not os.path.exists (i + '.eps') and os.path.exists (i + '.tex'):
989                                 to_eps (i)
990                                 ly.make_ps_images (i + '.eps', resolution=110)
991
992 #                       elif os.path.exists (i + '.ps'):
993 #                               ly.make_ps_images (i + '.ps', resolution=110)
994
995
996 LATEX_DOCUMENT = r'''
997 %(preamble)s
998 \begin{document}
999 \typeout{textwidth=\the\textwidth}
1000 \typeout{columnsep=\the\columnsep}
1001 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1002 \end{document}
1003 '''
1004 #need anything else besides textwidth?
1005 def get_latex_textwidth (source):
1006         m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1007         preamble = source[:m.start (0)]
1008         latex_document = LATEX_DOCUMENT % vars ()
1009         parameter_string = filter_pipe (latex_document, latex_filter_cmd)
1010
1011         columns = 0
1012         m = re.search ('columns=([0-9.]*)', parameter_string)
1013         if m:
1014                 columns = string.atoi (m.group (1))
1015
1016         columnsep = 0
1017         m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1018         if m:
1019                 columnsep = string.atof (m.group (1))
1020
1021         textwidth = 0
1022         m = re.search('textwidth=([0-9.]*)pt', parameter_string)
1023         if m:
1024                 textwidth = string.atof (m.group (1))
1025                 if columns:
1026                         textwidth = (textwidth - columnsep) / columns
1027
1028         return textwidth
1029
1030 ext2format = {
1031         '.html': HTML,
1032         '.itely': TEXINFO,
1033         '.latex': LATEX,
1034         '.lytex': LATEX,
1035         '.tely': TEXINFO,
1036         '.tex': LATEX,
1037         '.texi': TEXINFO,
1038         '.texinfo': TEXINFO,
1039         '.xml': HTML,
1040 }
1041
1042 format2ext = {
1043         HTML: '.html',
1044         #TEXINFO: '.texinfo',
1045         TEXINFO: '.texi',
1046         LATEX: '.tex',
1047 }
1048
1049 class Compile_error:
1050         pass
1051
1052 def do_process_cmd (chunks):
1053         ly_outdated = filter (lambda x: is_derived_class (x.__class__, Lilypond_snippet) \
1054                         and x.ly_is_outdated (), chunks)
1055         png_outdated = filter (lambda x: is_derived_class (x.__class__, Lilypond_snippet) \
1056                          and x.png_is_outdated (), chunks)
1057
1058         ly.progress (_ ("Writing snippets..."))
1059         map (Lilypond_snippet.write_ly, ly_outdated)
1060         ly.progress ('\n')
1061
1062         if ly_outdated:
1063                 ly.progress (_ ("Processing..."))
1064                 process_snippets (process_cmd, ly_outdated, png_outdated)
1065         else:
1066                 ly.progress (_ ("All snippets are up to date..."))
1067         ly.progress ('\n')
1068
1069
1070 def do_file (input_filename):
1071         #ugh
1072         global format
1073         if not format:
1074                 e = os.path.splitext (input_filename)[1]
1075                 if e in ext2format.keys ():
1076                         #FIXME
1077                         format = ext2format[e]
1078                 else:
1079                         ly.error (_ ("cannot determine format for: %s" \
1080                                      % input_filename))
1081                         ly.exit (1)
1082
1083         if not input_filename or input_filename == '-':
1084                 in_handle = sys.stdin
1085                 input_fullname = '<stdin>'
1086         else:
1087                 if os.path.exists (input_filename):
1088                         input_fullname = input_filename
1089                 elif format == LATEX:
1090                         # urg python interface to libkpathsea?
1091                         input_fullname = ly.read_pipe ('kpsewhich '
1092                                                        + input_filename)[:-1]
1093                 else:
1094                         input_fullname = find_file (input_filename)
1095                 in_handle = open (input_fullname)
1096
1097         if input_filename == '-':
1098                 input_base = 'stdin'
1099         else:
1100                 input_base = os.path.basename \
1101                              (os.path.splitext (input_filename)[0])
1102
1103         # only default to stdout when filtering
1104         if output_name == '-' or (not output_name and filter_cmd):
1105                 output_filename = '-'
1106                 output_file = sys.stdout
1107         else:
1108                 if not output_name:
1109                         output_filename = input_base + format2ext[format]
1110                 else:
1111                         if not os.path.isdir (output_name):
1112                                 os.mkdir (output_name, 0777)
1113                         output_filename = (output_name
1114                                            + '/' + input_base
1115                                            + format2ext[format])
1116
1117
1118                 if (os.path.exists (input_filename) and
1119                     os.path.exists (output_filename) and
1120                     os.path.samefile (output_filename, input_fullname)):
1121                         ly.error (_("Output would overwrite input file; use --output."))
1122                         ly.exit (2)
1123
1124                 output_file = open (output_filename, 'w')
1125                 if output_name:
1126                         os.chdir (output_name)
1127         try:
1128                 ly.progress (_ ("Reading %s...") % input_fullname)
1129                 source = in_handle.read ()
1130                 ly.progress ('\n')
1131
1132                 # FIXME: containing blocks must be first, see find_toplevel_snippets
1133                 snippet_types = (
1134                         'multiline_comment',
1135                         'verbatim',
1136                         'lilypond_block',
1137         #               'verb',
1138                         'singleline_comment',
1139                         'lilypond_file',
1140                         'include',
1141                         'lilypond', )
1142                 ly.progress (_ ("Dissecting..."))
1143                 chunks = find_toplevel_snippets (source, snippet_types)
1144                 ly.progress ('\n')
1145
1146                 global default_ly_options
1147                 textwidth = 0
1148                 if not default_ly_options.has_key (LINEWIDTH):
1149                         if format == LATEX:
1150                                 textwidth = get_latex_textwidth (source)
1151                                 default_ly_options[LINEWIDTH] = '''%.0f\\pt''' \
1152                                                                 % textwidth
1153                         elif format == TEXINFO:
1154                                 for (k, v) in texinfo_linewidths.items ():
1155                                         # FIXME: @layout is usually not in chunk #0:
1156                                         #        \input texinfo @c -*-texinfo-*-
1157                                         # bluntly search first K of source
1158                                         # s = chunks[0].replacement_text ()
1159                                         if re.search (k, source[:1024]):
1160                                                 default_ly_options[LINEWIDTH] = v
1161                                                 break
1162
1163                 if filter_cmd:
1164                         output_file.writelines ([c.filter_text () for c in chunks])
1165
1166
1167                 elif process_cmd:
1168                         do_process_cmd (chunks)
1169                         ly.progress (_ ("Compiling %s...") % output_filename)
1170                         output_file.writelines ([s.replacement_text () \
1171                                                  for s in chunks])
1172                         ly.progress ('\n')
1173
1174                 def process_include (snippet):
1175                         os.chdir (original_dir)
1176                         name = snippet.substring ('filename')
1177                         ly.progress (_ ('Processing include: %s') % name)
1178                         ly.progress ('\n')
1179                         do_file (name)
1180
1181                 map (process_include,
1182                      filter (lambda x: is_derived_class (x.__class__, Include_snippet), chunks))
1183         except Compile_error:
1184                 os.chdir (original_dir)
1185                 ly.progress (_('Removing `%s\'') % output_filename)
1186                 ly.progress ('\n')
1187
1188                 os.unlink (output_filename)
1189                 raise Compile_error
1190
1191
1192 def do_options ():
1193         global format, output_name
1194         global filter_cmd, process_cmd, verbose_p
1195
1196         (sh, long) = ly.getopt_args (option_definitions)
1197         try:
1198                 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1199         except getopt.error, s:
1200                 sys.stderr.write ('\n')
1201                 ly.error (_ ("getopt says: `%s\'" % s))
1202                 sys.stderr.write ('\n')
1203                 ly.help ()
1204                 ly.exit (2)
1205
1206         for opt in options:
1207                 o = opt[0]
1208                 a = opt[1]
1209
1210                 if 0:
1211                         pass
1212                 elif o == '--filter' or o == '-F':
1213                         filter_cmd = a
1214                         process_cmd = 0
1215                 elif o == '--format' or o == '-f':
1216                         format = a
1217                         if a == 'texi-html' or a == 'texi':
1218                                 format = TEXINFO
1219                 elif o == '--help' or o == '-h':
1220                         ly.help ()
1221                         sys.exit (0)
1222                 elif o == '--include' or o == '-I':
1223                         include_path.append (os.path.join (original_dir,
1224                                                            ly.abspath (a)))
1225                 elif o == '--output' or o == '-o':
1226                         output_name = a
1227                 elif o == '--outdir':
1228                         output_name = a
1229                 elif o == '--process' or o == '-P':
1230                         process_cmd = a
1231                         filter_cmd = 0
1232                 elif o == '--version' or o == '-v':
1233                         ly.identify (sys.stdout)
1234                         sys.exit (0)
1235                 elif o == '--verbose' or o == '-V':
1236                         verbose_p = 1
1237                 elif o == '--warranty' or o == '-w':
1238                         if 1 or status:
1239                                 ly.warranty ()
1240                         sys.exit (0)
1241         return files
1242
1243 def main ():
1244         files = do_options ()
1245         global process_cmd
1246         if process_cmd == '':
1247                 process_cmd = lilypond_binary + " -f tex "
1248
1249         if process_cmd:
1250                 process_cmd += string.join ([(' -I %s' % p)
1251                                              for p in include_path])
1252
1253         ly.identify (sys.stderr)
1254         ly.setup_environment ()
1255         if files:
1256                 try:
1257                         do_file (files[0])
1258                 except Compile_error:
1259                         ly.exit (1)
1260
1261 if __name__ == '__main__':
1262         main ()