]> git.donarmstrong.com Git - lilypond.git/blob - scripts/filter-lilypond-book.py
Fixes
[lilypond.git] / scripts / filter-lilypond-book.py
1 #!@PYTHON@
2
3 '''
4 TODO:
5       ly-options: intertext, quote ?
6       --linewidth
7       check latex parameters, twocolumn
8       multicolumn?
9       papersizes?
10       ly2dvi/notexidoc?
11       
12 Example usage:
13
14 test:
15      filter-lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
16           
17 convert-ly on book:
18      filter-lilypond-book --filter="convert-ly --no-version --from=1.6.11 -" BOOK
19
20 classic lilypond-book (WIP):
21      filter-lilypond-book --process="lilypond-bin" BOOK.tely
22
23   options in .tely/.lytex must be converted (or grokked by me :-)
24      (([0-9][0-9])*pt) -> staffsize=\2
25      @mbinclude foo.itely -> @include foo.itely
26      \mbinput -> \input
27      relative X -> relative=X
28      singleline -> raggedright
29      
30 '''
31
32 import string
33 import __main__
34
35 ################################################################
36 # Users of python modules should include this snippet
37 # and customize variables below.
38
39 # We'll suffer this path init stuff as long as we don't install our
40 # python packages in <prefix>/lib/pythonx.y (and don't kludge around
41 # it as we do with teTeX on Red Hat Linux: set some environment var
42 # (PYTHONPATH) in profile)
43
44 # If set, LILYPONDPREFIX must take prevalence
45 # if datadir is not set, we're doing a build and LILYPONDPREFIX
46 import getopt, os, sys
47 datadir = '@local_lilypond_datadir@'
48 if not os.path.isdir (datadir):
49         datadir = '@lilypond_datadir@'
50 if os.environ.has_key ('LILYPONDPREFIX') :
51         datadir = os.environ['LILYPONDPREFIX']
52         while datadir[-1] == os.sep:
53                 datadir= datadir[:-1]
54
55 sys.path.insert (0, os.path.join (datadir, 'python'))
56
57 # Customize these
58 #if __name__ == '__main__':
59
60 import lilylib as ly
61 global _;_=ly._
62 global re;re = ly.re
63
64 # lilylib globals
65 program_version = '@TOPLEVEL_VERSION@'
66 #program_name = 'new-book'
67 program_name = 'filter-lilypond-book'
68 verbose_p = 0
69 pseudo_filter_p = 0
70 original_dir = os.getcwd ()
71
72
73 # help_summary = _ ("Process LilyPond snippets in hybrid html, LaTeX or texinfo document")
74 help_summary = _ ("""Process ly snippets from lilypond-book source.  Example usage:
75
76    filter-lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
77    filter-lilypond-book --filter="convert-ly --no-version --from=1.6.11 -" BOOK
78
79 """)
80 copyright = ('Jan Nieuwenhuizen <janneke@gnu.org>>',
81              'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
82
83 option_definitions = [
84         (_ ("EXT"), 'f', 'format', _ ("use output format EXT (texi [default], texi-html, latex, html)")),
85         (_ ("FILTER"), 'F', 'filter', _ ("pipe snippets through FILTER [convert-ly -n -]")),
86         ('', 'h', 'help', _ ("print this help")),
87         (_ ("DIR"), 'I', 'include', _ ("add DIR to include path")),
88         (_ ("COMMAND"), 'P', 'process', _ ("process ly_files using COMMAND FILE...")),
89         (_ ("FILE"), 'o', 'output', _ ("write output to FILE")),
90         ('', 'V', 'verbose', _ ("be verbose")),
91         ('', 'v', 'version', _ ("print version information")),
92         ('', 'w', 'warranty', _ ("show warranty and copyright")),
93         ('', 'M', 'dependencies', _ ("TODO")),
94         (_ ("DIR"), '', 'outdir', _ ("DEPRECATED, use --output")),
95         ]
96
97 include_path = [ly.abspath (os.getcwd ())]
98
99 lilypond_binary = os.path.join ('@bindir@', 'lilypond-bin')
100
101 # only use installed binary  when we're installed too.
102 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
103         lilypond_binary = 'lilypond-bin'
104
105
106 use_hash_p = 1
107 format = 0
108 output_name = 0
109 latex_filter_cmd = 'latex "\\nonstopmode \input /dev/stdin"'
110 ##filter_cmd = 'convert-ly --no-version --from=2.0.0 -'
111 filter_cmd = 0
112
113 #process_cmd = 'convert-ly --no-version --from=2.0.0'
114 #process_cmd = 0
115 # process_cmd = 'lilypond-bin'
116 process_cmd = 'lilypond-bin -I ../../../input/test'
117 default_ly_options = { }
118
119 LATEX = 'latex'
120 HTML = 'html'
121 TEXINFO = 'texinfo'
122 BEFORE = 'before'
123 OUTPUT = 'output'
124 AFTER = 'after'
125 VERBATIM = 'verbatim'
126 LINEWIDTH = 'linewidth'
127
128 ## lilypond-book heritage.  to be cleaned
129
130 ################################################################
131 # Recognize special sequences in the input 
132
133
134 # Warning: This uses extended regular expressions.  Tread with care.
135 #
136 # legenda
137 #
138 # (?P<name>regex) -- assign result of REGEX to NAME
139 # *? -- match non-greedily.
140 # (?m) -- multiline regex: make ^ and $ match at each line
141 # (?s) -- make the dot match all characters including newline
142 no_match = 'a\ba'
143 re_dict = {
144         HTML: {
145                 'include':  no_match,
146                 'input': no_match,
147                 'header': no_match,
148                 'landscape': no_match,
149                 'verbatim': r'''(?s)(?P<code><pre>\s.*?</pre>\s)''',
150                 'verb': r'''(?P<code><pre>.*?</pre>)''',
151                 'lilypond-file': r'(?m)(?P<match><lilypondfile(?P<options>[^>]+)?>\s*(?P<filename>[^<]+)\s*</lilypondfile>)',
152                 'lilypond' : '(?m)(?P<match><lilypond((?P<options>[^:]*):)(?P<code>.*?)/>)',
153                 'lilypond-block': r'''(?ms)(?P<match><lilypond(?P<options>[^>]+)?>(?P<code>.*?)</lilypond>)''',
154                 'option-sep' : '\s*',
155                 'intertext': r',?\s*intertext=\".*?\"',
156                 'multiline-comment': r"(?sm)\s*(?!@c\s+)(?P<code><!--\s.*?!-->)\s",
157                 'singleline-comment': no_match,
158                 'numcols': no_match,
159                 'multicols': no_match,
160                 'ly2dvi': r'(?m)(?P<match><ly2dvifile(?P<options>[^>]+)?>\s*(?P<filename>[^<]+)\s*</ly2dvifile>)',
161                 },
162
163         LATEX: {
164                 'include': r'(?m)^[^%\n]*?(?P<match>\\input{(?P<filename>[^}]+)})',
165                 'option-sep' : ',\s*',
166                 'header': r"\n*\\documentclass\s*(\[.*?\])?",
167                 'verbatim': r"(?s)(?P<code>\\begin\s*{verbatim}.*?\\end{verbatim})",
168                 'verb': r"(?P<code>\\verb(?P<del>.).*?(?P=del))",
169                 'lilypond-file': r'(?m)^[^%\n]*?(?P<match>\\lilypondfile\s*(\[(?P<options>.*?)\])?\s*\{(?P<filename>.+)})',
170                 'lilypond' : r'(?m)^[^%\n]*?(?P<match>\\lilypond\s*(\[(?P<options>.*?)\])?\s*{(?P<code>.*?)})',
171                 'lilypond-block': r"(?sm)^[^%\n]*?(?P<match>\\begin\s*(\[(?P<options>.*?)\])?\s*{lilypond}(?P<code>.*?)\\end{lilypond})",
172                 'def-post-re': r"\\def\\postLilyPondExample",
173                 'def-pre-re': r"\\def\\preLilyPondExample",
174                 'usepackage-graphics': r"\usepackage\s*{graphics}",
175                 'intertext': r',?\s*intertext=\".*?\"',
176                 'multiline-comment': no_match,
177                 'singleline-comment': r"(?m)^.*?(?P<match>(?P<code>^%.*$\n+))",
178                 'numcols': r"(?P<code>\\(?P<num>one|two)column)",
179                 'multicols': r"(?P<code>\\(?P<be>begin|end)\s*{multicols}({(?P<num>\d+)?})?)",
180                 'ly2dvi': no_match,
181
182                 },
183
184         # why do we have distinction between @mbinclude and @include?
185
186         TEXINFO: {
187                 'junkmeinclude':  '(?m)^[^%\n]*?(?P<match>@mbinclude\s+(?P<filename>\S*))',
188                 'include':  '(?m)^[^%\n]*?(?P<match>@include\s+(?P<filename>\S*))',
189                 'input': no_match,
190                 'header': no_match,
191                 'landscape': no_match,
192                 'verbatim': r'''(?s)(?P<code>@example\s.*?@end example\s)''',
193                 'verb': r'''(?P<code>@code{.*?})''',
194                 'lilypond-file': '(?m)^(?P<match>@lilypondfile(\[(?P<options>[^]]*)\])?{(?P<filename>[^}]+)})',
195                 'lilypond' : '(?m)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?{(?P<code>.*?)})',
196                 'lilypond-block': r'''(?ms)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?\s(?P<code>.*?)@end lilypond)\s''',
197                 'option-sep' : ',\s*',
198                 'intertext': r',?\s*intertext=\".*?\"',
199                 'multiline-comment': r"(?sm)^\s*(?!@c\s+)(?P<code>@ignore\s.*?@end ignore)\s",
200                 'singleline-comment': r"(?m)^.*?(?P<match>(?P<code>@c.*$\n+))",
201                 'numcols': no_match,
202                 'multicols': no_match,
203                 'ly2dvi': no_match,
204                 }
205         }
206
207 NOTES = 'body'
208 PREAMBLE = 'preamble'
209 PAPER = 'paper'
210
211 ly_options = {
212         NOTES: {
213         #'xrelative': r'''\relative #(ly:make-pitch %(relative)s 0 0)''',
214         'relative': r'''\relative c%(relative_quotes)s''',
215         },
216         PAPER: {
217         'indent' : r'''
218     indent = %(indent)s''',
219         'linewidth' : r'''
220     linewidth = %(linewidth)s''',
221         'noindent' : r'''
222     indent = 0.0\mm''',
223         'notime' : r'''
224     \translator {
225         \StaffContext
226         \remove Time_signature_engraver
227     }''',
228         'raggedright' : r'''
229     indent = 0.0\mm
230     raggedright = ##t''',
231         },
232         PREAMBLE: {
233         'staffsize': r'''
234 #(set-global-staff-size %(staffsize)s)''',
235         },
236         }
237
238 output = {
239         HTML : {
240         AFTER: '',
241         BEFORE: '',
242         OUTPUT: r'''<img align="center" valign="center"
243 border="0" src="%(base)s.png" alt="[picture of music]">''',
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\preLilyPondExample\fi
254 \def\lilypondbook{}
255 \input %(base)s.tex
256 \ifx\preLilyPondExample\postLilyPondExample\fi
257 \catcode`\@=0}''',
258         VERBATIM: r'''\begin{verbatim}
259 %(verb)s\end{verbatim}
260 ''',
261         },
262         
263         TEXINFO :       {
264         BEFORE: '',
265         AFTER: '',
266         VERBATIM: r'''@example
267 %(verb)s@end example''',
268         
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
287 def compose_ly (code, option_string):
288         options = []
289         # urg
290         for i in default_ly_options.keys ():
291                 options.append (i)
292                 vars ()[i] = default_ly_options[i]
293
294         if option_string:
295                 options = options + split_options (option_string)
296         
297         m = re.search (r'''\\score''', code)
298         if not m and (not options \
299                       or not 'nofragment' in options \
300                       or 'fragment' in options):
301                 options.append ('raggedright')
302                 body = FRAGMENT_LY
303         else:
304                 body = FULL_LY
305
306         # defaults
307         relative = 0
308         staffsize = '16'
309
310         notes_options = []
311         paper_options = []
312         preamble_options = []
313         for i in options:
314                 if string.find (i, '=') > 0:
315                         key, value = string.split (i, '=')
316                         # hmm
317                         vars ()[key] = value
318                 else:
319                         key = i
320
321                 if key in ly_options[NOTES].keys ():
322                         notes_options.append (ly_options[NOTES][key])
323                 elif key in ly_options[PREAMBLE].keys ():
324                         preamble_options.append (ly_options[PREAMBLE][key])
325                 elif key in ly_options[PAPER].keys ():
326                         paper_options.append (ly_options[PAPER][key])
327                 elif key not in ('fragment', 'nofragment',
328                                  'relative', 'verbatim'):
329                         ly.warning (_("ignoring unknown ly option: %s") % i)
330
331         relative_quotes = (",,,", ",,", ",", "", "'", "''", "'''")[relative-3]
332         program_name = __main__.program_name
333         notes_string = string.join (notes_options, '\n    ') % vars ()
334         paper_string = string.join (paper_options, '\n    ') % vars ()
335         preamble_string = string.join (preamble_options, '\n    ') % vars ()
336         return (PREAMBLE_LY + body) % vars ()
337
338
339 # BARF
340 # use lilypond-bin for latex (.lytex) books,
341 # and lilypond --preview for html, texinfo books?
342 def to_eps (file):
343         cmd = r'latex "\nonstopmode \input %s"' % file
344         # Ugh.  (La)TeX writes progress and error messages on stdout
345         # Redirect to stderr
346         cmd = '(( %s  >&2 ) >&- )' % cmd
347         ly.system (cmd)
348         ly.system ('dvips -Ppdf -u+lilypond.map -E -o %s.eps %s' \
349                    % (file, file))
350
351 ## make source, index statics of Snippet?
352 index = 0
353
354 def find_file (name):
355         for i in include_path:
356                 full = os.path.join (i, name)
357                 if os.path.exists (full):
358                         return full
359         ly.error (_ ('file not found: %s\n' % name))
360         ly.exit (1)
361         return ''
362         
363 def verbatim_html (s):
364         return re.sub ('>', '&gt;',
365                        re.sub ('<', '&lt;',
366                                re.sub ('&', '&amp;', s)))
367
368 def verbatim_texinfo (s):
369         return re.sub ('{', '@{',
370                        re.sub ('}', '@}',
371                                re.sub ('@', '@@', s)))
372
373 def split_options (option_string):
374         return re.split (re_dict[format]['option-sep'], option_string)
375         
376 class Snippet:
377         def __init__ (self, type, index, match):
378                 self.type = type
379                 self.index = index
380                 self.match = match
381                 self.hash = 0
382
383         def start (self, s):
384                 return self.index + self.match.start (s)
385
386         def end (self, s):
387                 return self.index + self.match.end (s)
388
389         def substring (self, source, s):
390                 return source[self.start (s):self.end (s)]
391
392         def ly (self, source):
393                 s = ''
394                 if self.type == 'lilypond-block' or self.type == 'lilypond':
395                         s = self.substring (source, 'code')
396                 elif self.type == 'lilypond-file':
397                         name = self.substring (source, 'filename')
398                         s = open (find_file (name)).read ()
399                 return s
400                 
401         def full_ly (self, source):
402                 s = self.ly (source)
403                 if s:
404                         return compose_ly (s, self.match.group ('options'))
405                 return ''
406         
407         def get_hash (self, source):
408                 if not self.hash:
409                         self.hash = abs (hash (self.ly (source)))
410                 if not self.hash:
411                         print 'TYPE:: ' + self.type
412                         print 'CODE:: ' + self.substring (source, 0)
413                         raise 'URG'
414                 return self.hash
415
416         def basename (self, source):
417                 if use_hash_p:
418                         return 'lily-%d' % self.get_hash (source)
419                 raise 'to be done'
420
421         def write_ly (self, source):
422                 if self.type == 'lilypond-block' or self.type == 'lilypond'\
423                        or self.type == 'lilypond-file':
424                         h = open (self.basename (source) + '.ly', 'w')
425                         h.write (self.full_ly (source))
426                         h.close ()
427
428         def output_html (self, source):
429                 base = self.basename (source)
430                 option_string = self.match.group ('options')
431                 if option_string and VERBATIM in split_options (option_string)\
432                    and format == HTML:
433                         verb = verbatim_html (self.substring (source, 'code'))
434                         h.write (output[HTML][VERBATIM] % vars ())
435                 h.write (output[HTML][BEFORE])
436                 h.write (output[HTML][OUTPUT] % vars ())
437                 h.write (output[HTML][AFTER])
438                         
439         def output_latex (self, source):
440                 option_string = self.match.group ('options')
441                 if option_string and VERBATIM in split_options (option_string)\
442                    and format == LATEX:
443                         verb = self.substring (source, 'code')
444                         h.write (output[LATEX][VERBATIM] % vars ())
445                 h.write (output[LATEX][BEFORE])
446                 base = self.basename (source)
447                 h.write (output[LATEX][OUTPUT] % vars ())
448                 h.write (output[LATEX][AFTER])
449                         
450         def output_texinfo (self, source):
451                 option_string = self.match.group ('options')
452                 if option_string and VERBATIM in split_options (option_string):
453                         verb = verbatim_texinfo (self.substring (source,
454                                                                  'code'))
455                         h.write (output[TEXINFO][VERBATIM] % vars ())
456                 h.write ('\n@tex\n')
457                 self.output_latex (source)
458                 h.write ('\n@end tex\n')
459                 
460                 h.write ('\n@html\n')
461                 self.output_html (source)
462                 h.write ('\n@end html\n')
463                         
464         def outdated_p (self, source):
465                 if self.type != 'lilypond-block' and self.type != 'lilypond'\
466                        and self.type != 'lilypond-file':
467                         return None
468                 base = self.basename (source)
469                 if os.path.exists (base + '.ly') \
470                    and os.path.exists (base + '.tex') \
471                    and (use_hash_p \
472                         or self.ly (source) == open (base + '.ly').read ()):
473                         # TODO: something smart with target formats
474                         # (ps, png) and m/ctimes
475                         return None
476                 return self
477
478 def find_snippets (s, type):
479         re = ly.re.compile (re_dict[format][type])
480         i = 0
481         snippets = []
482         m = re.search (s[i:])
483         while m:
484                 snippets.append (Snippet (type, i, m))
485                 i = i + m.end (0)
486                 m = re.search (s[i:])
487         return snippets
488
489 def filter_pipe (input, cmd):
490         if verbose_p:
491                 ly.progress (_ ("Opening filter `%s\'") % cmd)
492                 
493         stdin, stdout, stderr = os.popen3 (cmd)
494         stdin.write (input)
495         status = stdin.close ()
496
497         if not status:
498                 status = 0
499                 output = stdout.read ()
500                 status = stdout.close ()
501                 error = stderr.read ()
502                 
503         if not status:
504                 status = 0
505         signal = 0x0f & status
506         if status or (not output and error):
507                 exit_status = status >> 8
508                 ly.error (_ ("`%s\' failed (%d)") % (cmd, exit_status))
509                 ly.error (_ ("The error log is as follows:"))
510                 sys.stderr.write (error)
511                 sys.stderr.write (stderr.read ())
512                 ly.exit (status)
513         
514         if verbose_p:
515                 ly.progress ('\n')
516
517         return output
518         
519 def run_filter (s):
520         return filter_pipe (s, filter_cmd)
521
522 def compare_index (a, b):
523         return a.start (0) - b.start (0)
524
525 # apply FUNC to every toplevel block in SNIPPETS, ie, enclosed
526 # snippets are skipped.  return list with all non-empty return values
527 # of FUNC
528
529 # Hmm, do we need enclosed snippets at all?  Maybe use MAP_SNIPPETS
530 # once and use simple filter/map on that resulting toplevel list iso
531 # silly map_snippets/do_snippets.
532 def map_snippets (source, snippets, func):
533         global index
534         index = 0
535         lst = []
536         for i in snippets:
537                 if i.start (0) < index:
538                         continue
539                 # lst.append (func (i, source))
540                 x = func (i, source)
541                 if x:
542                         lst.append (x)
543                 index = i.end (0)
544         return lst
545
546 # apply FUNC to every toplevel block in SNIPPETS, ie, enclosed
547 # snippets are skipped.  return last snippet's index
548 def do_snippets (source, snippets, func):
549         global index
550         index = 0
551         for i in snippets:
552                 if i.start (0) < index:
553                         continue
554                 func (i, source)
555                 # ugr, moved to FUNC
556                 #index = i.end ('code')
557         return index
558
559 def process_snippets (source, snippets, cmd):
560         names = map_snippets (source, snippets, Snippet.basename)
561         if names:
562                 ly.system (string.join ([cmd] + names))
563
564         if format == HTML or format == TEXINFO:
565                 for i in names:
566                         to_eps (i)
567                         ly.make_ps_images (i + '.eps', resolution=110)
568
569 LATEX_DOCUMENT = r'''
570 %(preamble)s
571 \begin{document}
572 \typeout{textwidth=\the\textwidth}
573 \typeout{columnsep=\the\columnsep}
574 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
575 \end{document}
576 '''
577 #need anything else besides textwidth?
578 def get_latex_textwidth (source):
579         m = re.search (r'''(?P<preabmle>\\begin\s*{document})''', source)
580         preamble = source[:m.start (0)]
581         latex_document = LATEX_DOCUMENT % vars ()
582         parameter_string = filter_pipe (latex_document, latex_filter_cmd)
583
584         columns = 0
585         m = re.search ('columns=([0-9.]*)', parameter_string)
586         if m:
587                 columns = string.atoi (m.group (1))
588
589         columnsep = 0
590         m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
591         if m:
592                 columnsep = string.atof (m.group (1))
593
594         textwidth = 0
595         m = re.search('textwidth=([0-9.]*)pt', parameter_string)
596         if m:
597                 textwidth = string.atof (m.group (1))
598                 if columns:
599                         textwidth = (textwidth - columnsep) / columns
600
601         return textwidth
602
603
604 ext2format = {
605         '.html' : HTML,
606         '.itely' : TEXINFO,
607         '.lytex' : LATEX,
608         '.tely' : TEXINFO,
609         '.tex': LATEX,
610         '.texi' : TEXINFO,
611         '.texinfo' : TEXINFO,
612         '.xml' : HTML,
613         }
614                                
615 format2ext = {
616         HTML: '.html',
617         #TEXINFO: '.texinfo',
618         TEXINFO: '.texi',
619         LATEX: '.tex',
620         }
621
622 def do_file (input_filename):
623         global format
624         
625         if not format:
626                 e = os.path.splitext (input_filename)[1]
627                 if e in ext2format.keys ():
628                         #FIXME
629                         format = ext2format[e]
630                 else:
631                         ly.error (_ ("cannot determine format for: %s" \
632                                      % input_filename))
633
634         ly.progress (_ ("Reading %s...") % input_filename)
635         global h
636         if not input_filename or input_filename == '-':
637                 h = sys.stdin
638         else:
639                 h = open (input_filename)
640         source = h.read ()
641         ly.progress ('\n')
642
643         ly.progress (_ ("Dissecting..."))
644         snippet_types = ('verbatim', 'verb',
645                          'multiline-comment', 'singleline-comment',
646                          'lilypond', 'lilypond-block', 'lilypond-file',
647                          'include',)
648         snippets = []
649         for i in snippet_types:
650                 snippets += find_snippets (source, i)
651         snippets.sort (compare_index)
652         ly.progress ('\n')
653
654         if output_name == '-' or not output_name:
655                 h = sys.stdout
656                 output_filename = '-'
657         else:
658                 if not os.path.isdir (output_name):
659                         os.mkdir (output_name, 0777)
660                 if input_filename == '-':
661                         input_base = 'stdin'
662                 else:
663                         input_base = os.path.splitext (input_filename)[0]
664                 output_filename = output_name + '/' + input_base \
665                                   + format2ext[format]
666                 h = open (output_filename, 'w')
667                 os.chdir (output_name)
668
669         def filter_source (snippet, source):
670                 global index
671                 # Hmm, why is verbatim's group called 'code'; rename to 'verb'?
672                 #if snippet.match.group ('code'):
673                 # urg
674                 if snippet.type == 'lilypond' or snippet.type == 'lilypond-block':
675                         h.write (source[index:snippet.start ('code')])
676                         h.write (run_filter (snippet.substring (source, 'code')))
677                         h.write (source[snippet.end ('code'):snippet.end (0)])
678                 else:
679                         h.write (source[index:snippet.end (0)])
680                 index = snippet.end (0)
681
682         snippet_output = eval ("Snippet.output_" + format)
683         def compile_output (snippet, source):
684                 global index
685                 # Hmm, why is verbatim's group called 'code'; rename to 'verb'?
686                 # if snippet.match.group ('code'):
687                 # urg
688                 if snippet.type == 'lilypond' \
689                        or snippet.type == 'lilypond-block'\
690                        or snippet.type == 'lilypond-file':
691                         h.write (source[index:snippet.start (0)])
692                         snippet_output (snippet, source)
693                 elif snippet.type == 'include':
694                         h.write (source[index:snippet.start ('filename')])
695                         base = os.path.splitext (snippet.substring (source, 'filename'))[0]
696                         h.write (base + format2ext[format])
697                         h.write (source[snippet.end ('filename'):snippet.end (0)])
698                 else:
699                         h.write (source[index:snippet.end (0)])
700                 index = snippet.end (0)
701
702         global default_ly_options
703         textwidth = 0
704         if format == LATEX and LINEWIDTH not in default_ly_options.keys ():
705                 textwidth = get_latex_textwidth (source)
706                 default_ly_options[LINEWIDTH] = '''%.0f\pt''' % textwidth
707
708         global index
709         if filter_cmd:
710                 index = do_snippets (source, snippets, filter_source)
711                 h.write (source[index:])
712         elif process_cmd:
713                 outdated = map_snippets (source, snippets, Snippet.outdated_p)
714                 ly.progress (_ ("Writing snippets..."))
715                 do_snippets (source, snippets, Snippet.write_ly)
716                 ly.progress ('\n')
717                 if outdated:
718                         ly.progress (_ ("Processing..."))
719                         process_snippets (source, outdated, process_cmd)
720                 else:
721                         ly.progress (_ ("All snippets are up to date..."))
722                 ly.progress ('\n')
723                 ly.progress (_ ("Compiling %s...") % output_filename)
724                 do_snippets (source, snippets, compile_output)
725                 h.write (source[index:])
726                 ly.progress ('\n')
727
728         includes = find_snippets (source, 'include')
729         for i in includes:
730                 os.chdir (original_dir)
731                 options = []
732                 if textwidth:
733                         options.append ('--linewidth=%f' % textwidth)
734
735                 name = i.substring (source, 'filename')
736                 ly.progress (_ ('Processing include: %s') % name)
737                 ly.progress ('\n')
738                 cmd = 'python ' + string.join (sys.argv[:-1]) \
739                       + string.join (options) + ' ' + name
740                 ly.system (cmd)
741
742 def do_options ():
743         global format, output_name
744         global filter_cmd, process_cmd, verbose_p
745         
746         (sh, long) = ly.getopt_args (option_definitions)
747         try:
748                 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
749         except getopt.error, s:
750                 sys.stderr.write ('\n')
751                 ly.error (_ ("getopt says: `%s\'" % s))
752                 sys.stderr.write ('\n')
753                 ly.help ()
754                 ly.exit (2)
755
756         for opt in options:
757                 o = opt[0]
758                 a = opt[1]
759
760                 if 0:
761                         pass
762                 elif o == '--version' or o == '-v':
763                         ly.identify (sys.stdout)
764                         sys.exit (0)
765                 elif o == '--verbose' or o == '-V':
766                         verbose_p = 1
767                 elif o == '--filter' or o == '-F':
768                         filter_cmd = a
769                         process_cmd = 0
770                 elif o == '--format' or o == '-f':
771                         format = a
772                         if a == 'texi-html' or a == 'texi':
773                                 format = TEXINFO
774                 elif o == '--help' or o == '-h':
775                         ly.help ()
776                         sys.exit (0)
777                 elif o == '--include' or o == '-I':
778                         include_path.append (os.path.join (original_dir,
779                                                            ly.abspath (a)))
780                 elif o == '--output' or o == '-o':
781                         output_name = a
782                 elif o == '--outdir':
783                         output_name = a
784                 elif o == '--process' or o == '-P':
785                         process_cmd = a
786                         filter_cmd = 0
787                 elif o == '--warranty' or o == '-w':
788                         if 1 or status:
789                                 ly.warranty ()
790                         sys.exit (0)
791         return files
792
793 def main ():
794         files = do_options ()
795         ly.identify (sys.stderr)
796         ly.setup_environment ()
797         if files:
798                 do_file (files[0])
799
800 if __name__ == '__main__':
801         main ()