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