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