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