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