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