]> git.donarmstrong.com Git - lilypond.git/blob - scripts/filter-lilypond-book.py
Speed-up and clean-ups.
[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 snippet_res = {
144         HTML: {
145         #'header': no_match,
146         #'input': no_match,
147         #'landscape': no_match,
148         #'ly2dvi': r'(?m)(?P<match><ly2dvifile(?P<options>[^>]+)?>\s*(?P<filename>[^<]+)\s*</ly2dvifile>)',
149         #'multicols': no_match,
150         #'numcols': no_match,
151         'include':  no_match,
152         'lilypond' : '(?m)(?P<match><lilypond((?P<options>[^:]*):)(?P<code>.*?)/>)',
153         'lilypond-block': r'''(?ms)(?P<match><lilypond(?P<options>[^>]+)?>(?P<code>.*?)</lilypond>)''',
154         'lilypond-file': r'(?m)(?P<match><lilypondfile(?P<options>[^>]+)?>\s*(?P<filename>[^<]+)\s*</lilypondfile>)',
155         'multiline-comment': r"(?sm)\s*(?!@c\s+)(?P<code><!--\s.*?!-->)\s",
156         'singleline-comment': no_match,
157         'verb': r'''(?P<code><pre>.*?</pre>)''',
158         'verbatim': r'''(?s)(?P<code><pre>\s.*?</pre>\s)''',
159         },
160
161         LATEX: {
162         #'def-post-re': r"\\def\\postLilyPondExample",
163         #'def-pre-re': r"\\def\\preLilyPondExample",
164         #'header': r"\n*\\documentclass\s*(\[.*?\])?",
165         #'ly2dvi': no_match,
166         #'multicols': r"(?P<code>\\(?P<be>begin|end)\s*{multicols}({(?P<num>\d+)?})?)",
167         #'numcols': r"(?P<code>\\(?P<num>one|two)column)",
168         #'usepackage-graphics': r"\usepackage\s*{graphics}",
169         'include': r'(?m)^[^%\n]*?(?P<match>\\input{(?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         'lilypond-file': r'(?m)^[^%\n]*?(?P<match>\\lilypondfile\s*(\[(?P<options>.*?)\])?\s*\{(?P<filename>.+)})',
173         'multiline-comment': no_match,
174         'singleline-comment': r"(?m)^.*?(?P<match>(?P<code>^%.*$\n+))",
175         'verb': r"(?P<code>\\verb(?P<del>.).*?(?P=del))",
176         'verbatim': r"(?s)(?P<code>\\begin\s*{verbatim}.*?\\end{verbatim})",
177         },
178
179         TEXINFO: {
180         #'header': no_match,
181         #'landscape': no_match,
182         #'multicols': no_match,
183         #'numcols': no_match,
184         'include':  '(?m)^[^%\n]*?(?P<match>@include\s+(?P<filename>\S*))',
185         'lilypond' : '(?m)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?{(?P<code>.*?)})',
186         'lilypond-block': r'''(?ms)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?\s(?P<code>.*?)@end lilypond)\s''',
187         'lilypond-file': '(?m)^(?P<match>@lilypondfile(\[(?P<options>[^]]*)\])?{(?P<filename>[^}]+)})',
188         'multiline-comment': r"(?sm)^\s*(?!@c\s+)(?P<code>@ignore\s.*?@end ignore)\s",
189         'singleline-comment': r"(?m)^.*?(?P<match>(?P<code>@c.*$\n+))",
190         'verb': r'''(?P<code>@code{.*?})''',
191         'verbatim': r'''(?s)(?P<code>@example\s.*?@end example\s)''',
192         },
193         }
194
195 format_res = {
196         HTML: {
197         'option-sep' : '\s*',
198         'intertext': r',?\s*intertext=\".*?\"',
199         },
200         LATEX: {
201         'intertext': r',?\s*intertext=\".*?\"',
202         'option-sep' : ',\s*',
203         },
204         TEXINFO: {
205         'intertext': r',?\s*intertext=\".*?\"',
206         'option-sep' : ',\s*',
207         },
208         }
209
210 NOTES = 'body'
211 PREAMBLE = 'preamble'
212 PAPER = 'paper'
213
214 ly_options = {
215         NOTES: {
216         #'xrelative': r'''\relative #(ly:make-pitch %(relative)s 0 0)''',
217         'relative': r'''\relative c%(relative_quotes)s''',
218         },
219         PAPER: {
220         'indent' : r'''
221     indent = %(indent)s''',
222         'linewidth' : r'''
223     linewidth = %(linewidth)s''',
224         'noindent' : r'''
225     indent = 0.0\mm''',
226         'notime' : r'''
227     \translator {
228         \StaffContext
229         \remove Time_signature_engraver
230     }''',
231         'raggedright' : r'''
232     indent = 0.0\mm
233     raggedright = ##t''',
234         },
235         PREAMBLE: {
236         'staffsize': r'''
237 #(set-global-staff-size %(staffsize)s)''',
238         },
239         }
240
241 output = {
242         HTML : {
243         AFTER: '',
244         BEFORE: '',
245         OUTPUT: r'''<img align="center" valign="center"
246 border="0" src="%(base)s.png" alt="[picture of music]">''',
247         VERBATIM: r'''<pre>
248 %(verb)s</pre>''',
249         },
250         
251         LATEX : {
252         AFTER: '',
253         BEFORE: '',
254         OUTPUT: r'''{\parindent 0pt
255 \catcode`\@=12
256 \ifx\preLilyPondExample\preLilyPondExample\fi
257 \def\lilypondbook{}
258 \input %(base)s.tex
259 \ifx\preLilyPondExample\postLilyPondExample\fi
260 \catcode`\@=0}''',
261         VERBATIM: r'''\begin{verbatim}
262 %(verb)s\end{verbatim}
263 ''',
264         },
265         
266         TEXINFO :       {
267         BEFORE: '',
268         AFTER: '',
269         VERBATIM: r'''@example
270 %(verb)s@end example''',
271         
272         },
273         
274         }
275
276 PREAMBLE_LY = r'''%% Generated by %(program_name)s
277 %% Options: [%(option_string)s]
278 %(preamble_string)s
279 \paper {%(paper_string)s
280 }
281 ''' 
282
283 FRAGMENT_LY = r'''\score{
284     \notes%(notes_string)s{
285         %(code)s    }
286 }'''
287 FULL_LY = '%(code)s'
288
289
290 def compose_ly (code, option_string):
291         options = []
292         # urg
293         for i in default_ly_options.keys ():
294                 options.append (i)
295                 vars ()[i] = default_ly_options[i]
296
297         if option_string:
298                 options = options + split_options (option_string)
299         
300         m = re.search (r'''\\score''', code)
301         if not m and (not options \
302                       or not 'nofragment' in options \
303                       or 'fragment' in options):
304                 options.append ('raggedright')
305                 body = FRAGMENT_LY
306         else:
307                 body = FULL_LY
308
309         # defaults
310         relative = 0
311         staffsize = '16'
312
313         notes_options = []
314         paper_options = []
315         preamble_options = []
316         for i in options:
317                 if string.find (i, '=') > 0:
318                         key, value = string.split (i, '=')
319                         # hmm
320                         vars ()[key] = value
321                 else:
322                         key = i
323
324                 if key in ly_options[NOTES].keys ():
325                         notes_options.append (ly_options[NOTES][key])
326                 elif key in ly_options[PREAMBLE].keys ():
327                         preamble_options.append (ly_options[PREAMBLE][key])
328                 elif key in ly_options[PAPER].keys ():
329                         paper_options.append (ly_options[PAPER][key])
330                 elif key not in ('fragment', 'nofragment',
331                                  'relative', 'verbatim'):
332                         ly.warning (_("ignoring unknown ly option: %s") % i)
333
334         relative_quotes = (",,,", ",,", ",", "", "'", "''", "'''")[relative-3]
335         program_name = __main__.program_name
336         notes_string = string.join (notes_options, '\n    ') % vars ()
337         paper_string = string.join (paper_options, '\n    ') % vars ()
338         preamble_string = string.join (preamble_options, '\n    ') % vars ()
339         return (PREAMBLE_LY + body) % vars ()
340
341
342 # BARF
343 # use lilypond-bin for latex (.lytex) books,
344 # and lilypond --preview for html, texinfo books?
345 def to_eps (file):
346         cmd = r'latex "\nonstopmode \input %s"' % file
347         # Ugh.  (La)TeX writes progress and error messages on stdout
348         # Redirect to stderr
349         cmd = '(( %s  >&2 ) >&- )' % cmd
350         ly.system (cmd)
351         ly.system ('dvips -Ppdf -u+lilypond.map -E -o %s.eps %s' \
352                    % (file, file))
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 (format_res[format]['option-sep'], option_string)
375
376
377 ## make index static of Snippet?
378 index = 0
379
380 class Snippet:
381         def __init__ (self, type, source, index, match):
382                 self.type = type
383                 self.source = source
384                 self.index = index
385                 self.match = match
386                 self.hash = 0
387
388         def start (self, s):
389                 return self.index + self.match.start (s)
390
391         def end (self, s):
392                 return self.index + self.match.end (s)
393
394         def substring (self, s):
395                 return self.source[self.start (s):self.end (s)]
396
397         def ly (self):
398                 s = ''
399                 if self.type == 'lilypond-block' or self.type == 'lilypond':
400                         s = self.substring ('code')
401                 elif self.type == 'lilypond-file':
402                         name = self.substring ('filename')
403                         s = open (find_file (name)).read ()
404                 return s
405                 
406         def full_ly (self):
407                 s = self.ly ()
408                 if s:
409                         return compose_ly (s, self.match.group ('options'))
410                 return ''
411         
412         def get_hash (self):
413                 if not self.hash:
414                         self.hash = abs (hash (self.ly ()))
415                 if not self.hash:
416                         print 'TYPE:: ' + self.type
417                         print 'CODE:: ' + self.substring (0)
418                         raise 'URG'
419                 return self.hash
420
421         def basename (self):
422                 if use_hash_p:
423                         return 'lily-%d' % self.get_hash ()
424                 raise 'to be done'
425
426         def write_ly (self):
427                 if self.type == 'lilypond-block' or self.type == 'lilypond'\
428                        or self.type == 'lilypond-file':
429                         h = open (self.basename () + '.ly', 'w')
430                         h.write (self.full_ly ())
431                         h.close ()
432
433         def output_html (self):
434                 base = self.basename ()
435                 option_string = self.match.group ('options')
436                 if option_string and VERBATIM in split_options (option_string)\
437                    and format == HTML:
438                         verb = verbatim_html (self.substring ('code'))
439                         h.write (output[HTML][VERBATIM] % vars ())
440                 h.write (output[HTML][BEFORE])
441                 h.write (output[HTML][OUTPUT] % vars ())
442                 h.write (output[HTML][AFTER])
443                         
444         def output_latex (self):
445                 option_string = self.match.group ('options')
446                 if option_string and VERBATIM in split_options (option_string)\
447                    and format == LATEX:
448                         verb = self.substring ('code')
449                         h.write (output[LATEX][VERBATIM] % vars ())
450                 h.write (output[LATEX][BEFORE])
451                 base = self.basename ()
452                 h.write (output[LATEX][OUTPUT] % vars ())
453                 h.write (output[LATEX][AFTER])
454                         
455         def output_texinfo (self):
456                 option_string = self.match.group ('options')
457                 if option_string and VERBATIM in split_options (option_string):
458                         verb = verbatim_texinfo (self.substring ('code'))
459                         h.write (output[TEXINFO][VERBATIM] % vars ())
460                 h.write ('\n@tex\n')
461                 self.output_latex ()
462                 h.write ('\n@end tex\n')
463                 
464                 h.write ('\n@html\n')
465                 self.output_html ()
466                 h.write ('\n@end html\n')
467                         
468         def outdated_p (self):
469                 if self.type != 'lilypond-block' and self.type != 'lilypond'\
470                        and self.type != 'lilypond-file':
471                         return None
472                 base = self.basename ()
473                 if os.path.exists (base + '.ly') \
474                    and os.path.exists (base + '.tex') \
475                    and (use_hash_p \
476                         or self.ly () == open (base + '.ly').read ()):
477                         # TODO: something smart with target formats
478                         # (ps, png) and m/ctimes
479                         return None
480                 return self
481
482         def filter_code (self):
483                 global index
484                 # Hmm, why is verbatim's group called 'code'; rename to 'verb'?
485                 #if snippet.match.group ('code'):
486                 # urg
487                 if self.type == 'lilypond' or self.type == 'lilypond-block':
488                         h.write (self.source[index:self.start ('code')])
489                         h.write (run_filter (self.substring ('code')))
490                         h.write (self.source[self.end ('code'):self.end (0)])
491                 else:
492                         h.write (self.source[index:self.end (0)])
493                 index = self.end (0)
494
495         def compile_output (self):
496                 global index
497                 # Hmm, why is verbatim's group called 'code'; rename to 'verb'?
498                 # if snippet.match.group ('code'):
499                 # urg
500                 if self.type == 'lilypond' \
501                        or self.type == 'lilypond-block'\
502                        or self.type == 'lilypond-file':
503                         h.write (self.source[index:self.start (0)])
504                         snippet_output = eval ("Snippet.output_" + format)
505                         snippet_output (self)
506                 elif self.type == 'include':
507                         h.write (self.source[index:self.start ('filename')])
508                         base = os.path.splitext (self.substring ('filename'))[0]
509                         h.write (base + format2ext[format])
510                         h.write (self.source[self.end ('filename'):self.end (0)])
511                 else:
512                         h.write (self.source[index:self.end (0)])
513                 index = self.end (0)
514
515 def find_toplevel_snippets (s, types):
516         res = {}
517         for i in types:
518                 res[i] = ly.re.compile (snippet_res[format][i])
519
520         snippets = []
521         index = 0
522         while 1:
523                 matches = {}
524                 first = 0
525                 endex = 1 << 30
526                 for i in types:
527                         matches[i] = res[i].search (s[index:index+endex])
528                         if matches[i]:
529                                 start = matches[i].start (0)
530                                 if start < endex:
531                                         endex = start
532                                 if not first \
533                                        or start < matches[first].start (0):
534                                         first = i
535                 if not first:
536                         break
537                 snippets.append (Snippet (first, s, index, matches[first]))
538                 index = index + matches[first].end (0)
539                 
540         return snippets
541
542 def filter_pipe (input, cmd):
543         if verbose_p:
544                 ly.progress (_ ("Opening filter `%s\'") % cmd)
545                 
546         stdin, stdout, stderr = os.popen3 (cmd)
547         stdin.write (input)
548         status = stdin.close ()
549
550         if not status:
551                 status = 0
552                 output = stdout.read ()
553                 status = stdout.close ()
554                 error = stderr.read ()
555                 
556         if not status:
557                 status = 0
558         signal = 0x0f & status
559         if status or (not output and error):
560                 exit_status = status >> 8
561                 ly.error (_ ("`%s\' failed (%d)") % (cmd, exit_status))
562                 ly.error (_ ("The error log is as follows:"))
563                 sys.stderr.write (error)
564                 sys.stderr.write (stderr.read ())
565                 ly.exit (status)
566         
567         if verbose_p:
568                 ly.progress ('\n')
569
570         return output
571         
572 def run_filter (s):
573         return filter_pipe (s, filter_cmd)
574
575 def process_snippets (cmd, snippets):
576         names = filter (lambda x:x, map (Snippet.basename, snippets))
577         if names:
578                 ly.system (string.join ([cmd] + names))
579
580         if format == HTML or format == TEXINFO:
581                 for i in names:
582                         to_eps (i)
583                         ly.make_ps_images (i + '.eps', resolution=110)
584
585 LATEX_DOCUMENT = r'''
586 %(preamble)s
587 \begin{document}
588 \typeout{textwidth=\the\textwidth}
589 \typeout{columnsep=\the\columnsep}
590 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
591 \end{document}
592 '''
593 #need anything else besides textwidth?
594 def get_latex_textwidth (source):
595         m = re.search (r'''(?P<preabmle>\\begin\s*{document})''', source)
596         preamble = source[:m.start (0)]
597         latex_document = LATEX_DOCUMENT % vars ()
598         parameter_string = filter_pipe (latex_document, latex_filter_cmd)
599
600         columns = 0
601         m = re.search ('columns=([0-9.]*)', parameter_string)
602         if m:
603                 columns = string.atoi (m.group (1))
604
605         columnsep = 0
606         m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
607         if m:
608                 columnsep = string.atof (m.group (1))
609
610         textwidth = 0
611         m = re.search('textwidth=([0-9.]*)pt', parameter_string)
612         if m:
613                 textwidth = string.atof (m.group (1))
614                 if columns:
615                         textwidth = (textwidth - columnsep) / columns
616
617         return textwidth
618
619
620 ext2format = {
621         '.html' : HTML,
622         '.itely' : TEXINFO,
623         '.lytex' : LATEX,
624         '.tely' : TEXINFO,
625         '.tex': LATEX,
626         '.texi' : TEXINFO,
627         '.texinfo' : TEXINFO,
628         '.xml' : HTML,
629         }
630                                
631 format2ext = {
632         HTML: '.html',
633         #TEXINFO: '.texinfo',
634         TEXINFO: '.texi',
635         LATEX: '.tex',
636         }
637
638 def do_file (input_filename):
639
640         print 'do_file: ' + input_filename
641         global format
642         
643         if not format:
644                 e = os.path.splitext (input_filename)[1]
645                 if e in ext2format.keys ():
646                         #FIXME
647                         format = ext2format[e]
648                 else:
649                         ly.error (_ ("cannot determine format for: %s" \
650                                      % input_filename))
651
652         ly.progress (_ ("Reading %s...") % input_filename)
653         global h
654         if not input_filename or input_filename == '-':
655                 h = sys.stdin
656         else:
657                 h = open (input_filename)
658         source = h.read ()
659         ly.progress ('\n')
660
661         ly.progress (_ ("Dissecting..."))
662         snippets = find_toplevel_snippets (source, snippet_res[format].keys ())
663         ly.progress ('\n')
664
665         if output_name == '-' or not output_name:
666                 h = sys.stdout
667                 output_filename = '-'
668         else:
669                 if not os.path.isdir (output_name):
670                         os.mkdir (output_name, 0777)
671                 if input_filename == '-':
672                         input_base = 'stdin'
673                 else:
674                         input_base = os.path.splitext (input_filename)[0]
675                 output_filename = output_name + '/' + input_base \
676                                   + format2ext[format]
677                 h = open (output_filename, 'w')
678                 os.chdir (output_name)
679
680         global default_ly_options
681         textwidth = 0
682         if format == LATEX and LINEWIDTH not in default_ly_options.keys ():
683                 textwidth = get_latex_textwidth (source)
684                 default_ly_options[LINEWIDTH] = '''%.0f\pt''' % textwidth
685
686         global index
687         if filter_cmd:
688                 index = 0
689                 map (Snippet.filter_code, snippets)
690                 h.write (source[index:])
691         elif process_cmd:
692                 outdated = filter (lambda x:x,
693                                    map (Snippet.outdated_p, snippets))
694                 ly.progress (_ ("Writing snippets..."))
695                 map (Snippet.write_ly, snippets)
696                 ly.progress ('\n')
697                 
698                 if outdated:
699                         ly.progress (_ ("Processing..."))
700                         process_snippets (process_cmd, outdated)
701                 else:
702                         ly.progress (_ ("All snippets are up to date..."))
703                 ly.progress ('\n')
704                 
705                 ly.progress (_ ("Compiling %s...") % output_filename)
706                 index = 0
707                 map (Snippet.compile_output, snippets)
708                 h.write (source[index:])
709                 ly.progress ('\n')
710
711         if h != sys.stdout:
712                 h.close ()
713
714         def process_include (snippet):
715                 print 'type: ' + snippet.type
716                 os.chdir (original_dir)
717                 name = snippet.substring ('filename')
718                 ly.progress (_ ('Processing include: %s') % name)
719                 ly.progress ('\n')
720                 do_file (name)
721
722         map (process_include, filter (lambda x: x.type == 'include', snippets))
723
724 def do_options ():
725         global format, output_name
726         global filter_cmd, process_cmd, verbose_p
727         
728         (sh, long) = ly.getopt_args (option_definitions)
729         try:
730                 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
731         except getopt.error, s:
732                 sys.stderr.write ('\n')
733                 ly.error (_ ("getopt says: `%s\'" % s))
734                 sys.stderr.write ('\n')
735                 ly.help ()
736                 ly.exit (2)
737
738         for opt in options:
739                 o = opt[0]
740                 a = opt[1]
741
742                 if 0:
743                         pass
744                 elif o == '--version' or o == '-v':
745                         ly.identify (sys.stdout)
746                         sys.exit (0)
747                 elif o == '--verbose' or o == '-V':
748                         verbose_p = 1
749                 elif o == '--filter' or o == '-F':
750                         filter_cmd = a
751                         process_cmd = 0
752                 elif o == '--format' or o == '-f':
753                         format = a
754                         if a == 'texi-html' or a == 'texi':
755                                 format = TEXINFO
756                 elif o == '--help' or o == '-h':
757                         ly.help ()
758                         sys.exit (0)
759                 elif o == '--include' or o == '-I':
760                         include_path.append (os.path.join (original_dir,
761                                                            ly.abspath (a)))
762                 elif o == '--output' or o == '-o':
763                         output_name = a
764                 elif o == '--outdir':
765                         output_name = a
766                 elif o == '--process' or o == '-P':
767                         process_cmd = a
768                         filter_cmd = 0
769                 elif o == '--warranty' or o == '-w':
770                         if 1 or status:
771                                 ly.warranty ()
772                         sys.exit (0)
773         return files
774
775 def main ():
776         files = do_options ()
777         ly.identify (sys.stderr)
778         ly.setup_environment ()
779         if files:
780                 do_file (files[0])
781
782 if __name__ == '__main__':
783         main ()