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