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