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