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