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