]> git.donarmstrong.com Git - lilypond.git/blob - scripts/lilypond-book.py
* scripts/lilypond-book.py (snippet_res): Fix regexps and make them ignore
[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'''
370     indent = %(indent)s''',
371         'linewidth': r'''
372     linewidth = %(linewidth)s''',
373
374                 NOINDENT: r'''
375     indent = 0.0\mm''',
376
377                 QUOTE: r'''
378     linewidth = %(linewidth)s - 2.0 * %(exampleindent)s
379 ''',
380
381                 RAGGEDRIGHT: r'''
382     indent = 0.0\mm
383     raggedright = ##t''',
384         },
385
386         ##
387         LAYOUT: {
388                 EXAMPLEINDENT: '',
389
390                 NOTIME: r'''
391     \context {
392         \Staff
393         \remove Time_signature_engraver
394     }''',
395         },
396
397         ##
398         PREAMBLE: {
399                 STAFFSIZE: r'''
400 #(set-global-staff-size %(staffsize)s)''',
401         },
402 }
403
404 output = {
405         ##
406         HTML: {
407                 FILTER: r'''<lilypond %(options)s>
408 %(code)s
409 </lilypond>
410 ''',
411
412                 AFTER: r'''
413   </a>
414 </p>''',
415
416                 BEFORE: r'''<p>
417   <a href="%(base)s.ly">''',
418
419                 OUTPUT: r'''
420     <img align="center" valign="center"
421          border="0" src="%(image)s" alt="[image of music]">''',
422
423                 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
424
425                 QUOTE: r'''<blockquote>
426 %(str)s
427 </blockquote>
428 ''',
429                 VERBATIM: r'''<pre>
430 %(verb)s</pre>''',
431         },
432
433         ##
434         LATEX: {
435                 AFTER: '',
436
437                 BEFORE: '',
438
439                 OUTPUT: r'''{\parindent 0pt
440 \catcode`\@=12
441 \ifx\preLilyPondExample\undefined\relax\else\preLilyPondExample\fi
442 \def\lilypondbook{}%%
443 \input %(base)s.tex
444 \ifx\postLilyPondExample\undefined\relax\else\postLilyPondExample\fi
445 \catcode`\@=0}''',
446
447                 PRINTFILENAME: '''\\texttt{%(filename)s}
448         ''',
449
450                 QUOTE: r'''\begin{quotation}
451 %(str)s
452 \end{quotation}
453 ''',
454
455                 VERBATIM: r'''\noindent
456 \begin{verbatim}
457 %(verb)s\end{verbatim}
458 ''',
459
460                 FILTER: r'''\begin{lilypond}[%(options)s]
461 %(code)s
462 \end{lilypond}''',
463         },
464
465         ##
466         TEXINFO: {
467                 FILTER: r'''@lilypond[%(options)s]
468 %(code)s
469 @lilypond''',
470
471                 AFTER: '',
472
473                 BEFORE: '',
474
475                 OUTPUT: r'''@noindent
476 @image{%(base)s,,,[image of music],%(ext)s}''',
477
478                 PRINTFILENAME: '''@file{%(filename)s}
479         ''',
480
481                 QUOTE: r'''@quotation
482 %(str)s
483 @end quotation
484 ''',
485
486                 # FIXME: @exampleindent 5  is the default...
487                 VERBATIM: r'''@exampleindent 0
488 @example
489 %(verb)s@end example
490 @exampleindent 5
491 ''',
492         },
493 }
494
495 PREAMBLE_LY = r'''%%%% Generated by %(program_name)s
496 %%%% Options: [%(option_string)s]
497 #(set! toplevel-score-handler ly:parser-print-score)
498 #(set! toplevel-music-handler (lambda (p m)
499                                (ly:parser-print-score
500                                 p (ly:music-scorify m p))
501                             ))
502 %(preamble_string)s
503 \paper {
504   #(define dump-extents #t)
505   %(paper_string)s
506 }
507 \layout { %(layout_string)s
508 }
509
510 '''
511
512 FRAGMENT_LY = r'''
513     %(notes_string)s{
514 %% ly snippet contents follows:
515         %(code)s
516 %% end ly snippet
517         }
518 '''
519
520 FULL_LY = '''
521 %% ly snippet:
522 %(code)s
523 %% end ly snippet
524 '''
525
526 texinfo_linewidths = {
527         '@afourpaper': '160\\mm',
528         '@afourwide': '6.5\\in',
529         '@afourlatex': '150\\mm',
530         '@smallbook': '5\\in',
531         '@letterpaper': '6\\in',
532 }
533
534 def classic_lilypond_book_compatibility (o):
535         if o == 'singleline':
536                 return RAGGEDRIGHT
537         m = re.search ('relative\s*([-0-9])', o)
538         if m:
539                 return 'relative=%s' % m.group (1)
540         m = re.match ('([0-9]+)pt', o)
541         if m:
542                 return 'staffsize=%s' % m.group (1)
543         m = re.match ('indent=([-.0-9]+)(cm|in|mm|pt|staffspace)', o)
544         if m:
545                 f = float (m.group (1))
546                 return 'indent=%f\\%s' % (f, m.group (2))
547         m = re.match ('linewidth=([-.0-9]+)(cm|in|mm|pt|staffspace)', o)
548         if m:
549                 f = float (m.group (1))
550                 return 'linewidth=%f\\%s' % (f, m.group (2))
551         return None
552
553 def compose_ly (code, options):
554         #Hmm
555         for i in default_ly_options.keys ():
556                 if i not in options:
557                         options.append (i)
558
559         #Hmm
560         if QUOTE in options and LINEWIDTH in options:
561                 options.remove (LINEWIDTH)
562
563         if FRAGMENT in options:
564                 if RAGGEDRIGHT not in options:
565                         options.append (RAGGEDRIGHT)
566                 body = FRAGMENT_LY
567         else:
568                 body = FULL_LY
569
570         # defaults
571         relative = 1
572         staffsize = 16
573         override = {}
574         #FIXME: where to get sane value for exampleindent?
575         override[EXAMPLEINDENT] = r'9.0 \mm'
576         override[LINEWIDTH] = None
577         override.update (default_ly_options)
578
579         option_string = string.join (options, ',')
580
581         options_dict = {}
582         option_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
583         for a in option_types:
584                 options_dict[a] = []
585
586         for i in options:
587                 c = classic_lilypond_book_compatibility (i)
588                 if c:
589                         ly.warning (_ ("deprecated ly-option used: %s" % i))
590                         ly.warning (_ ("compatibility mode translation: %s" \
591                                        % c))
592                         i = c
593
594                 if string.find (i, '=') > 0:
595                         key, value = re.split ('\s*=\s*', i)
596                         override[key] = value
597                 else:
598                         key = i
599                         if not override.has_key (i):
600                                 override[i] = None
601
602                 found = 0
603                 for type in option_types:
604                         if ly_options[type].has_key (key):
605
606                                 options_dict[type].append (ly_options[type][key])
607                                 found = 1
608                                 break
609
610                 if not found and key not in (FRAGMENT, NOFRAGMENT, PRINTFILENAME,
611                                              RELATIVE, VERBATIM, TEXIDOC):
612                         ly.warning (_ ("ignoring unknown ly option: %s") % i)
613
614         #URGS
615         if RELATIVE in override.keys () and override[RELATIVE]:
616                 relative = string.atoi (override[RELATIVE])
617
618         relative_quotes = ''
619
620         # 1 = central C
621         if relative < 0:
622                 relative_quotes += ',' * (- relative)
623         elif relative > 0:
624                 relative_quotes += "'" * relative
625
626         program_name = __main__.program_name
627
628         paper_string = string.join (options_dict[PAPER], '\n    ') % override
629         layout_string = string.join (options_dict[LAYOUT], '\n    ') % override
630         notes_string = string.join (options_dict[NOTES], '\n    ') % vars ()
631         preamble_string = string.join (options_dict[PREAMBLE], '\n    ') % override
632         return (PREAMBLE_LY + body) % vars ()
633
634 # BARF
635 # use lilypond for latex (.lytex) books,
636 # and lilypond --preview for html, texinfo books?
637 def to_eps (file):
638         cmd = r'latex "\nonstopmode \input %s"' % file
639         # Ugh.  (La)TeX writes progress and error messages on stdout
640         # Redirect to stderr
641         cmd = '(( %s >&2 ) >&- )' % cmd
642         ly.system (cmd)
643         ly.system ('dvips -Ppdf -u+ec-mftrace.map -u+lilypond.map -E -o %s.eps %s' \
644                    % (file, file))
645
646         # check if it really is EPS.
647         # Otherwise music glyphs disappear from 2nd and following pages.
648
649         # TODO: should run dvips -pp -E per page, then we get proper
650         # cropping as well.
651
652         f = open ('%s.eps' % file)
653         for x in range (0, 10):
654                 if re.search ("^%%Pages: ", f.readline ()):
655                         # make non EPS.
656                         ly.system ('dvips -Ppdf -u+ec-mftrace.map -u+lilypond.map -o %s.eps %s' \
657                                    % (file, file))
658                         break
659
660 def find_file (name):
661         for i in include_path:
662                 full = os.path.join (i, name)
663                 if os.path.exists (full):
664                         return full
665         ly.error (_ ('file not found: %s') % name + '\n')
666         ly.exit (1)
667         return ''
668
669 def verbatim_html (s):
670         return re.sub ('>', '&gt;',
671                        re.sub ('<', '&lt;',
672                                re.sub ('&', '&amp;', s)))
673
674 def verbatim_texinfo (s):
675         return re.sub ('{', '@{',
676                        re.sub ('}', '@}',
677                                re.sub ('@', '@@', s)))
678
679 def split_options (option_string):
680         return re.split (format_res[format]['option_sep'], option_string)
681
682 class Chunk:
683         def replacement_text (self):
684                 return ''
685
686         def filter_text (self):
687                 return self.replacement_text ()
688
689         def ly_is_outdated (self):
690                 return 0
691
692         def png_is_outdated (self):
693                 return 0
694
695 class Substring (Chunk):
696         def __init__ (self, source, start, end):
697                 self.source = source
698                 self.start = start
699                 self.end = end
700
701         def replacement_text (self):
702                 return self.source [self.start:self.end]
703
704 class Snippet (Chunk):
705         def __init__ (self, type, match, format):
706                 self.type = type
707                 self.match = match
708                 self.hash = 0
709                 self.options = []
710                 self.format = format
711
712         def replacement_text (self):
713                 return self.match.group ('match')
714
715         def substring (self, s):
716                 return self.match.group (s)
717
718         def __repr__ (self):
719                 return `self.__class__` + " type = " + self.type
720
721 class Include_snippet (Snippet):
722         def processed_filename (self):
723                 f = self.substring ('filename')
724                 return os.path.splitext (f)[0] + format2ext[format]
725
726         def replacement_text (self):
727                 s = self.match.group ('match')
728                 f = self.substring ('filename')
729
730                 return re.sub (f, self.processed_filename (), s)
731
732 class Lilypond_snippet (Snippet):
733         def __init__ (self, type, match, format):
734                 Snippet.__init__ (self, type, match, format)
735                 os = match.group ('options')
736                 if os:
737                         self.options = split_options (os)
738
739         def ly (self):
740                 return self.substring ('code')
741
742         def full_ly (self):
743                 s = self.ly ()
744                 if s:
745                         return compose_ly (s, self.options)
746                 return ''
747
748         # todo: use md5?
749         def get_hash (self):
750                 if not self.hash:
751                         self.hash = abs (hash (self.full_ly ()))
752                 return self.hash
753
754         def basename (self):
755                 if use_hash_p:
756                         return 'lily-%d' % self.get_hash ()
757                 raise 'to be done'
758
759         def write_ly (self):
760                 outf = open (self.basename () + '.ly', 'w')
761                 outf.write (self.full_ly ())
762
763                 open (self.basename () + '.txt', 'w').write ("image of music")
764
765         def ly_is_outdated (self):
766                 base = self.basename ()
767
768                 tex_file = '%s.tex' % base
769                 ly_file = '%s.ly' % base
770                 ok = os.path.exists (ly_file) and os.path.exists (tex_file)\
771                      and os.stat (tex_file)[stat.ST_SIZE] \
772                      and open (tex_file).readlines ()[-1][1:-1] \
773                      == 'lilypondend'
774
775                 if ok and (use_hash_p or self.ly () == open (ly_file).read ()):
776                         # TODO: something smart with target formats
777                         # (ps, png) and m/ctimes
778                         return None
779                 return self
780
781         def png_is_outdated (self):
782                 base = self.basename ()
783                 ok = self.ly_is_outdated ()
784                 if format == HTML or format == TEXINFO:
785                         ok = ok and (os.path.exists (base + '.png')
786                                      or glob.glob (base + '-page*.png'))
787                 return not ok
788
789         def filter_text (self):
790                 code = self.substring ('code')
791                 s = run_filter (code)
792                 d = {
793                   'code': s,
794                   'options': self.match.group ('options')
795                 }
796                 # TODO
797                 return output[self.format][FILTER] % d
798
799         def replacement_text (self):
800                 func = Lilypond_snippet.__dict__ ['output_' + self.format]
801                 return func (self)
802
803         def get_images (self):
804                 base = self.basename ()
805                 # URGUGHUGHUGUGHU
806                 single = '%(base)s.png' % vars ()
807                 multiple = '%(base)s-page1.png' % vars ()
808                 images = (single,)
809                 if os.path.exists (multiple) \
810                    and (not os.path.exists (single)\
811                         or (os.stat (multiple)[stat.ST_MTIME] \
812                             > os.stat (single)[stat.ST_MTIME])):
813                         images = glob.glob ('%(base)s-page*.png' % vars ())
814                 return images
815
816         def output_html (self):
817                 str = ''
818                 base = self.basename ()
819                 if format == HTML:
820                         str += self.output_print_filename (HTML)
821                         if VERBATIM in self.options:
822                                 verb = verbatim_html (self.substring ('code'))
823                                 str += write (output[HTML][VERBATIM] % vars ())
824                         if QUOTE in self.options:
825                                 str = output[HTML][QUOTE] % vars ()
826
827                 str += output[HTML][BEFORE] % vars ()
828                 for image in self.get_images ():
829                         base, ext = os.path.splitext (image)
830                         str += output[HTML][OUTPUT] % vars ()
831                 str += output[HTML][AFTER] % vars ()
832                 return str
833
834         def output_info (self):
835                 str = self.output_print_filename (HTML)
836                 str = output[TEXINFO][BEFORE] % vars ()
837                 for image in self.get_images ():
838                         base, ext = os.path.splitext (image)
839
840                         # URG, makeinfo implicitely prepends dot to ext
841                         # specifying no extension is most robust
842                         ext = ''
843                         str += output[TEXINFO][OUTPUT] % vars ()
844                 str += output[TEXINFO][AFTER] % vars ()
845                 return str
846
847         def output_latex (self):
848                 str = ''
849                 base = self.basename ()
850                 if format == LATEX:
851                         str += self.output_print_filename (LATEX)
852                         if VERBATIM in self.options:
853                                 verb = self.substring ('code')
854                                 str += (output[LATEX][VERBATIM] % vars ())
855                         if QUOTE in self.options:
856                                 str = output[LATEX][QUOTE] % vars ()
857
858                 str += (output[LATEX][BEFORE]
859                         + (output[LATEX][OUTPUT] % vars ())
860                         + output[LATEX][AFTER])
861                 return str
862
863         def output_print_filename (self,format):
864                 str = ''
865                 if PRINTFILENAME in self.options:
866                         base = self.basename ()
867                         filename = self.substring ('filename')
868                         str = output[format][PRINTFILENAME] % vars ()
869                 return str
870
871         def output_texinfo (self):
872                 str = ''
873                 if self.output_print_filename (TEXINFO):
874                         str += ('@html\n' + self.output_print_filename (HTML)
875                                 + '\n@end html\n')
876                         str += ('@tex\n' + self.output_print_filename (LATEX)
877                                 + '\n@end tex\n')
878                 base = self.basename ()
879                 if TEXIDOC in self.options:
880                         texidoc = base + '.texidoc'
881                         if os.path.exists (texidoc):
882                                 str += '@include %(texidoc)s\n\n' % vars ()
883
884                 if VERBATIM in self.options:
885                         verb = verbatim_texinfo (self.substring ('code'))
886                         str += (output[TEXINFO][VERBATIM] % vars ())
887
888                 str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
889                 str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
890                 str += ('@html\n' + self.output_html () + '\n@end html\n')
891
892                 if QUOTE in self.options:
893                         str = output[TEXINFO][QUOTE] % vars ()
894
895                 # need par after image
896                 str += '\n'
897
898                 return str
899
900 class Lilypond_file_snippet (Lilypond_snippet):
901         def ly (self):
902                 name = self.substring ('filename')
903                 return '\\renameinput \"%s\"\n%s' % (name, open (find_file (name)).read ())
904
905 snippet_type_to_class = {
906         'lilypond_file': Lilypond_file_snippet,
907         'lilypond_block': Lilypond_snippet,
908         'lilypond': Lilypond_snippet,
909         'include': Include_snippet,
910 }
911
912 def find_toplevel_snippets (s, types):
913         res = {}
914         for i in types:
915                 res[i] = ly.re.compile (snippet_res[format][i])
916
917         snippets = []
918         index = 0
919         ## found = dict (map (lambda x: (x, None), types))
920         ## urg python2.1
921         found = {}
922         map (lambda x, f=found: f.setdefault (x, None), types)
923
924         # We want to search for multiple regexes, without searching
925         # the string multiple times for one regex.
926         # Hence, we use earlier results to limit the string portion
927         # where we search.
928         # Since every part of the string is traversed at most once for
929         # every type of snippet, this is linear.
930
931         while 1:
932                 first = None
933                 endex = 1 << 30
934                 for type in types:
935                         if not found[type] or found[type][0] < index:
936                                 found[type] = None
937                                 m = res[type].search (s[index:endex])
938                                 if not m:
939                                         continue
940
941                                 cl = Snippet
942                                 if snippet_type_to_class.has_key (type):
943                                         cl = snippet_type_to_class[type]
944                                 snip = cl (type, m, format)
945                                 start = index + m.start ('match')
946                                 found[type] = (start, snip)
947
948                         if found[type] \
949                            and (not first or found[type][0] < found[first][0]):
950                                 first = type
951
952                                 # FIXME.
953
954                                 # Limiting the search space is a cute
955                                 # idea, but this *requires* to search
956                                 # for possible containing blocks
957                                 # first, at least as long as we do not
958                                 # search for the start of blocks, but
959                                 # always/directly for the entire
960                                 # @block ... @end block.
961
962                                 endex = found[first][0]
963
964                 if not first:
965                         snippets.append (Substring (s, index, len (s)))
966                         break
967
968                 (start, snip) = found[first]
969                 snippets.append (Substring (s, index, start))
970                 snippets.append (snip)
971                 found[first] = None
972                 index = start + len (snip.match.group ('match'))
973
974         return snippets
975
976 def filter_pipe (input, cmd):
977         if verbose_p:
978                 ly.progress (_ ("Opening filter `%s\'") % cmd)
979
980         stdin, stdout, stderr = os.popen3 (cmd)
981         stdin.write (input)
982         status = stdin.close ()
983
984         if not status:
985                 status = 0
986                 output = stdout.read ()
987                 status = stdout.close ()
988                 error = stderr.read ()
989
990         if not status:
991                 status = 0
992         signal = 0x0f & status
993         if status or (not output and error):
994                 exit_status = status >> 8
995                 ly.error (_ ("`%s\' failed (%d)") % (cmd, exit_status))
996                 ly.error (_ ("The error log is as follows:"))
997                 sys.stderr.write (error)
998                 sys.stderr.write (stderr.read ())
999                 ly.exit (status)
1000
1001         if verbose_p:
1002                 ly.progress ('\n')
1003
1004         return output
1005
1006 def run_filter (s):
1007         return filter_pipe (s, filter_cmd)
1008
1009 def is_derived_class (cl, baseclass):
1010         if cl == baseclass:
1011                 return 1
1012         for b in cl.__bases__:
1013                 if is_derived_class (b, baseclass):
1014                         return 1
1015         return 0
1016
1017 def process_snippets (cmd, ly_snippets, png_snippets):
1018         ly_names = filter (lambda x: x, map (Lilypond_snippet.basename, ly_snippets))
1019         png_names = filter (lambda x: x, map (Lilypond_snippet.basename, png_snippets))
1020
1021         status = 0
1022         if ly_names:
1023                 status = ly.system (string.join ([cmd] + ly_names),
1024                                     ignore_error = 1, progress_p = 1)
1025
1026         if status:
1027                 ly.error ('Process %s exited unsuccessfully.' % cmd)
1028                 raise Compile_error
1029
1030         if format == HTML or format == TEXINFO:
1031                 for i in png_names:
1032                         if not os.path.exists (i + '.eps') and os.path.exists (i + '.tex'):
1033                                 to_eps (i)
1034                                 ly.make_ps_images (i + '.eps', resolution=110)
1035
1036 #                       elif os.path.exists (i + '.ps'):
1037 #                               ly.make_ps_images (i + '.ps', resolution=110)
1038
1039 LATEX_DOCUMENT = r'''
1040 %(preamble)s
1041 \begin{document}
1042 \typeout{textwidth=\the\textwidth}
1043 \typeout{columnsep=\the\columnsep}
1044 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1045 \end{document}
1046 '''
1047 #need anything else besides textwidth?
1048 def get_latex_textwidth (source):
1049         m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1050         preamble = source[:m.start (0)]
1051         latex_document = LATEX_DOCUMENT % vars ()
1052         parameter_string = filter_pipe (latex_document, latex_filter_cmd)
1053
1054         columns = 0
1055         m = re.search ('columns=([0-9.]*)', parameter_string)
1056         if m:
1057                 columns = string.atoi (m.group (1))
1058
1059         columnsep = 0
1060         m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1061         if m:
1062                 columnsep = string.atof (m.group (1))
1063
1064         textwidth = 0
1065         m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1066         if m:
1067                 textwidth = string.atof (m.group (1))
1068                 if columns:
1069                         textwidth = (textwidth - columnsep) / columns
1070
1071         return textwidth
1072
1073 ext2format = {
1074         '.html': HTML,
1075         '.itely': TEXINFO,
1076         '.latex': LATEX,
1077         '.lytex': LATEX,
1078         '.tely': TEXINFO,
1079         '.tex': LATEX,
1080         '.texi': TEXINFO,
1081         '.texinfo': TEXINFO,
1082         '.xml': HTML,
1083 }
1084
1085 format2ext = {
1086         HTML: '.html',
1087         #TEXINFO: '.texinfo',
1088         TEXINFO: '.texi',
1089         LATEX: '.tex',
1090 }
1091
1092 class Compile_error:
1093         pass
1094
1095 def do_process_cmd (chunks):
1096         ly_outdated = filter (lambda x: is_derived_class (x.__class__, Lilypond_snippet) \
1097                         and x.ly_is_outdated (), chunks)
1098         png_outdated = filter (lambda x: is_derived_class (x.__class__, Lilypond_snippet) \
1099                          and x.png_is_outdated (), chunks)
1100
1101         ly.progress (_ ("Writing snippets..."))
1102         map (Lilypond_snippet.write_ly, ly_outdated)
1103         ly.progress ('\n')
1104
1105         if ly_outdated:
1106                 ly.progress (_ ("Processing..."))
1107                 process_snippets (process_cmd, ly_outdated, png_outdated)
1108         else:
1109                 ly.progress (_ ("All snippets are up to date..."))
1110         ly.progress ('\n')
1111
1112 def do_file (input_filename):
1113         #ugh
1114         global format
1115         if not format:
1116                 e = os.path.splitext (input_filename)[1]
1117                 if e in ext2format.keys ():
1118                         #FIXME
1119                         format = ext2format[e]
1120                 else:
1121                         ly.error (_ ("cannot determine format for: %s" \
1122                                      % input_filename))
1123                         ly.exit (1)
1124
1125         if not input_filename or input_filename == '-':
1126                 in_handle = sys.stdin
1127                 input_fullname = '<stdin>'
1128         else:
1129                 if os.path.exists (input_filename):
1130                         input_fullname = input_filename
1131                 elif format == LATEX:
1132                         # urg python interface to libkpathsea?
1133                         input_fullname = ly.read_pipe ('kpsewhich '
1134                                                        + input_filename)[:-1]
1135                 else:
1136                         input_fullname = find_file (input_filename)
1137                 in_handle = open (input_fullname)
1138
1139         if input_filename == '-':
1140                 input_base = 'stdin'
1141         else:
1142                 input_base = os.path.basename \
1143                              (os.path.splitext (input_filename)[0])
1144
1145         # only default to stdout when filtering
1146         if output_name == '-' or (not output_name and filter_cmd):
1147                 output_filename = '-'
1148                 output_file = sys.stdout
1149         else:
1150                 if not output_name:
1151                         output_filename = input_base + format2ext[format]
1152                 else:
1153                         if not os.path.isdir (output_name):
1154                                 os.mkdir (output_name, 0777)
1155                         output_filename = (output_name
1156                                            + '/' + input_base
1157                                            + format2ext[format])
1158
1159                 if (os.path.exists (input_filename) and
1160                     os.path.exists (output_filename) and
1161                     os.path.samefile (output_filename, input_fullname)):
1162                         ly.error (_ ("Output would overwrite input file; use --output."))
1163                         ly.exit (2)
1164
1165                 output_file = open (output_filename, 'w')
1166                 if output_name:
1167                         os.chdir (output_name)
1168         try:
1169                 ly.progress (_ ("Reading %s...") % input_fullname)
1170                 source = in_handle.read ()
1171                 ly.progress ('\n')
1172
1173                 # FIXME: containing blocks must be first, see find_toplevel_snippets
1174                 snippet_types = (
1175                         'multiline_comment',
1176                         'verbatim',
1177                         'lilypond_block',
1178         #               'verb',
1179                         'singleline_comment',
1180                         'lilypond_file',
1181                         'include',
1182                         'lilypond', )
1183                 ly.progress (_ ("Dissecting..."))
1184                 chunks = find_toplevel_snippets (source, snippet_types)
1185                 ly.progress ('\n')
1186
1187                 global default_ly_options
1188                 textwidth = 0
1189                 if not default_ly_options.has_key (LINEWIDTH):
1190                         if format == LATEX:
1191                                 textwidth = get_latex_textwidth (source)
1192                                 default_ly_options[LINEWIDTH] = '''%.0f\\pt''' \
1193                                                                 % textwidth
1194                         elif format == TEXINFO:
1195                                 for (k, v) in texinfo_linewidths.items ():
1196                                         # FIXME: @layout is usually not in chunk #0:
1197                                         #        \input texinfo @c -*-texinfo-*-
1198                                         # bluntly search first K of source
1199                                         # s = chunks[0].replacement_text ()
1200                                         if re.search (k, source[:1024]):
1201                                                 default_ly_options[LINEWIDTH] = v
1202                                                 break
1203
1204                 if filter_cmd:
1205                         output_file.writelines ([c.filter_text () for c in chunks])
1206
1207                 elif process_cmd:
1208                         do_process_cmd (chunks)
1209                         ly.progress (_ ("Compiling %s...") % output_filename)
1210                         output_file.writelines ([s.replacement_text () \
1211                                                  for s in chunks])
1212                         ly.progress ('\n')
1213
1214                 def process_include (snippet):
1215                         os.chdir (original_dir)
1216                         name = snippet.substring ('filename')
1217                         ly.progress (_ ('Processing include: %s') % name)
1218                         ly.progress ('\n')
1219                         do_file (name)
1220
1221                 map (process_include,
1222                      filter (lambda x: is_derived_class (x.__class__, Include_snippet), chunks))
1223         except Compile_error:
1224                 os.chdir (original_dir)
1225                 ly.progress (_ ('Removing `%s\'') % output_filename)
1226                 ly.progress ('\n')
1227
1228                 os.unlink (output_filename)
1229                 raise Compile_error
1230
1231 def do_options ():
1232         global format, output_name
1233         global filter_cmd, process_cmd, verbose_p
1234
1235         (sh, long) = ly.getopt_args (option_definitions)
1236         try:
1237                 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1238         except getopt.error, s:
1239                 sys.stderr.write ('\n')
1240                 ly.error (_ ("getopt says: `%s\'" % s))
1241                 sys.stderr.write ('\n')
1242                 ly.help ()
1243                 ly.exit (2)
1244
1245         for opt in options:
1246                 o = opt[0]
1247                 a = opt[1]
1248
1249                 if 0:
1250                         pass
1251                 elif o == '--filter' or o == '-F':
1252                         filter_cmd = a
1253                         process_cmd = 0
1254                 elif o == '--format' or o == '-f':
1255                         format = a
1256                         if a == 'texi-html' or a == 'texi':
1257                                 format = TEXINFO
1258                 elif o == '--help' or o == '-h':
1259                         ly.help ()
1260                         sys.exit (0)
1261                 elif o == '--include' or o == '-I':
1262                         include_path.append (os.path.join (original_dir,
1263                                                            ly.abspath (a)))
1264                 elif o == '--output' or o == '-o':
1265                         output_name = a
1266                 elif o == '--outdir':
1267                         output_name = a
1268                 elif o == '--process' or o == '-P':
1269                         process_cmd = a
1270                         filter_cmd = 0
1271                 elif o == '--version' or o == '-v':
1272                         ly.identify (sys.stdout)
1273                         sys.exit (0)
1274                 elif o == '--verbose' or o == '-V':
1275                         verbose_p = 1
1276                 elif o == '--warranty' or o == '-w':
1277                         if 1 or status:
1278                                 ly.warranty ()
1279                         sys.exit (0)
1280         return files
1281
1282 def main ():
1283         files = do_options ()
1284         global process_cmd
1285         if process_cmd == '':
1286                 process_cmd = lilypond_binary + " -f tex "
1287
1288         if process_cmd:
1289                 process_cmd += string.join ([(' -I %s' % p)
1290                                              for p in include_path])
1291
1292         ly.identify (sys.stderr)
1293         ly.setup_environment ()
1294         if files:
1295                 try:
1296                         do_file (files[0])
1297                 except Compile_error:
1298                         ly.exit (1)
1299
1300 if __name__ == '__main__':
1301         main ()