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