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