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