]> git.donarmstrong.com Git - lilypond.git/blob - scripts/lilypond-book.py
f19803b8753e52f117d708b476e6e47f2c5bfeff
[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" BOOK.tely
14
15 TODO:
16     *  ly-options: intertext ?
17     *  --linewidth?
18     *  eps in latex / eps by lilypond -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 stat
30 import string
31
32 #
33 # TODO:
34 #
35 #  * use --png --ps --pdf for making images?
36 #
37
38 ################################################################
39 # Users of python modules should include this snippet
40 # and customize variables below.
41
42 # We'll suffer this path init stuff as long as we don't install our
43 # python packages in <prefix>/lib/pythonx.y (and don't kludge around
44 # it as we do with teTeX on Red Hat Linux: set some environment var
45 # (PYTHONPATH) in profile)
46
47 # If set, LILYPONDPREFIX must take prevalence
48 # if datadir is not set, we're doing a build and LILYPONDPREFIX
49 import getopt, os, sys
50 datadir = '@local_lilypond_datadir@'
51 if not os.path.isdir (datadir):
52         datadir = '@lilypond_datadir@'
53 if os.environ.has_key ('LILYPONDPREFIX'):
54         datadir = os.environ['LILYPONDPREFIX']
55         while datadir[-1] == os.sep:
56                 datadir= datadir[:-1]
57
58 sys.path.insert (0, os.path.join (datadir, 'python'))
59
60 # Customize these
61 #if __name__ == '__main__':
62
63 import lilylib as ly
64 global _;_=ly._
65 global re;re = ly.re
66
67 # lilylib globals
68 program_version = '@TOPLEVEL_VERSION@'
69 program_name = sys.argv[0]
70 verbose_p = 0
71 pseudo_filter_p = 0
72 original_dir = os.getcwd ()
73
74 help_summary = _ ('''Process LilyPond snippets in hybrid HTML, LaTeX or texinfo document.
75 Example usage:
76
77    lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
78    lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" BOOK
79    lilypond-book --process='lilypond -I include' BOOK
80
81 ''')
82
83 copyright = ('Jan Nieuwenhuizen <janneke@gnu.org>',
84              'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
85
86 option_definitions = [
87         (_ ("EXT"), 'f', 'format', _ ("use output format EXT (texi [default], texi-html, latex, html)")),
88         (_ ("FILTER"), 'F', 'filter', _ ("pipe snippets through FILTER [convert-ly -n -]")),
89         ('', 'h', 'help', _ ("print this help")),
90         (_ ("DIR"), 'I', 'include', _ ("add DIR to include path")),
91         (_ ("COMMAND"), 'P', 'process', _ ("process ly_files using COMMAND FILE...")),
92         (_ ("DIR"), 'o', 'output', _ ("write output to DIR")),
93         ('', 'V', 'verbose', _ ("be verbose")),
94         ('', 'v', 'version', _ ("print version information")),
95         ('', 'w', 'warranty', _ ("show warranty and copyright")),
96 ]
97
98 include_path = [ly.abspath (os.getcwd ())]
99 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
100
101 # only use installed binary when we're installed too.
102 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
103         lilypond_binary = 'lilypond'
104
105 use_hash_p = 1
106 format = 0
107 output_name = 0
108 latex_filter_cmd = 'latex "\\nonstopmode \input /dev/stdin"'
109 filter_cmd = 0
110 process_cmd = ''
111 default_ly_options = {}
112
113 #
114 # is this pythonic? Personally, I find this rather #define-nesque. --hwn
115 #
116 AFTER = 'after'
117 BEFORE = 'before'
118 EXAMPLEINDENT = 'exampleindent'
119 FILTER = 'filter'
120 FRAGMENT = 'fragment'
121 HTML = 'html'
122 INDENT = 'indent'
123 LATEX = 'latex'
124 LAYOUT = 'layout'
125 LINEWIDTH = 'linewidth'
126 NOFRAGMENT = 'nofragment'
127 NOINDENT = 'noindent'
128 NOTES = 'body'
129 NOTIME = 'notime'
130 OUTPUT = 'output'
131 PAPER = 'paper'
132 PREAMBLE = 'preamble'
133 PRINTFILENAME = 'printfilename'
134 QUOTE = 'quote'
135 RAGGEDRIGHT = 'raggedright'
136 RELATIVE = 'relative'
137 STAFFSIZE = 'staffsize'
138 TEXIDOC = 'texidoc'
139 TEXINFO = 'texinfo'
140 VERBATIM = 'verbatim'
141
142 # Recognize special sequences in the input;
143 #
144 # (?P<name>regex) -- assign result of REGEX to NAME
145 # *? -- match non-greedily.
146 # (?m) -- multiline regex: make ^ and $ match at each line
147 # (?s) -- make the dot match all characters including newline
148 # (?x) -- ignore whitespace in patterns
149 no_match = 'a\ba'
150 snippet_res = {
151         ##
152         HTML: {
153                 'include':
154                   no_match,
155
156                 'lilypond':
157                   r'''(?mx)
158                     (?P<match>
159                     <lilypond
160                       (\s*(?P<options>.*?)\s*:)?\s*
161                       (?P<code>.*?)
162                     />)''',
163
164                 'lilypond_block':
165                   r'''(?msx)
166                     (?P<match>
167                     <lilypond
168                       \s*(?P<options>.*?)\s*
169                     >
170                     (?P<code>.*?)
171                     </lilypond>)''',
172
173                 'lilypond_file':
174                   r'''(?mx)
175                     (?P<match>
176                     <lilypondfile
177                       \s*(?P<options>.*?)\s*
178                     >
179                     \s*(?P<filename>.*?)\s*
180                     </lilypondfile>)''',
181
182                 'multiline_comment':
183                   r'''(?smx)
184                     (?P<match>
185                     \s*(?!@c\s+)
186                     (?P<code><!--\s.*?!-->)
187                     \s)''',
188
189                 'singleline_comment':
190                   no_match,
191
192                 'verb':
193                   r'''(?x)
194                     (?P<match>
195                       (?P<code><pre>.*?</pre>))''',
196
197                 'verbatim':
198                   r'''(?x)
199                     (?s)
200                     (?P<match>
201                       (?P<code><pre>\s.*?</pre>\s))''',
202         },
203
204         ##
205         LATEX: {
206                 'include':
207                   r'''(?smx)
208                     ^[^%\n]*?
209                     (?P<match>
210                     \\input\s*{
211                       (?P<filename>\S+?)
212                     })''',
213
214                 'lilypond':
215                   r'''(?smx)
216                     ^[^%\n]*?
217                     (?P<match>
218                     \\lilypond\s*(
219                     \[
220                       \s*(?P<options>.*?)\s*
221                     \])?\s*{
222                       (?P<code>.*?)
223                     })''',
224
225                 'lilypond_block':
226                   r'''(?smx)
227                     ^[^%\n]*?
228                     (?P<match>
229                     \\begin\s*(
230                     \[
231                       \s*(?P<options>.*?)\s*
232                     \])?\s*{lilypond}
233                       (?P<code>.*?)
234                     ^[^%\n]*?
235                     \\end\s*{lilypond})''',
236
237                 'lilypond_file':
238                   r'''(?smx)
239                     ^[^%\n]*?
240                     (?P<match>
241                     \\lilypondfile\s*(
242                     \[
243                       \s*(?P<options>.*?)\s*
244                     \])?\s*\{
245                       (?P<filename>\S+?)
246                     })''',
247
248                 'multiline_comment':
249                   no_match,
250
251                 'singleline_comment':
252                   r'''(?mx)
253                     ^.*?
254                     (?P<match>
255                       (?P<code>
256                       %.*$\n+))''',
257
258                 'verb':
259                   r'''(?mx)
260                     ^[^%\n]*?
261                     (?P<match>
262                       (?P<code>
263                       \\verb(?P<del>.)
264                         .*?
265                       (?P=del)))''',
266
267                 'verbatim':
268                   r'''(?msx)
269                     ^[^%\n]*?
270                     (?P<match>
271                       (?P<code>
272                       \\begin\s*{verbatim}
273                         .*?
274                       \\end\s*{verbatim}))''',
275         },
276
277         ##
278         TEXINFO: {
279                 'include':
280                   r'''(?mx)
281                     ^(?P<match>
282                     @include\s+
283                       (?P<filename>\S+))''',
284
285                 'lilypond':
286                   r'''(?smx)
287                     ^[^\n]*?(?!@c\s+)[^\n]*?
288                     (?P<match>
289                     @lilypond\s*(
290                     \[
291                       \s*(?P<options>.*?)\s*
292                     \])?\s*{
293                       (?P<code>.*?)
294                     })''',
295
296                 'lilypond_block':
297                   r'''(?msx)
298                     ^(?P<match>
299                     @lilypond\s*(
300                     \[
301                       \s*(?P<options>.*?)\s*
302                     \])?\s+?
303                     ^(?P<code>.*?)
304                     ^@end\s+lilypond)\s''',
305
306                 'lilypond_file':
307                   r'''(?mx)
308                     ^(?P<match>
309                     @lilypondfile\s*(
310                     \[
311                       \s*(?P<options>.*?)\s*
312                     \])?\s*{
313                       (?P<filename>\S+)
314                     })''',
315
316                 'multiline_comment':
317                   r'''(?smx)
318                     ^(?P<match>
319                       (?P<code>
320                       @ignore\s
321                         .*?
322                       @end\s+ignore))\s''',
323
324                 'singleline_comment':
325                   r'''(?mx)
326                     ^.*
327                     (?P<match>
328                       (?P<code>
329                       @c([ \t][^\n]*|)\n))''',
330
331         # don't do this: fucks up with @code{@{}
332         #       'verb': r'''(?P<code>@code{.*?})''',
333
334                 'verbatim':
335                   r'''(?sx)
336                     (?P<match>
337                       (?P<code>
338                       @example
339                         \s.*?
340                       @end\s+example\s))''',
341         },
342 }
343
344 format_res = {
345         HTML: {
346                 'intertext': r',?\s*intertext=\".*?\"',
347                 'option_sep': '\s*',
348         },
349
350         LATEX: {
351                 'intertext': r',?\s*intertext=\".*?\"',
352                 'option_sep': '\s*,\s*',
353         },
354
355         TEXINFO: {
356                 'intertext': r',?\s*intertext=\".*?\"',
357                 'option_sep': '\s*,\s*',
358         },
359 }
360
361 ly_options = {
362         ##
363         NOTES: {
364                 RELATIVE: r'''\relative c%(relative_quotes)s''',
365         },
366
367         ##
368         PAPER: {
369                 INDENT: r'''indent = %(indent)s''',
370
371                 LINEWIDTH: r'''linewidth = %(linewidth)s''',
372
373                 NOINDENT: r'''indent = 0.0\mm''',
374
375                 QUOTE: r'''linewidth = %(linewidth)s - 2.0 * %(exampleindent)s''',
376
377                 RAGGEDRIGHT: r'''raggedright = ##t''',
378         },
379
380         ##
381         LAYOUT: {
382                 EXAMPLEINDENT: '',
383
384                 NOTIME: r'''\context {
385     \Staff
386     \remove Time_signature_engraver
387   }''',
388         },
389
390         ##
391         PREAMBLE: {
392                 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
393         },
394 }
395
396 output = {
397         ##
398         HTML: {
399                 FILTER: r'''<lilypond %(options)s>
400 %(code)s
401 </lilypond>
402 ''',
403
404                 AFTER: r'''
405   </a>
406 </p>''',
407
408                 BEFORE: r'''<p>
409   <a href="%(base)s.ly">''',
410
411                 OUTPUT: r'''
412     <img align="center" valign="center"
413          border="0" src="%(image)s" alt="[image of music]">''',
414
415                 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
416
417                 QUOTE: r'''<blockquote>
418 %(str)s
419 </blockquote>
420 ''',
421                 VERBATIM: r'''<pre>
422 %(verb)s</pre>''',
423         },
424
425         ##
426         LATEX: {
427                 AFTER: '',
428
429                 BEFORE: '',
430
431                 OUTPUT: r'''{%%
432 \parindent 0pt
433 \catcode`\@=12
434 \ifx\preLilyPondExample \undefined
435   \relax
436 \else
437   \preLilyPondExample
438 \fi
439 \def\lilypondbook{}%%
440 \input %(base)s.tex
441 \ifx\postLilyPondExample \undefined
442   \relax
443 \else
444   \postLilyPondExample
445 \fi
446 }''',
447
448                 PRINTFILENAME: '''\\texttt{%(filename)s}
449         ''',
450
451                 QUOTE: r'''\begin{quotation}
452 %(str)s
453 \end{quotation}
454 ''',
455
456                 VERBATIM: r'''\noindent
457 \begin{verbatim}
458 %(verb)s\end{verbatim}
459 ''',
460
461                 FILTER: r'''\begin{lilypond}[%(options)s]
462 %(code)s
463 \end{lilypond}''',
464         },
465
466         ##
467         TEXINFO: {
468                 FILTER: r'''@lilypond[%(options)s]
469 %(code)s
470 @lilypond''',
471
472                 AFTER: '',
473
474                 BEFORE: '',
475
476                 OUTPUT: r'''@noindent
477 @image{%(base)s,,,[image of music],%(ext)s}''',
478
479                 PRINTFILENAME: '''@file{%(filename)s}
480         ''',
481
482                 QUOTE: r'''@quotation
483 %(str)s
484 @end quotation
485 ''',
486
487                 # FIXME: @exampleindent 5  is the default...
488                 VERBATIM: r'''@exampleindent 0
489 @example
490 %(verb)s@end example
491 @exampleindent 5
492 ''',
493         },
494 }
495
496 PREAMBLE_LY = r'''%%%% Generated by %(program_name)s
497 %%%% Options: [%(option_string)s]
498
499 #(set! toplevel-score-handler ly:parser-print-score)
500 #(set! toplevel-music-handler (lambda (p m)
501                                (ly:parser-print-score
502                                 p (ly:music-scorify m p))))
503
504 %(preamble_string)s
505
506 \paper {
507   #(define dump-extents #t)
508   %(paper_string)s
509 }
510
511 \layout {
512   %(layout_string)s
513 }
514 '''
515
516 FRAGMENT_LY = r'''
517 %(notes_string)s
518 {
519 %% ly snippet contents follows:
520 %(code)s
521 %% end ly snippet
522 }
523 '''
524
525 FULL_LY = '''
526 %% ly snippet:
527 %(code)s
528 %% end ly snippet
529 '''
530
531 texinfo_linewidths = {
532         '@afourpaper': '160\\mm',
533         '@afourwide': '6.5\\in',
534         '@afourlatex': '150\\mm',
535         '@smallbook': '5\\in',
536         '@letterpaper': '6\\in',
537 }
538
539 def classic_lilypond_book_compatibility (key, value):
540         if key == 'singleline' and value == None:
541                 return (RAGGEDRIGHT, None)
542
543         m = re.search ('relative\s*([-0-9])', key)
544         if m:
545                 return ('relative', m.group (1))
546
547         m = re.match ('([0-9]+)pt', key)
548         if m:
549                 return ('staffsize', m.group (1))
550
551         if key == 'indent' or key == 'linewidth':
552                 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
553                 if m:
554                         f = float (m.group (1))
555                         return (key, '%f\\%s' % (f, m.group (2)))
556
557         return (None, None)
558
559 def compose_ly (code, options, type):
560         option_dict = {}
561         for i in options:
562                 if string.find (i, '=') > 0:
563                         (key, value) = re.split ('\s*=\s*', i)
564                         option_dict[key] = value
565                 else:
566                         option_dict[i] = None
567
568         has_linewidth = option_dict.has_key (LINEWIDTH)
569
570         for i in default_ly_options.keys ():
571                 if i not in option_dict.keys ():
572                         option_dict[i] = default_ly_options[i]
573
574         if not INDENT in option_dict.keys ():
575                 option_dict[NOINDENT] = None
576
577         if not has_linewidth and LINEWIDTH in option_dict.keys ():
578                 if QUOTE in option_dict.keys () or type == 'lilypond':
579                         del option_dict[LINEWIDTH]
580                         option_dict[RAGGEDRIGHT] = None
581
582         if FRAGMENT in option_dict.keys ():
583                 body = FRAGMENT_LY
584         else:
585                 body = FULL_LY
586
587         # defaults
588         relative = 1
589         override = {}
590         #FIXME: where to get sane value for exampleindent?
591         override[EXAMPLEINDENT] = r'9.0\mm'
592         override[LINEWIDTH] = None
593         override.update (default_ly_options)
594
595         option_list = []
596         for (key, value) in option_dict.items ():
597                 if value == None:
598                         option_list.append (key)
599                 else:
600                         option_list.append (key + '=' + value)
601         option_string = string.join (option_list, ',')
602
603         compose_dict = {}
604         compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
605         for a in compose_types:
606                 compose_dict[a] = []
607
608         for (key, value) in option_dict.items():
609                 (c_key, c_value) = \
610                   classic_lilypond_book_compatibility (key, value)
611                 if c_key:
612                         if c_value:
613                                 ly.warning \
614                                   (_ ("deprecated ly-option used: %s=%s" \
615                                     % (key, value)))
616                                 ly.warning \
617                                   (_ ("compatibility mode translation: %s=%s" \
618                                     % (c_key, c_value)))
619                         else:
620                                 ly.warning \
621                                   (_ ("deprecated ly-option used: %s" \
622                                     % key))
623                                 ly.warning \
624                                   (_ ("compatibility mode translation: %s" \
625                                     % c_key))
626
627                         (key, value) = (c_key, c_value)
628
629                 if value:
630                         override[key] = value
631                 else:
632                         if not override.has_key (key):
633                                 override[key] = None
634
635                 found = 0
636                 for type in compose_types:
637                         if ly_options[type].has_key (key):
638                                 compose_dict[type].append (ly_options[type][key])
639                                 found = 1
640                                 break
641
642                 if not found and key not in (FRAGMENT, NOFRAGMENT, PRINTFILENAME,
643                                              RELATIVE, VERBATIM, TEXIDOC):
644                         ly.warning (_ ("ignoring unknown ly option: %s") % i)
645
646         #URGS
647         if RELATIVE in override.keys () and override[RELATIVE]:
648                 relative = string.atoi (override[RELATIVE])
649
650         relative_quotes = ''
651
652         # 1 = central C
653         if relative < 0:
654                 relative_quotes += ',' * (- relative)
655         elif relative > 0:
656                 relative_quotes += "'" * relative
657
658         program_name = __main__.program_name
659
660         paper_string = \
661           string.join (compose_dict[PAPER], '\n  ') % override
662         layout_string = \
663           string.join (compose_dict[LAYOUT], '\n  ') % override
664         notes_string = \
665           string.join (compose_dict[NOTES], '\n  ') % vars ()
666         preamble_string = \
667           string.join (compose_dict[PREAMBLE], '\n  ') % override
668
669         return (PREAMBLE_LY + body) % vars ()
670
671 # BARF
672 # use lilypond for latex (.lytex) books,
673 # and lilypond --preview for html, texinfo books?
674 def to_eps (file):
675         cmd = r'latex "\nonstopmode \input %s"' % file
676         # Ugh.  (La)TeX writes progress and error messages on stdout
677         # Redirect to stderr
678         cmd = '(( %s >&2 ) >&- )' % cmd
679         ly.system (cmd)
680         ly.system ('dvips -Ppdf -u+ec-mftrace.map -u+lilypond.map -E -o %s.eps %s' \
681                    % (file, file))
682
683         # check if it really is EPS.
684         # Otherwise music glyphs disappear from 2nd and following pages.
685
686         # TODO: should run dvips -pp -E per page, then we get proper
687         # cropping as well.
688
689         f = open ('%s.eps' % file)
690         for x in range (0, 10):
691                 if re.search ("^%%Pages: ", f.readline ()):
692                         # make non EPS.
693                         ly.system ('dvips -Ppdf -u+ec-mftrace.map -u+lilypond.map -o %s.eps %s' \
694                                    % (file, file))
695                         break
696
697 def find_file (name):
698         for i in include_path:
699                 full = os.path.join (i, name)
700                 if os.path.exists (full):
701                         return full
702         ly.error (_ ("file not found: %s") % name + '\n')
703         ly.exit (1)
704         return ''
705
706 def verbatim_html (s):
707         return re.sub ('>', '&gt;',
708                        re.sub ('<', '&lt;',
709                                re.sub ('&', '&amp;', s)))
710
711 def verbatim_texinfo (s):
712         return re.sub ('{', '@{',
713                        re.sub ('}', '@}',
714                                re.sub ('@', '@@', s)))
715
716 def split_options (option_string):
717         return re.split (format_res[format]['option_sep'], option_string)
718
719 class Chunk:
720         def replacement_text (self):
721                 return ''
722
723         def filter_text (self):
724                 return self.replacement_text ()
725
726         def ly_is_outdated (self):
727                 return 0
728
729         def png_is_outdated (self):
730                 return 0
731
732 class Substring (Chunk):
733         def __init__ (self, source, start, end):
734                 self.source = source
735                 self.start = start
736                 self.end = end
737
738         def replacement_text (self):
739                 return self.source [self.start:self.end]
740
741 class Snippet (Chunk):
742         def __init__ (self, type, match, format):
743                 self.type = type
744                 self.match = match
745                 self.hash = 0
746                 self.options = []
747                 self.format = format
748
749         def replacement_text (self):
750                 return self.match.group ('match')
751
752         def substring (self, s):
753                 return self.match.group (s)
754
755         def __repr__ (self):
756                 return `self.__class__` + " type = " + self.type
757
758 class Include_snippet (Snippet):
759         def processed_filename (self):
760                 f = self.substring ('filename')
761                 return os.path.splitext (f)[0] + format2ext[format]
762
763         def replacement_text (self):
764                 s = self.match.group ('match')
765                 f = self.substring ('filename')
766
767                 return re.sub (f, self.processed_filename (), s)
768
769 class Lilypond_snippet (Snippet):
770         def __init__ (self, type, match, format):
771                 Snippet.__init__ (self, type, match, format)
772                 os = match.group ('options')
773                 if os:
774                         self.options = split_options (os)
775
776         def ly (self):
777                 return self.substring ('code')
778
779         def full_ly (self):
780                 s = self.ly ()
781                 if s:
782                         return compose_ly (s, self.options, self.type)
783                 return ''
784
785         # todo: use md5?
786         def get_hash (self):
787                 if not self.hash:
788                         self.hash = abs (hash (self.full_ly ()))
789                 return self.hash
790
791         def basename (self):
792                 if use_hash_p:
793                         return 'lily-%d' % self.get_hash ()
794                 raise 'to be done'
795
796         def write_ly (self):
797                 outf = open (self.basename () + '.ly', 'w')
798                 outf.write (self.full_ly ())
799
800                 open (self.basename () + '.txt', 'w').write ("image of music")
801
802         def ly_is_outdated (self):
803                 base = self.basename ()
804
805                 tex_file = '%s.tex' % base
806                 ly_file = '%s.ly' % base
807                 ok = os.path.exists (ly_file) and os.path.exists (tex_file)\
808                      and os.stat (tex_file)[stat.ST_SIZE] \
809                      and open (tex_file).readlines ()[-1][1:-1] \
810                      == 'lilypondend'
811
812                 if ok and (use_hash_p or self.ly () == open (ly_file).read ()):
813                         # TODO: something smart with target formats
814                         # (ps, png) and m/ctimes
815                         return None
816                 return self
817
818         def png_is_outdated (self):
819                 base = self.basename ()
820                 ok = self.ly_is_outdated ()
821                 if format == HTML or format == TEXINFO:
822                         ok = ok and (os.path.exists (base + '.png')
823                                      or glob.glob (base + '-page*.png'))
824                 return not ok
825
826         def filter_text (self):
827                 code = self.substring ('code')
828                 s = run_filter (code)
829                 d = {
830                   'code': s,
831                   'options': self.match.group ('options')
832                 }
833                 # TODO
834                 return output[self.format][FILTER] % d
835
836         def replacement_text (self):
837                 func = Lilypond_snippet.__dict__ ['output_' + self.format]
838                 return func (self)
839
840         def get_images (self):
841                 base = self.basename ()
842                 # URGUGHUGHUGUGHU
843                 single = '%(base)s.png' % vars ()
844                 multiple = '%(base)s-page1.png' % vars ()
845                 images = (single,)
846                 if os.path.exists (multiple) \
847                    and (not os.path.exists (single) \
848                         or (os.stat (multiple)[stat.ST_MTIME] \
849                             > os.stat (single)[stat.ST_MTIME])):
850                         images = glob.glob ('%(base)s-page*.png' % vars ())
851                 return images
852
853         def output_html (self):
854                 str = ''
855                 base = self.basename ()
856                 if format == HTML:
857                         str += self.output_print_filename (HTML)
858                         if VERBATIM in self.options:
859                                 verb = verbatim_html (self.substring ('code'))
860                                 str += write (output[HTML][VERBATIM] % vars ())
861                         if QUOTE in self.options:
862                                 str = output[HTML][QUOTE] % vars ()
863
864                 str += output[HTML][BEFORE] % vars ()
865                 for image in self.get_images ():
866                         (base, ext) = os.path.splitext (image)
867                         str += output[HTML][OUTPUT] % vars ()
868                 str += output[HTML][AFTER] % vars ()
869                 return str
870
871         def output_info (self):
872                 str = self.output_print_filename (HTML)
873                 str = output[TEXINFO][BEFORE] % vars ()
874                 for image in self.get_images ():
875                         (base, ext) = os.path.splitext (image)
876
877                         # URG, makeinfo implicitely prepends dot to ext
878                         # specifying no extension is most robust
879                         ext = ''
880                         str += output[TEXINFO][OUTPUT] % vars ()
881                 str += output[TEXINFO][AFTER] % vars ()
882                 return str
883
884         def output_latex (self):
885                 str = ''
886                 base = self.basename ()
887                 if format == LATEX:
888                         str += self.output_print_filename (LATEX)
889                         if VERBATIM in self.options:
890                                 verb = self.substring ('code')
891                                 str += (output[LATEX][VERBATIM] % vars ())
892                         if QUOTE in self.options:
893                                 str = output[LATEX][QUOTE] % vars ()
894
895                 str += (output[LATEX][BEFORE]
896                         + (output[LATEX][OUTPUT] % vars ())
897                         + output[LATEX][AFTER])
898                 return str
899
900         def output_print_filename (self,format):
901                 str = ''
902                 if PRINTFILENAME in self.options:
903                         base = self.basename ()
904                         filename = self.substring ('filename')
905                         str = output[format][PRINTFILENAME] % vars ()
906                 return str
907
908         def output_texinfo (self):
909                 str = ''
910                 if self.output_print_filename (TEXINFO):
911                         str += ('@html\n' + self.output_print_filename (HTML)
912                                 + '\n@end html\n')
913                         str += ('@tex\n' + self.output_print_filename (LATEX)
914                                 + '\n@end tex\n')
915                 base = self.basename ()
916                 if TEXIDOC in self.options:
917                         texidoc = base + '.texidoc'
918                         if os.path.exists (texidoc):
919                                 str += '@include %(texidoc)s\n\n' % vars ()
920
921                 if VERBATIM in self.options:
922                         verb = verbatim_texinfo (self.substring ('code'))
923                         str += (output[TEXINFO][VERBATIM] % vars ())
924
925                 str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
926                 str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
927                 str += ('@html\n' + self.output_html () + '\n@end html\n')
928
929                 if QUOTE in self.options:
930                         str = output[TEXINFO][QUOTE] % vars ()
931
932                 # need par after image
933                 str += '\n'
934
935                 return str
936
937 class Lilypond_file_snippet (Lilypond_snippet):
938         def ly (self):
939                 name = self.substring ('filename')
940                 return '\\renameinput \"%s\"\n%s' % (name, open (find_file (name)).read ())
941
942 snippet_type_to_class = {
943         'lilypond_file': Lilypond_file_snippet,
944         'lilypond_block': Lilypond_snippet,
945         'lilypond': Lilypond_snippet,
946         'include': Include_snippet,
947 }
948
949 def find_toplevel_snippets (s, types):
950         res = {}
951         for i in types:
952                 res[i] = ly.re.compile (snippet_res[format][i])
953
954         snippets = []
955         index = 0
956         ## found = dict (map (lambda x: (x, None), types))
957         ## urg python2.1
958         found = {}
959         map (lambda x, f = found: f.setdefault (x, None), types)
960
961         # We want to search for multiple regexes, without searching
962         # the string multiple times for one regex.
963         # Hence, we use earlier results to limit the string portion
964         # where we search.
965         # Since every part of the string is traversed at most once for
966         # every type of snippet, this is linear.
967
968         while 1:
969                 first = None
970                 endex = 1 << 30
971                 for type in types:
972                         if not found[type] or found[type][0] < index:
973                                 found[type] = None
974                                 m = res[type].search (s[index:endex])
975                                 if not m:
976                                         continue
977
978                                 cl = Snippet
979                                 if snippet_type_to_class.has_key (type):
980                                         cl = snippet_type_to_class[type]
981                                 snip = cl (type, m, format)
982                                 start = index + m.start ('match')
983                                 found[type] = (start, snip)
984
985                         if found[type] \
986                            and (not first or found[type][0] < found[first][0]):
987                                 first = type
988
989                                 # FIXME.
990
991                                 # Limiting the search space is a cute
992                                 # idea, but this *requires* to search
993                                 # for possible containing blocks
994                                 # first, at least as long as we do not
995                                 # search for the start of blocks, but
996                                 # always/directly for the entire
997                                 # @block ... @end block.
998
999                                 endex = found[first][0]
1000
1001                 if not first:
1002                         snippets.append (Substring (s, index, len (s)))
1003                         break
1004
1005                 (start, snip) = found[first]
1006                 snippets.append (Substring (s, index, start))
1007                 snippets.append (snip)
1008                 found[first] = None
1009                 index = start + len (snip.match.group ('match'))
1010
1011         return snippets
1012
1013 def filter_pipe (input, cmd):
1014         if verbose_p:
1015                 ly.progress (_ ("Opening filter `%s'") % cmd)
1016
1017         (stdin, stdout, stderr) = os.popen3 (cmd)
1018         stdin.write (input)
1019         status = stdin.close ()
1020
1021         if not status:
1022                 status = 0
1023                 output = stdout.read ()
1024                 status = stdout.close ()
1025                 error = stderr.read ()
1026
1027         if not status:
1028                 status = 0
1029         signal = 0x0f & status
1030         if status or (not output and error):
1031                 exit_status = status >> 8
1032                 ly.error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1033                 ly.error (_ ("The error log is as follows:"))
1034                 sys.stderr.write (error)
1035                 sys.stderr.write (stderr.read ())
1036                 ly.exit (status)
1037
1038         if verbose_p:
1039                 ly.progress ('\n')
1040
1041         return output
1042
1043 def run_filter (s):
1044         return filter_pipe (s, filter_cmd)
1045
1046 def is_derived_class (cl, baseclass):
1047         if cl == baseclass:
1048                 return 1
1049         for b in cl.__bases__:
1050                 if is_derived_class (b, baseclass):
1051                         return 1
1052         return 0
1053
1054 def process_snippets (cmd, ly_snippets, png_snippets):
1055         ly_names = filter (lambda x: x, map (Lilypond_snippet.basename, ly_snippets))
1056         png_names = filter (lambda x: x, map (Lilypond_snippet.basename, png_snippets))
1057
1058         status = 0
1059         if ly_names:
1060                 status = ly.system (string.join ([cmd] + ly_names),
1061                                     ignore_error = 1, progress_p = 1)
1062
1063         if status:
1064                 ly.error ('Process %s exited unsuccessfully.' % cmd)
1065                 raise Compile_error
1066
1067         if format == HTML or format == TEXINFO:
1068                 for i in png_names:
1069                         if not os.path.exists (i + '.eps') and os.path.exists (i + '.tex'):
1070                                 to_eps (i)
1071                                 ly.make_ps_images (i + '.eps', resolution = 110)
1072
1073 #                       elif os.path.exists (i + '.ps'):
1074 #                               ly.make_ps_images (i + '.ps', resolution = 110)
1075
1076 LATEX_DOCUMENT = r'''
1077 %(preamble)s
1078 \begin{document}
1079 \typeout{textwidth=\the\textwidth}
1080 \typeout{columnsep=\the\columnsep}
1081 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1082 \end{document}
1083 '''
1084 #need anything else besides textwidth?
1085 def get_latex_textwidth (source):
1086         m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1087         preamble = source[:m.start (0)]
1088         latex_document = LATEX_DOCUMENT % vars ()
1089         parameter_string = filter_pipe (latex_document, latex_filter_cmd)
1090
1091         columns = 0
1092         m = re.search ('columns=([0-9.]*)', parameter_string)
1093         if m:
1094                 columns = string.atoi (m.group (1))
1095
1096         columnsep = 0
1097         m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1098         if m:
1099                 columnsep = string.atof (m.group (1))
1100
1101         textwidth = 0
1102         m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1103         if m:
1104                 textwidth = string.atof (m.group (1))
1105                 if columns:
1106                         textwidth = (textwidth - columnsep) / columns
1107
1108         return textwidth
1109
1110 ext2format = {
1111         '.html': HTML,
1112         '.itely': TEXINFO,
1113         '.latex': LATEX,
1114         '.lytex': LATEX,
1115         '.tely': TEXINFO,
1116         '.tex': LATEX,
1117         '.texi': TEXINFO,
1118         '.texinfo': TEXINFO,
1119         '.xml': HTML,
1120 }
1121
1122 format2ext = {
1123         HTML: '.html',
1124         #TEXINFO: '.texinfo',
1125         TEXINFO: '.texi',
1126         LATEX: '.tex',
1127 }
1128
1129 class Compile_error:
1130         pass
1131
1132 def do_process_cmd (chunks):
1133         ly_outdated = filter (lambda x: is_derived_class (x.__class__, Lilypond_snippet) \
1134                         and x.ly_is_outdated (), chunks)
1135         png_outdated = filter (lambda x: is_derived_class (x.__class__, Lilypond_snippet) \
1136                          and x.png_is_outdated (), chunks)
1137
1138         ly.progress (_ ("Writing snippets..."))
1139         map (Lilypond_snippet.write_ly, ly_outdated)
1140         ly.progress ('\n')
1141
1142         if ly_outdated:
1143                 ly.progress (_ ("Processing...\n"))
1144                 process_snippets (process_cmd, ly_outdated, png_outdated)
1145         else:
1146                 ly.progress (_ ("All snippets are up to date..."))
1147         ly.progress ('\n')
1148
1149 def do_file (input_filename):
1150         #ugh
1151         global format
1152         if not format:
1153                 e = os.path.splitext (input_filename)[1]
1154                 if e in ext2format.keys ():
1155                         #FIXME
1156                         format = ext2format[e]
1157                 else:
1158                         ly.error (_ ("cannot determine format for: %s" \
1159                                      % input_filename))
1160                         ly.exit (1)
1161
1162         if not input_filename or input_filename == '-':
1163                 in_handle = sys.stdin
1164                 input_fullname = '<stdin>'
1165         else:
1166                 if os.path.exists (input_filename):
1167                         input_fullname = input_filename
1168                 elif format == LATEX:
1169                         # urg python interface to libkpathsea?
1170                         input_fullname = ly.read_pipe ('kpsewhich '
1171                                                        + input_filename)[:-1]
1172                 else:
1173                         input_fullname = find_file (input_filename)
1174                 in_handle = open (input_fullname)
1175
1176         if input_filename == '-':
1177                 input_base = 'stdin'
1178         else:
1179                 input_base = os.path.basename \
1180                              (os.path.splitext (input_filename)[0])
1181
1182         # only default to stdout when filtering
1183         if output_name == '-' or (not output_name and filter_cmd):
1184                 output_filename = '-'
1185                 output_file = sys.stdout
1186         else:
1187                 if not output_name:
1188                         output_filename = input_base + format2ext[format]
1189                 else:
1190                         if not os.path.isdir (output_name):
1191                                 os.mkdir (output_name, 0777)
1192                         output_filename = (output_name
1193                                            + '/' + input_base
1194                                            + format2ext[format])
1195
1196                 if (os.path.exists (input_filename) and
1197                     os.path.exists (output_filename) and
1198                     os.path.samefile (output_filename, input_fullname)):
1199                         ly.error (_ ("Output would overwrite input file; use --output."))
1200                         ly.exit (2)
1201
1202                 output_file = open (output_filename, 'w')
1203                 if output_name:
1204                         os.chdir (output_name)
1205         try:
1206                 ly.progress (_ ("Reading %s...") % input_fullname)
1207                 source = in_handle.read ()
1208                 ly.progress ('\n')
1209
1210                 # FIXME: containing blocks must be first, see find_toplevel_snippets
1211                 snippet_types = (
1212                         'multiline_comment',
1213                         'verbatim',
1214                         'lilypond_block',
1215         #               'verb',
1216                         'singleline_comment',
1217                         'lilypond_file',
1218                         'include',
1219                         'lilypond', )
1220                 ly.progress (_ ("Dissecting..."))
1221                 chunks = find_toplevel_snippets (source, snippet_types)
1222                 ly.progress ('\n')
1223
1224                 global default_ly_options
1225                 textwidth = 0
1226                 if not default_ly_options.has_key (LINEWIDTH):
1227                         if format == LATEX:
1228                                 textwidth = get_latex_textwidth (source)
1229                                 default_ly_options[LINEWIDTH] = \
1230                                   '''%.0f\\pt''' % textwidth
1231                         elif format == TEXINFO:
1232                                 for (k, v) in texinfo_linewidths.items ():
1233                                         # FIXME: @layout is usually not in chunk #0:
1234                                         #        \input texinfo @c -*-texinfo-*-
1235                                         # bluntly search first K of source
1236                                         # s = chunks[0].replacement_text ()
1237                                         if re.search (k, source[:1024]):
1238                                                 default_ly_options[LINEWIDTH] = v
1239                                                 break
1240
1241                 if filter_cmd:
1242                         output_file.writelines ([c.filter_text () for c in chunks])
1243
1244                 elif process_cmd:
1245                         do_process_cmd (chunks)
1246                         ly.progress (_ ("Compiling %s...") % output_filename)
1247                         output_file.writelines ([s.replacement_text () \
1248                                                  for s in chunks])
1249                         ly.progress ('\n')
1250
1251                 def process_include (snippet):
1252                         os.chdir (original_dir)
1253                         name = snippet.substring ('filename')
1254                         ly.progress (_ ("Processing include: %s") % name)
1255                         ly.progress ('\n')
1256                         do_file (name)
1257
1258                 map (process_include,
1259                      filter (lambda x: is_derived_class (x.__class__, Include_snippet), chunks))
1260         except Compile_error:
1261                 os.chdir (original_dir)
1262                 ly.progress (_ ("Removing `%s'") % output_filename)
1263                 ly.progress ('\n')
1264
1265                 os.unlink (output_filename)
1266                 raise Compile_error
1267
1268 def do_options ():
1269         global format, output_name
1270         global filter_cmd, process_cmd, verbose_p
1271
1272         (sh, long) = ly.getopt_args (option_definitions)
1273         try:
1274                 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1275         except getopt.error, s:
1276                 sys.stderr.write ('\n')
1277                 ly.error (_ ("getopt says: `%s'" % s))
1278                 sys.stderr.write ('\n')
1279                 ly.help ()
1280                 ly.exit (2)
1281
1282         for opt in options:
1283                 o = opt[0]
1284                 a = opt[1]
1285
1286                 if 0:
1287                         pass
1288                 elif o == '--filter' or o == '-F':
1289                         filter_cmd = a
1290                         process_cmd = 0
1291                 elif o == '--format' or o == '-f':
1292                         format = a
1293                         if a == 'texi-html' or a == 'texi':
1294                                 format = TEXINFO
1295                 elif o == '--help' or o == '-h':
1296                         ly.help ()
1297                         sys.exit (0)
1298                 elif o == '--include' or o == '-I':
1299                         include_path.append (os.path.join (original_dir,
1300                                                            ly.abspath (a)))
1301                 elif o == '--output' or o == '-o':
1302                         output_name = a
1303                 elif o == '--outdir':
1304                         output_name = a
1305                 elif o == '--process' or o == '-P':
1306                         process_cmd = a
1307                         filter_cmd = 0
1308                 elif o == '--version' or o == '-v':
1309                         ly.identify (sys.stdout)
1310                         sys.exit (0)
1311                 elif o == '--verbose' or o == '-V':
1312                         verbose_p = 1
1313                 elif o == '--warranty' or o == '-w':
1314                         if 1 or status:
1315                                 ly.warranty ()
1316                         sys.exit (0)
1317         return files
1318
1319 def main ():
1320         files = do_options ()
1321         global process_cmd
1322         if process_cmd == '':
1323                 process_cmd = lilypond_binary + " -f tex "
1324
1325         if process_cmd:
1326                 process_cmd += string.join ([(' -I %s' % p)
1327                                              for p in include_path])
1328
1329         ly.identify (sys.stderr)
1330         ly.setup_environment ()
1331         if files:
1332                 try:
1333                         do_file (files[0])
1334                 except Compile_error:
1335                         ly.exit (1)
1336
1337 if __name__ == '__main__':
1338         main ()