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