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