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