]> git.donarmstrong.com Git - lilypond.git/blob - scripts/lilypond-book.py
* lily/hyphen-engraver.cc (finalize): suicide unterminated hyphens.
[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 = ''
354
355         # 1 = central C
356         if relative < 0:
357                 relative_quotes += ',' * (- relative - 1)
358         elif relative > 0:
359                 relative_quotes += "'" * relative
360                 
361         program_name = __main__.program_name
362         paper_string = string.join (paper_options, '\n    ') % override
363         preamble_string = string.join (preamble_options, '\n    ') % override
364         notes_string = string.join (notes_options, '\n    ') % vars ()
365         return (PREAMBLE_LY + body) % vars ()
366
367 # BARF
368 # use lilypond-bin for latex (.lytex) books,
369 # and lilypond --preview for html, texinfo books?
370 def to_eps (file):
371         cmd = r'latex "\nonstopmode \input %s"' % file
372         # Ugh.  (La)TeX writes progress and error messages on stdout
373         # Redirect to stderr
374         cmd = '(( %s  >&2 ) >&- )' % cmd
375         ly.system (cmd)
376         ly.system ('dvips -Ppdf -u+lilypond.map -E -o %s.eps %s' \
377                    % (file, file))
378
379 def find_file (name):
380         for i in include_path:
381                 full = os.path.join (i, name)
382                 if os.path.exists (full):
383                         return full
384         ly.error (_ ('file not found: %s\n' % name))
385         ly.exit (1)
386         return ''
387         
388 def verbatim_html (s):
389         return re.sub ('>', '&gt;',
390                        re.sub ('<', '&lt;',
391                                re.sub ('&', '&amp;', s)))
392
393 def verbatim_texinfo (s):
394         return re.sub ('{', '@{',
395                        re.sub ('}', '@}',
396                                re.sub ('@', '@@', s)))
397
398 def split_options (option_string):
399         return re.split (format_res[format]['option-sep'], option_string)
400
401
402 class Chunk:
403         def replacement_text (self):
404                 return ''
405
406         def is_outdated (self):
407                 return 0
408
409 class Substring (Chunk):
410         def __init__ (self, source, start, end):
411                 self.source = source
412                 self.start = start
413                 self.end = end
414
415         def replacement_text (self):
416                 return self.source [self.start:self.end]
417         
418 class Snippet (Chunk):
419         def __init__ (self, type, match, format):
420                 self.type = type
421                 self.match = match
422                 self.hash = 0
423                 self.options = []
424                 self.format = format
425
426         def replacement_text (self):
427                 return self.match.group (0)
428         
429         def substring (self, s):
430                 return self.match.group (s)
431
432         def filter_code (self):
433                 pass # todo
434
435         def __repr__ (self):
436                 return `self.__class__`  +  " type =  " + self.type
437
438 class Include_snippet (Snippet):
439         def processed_filename (self):
440                 f = self.substring ('filename')
441                 return os.path.splitext (f)[0] + format2ext[format]
442
443         def replacement_text (self):
444                 s = self.match.group (0)
445                 f = self.substring ('filename')
446         
447                 return re.sub (f, self.processed_filename (), s)
448
449 class Lilypond_snippet (Snippet):
450         def __init__ (self, type, match, format):
451                 Snippet.__init__ (self, type, match, format)
452                 os = match.group ('options')
453                 if os:
454                         self.options = split_options (os)
455
456         def ly (self):
457                 if self.type == 'lilypond_file':
458                         name = self.substring ('filename')
459                         return '\\renameinput \"%s\"\n' % name\
460                                + open (find_file (name)).read ()
461                 else:
462                         return self.substring ('code')
463                 
464         def full_ly (self):
465                 s = self.ly ()
466                 if s:
467                         return compose_ly (s, self.options)
468                 return ''
469         
470         def get_hash (self):
471                 if not self.hash:
472                         self.hash = abs (hash (self.full_ly ()))
473                 return self.hash
474
475         def basename (self):
476                 if use_hash_p:
477                         return 'lily-%d' % self.get_hash ()
478                 raise 'to be done'
479
480         def write_ly (self):
481                 outf = open (self.basename () + '.ly', 'w')
482                 outf.write (self.full_ly ())
483
484         def is_outdated (self):
485                 base = self.basename ()
486                 if os.path.exists (base + '.ly') \
487                    and os.path.exists (base + '.tex') \
488                    and (use_hash_p \
489                         or self.ly () == open (base + '.ly').read ()):
490                         # TODO: something smart with target formats
491                         # (ps, png) and m/ctimes
492                         return None
493                 return self
494         
495         def replacement_text (self):
496                 func = Lilypond_snippet.__dict__ ['output_' + self.format]
497                 return func (self)
498         
499         def output_html (self):
500                 base = self.basename ()
501                 str = ''
502                 if format == HTML:
503                         str = self.output_print_filename (HTML)
504                         if VERBATIM in self.options:
505                                 verb = verbatim_html (self.substring ('code'))
506                                 str += write (output[HTML][VERBATIM] % vars ())
507                                 
508                 # URGUGHUGHUGUGHU
509                 single = '%(base)s.png' % vars ()
510                 multiple = '%(base)s-page1.png' % vars ()
511                 pictures = (single,)
512                 if os.path.exists (multiple) \
513                    and (not os.path.exists (single)\
514                         or (os.stat (multiple)[stat.ST_MTIME] \
515                             > os.stat (single)[stat.ST_MTIME])):
516                         pictures = glob.glob ('%(base)s-page*.png' % vars ())
517                 
518                 str += output[HTML][BEFORE] % vars ()
519                 for picture in pictures:
520                         str += output[HTML][OUTPUT] % vars ()
521                 str += output[HTML][AFTER] % vars ()
522                 return str
523                         
524         def output_latex (self):
525                 str = ''
526                 base = self.basename ()
527                 if format == LATEX:
528                         str = self.output_print_filename (LATEX)
529                         if  VERBATIM in self.options:
530                                 verb = self.substring ('code')
531                                 str += (output[LATEX][VERBATIM] % vars ())
532                 str +=  (output[LATEX][BEFORE]
533                          + (output[LATEX][OUTPUT] % vars ())
534                          + output[LATEX][AFTER])
535                 return str
536
537         def output_print_filename (self,format):
538                 str = ''
539                 if  PRINTFILENAME in self.options:
540                         base = self.basename ()
541                         filename = self.substring ('filename')
542                         str = output[format][PRINTFILENAME] % vars ()
543                 return str
544
545         def output_texinfo (self):
546                 str = ''
547                 base = self.basename ()
548                 if TEXIDOC in self.options:
549                         texidoc = base + '.texidoc'
550                         if os.path.exists (texidoc):
551                                 str += '@include %(texidoc)s\n' % vars ()
552
553                 if  VERBATIM in self.options:
554                         verb = verbatim_texinfo (self.substring ('code'))
555                         str +=  (output[TEXINFO][VERBATIM] % vars ())
556
557                 str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
558                 str += ('@html\n' + self.output_html () + '\n@end html\n')
559                 # need par after picture
560                 str += '\n'
561
562                 return str
563                         
564 snippet_type_to_class = {
565         'lilypond_file' : Lilypond_snippet,
566         'lilypond_block' : Lilypond_snippet,
567         'lilypond' : Lilypond_snippet,
568         'include' : Include_snippet,
569         }
570
571 def find_toplevel_snippets (s, types):
572         res = {}
573         for i in types:
574                 res[i] = ly.re.compile (snippet_res[format][i])
575
576         snippets = []
577         index = 0
578         ##  found = dict (map (lambda x: (x, None), types))
579         ## urg python2.1
580         found = {}
581         map (lambda x, f=found: f.setdefault (x, None), types)
582
583         # We want to search for multiple regexes, without searching
584         # the string multiple times for one regex.
585         # Hence, we use earlier results to limit the string portion
586         # where we search.
587         # Since every part of the string is traversed at most once for
588         # every type of snippet, this is linear.
589
590         while 1:
591                 first = None
592                 endex = 1 << 30
593                 for type in types:
594                         if not found[type] or found[type][0] < index:
595                                 found[type] = None
596                                 m = res[type].search (s[index:endex])
597                                 if not m:
598                                         continue
599                                 
600                                 cl = Snippet
601                                 if snippet_type_to_class.has_key (type):
602                                         cl = snippet_type_to_class[type]
603                                 snip = cl (type, m, format)
604                                 start = index + m.start (0)
605                                 found[type] = (start, snip)
606
607                         if found[type] \
608                            and (not first or found[type][0] < found[first][0]):
609                                 first = type
610                                 endex = found[first][0]
611
612                 if not first:
613                         snippets.append (Substring (s, index, len (s)))
614                         break
615
616                 (start , snip) = found[first]
617                 snippets.append (Substring (s, index, start))
618                 snippets.append (snip)
619                 index = start + len (snip.match.group (0))
620
621         return snippets
622
623 def filter_pipe (input, cmd):
624         if verbose_p:
625                 ly.progress (_ ("Opening filter `%s\'") % cmd)
626                 
627         stdin, stdout, stderr = os.popen3 (cmd)
628         stdin.write (input)
629         status = stdin.close ()
630
631         if not status:
632                 status = 0
633                 output = stdout.read ()
634                 status = stdout.close ()
635                 error = stderr.read ()
636                 
637         if not status:
638                 status = 0
639         signal = 0x0f & status
640         if status or (not output and error):
641                 exit_status = status >> 8
642                 ly.error (_ ("`%s\' failed (%d)") % (cmd, exit_status))
643                 ly.error (_ ("The error log is as follows:"))
644                 sys.stderr.write (error)
645                 sys.stderr.write (stderr.read ())
646                 ly.exit (status)
647         
648         if verbose_p:
649                 ly.progress ('\n')
650
651         return output
652         
653 def run_filter (s):
654         return filter_pipe (s, filter_cmd)
655
656 def process_snippets (cmd, snippets):
657         names = filter (lambda x: x, map (Lilypond_snippet.basename, snippets))
658         if names:
659                 ly.system (string.join ([cmd] + names))
660
661         if format == HTML or format == TEXINFO:
662                 for i in names:
663                         if os.path.exists (i + '.tex'):
664                                 to_eps (i)
665                                 ly.make_ps_images (i + '.eps', resolution=110)
666
667 LATEX_DOCUMENT = r'''
668 %(preamble)s
669 \begin{document}
670 \typeout{textwidth=\the\textwidth}
671 \typeout{columnsep=\the\columnsep}
672 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
673 \end{document}
674 '''
675 #need anything else besides textwidth?
676 def get_latex_textwidth (source):
677         m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
678         preamble = source[:m.start (0)]
679         latex_document = LATEX_DOCUMENT % vars ()
680         parameter_string = filter_pipe (latex_document, latex_filter_cmd)
681
682         columns = 0
683         m = re.search ('columns=([0-9.]*)', parameter_string)
684         if m:
685                 columns = string.atoi (m.group (1))
686
687         columnsep = 0
688         m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
689         if m:
690                 columnsep = string.atof (m.group (1))
691
692         textwidth = 0
693         m = re.search('textwidth=([0-9.]*)pt', parameter_string)
694         if m:
695                 textwidth = string.atof (m.group (1))
696                 if columns:
697                         textwidth = (textwidth - columnsep) / columns
698
699         return textwidth
700
701 ext2format = {
702         '.html' : HTML,
703         '.itely' : TEXINFO,
704         '.lytex' : LATEX,
705         '.tely' : TEXINFO,
706         '.tex': LATEX,
707         '.texi' : TEXINFO,
708         '.texinfo' : TEXINFO,
709         '.xml' : HTML,
710         }
711                                
712 format2ext = {
713         HTML: '.html',
714         #TEXINFO: '.texinfo',
715         TEXINFO: '.texi',
716         LATEX: '.tex',
717         }
718         
719 def do_file (input_filename):
720         #ugh
721         global format
722         if not format:
723                 e = os.path.splitext (input_filename)[1]
724                 if e in ext2format.keys ():
725                         #FIXME
726                         format = ext2format[e]
727                 else:
728                         ly.error (_ ("cannot determine format for: %s" \
729                                      % input_filename))
730
731         if not input_filename or input_filename == '-':
732                 in_handle = sys.stdin
733                 input_fullname = '<stdin>'
734         else:
735                 if os.path.exists (input_filename):
736                         input_fullname = input_filename
737                 elif format == LATEX:
738                         # urg python interface to libkpathsea?
739                         input_fullname = ly.read_pipe ('kpsewhich '
740                                                        + input_filename)[:-1]
741                 else:
742                         input_fullname = find_file (input_filename)
743                 in_handle = open (input_fullname)
744                 
745         if input_filename == '-':
746                 input_base = 'stdin'
747         else:
748                 input_base = os.path.basename \
749                              (os.path.splitext (input_filename)[0])
750
751         # only default to stdout when filtering 
752         if output_name == '-' or (not output_name and filter_cmd):
753                 output_filename = '-'
754                 output_file = sys.stdout
755         else:
756                 if not output_name:
757                         output_filename = input_base + format2ext[format]
758                 else:
759                         if not os.path.isdir (output_name):
760                                 os.mkdir (output_name, 0777)
761                         output_filename = (output_name
762                                            + '/' + input_base
763                                            + format2ext[format])
764
765
766                 if (os.path.exists (input_filename) and 
767                     os.path.exists (output_filename) and 
768                     os.path.samefile (output_filename, input_fullname)):
769                         ly.error (_("Output would overwrite input file; use --output."))
770                         sys.exit (2)
771
772                 output_file = open (output_filename, 'w')
773                 if output_name:
774                         os.chdir (output_name)
775
776         ly.progress (_ ("Reading %s...") % input_fullname)
777         source = in_handle.read ()
778         ly.progress ('\n')
779         
780         snippet_types = (
781                 'lilypond_block',
782 #               'verb',
783                 'verbatim',
784                 'singleline_comment',
785                 'multiline_comment',
786                 'lilypond_file',
787                 'include',
788                 'lilypond', )
789         ly.progress (_ ("Dissecting..."))
790         chunks = find_toplevel_snippets (source, snippet_types)
791         ly.progress ('\n')
792
793         global default_ly_options
794         textwidth = 0
795         if LINEWIDTH not in default_ly_options.keys ():
796                 if format == LATEX:
797                         textwidth = get_latex_textwidth (source)
798                         default_ly_options[LINEWIDTH] = '''%.0f\\pt''' \
799                                                         % textwidth
800                 elif format == TEXINFO:
801                         for (k, v) in texi_linewidths.items ():
802                                 s = chunks[0].replacement_text ()
803                                 if re.search (k, s):
804                                         default_ly_options[LINEWIDTH] = v
805                                         break
806
807         if filter_cmd:
808                 pass # todo
809         elif process_cmd:
810                 outdated = filter (lambda x: x.__class__ == Lilypond_snippet \
811                                    and x.is_outdated (), chunks)
812                 ly.progress (_ ("Writing snippets..."))
813                 map (Lilypond_snippet.write_ly, outdated)
814                 ly.progress ('\n')
815
816                 if outdated:
817                         ly.progress (_ ("Processing..."))
818                         process_snippets (process_cmd, outdated)
819                 else:
820                         ly.progress (_ ("All snippets are up to date..."))
821                 ly.progress ('\n')
822
823                 ly.progress (_ ("Compiling %s...") % output_filename)
824                 output_file.writelines ([s.replacement_text () \
825                                          for s in chunks])
826                 ly.progress ('\n')
827
828         def process_include (snippet):
829                 os.chdir (original_dir)
830                 name = snippet.substring ('filename')
831                 ly.progress (_ ('Processing include: %s') % name)
832                 ly.progress ('\n')
833                 do_file (name)
834                 
835         map (process_include,
836              filter (lambda x: x.__class__ == Include_snippet, chunks))
837
838 def do_options ():
839         global format, output_name
840         global filter_cmd, process_cmd, verbose_p
841         
842         (sh, long) = ly.getopt_args (option_definitions)
843         try:
844                 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
845         except getopt.error, s:
846                 sys.stderr.write ('\n')
847                 ly.error (_ ("getopt says: `%s\'" % s))
848                 sys.stderr.write ('\n')
849                 ly.help ()
850                 ly.exit (2)
851
852         for opt in options:
853                 o = opt[0]
854                 a = opt[1]
855
856                 if 0:
857                         pass
858                 elif o == '--filter' or o == '-F':
859                         filter_cmd = a
860                         process_cmd = 0
861                 elif o == '--format' or o == '-f':
862                         format = a
863                         if a == 'texi-html' or a == 'texi':
864                                 format = TEXINFO
865                 elif o == '--help' or o == '-h':
866                         ly.help ()
867                         sys.exit (0)
868                 elif o == '--include' or o == '-I':
869                         include_path.append (os.path.join (original_dir,
870                                                            ly.abspath (a)))
871                 elif o == '--output' or o == '-o':
872                         output_name = a
873                 elif o == '--outdir':
874                         output_name = a
875                 elif o == '--process' or o == '-P':
876                         process_cmd = a
877                         filter_cmd = 0
878                 elif o == '--version' or o == '-v':
879                         ly.identify (sys.stdout)
880                         sys.exit (0)
881                 elif o == '--verbose' or o == '-V':
882                         verbose_p = 1
883                 elif o == '--warranty' or o == '-w':
884                         if 1 or status:
885                                 ly.warranty ()
886                         sys.exit (0)
887         return files
888
889 def main ():
890         files = do_options ()
891         global process_cmd
892         if process_cmd:
893                 process_cmd += string.join ([(' -I %s' % p)
894                                              for p in include_path])
895
896         ly.identify (sys.stderr)
897         ly.setup_environment ()
898         if files:
899                 do_file (files[0])
900
901 if __name__ == '__main__':
902         main ()