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