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