]> git.donarmstrong.com Git - lilypond.git/blob - scripts/lilypond-book.py
* lily/ledger-line-spanner.cc (print): swap linear_combination
[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         #        In texinfo.tex, its maximum value is 0.4in, so we use that.
592         override[EXAMPLEINDENT] = r'0.4\in'
593         override[LINEWIDTH] = None
594         override.update (default_ly_options)
595
596         option_list = []
597         for (key, value) in option_dict.items ():
598                 if value == None:
599                         option_list.append (key)
600                 else:
601                         option_list.append (key + '=' + value)
602         option_string = string.join (option_list, ',')
603
604         compose_dict = {}
605         compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
606         for a in compose_types:
607                 compose_dict[a] = []
608
609         for (key, value) in option_dict.items():
610                 (c_key, c_value) = \
611                   classic_lilypond_book_compatibility (key, value)
612                 if c_key:
613                         if c_value:
614                                 ly.warning \
615                                   (_ ("deprecated ly-option used: %s=%s" \
616                                     % (key, value)))
617                                 ly.warning \
618                                   (_ ("compatibility mode translation: %s=%s" \
619                                     % (c_key, c_value)))
620                         else:
621                                 ly.warning \
622                                   (_ ("deprecated ly-option used: %s" \
623                                     % key))
624                                 ly.warning \
625                                   (_ ("compatibility mode translation: %s" \
626                                     % c_key))
627
628                         (key, value) = (c_key, c_value)
629
630                 if value:
631                         override[key] = value
632                 else:
633                         if not override.has_key (key):
634                                 override[key] = None
635
636                 found = 0
637                 for type in compose_types:
638                         if ly_options[type].has_key (key):
639                                 compose_dict[type].append (ly_options[type][key])
640                                 found = 1
641                                 break
642
643                 if not found and key not in (FRAGMENT, NOFRAGMENT, PRINTFILENAME,
644                                              RELATIVE, VERBATIM, TEXIDOC):
645                         ly.warning (_ ("ignoring unknown ly option: %s") % i)
646
647         #URGS
648         if RELATIVE in override.keys () and override[RELATIVE]:
649                 relative = string.atoi (override[RELATIVE])
650
651         relative_quotes = ''
652
653         # 1 = central C
654         if relative < 0:
655                 relative_quotes += ',' * (- relative)
656         elif relative > 0:
657                 relative_quotes += "'" * relative
658
659         program_name = __main__.program_name
660
661         paper_string = \
662           string.join (compose_dict[PAPER], '\n  ') % override
663         layout_string = \
664           string.join (compose_dict[LAYOUT], '\n  ') % override
665         notes_string = \
666           string.join (compose_dict[NOTES], '\n  ') % vars ()
667         preamble_string = \
668           string.join (compose_dict[PREAMBLE], '\n  ') % override
669
670         return (PREAMBLE_LY + body) % vars ()
671
672 # BARF
673 # use lilypond for latex (.lytex) books,
674 # and lilypond --preview for html, texinfo books?
675 def to_eps (file):
676         cmd = r'latex "\nonstopmode \input %s"' % file
677         # Ugh.  (La)TeX writes progress and error messages on stdout
678         # Redirect to stderr
679         cmd = '(( %s >&2 ) >&- )' % cmd
680         ly.system (cmd)
681         ly.system ('dvips -Ppdf -u+ec-mftrace.map -u+lilypond.map -E -o %s.eps %s' \
682                    % (file, file))
683
684         # check if it really is EPS.
685         # Otherwise music glyphs disappear from 2nd and following pages.
686
687         # TODO: should run dvips -pp -E per page, then we get proper
688         # cropping as well.
689
690         f = open ('%s.eps' % file)
691         for x in range (0, 10):
692                 if re.search ("^%%Pages: ", f.readline ()):
693                         # make non EPS.
694                         ly.system ('dvips -Ppdf -u+ec-mftrace.map -u+lilypond.map -o %s.eps %s' \
695                                    % (file, file))
696                         break
697
698 def find_file (name):
699         for i in include_path:
700                 full = os.path.join (i, name)
701                 if os.path.exists (full):
702                         return full
703         ly.error (_ ("file not found: %s") % name + '\n')
704         ly.exit (1)
705         return ''
706
707 def verbatim_html (s):
708         return re.sub ('>', '&gt;',
709                        re.sub ('<', '&lt;',
710                                re.sub ('&', '&amp;', s)))
711
712 def verbatim_texinfo (s):
713         return re.sub ('{', '@{',
714                        re.sub ('}', '@}',
715                                re.sub ('@', '@@', s)))
716
717 def split_options (option_string):
718         return re.split (format_res[format]['option_sep'], option_string)
719
720 class Chunk:
721         def replacement_text (self):
722                 return ''
723
724         def filter_text (self):
725                 return self.replacement_text ()
726
727         def ly_is_outdated (self):
728                 return 0
729
730         def png_is_outdated (self):
731                 return 0
732
733 class Substring (Chunk):
734         def __init__ (self, source, start, end):
735                 self.source = source
736                 self.start = start
737                 self.end = end
738
739         def replacement_text (self):
740                 return self.source [self.start:self.end]
741
742 class Snippet (Chunk):
743         def __init__ (self, type, match, format):
744                 self.type = type
745                 self.match = match
746                 self.hash = 0
747                 self.options = []
748                 self.format = format
749
750         def replacement_text (self):
751                 return self.match.group ('match')
752
753         def substring (self, s):
754                 return self.match.group (s)
755
756         def __repr__ (self):
757                 return `self.__class__` + " type = " + self.type
758
759 class Include_snippet (Snippet):
760         def processed_filename (self):
761                 f = self.substring ('filename')
762                 return os.path.splitext (f)[0] + format2ext[format]
763
764         def replacement_text (self):
765                 s = self.match.group ('match')
766                 f = self.substring ('filename')
767
768                 return re.sub (f, self.processed_filename (), s)
769
770 class Lilypond_snippet (Snippet):
771         def __init__ (self, type, match, format):
772                 Snippet.__init__ (self, type, match, format)
773                 os = match.group ('options')
774                 if os:
775                         self.options = split_options (os)
776
777         def ly (self):
778                 return self.substring ('code')
779
780         def full_ly (self):
781                 s = self.ly ()
782                 if s:
783                         return compose_ly (s, self.options, self.type)
784                 return ''
785
786         # todo: use md5?
787         def get_hash (self):
788                 if not self.hash:
789                         self.hash = abs (hash (self.full_ly ()))
790                 return self.hash
791
792         def basename (self):
793                 if use_hash_p:
794                         return 'lily-%d' % self.get_hash ()
795                 raise 'to be done'
796
797         def write_ly (self):
798                 outf = open (self.basename () + '.ly', 'w')
799                 outf.write (self.full_ly ())
800
801                 open (self.basename () + '.txt', 'w').write ("image of music")
802
803         def ly_is_outdated (self):
804                 base = self.basename ()
805
806                 tex_file = '%s.tex' % base
807                 ly_file = '%s.ly' % base
808                 ok = os.path.exists (ly_file) and os.path.exists (tex_file)\
809                      and os.stat (tex_file)[stat.ST_SIZE] \
810                      and open (tex_file).readlines ()[-1][1:-1] \
811                      == 'lilypondend'
812
813                 if ok and (use_hash_p or self.ly () == open (ly_file).read ()):
814                         # TODO: something smart with target formats
815                         # (ps, png) and m/ctimes
816                         return None
817                 return self
818
819         def png_is_outdated (self):
820                 base = self.basename ()
821                 ok = self.ly_is_outdated ()
822                 if format == HTML or format == TEXINFO:
823                         ok = ok and (os.path.exists (base + '.png')
824                                      or glob.glob (base + '-page*.png'))
825                 return not ok
826
827         def filter_text (self):
828                 code = self.substring ('code')
829                 s = run_filter (code)
830                 d = {
831                   'code': s,
832                   'options': self.match.group ('options')
833                 }
834                 # TODO
835                 return output[self.format][FILTER] % d
836
837         def replacement_text (self):
838                 func = Lilypond_snippet.__dict__ ['output_' + self.format]
839                 return func (self)
840
841         def get_images (self):
842                 base = self.basename ()
843                 # URGUGHUGHUGUGHU
844                 single = '%(base)s.png' % vars ()
845                 multiple = '%(base)s-page1.png' % vars ()
846                 images = (single,)
847                 if os.path.exists (multiple) \
848                    and (not os.path.exists (single) \
849                         or (os.stat (multiple)[stat.ST_MTIME] \
850                             > os.stat (single)[stat.ST_MTIME])):
851                         images = glob.glob ('%(base)s-page*.png' % vars ())
852                 return images
853
854         def output_html (self):
855                 str = ''
856                 base = self.basename ()
857                 if format == HTML:
858                         str += self.output_print_filename (HTML)
859                         if VERBATIM in self.options:
860                                 verb = verbatim_html (self.substring ('code'))
861                                 str += write (output[HTML][VERBATIM] % vars ())
862                         if QUOTE in self.options:
863                                 str = output[HTML][QUOTE] % vars ()
864
865                 str += output[HTML][BEFORE] % vars ()
866                 for image in self.get_images ():
867                         (base, ext) = os.path.splitext (image)
868                         str += output[HTML][OUTPUT] % vars ()
869                 str += output[HTML][AFTER] % vars ()
870                 return str
871
872         def output_info (self):
873                 str = self.output_print_filename (HTML)
874                 str = output[TEXINFO][BEFORE] % vars ()
875                 for image in self.get_images ():
876                         (base, ext) = os.path.splitext (image)
877
878                         # URG, makeinfo implicitely prepends dot to ext
879                         # specifying no extension is most robust
880                         ext = ''
881                         str += output[TEXINFO][OUTPUT] % vars ()
882                 str += output[TEXINFO][AFTER] % vars ()
883                 return str
884
885         def output_latex (self):
886                 str = ''
887                 base = self.basename ()
888                 if format == LATEX:
889                         str += self.output_print_filename (LATEX)
890                         if VERBATIM in self.options:
891                                 verb = self.substring ('code')
892                                 str += (output[LATEX][VERBATIM] % vars ())
893                         if QUOTE in self.options:
894                                 str = output[LATEX][QUOTE] % vars ()
895
896                 str += (output[LATEX][BEFORE]
897                         + (output[LATEX][OUTPUT] % vars ())
898                         + output[LATEX][AFTER])
899                 return str
900
901         def output_print_filename (self,format):
902                 str = ''
903                 if PRINTFILENAME in self.options:
904                         base = self.basename ()
905                         filename = self.substring ('filename')
906                         str = output[format][PRINTFILENAME] % vars ()
907                 return str
908
909         def output_texinfo (self):
910                 str = ''
911                 if self.output_print_filename (TEXINFO):
912                         str += ('@html\n' + self.output_print_filename (HTML)
913                                 + '\n@end html\n')
914                         str += ('@tex\n' + self.output_print_filename (LATEX)
915                                 + '\n@end tex\n')
916                 base = self.basename ()
917                 if TEXIDOC in self.options:
918                         texidoc = base + '.texidoc'
919                         if os.path.exists (texidoc):
920                                 str += '@include %(texidoc)s\n\n' % vars ()
921
922                 if VERBATIM in self.options:
923                         verb = verbatim_texinfo (self.substring ('code'))
924                         str += (output[TEXINFO][VERBATIM] % vars ())
925
926                 str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
927                 str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
928                 str += ('@html\n' + self.output_html () + '\n@end html\n')
929
930                 if QUOTE in self.options:
931                         str = output[TEXINFO][QUOTE] % vars ()
932
933                 # need par after image
934                 str += '\n'
935
936                 return str
937
938 class Lilypond_file_snippet (Lilypond_snippet):
939         def ly (self):
940                 name = self.substring ('filename')
941                 return '\\renameinput \"%s\"\n%s' % (name, open (find_file (name)).read ())
942
943 snippet_type_to_class = {
944         'lilypond_file': Lilypond_file_snippet,
945         'lilypond_block': Lilypond_snippet,
946         'lilypond': Lilypond_snippet,
947         'include': Include_snippet,
948 }
949
950 def find_toplevel_snippets (s, types):
951         res = {}
952         for i in types:
953                 res[i] = ly.re.compile (snippet_res[format][i])
954
955         snippets = []
956         index = 0
957         ## found = dict (map (lambda x: (x, None), types))
958         ## urg python2.1
959         found = {}
960         map (lambda x, f = found: f.setdefault (x, None), types)
961
962         # We want to search for multiple regexes, without searching
963         # the string multiple times for one regex.
964         # Hence, we use earlier results to limit the string portion
965         # where we search.
966         # Since every part of the string is traversed at most once for
967         # every type of snippet, this is linear.
968
969         while 1:
970                 first = None
971                 endex = 1 << 30
972                 for type in types:
973                         if not found[type] or found[type][0] < index:
974                                 found[type] = None
975                                 m = res[type].search (s[index:endex])
976                                 if not m:
977                                         continue
978
979                                 cl = Snippet
980                                 if snippet_type_to_class.has_key (type):
981                                         cl = snippet_type_to_class[type]
982                                 snip = cl (type, m, format)
983                                 start = index + m.start ('match')
984                                 found[type] = (start, snip)
985
986                         if found[type] \
987                            and (not first or found[type][0] < found[first][0]):
988                                 first = type
989
990                                 # FIXME.
991
992                                 # Limiting the search space is a cute
993                                 # idea, but this *requires* to search
994                                 # for possible containing blocks
995                                 # first, at least as long as we do not
996                                 # search for the start of blocks, but
997                                 # always/directly for the entire
998                                 # @block ... @end block.
999
1000                                 endex = found[first][0]
1001
1002                 if not first:
1003                         snippets.append (Substring (s, index, len (s)))
1004                         break
1005
1006                 (start, snip) = found[first]
1007                 snippets.append (Substring (s, index, start))
1008                 snippets.append (snip)
1009                 found[first] = None
1010                 index = start + len (snip.match.group ('match'))
1011
1012         return snippets
1013
1014 def filter_pipe (input, cmd):
1015         if verbose_p:
1016                 ly.progress (_ ("Opening filter `%s'") % cmd)
1017
1018         (stdin, stdout, stderr) = os.popen3 (cmd)
1019         stdin.write (input)
1020         status = stdin.close ()
1021
1022         if not status:
1023                 status = 0
1024                 output = stdout.read ()
1025                 status = stdout.close ()
1026                 error = stderr.read ()
1027
1028         if not status:
1029                 status = 0
1030         signal = 0x0f & status
1031         if status or (not output and error):
1032                 exit_status = status >> 8
1033                 ly.error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1034                 ly.error (_ ("The error log is as follows:"))
1035                 sys.stderr.write (error)
1036                 sys.stderr.write (stderr.read ())
1037                 ly.exit (status)
1038
1039         if verbose_p:
1040                 ly.progress ('\n')
1041
1042         return output
1043
1044 def run_filter (s):
1045         return filter_pipe (s, filter_cmd)
1046
1047 def is_derived_class (cl, baseclass):
1048         if cl == baseclass:
1049                 return 1
1050         for b in cl.__bases__:
1051                 if is_derived_class (b, baseclass):
1052                         return 1
1053         return 0
1054
1055 def process_snippets (cmd, ly_snippets, png_snippets):
1056         ly_names = filter (lambda x: x, map (Lilypond_snippet.basename, ly_snippets))
1057         png_names = filter (lambda x: x, map (Lilypond_snippet.basename, png_snippets))
1058
1059         status = 0
1060         if ly_names:
1061                 status = ly.system (string.join ([cmd] + ly_names),
1062                                     ignore_error = 1, progress_p = 1)
1063
1064         if status:
1065                 ly.error ('Process %s exited unsuccessfully.' % cmd)
1066                 raise Compile_error
1067
1068         if format == HTML or format == TEXINFO:
1069                 for i in png_names:
1070                         if not os.path.exists (i + '.eps') and os.path.exists (i + '.tex'):
1071                                 to_eps (i)
1072                                 ly.make_ps_images (i + '.eps', resolution = 110)
1073
1074 #                       elif os.path.exists (i + '.ps'):
1075 #                               ly.make_ps_images (i + '.ps', resolution = 110)
1076
1077 LATEX_DOCUMENT = r'''
1078 %(preamble)s
1079 \begin{document}
1080 \typeout{textwidth=\the\textwidth}
1081 \typeout{columnsep=\the\columnsep}
1082 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1083 \end{document}
1084 '''
1085 #need anything else besides textwidth?
1086 def get_latex_textwidth (source):
1087         m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1088         preamble = source[:m.start (0)]
1089         latex_document = LATEX_DOCUMENT % vars ()
1090         parameter_string = filter_pipe (latex_document, latex_filter_cmd)
1091
1092         columns = 0
1093         m = re.search ('columns=([0-9.]*)', parameter_string)
1094         if m:
1095                 columns = string.atoi (m.group (1))
1096
1097         columnsep = 0
1098         m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1099         if m:
1100                 columnsep = string.atof (m.group (1))
1101
1102         textwidth = 0
1103         m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1104         if m:
1105                 textwidth = string.atof (m.group (1))
1106                 if columns:
1107                         textwidth = (textwidth - columnsep) / columns
1108
1109         return textwidth
1110
1111 ext2format = {
1112         '.html': HTML,
1113         '.itely': TEXINFO,
1114         '.latex': LATEX,
1115         '.lytex': LATEX,
1116         '.tely': TEXINFO,
1117         '.tex': LATEX,
1118         '.texi': TEXINFO,
1119         '.texinfo': TEXINFO,
1120         '.xml': HTML,
1121 }
1122
1123 format2ext = {
1124         HTML: '.html',
1125         #TEXINFO: '.texinfo',
1126         TEXINFO: '.texi',
1127         LATEX: '.tex',
1128 }
1129
1130 class Compile_error:
1131         pass
1132
1133 def do_process_cmd (chunks):
1134         ly_outdated = filter (lambda x: is_derived_class (x.__class__, Lilypond_snippet) \
1135                         and x.ly_is_outdated (), chunks)
1136         png_outdated = filter (lambda x: is_derived_class (x.__class__, Lilypond_snippet) \
1137                          and x.png_is_outdated (), chunks)
1138
1139         ly.progress (_ ("Writing snippets..."))
1140         map (Lilypond_snippet.write_ly, ly_outdated)
1141         ly.progress ('\n')
1142
1143         if ly_outdated:
1144                 ly.progress (_ ("Processing...\n"))
1145                 process_snippets (process_cmd, ly_outdated, png_outdated)
1146         else:
1147                 ly.progress (_ ("All snippets are up to date..."))
1148         ly.progress ('\n')
1149
1150 def do_file (input_filename):
1151         #ugh
1152         global format
1153         if not format:
1154                 e = os.path.splitext (input_filename)[1]
1155                 if e in ext2format.keys ():
1156                         # FIXME
1157                         format = ext2format[e]
1158                 else:
1159                         ly.error (_ ("cannot determine format for: %s" \
1160                                      % input_filename))
1161                         ly.exit (1)
1162
1163         if not input_filename or input_filename == '-':
1164                 in_handle = sys.stdin
1165                 input_fullname = '<stdin>'
1166         else:
1167                 if os.path.exists (input_filename):
1168                         input_fullname = input_filename
1169                 elif format == LATEX:
1170                         # urg python interface to libkpathsea?
1171                         input_fullname = ly.read_pipe ('kpsewhich '
1172                                                        + input_filename)[:-1]
1173                 else:
1174                         input_fullname = find_file (input_filename)
1175                 in_handle = open (input_fullname)
1176
1177         if input_filename == '-':
1178                 input_base = 'stdin'
1179         else:
1180                 input_base = os.path.basename \
1181                              (os.path.splitext (input_filename)[0])
1182
1183         # only default to stdout when filtering
1184         if output_name == '-' or (not output_name and filter_cmd):
1185                 output_filename = '-'
1186                 output_file = sys.stdout
1187         else:
1188                 if not output_name:
1189                         output_filename = input_base + format2ext[format]
1190                 else:
1191                         if not os.path.isdir (output_name):
1192                                 os.mkdir (output_name, 0777)
1193                         output_filename = (output_name
1194                                            + '/' + input_base
1195                                            + format2ext[format])
1196
1197                 if (os.path.exists (input_filename) and
1198                     os.path.exists (output_filename) and
1199                     os.path.samefile (output_filename, input_fullname)):
1200                         ly.error (_ ("Output would overwrite input file; use --output."))
1201                         ly.exit (2)
1202
1203                 output_file = open (output_filename, 'w')
1204                 if output_name:
1205                         os.chdir (output_name)
1206         try:
1207                 ly.progress (_ ("Reading %s...") % input_fullname)
1208                 source = in_handle.read ()
1209                 ly.progress ('\n')
1210
1211                 # FIXME: containing blocks must be first, see
1212                 #        find_toplevel_snippets
1213                 snippet_types = (
1214                         'multiline_comment',
1215                         'verbatim',
1216                         'lilypond_block',
1217         #               'verb',
1218                         'singleline_comment',
1219                         'lilypond_file',
1220                         'include',
1221                         'lilypond', )
1222                 ly.progress (_ ("Dissecting..."))
1223                 chunks = find_toplevel_snippets (source, snippet_types)
1224                 ly.progress ('\n')
1225
1226                 global default_ly_options
1227                 textwidth = 0
1228                 if not default_ly_options.has_key (LINEWIDTH):
1229                         if format == LATEX:
1230                                 textwidth = get_latex_textwidth (source)
1231                                 default_ly_options[LINEWIDTH] = \
1232                                   '''%.0f\\pt''' % textwidth
1233                         elif format == TEXINFO:
1234                                 for (k, v) in texinfo_linewidths.items ():
1235                                         # FIXME: @layout is usually not in chunk #0:
1236                                         #        \input texinfo @c -*-texinfo-*-
1237                                         # bluntly search first K of source
1238                                         # s = chunks[0].replacement_text ()
1239                                         if re.search (k, source[:1024]):
1240                                                 default_ly_options[LINEWIDTH] = v
1241                                                 break
1242
1243                 if filter_cmd:
1244                         output_file.writelines ([c.filter_text () for c in chunks])
1245
1246                 elif process_cmd:
1247                         do_process_cmd (chunks)
1248                         ly.progress (_ ("Compiling %s...") % output_filename)
1249                         output_file.writelines ([s.replacement_text () \
1250                                                  for s in chunks])
1251                         ly.progress ('\n')
1252
1253                 def process_include (snippet):
1254                         os.chdir (original_dir)
1255                         name = snippet.substring ('filename')
1256                         ly.progress (_ ("Processing include: %s") % name)
1257                         ly.progress ('\n')
1258                         do_file (name)
1259
1260                 map (process_include,
1261                      filter (lambda x: is_derived_class (x.__class__, Include_snippet), chunks))
1262         except Compile_error:
1263                 os.chdir (original_dir)
1264                 ly.progress (_ ("Removing `%s'") % output_filename)
1265                 ly.progress ('\n')
1266
1267                 os.unlink (output_filename)
1268                 raise Compile_error
1269
1270 def do_options ():
1271         global format, output_name
1272         global filter_cmd, process_cmd, verbose_p
1273
1274         (sh, long) = ly.getopt_args (option_definitions)
1275         try:
1276                 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1277         except getopt.error, s:
1278                 sys.stderr.write ('\n')
1279                 ly.error (_ ("getopt says: `%s'" % s))
1280                 sys.stderr.write ('\n')
1281                 ly.help ()
1282                 ly.exit (2)
1283
1284         for opt in options:
1285                 o = opt[0]
1286                 a = opt[1]
1287
1288                 if 0:
1289                         pass
1290                 elif o == '--filter' or o == '-F':
1291                         filter_cmd = a
1292                         process_cmd = 0
1293                 elif o == '--format' or o == '-f':
1294                         format = a
1295                         if a == 'texi-html' or a == 'texi':
1296                                 format = TEXINFO
1297                 elif o == '--help' or o == '-h':
1298                         ly.help ()
1299                         sys.exit (0)
1300                 elif o == '--include' or o == '-I':
1301                         include_path.append (os.path.join (original_dir,
1302                                                            ly.abspath (a)))
1303                 elif o == '--output' or o == '-o':
1304                         output_name = a
1305                 elif o == '--outdir':
1306                         output_name = a
1307                 elif o == '--process' or o == '-P':
1308                         process_cmd = a
1309                         filter_cmd = 0
1310                 elif o == '--version' or o == '-v':
1311                         ly.identify (sys.stdout)
1312                         sys.exit (0)
1313                 elif o == '--verbose' or o == '-V':
1314                         verbose_p = 1
1315                 elif o == '--warranty' or o == '-w':
1316                         if 1 or status:
1317                                 ly.warranty ()
1318                         sys.exit (0)
1319         return files
1320
1321 def main ():
1322         files = do_options ()
1323         global process_cmd
1324         if process_cmd == '':
1325                 process_cmd = lilypond_binary + " -f tex "
1326
1327         if process_cmd:
1328                 process_cmd += string.join ([(' -I %s' % p)
1329                                              for p in include_path])
1330
1331         ly.identify (sys.stderr)
1332         ly.setup_environment ()
1333         if files:
1334                 try:
1335                         do_file (files[0])
1336                 except Compile_error:
1337                         ly.exit (1)
1338
1339 if __name__ == '__main__':
1340         main ()