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