]> git.donarmstrong.com Git - lilypond.git/blob - scripts/lilypond-book.py
* lily/lily-parser-scheme.cc: print mapped file name for progress
[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, line_number):
804                 self.source = source
805                 self.start = start
806                 self.end = end
807                 self.line_number = line_number
808
809         def replacement_text (self):
810                 return self.source[self.start:self.end]
811
812 class Snippet (Chunk):
813         def __init__ (self, type, match, format, line_number):
814                 self.type = type
815                 self.match = match
816                 self.hash = 0
817                 self.options = []
818                 self.format = format
819                 self.line_number = line_number
820
821         def replacement_text (self):
822                 return self.match.group ('match')
823
824         def substring (self, s):
825                 return self.match.group (s)
826
827         def __repr__ (self):
828                 return `self.__class__` + ' type = ' + self.type
829
830 class Include_snippet (Snippet):
831         def processed_filename (self):
832                 f = self.substring ('filename')
833                 return os.path.splitext (f)[0] + format2ext[format]
834
835         def replacement_text (self):
836                 s = self.match.group ('match')
837                 f = self.substring ('filename')
838
839                 return re.sub (f, self.processed_filename (), s)
840
841 class Lilypond_snippet (Snippet):
842         def __init__ (self, type, match, format, line_number):
843                 Snippet.__init__ (self, type, match, format, line_number)
844                 os = match.group ('options')
845                 if os:
846                         self.options = split_options (os)
847
848         def ly (self):
849                 return self.substring ('code')
850
851         def full_ly (self):
852                 s = self.ly ()
853                 if s:
854                         return compose_ly (s, self.options, self.type)
855                 return ''
856
857         # TODO: Use md5?
858         def get_hash (self):
859                 if not self.hash:
860                         self.hash = abs (hash (self.full_ly ()))
861                 return self.hash
862
863         def basename (self):
864                 if use_hash_p:
865                         return 'lily-%d' % self.get_hash ()
866                 raise 'to be done'
867
868         def write_ly (self):
869                 outf = open (self.basename () + '.ly', 'w')
870                 outf.write (self.full_ly ())
871
872                 open (self.basename () + '.txt', 'w').write ('image of music')
873
874         def ly_is_outdated (self):
875                 base = self.basename ()
876
877                 tex_file = '%s.tex' % base
878                 eps_file = '%s.eps' % base
879                 system_file = '%s-systems.tex' % base
880                 ly_file = '%s.ly' % base
881                 ok = os.path.exists (ly_file) \
882                      and os.path.exists (system_file)\
883                      and os.stat (system_file)[stat.ST_SIZE] \
884                      and re.match ('% eof', open (system_file).readlines ()[-1])
885                 if ok and (use_hash_p \
886                            or self.ly () == open (ly_file).read ()):
887                         # TODO: Do something smart with target formats
888                         #       (ps, png) and m/ctimes.
889                         return None
890                 return self
891
892         def png_is_outdated (self):
893                 base = self.basename ()
894                 ok = self.ly_is_outdated ()
895                 if format == HTML or format == TEXINFO:
896                         ok = ok and (os.path.exists (base + '.png')
897                                      or glob.glob (base + '-page*.png'))
898                 return not ok
899         def texstr_is_outdated (self):
900                 if backend == 'ps':
901                         return 0
902
903                 base = self.basename ()
904                 ok = self.ly_is_outdated ()
905                 ok = ok and (os.path.exists (base + '.texstr'))
906                 return not ok
907
908         def filter_text (self):
909                 code = self.substring ('code')
910                 s = run_filter (code)
911                 d = {
912                         'code': s,
913                         'options': self.match.group ('options')
914                 }
915                 # TODO
916                 return output[self.format][FILTER] % d
917
918         def replacement_text (self):
919                 func = Lilypond_snippet.__dict__['output_' + self.format]
920                 return func (self)
921
922         def get_images (self):
923                 base = self.basename ()
924                 # URGUGHUGHUGUGH
925                 single = '%(base)s.png' % vars ()
926                 multiple = '%(base)s-page1.png' % vars ()
927                 images = (single,)
928                 if os.path.exists (multiple) \
929                    and (not os.path.exists (single) \
930                         or (os.stat (multiple)[stat.ST_MTIME] \
931                             > os.stat (single)[stat.ST_MTIME])):
932                         images = glob.glob ('%(base)s-page*.png' % vars ())
933                 return images
934
935         def output_html (self):
936                 str = ''
937                 base = self.basename ()
938                 if format == HTML:
939                         str += self.output_print_filename (HTML)
940                         if VERBATIM in self.options:
941                                 verb = verbatim_html (self.substring ('code'))
942                                 str += write (output[HTML][VERBATIM] % vars ())
943                         if QUOTE in self.options:
944                                 str = output[HTML][QUOTE] % vars ()
945
946                 str += output[HTML][BEFORE] % vars ()
947                 for image in self.get_images ():
948                         (base, ext) = os.path.splitext (image)
949                         str += output[HTML][OUTPUT] % vars ()
950                 str += output[HTML][AFTER] % vars ()
951                 return str
952
953         def output_info (self):
954                 str = ''
955                 for image in self.get_images ():
956                         (base, ext) = os.path.splitext (image)
957
958                         # URG, makeinfo implicitly prepends dot to extension.
959                         # Specifying no extension is most robust.
960                         ext = ''
961                         str += output[TEXINFO][OUTPUTIMAGE] % vars ()
962
963                 base = self.basename ()
964                 str += output[format][OUTPUT] % vars ()
965                 return str
966
967         def output_latex (self):
968                 str = ''
969                 base = self.basename ()
970                 if format == LATEX:
971                         str += self.output_print_filename (LATEX)
972                         if VERBATIM in self.options:
973                                 verb = self.substring ('code')
974                                 str += (output[LATEX][VERBATIM] % vars ())
975                         if QUOTE in self.options:
976                                 str = output[LATEX][QUOTE] % vars ()
977
978                 str += (output[LATEX][OUTPUT] % vars ())
979                 return str
980
981         def output_print_filename (self, format):
982                 str = ''
983                 if PRINTFILENAME in self.options:
984                         base = self.basename ()
985                         filename = self.substring ('filename')
986                         str = output[format][PRINTFILENAME] % vars ()
987
988                 return str
989
990         def output_texinfo (self):
991                 str = ''
992                 if self.output_print_filename (TEXINFO):
993                         str += ('@html\n'
994                                 + self.output_print_filename (HTML)
995                                 + '\n@end html\n')
996                         str += ('@tex\n'
997                                 + self.output_print_filename (LATEX)
998                                 + '\n@end tex\n')
999                 base = self.basename ()
1000                 if TEXIDOC in self.options:
1001                         texidoc = base + '.texidoc'
1002                         if os.path.exists (texidoc):
1003                                 str += '@include %(texidoc)s\n\n' % vars ()
1004
1005                 if VERBATIM in self.options:
1006                         verb = verbatim_texinfo (self.substring ('code'))
1007                         str += (output[TEXINFO][VERBATIM] % vars ())
1008                         if not QUOTE in self.options:
1009                                 str = output[TEXINFO][NOQUOTE] % vars ()
1010
1011                 str += self.output_info ()
1012
1013 #               str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1014 #               str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1015 #               str += ('@html\n' + self.output_html () + '\n@end html\n')
1016
1017                 if QUOTE in self.options:
1018                         str = output[TEXINFO][QUOTE] % vars ()
1019
1020                 # need par after image
1021                 str += '\n'
1022
1023                 return str
1024
1025 class Lilypond_file_snippet (Lilypond_snippet):
1026         def ly (self):
1027                 name = self.substring ('filename')
1028                 return '\\renameinput \"%s\"\n%s' \
1029                          % (name, open (find_file (name)).read ())
1030
1031 snippet_type_to_class = {
1032         'lilypond_file': Lilypond_file_snippet,
1033         'lilypond_block': Lilypond_snippet,
1034         'lilypond': Lilypond_snippet,
1035         'include': Include_snippet,
1036 }
1037
1038 def find_linestarts (s):
1039         nls = [0]
1040         start = 0
1041         end = len (s)
1042         while 1:
1043                 i = s.find ('\n', start)
1044                 if i < 0:
1045                         break
1046
1047                 i = i + 1 
1048                 nls.append (i)
1049                 start = i
1050
1051         nls.append (len (s))
1052         return nls
1053
1054 def find_toplevel_snippets (s, types):
1055         res = {}
1056         for i in types:
1057                 res[i] = ly.re.compile (snippet_res[format][i])
1058
1059         snippets = []
1060         index = 0
1061         ## found = dict (map (lambda x: (x, None),
1062         ##                    types))
1063         ## urg python2.1
1064         found = {}
1065         map (lambda x, f = found: f.setdefault (x, None),
1066              types)
1067
1068         line_starts = find_linestarts (s)
1069         line_start_idx = 0
1070         # We want to search for multiple regexes, without searching
1071         # the string multiple times for one regex.
1072         # Hence, we use earlier results to limit the string portion
1073         # where we search.
1074         # Since every part of the string is traversed at most once for
1075         # every type of snippet, this is linear.
1076
1077         while 1:
1078                 first = None
1079                 endex = 1 << 30
1080                 for type in types:
1081                         if not found[type] or found[type][0] < index:
1082                                 found[type] = None
1083                                 m = res[type].search (s[index:endex])
1084                                 if not m:
1085                                         continue
1086
1087                                 cl = Snippet
1088                                 if snippet_type_to_class.has_key (type):
1089                                         cl = snippet_type_to_class[type]
1090
1091                                 line_number = line_start_idx
1092                                 while (line_starts[line_number] < index):
1093                                         line_number += 1
1094
1095                                 line_number ++
1096                                 snip = cl (type, m, format, line_number)
1097                                 start = index + m.start ('match')
1098                                 found[type] = (start, snip)
1099
1100                         if found[type] \
1101                            and (not first \
1102                                 or found[type][0] < found[first][0]):
1103                                 first = type
1104
1105                                 # FIXME.
1106
1107                                 # Limiting the search space is a cute
1108                                 # idea, but this *requires* to search
1109                                 # for possible containing blocks
1110                                 # first, at least as long as we do not
1111                                 # search for the start of blocks, but
1112                                 # always/directly for the entire
1113                                 # @block ... @end block.
1114
1115                                 endex = found[first][0]
1116
1117                 if not first:
1118                         snippets.append (Substring (s, index, len (s), line_start_idx))
1119                         break
1120
1121                 while (start > line_starts[line_start_idx+1]):
1122                         line_start_idx += 1
1123                 
1124                 (start, snip) = found[first]
1125                 snippets.append (Substring (s, index, start, line_start_idx + 1))
1126                 snippets.append (snip)
1127                 found[first] = None
1128                 index = start + len (snip.match.group ('match'))
1129
1130         return snippets
1131
1132 def filter_pipe (input, cmd):
1133         if verbose_p:
1134                 ly.progress (_ ("Opening filter `%s'") % cmd)
1135
1136         (stdin, stdout, stderr) = os.popen3 (cmd)
1137         stdin.write (input)
1138         status = stdin.close ()
1139
1140         if not status:
1141                 status = 0
1142                 output = stdout.read ()
1143                 status = stdout.close ()
1144                 error = stderr.read ()
1145
1146         if not status:
1147                 status = 0
1148         signal = 0x0f & status
1149         if status or (not output and error):
1150                 exit_status = status >> 8
1151                 ly.error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1152                 ly.error (_ ("The error log is as follows:"))
1153                 sys.stderr.write (error)
1154                 sys.stderr.write (stderr.read ())
1155                 ly.exit (status)
1156
1157         if verbose_p:
1158                 ly.progress ('\n')
1159
1160         return output
1161
1162 def run_filter (s):
1163         return filter_pipe (s, filter_cmd)
1164
1165 def is_derived_class (cl, baseclass):
1166         if cl == baseclass:
1167                 return 1
1168         for b in cl.__bases__:
1169                 if is_derived_class (b, baseclass):
1170                         return 1
1171         return 0
1172
1173 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1174         ly_names = filter (lambda x: x,
1175                            map (Lilypond_snippet.basename, ly_snippets))
1176         texstr_names = filter (lambda x: x,
1177                            map (Lilypond_snippet.basename, texstr_snippets))
1178         png_names = filter (lambda x: x,
1179                             map (Lilypond_snippet.basename, png_snippets))
1180
1181         status = 0
1182         def my_system (cmd):
1183                 status = ly.system (cmd,
1184                                     ignore_error = 1, progress_p = 1)
1185
1186                 if status:
1187                         ly.error ('Process %s exited unsuccessfully.' % cmd)
1188                         raise Compile_error
1189
1190         # UGH
1191         # the --process=CMD switch is a bad idea
1192         # it is too generic for lilypond-book.
1193         if texstr_names and re.search ('^[0-9A-Za-z/]*lilypond', cmd):
1194
1195                 my_system (string.join ([cmd,'--backend texstr', 'snippet-map.ly'] + texstr_names))
1196                 for l in texstr_names:
1197                         my_system ('latex %s.texstr' % l)
1198
1199         if ly_names:
1200                 my_system (string.join ([cmd, 'snippet-map.ly'] + ly_names))
1201
1202 LATEX_DOCUMENT = r'''
1203 %(preamble)s
1204 \begin{document}
1205 \typeout{textwidth=\the\textwidth}
1206 \typeout{columnsep=\the\columnsep}
1207 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1208 \end{document}
1209 '''
1210
1211 # Do we need anything else besides `textwidth'?
1212 def get_latex_textwidth (source):
1213         m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1214         preamble = source[:m.start (0)]
1215         latex_document = LATEX_DOCUMENT % vars ()
1216         parameter_string = filter_pipe (latex_document, latex_filter_cmd)
1217
1218         columns = 0
1219         m = re.search ('columns=([0-9.]*)', parameter_string)
1220         if m:
1221                 columns = string.atoi (m.group (1))
1222
1223         columnsep = 0
1224         m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1225         if m:
1226                 columnsep = string.atof (m.group (1))
1227
1228         textwidth = 0
1229         m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1230         if m:
1231                 textwidth = string.atof (m.group (1))
1232                 if columns:
1233                         textwidth = (textwidth - columnsep) / columns
1234
1235         return textwidth
1236
1237 ext2format = {
1238         '.html': HTML,
1239         '.itely': TEXINFO,
1240         '.latex': LATEX,
1241         '.lytex': LATEX,
1242         '.tely': TEXINFO,
1243         '.tex': LATEX,
1244         '.texi': TEXINFO,
1245         '.texinfo': TEXINFO,
1246         '.xml': HTML,
1247 }
1248
1249 format2ext = {
1250         HTML: '.html',
1251         # TEXINFO: '.texinfo',
1252         TEXINFO: '.texi',
1253         LATEX: '.tex',
1254 }
1255
1256 class Compile_error:
1257         pass
1258
1259 def write_file_map (lys, name):
1260         snippet_map = open ('snippet-map.ly', 'w')
1261         snippet_map.write ("\n#(ly:add-file-name-alist '(")
1262         for ly in lys:
1263                 snippet_map.write ('("%s" . "%s:%d (%s.ly)")\n' % (ly.basename(),
1264                                            name,
1265                                            ly.line_number,
1266                                            ly.basename()))
1267
1268         snippet_map.write ('))\n')
1269
1270 def do_process_cmd (chunks, input_name):
1271         all_lys = filter(lambda x: is_derived_class (x.__class__, Lilypond_snippet),
1272                          chunks)
1273         
1274         write_file_map (all_lys, input_name)
1275         ly_outdated = \
1276           filter (lambda x: is_derived_class (x.__class__,
1277                                               Lilypond_snippet)
1278                             and x.ly_is_outdated (),
1279                   chunks)
1280         texstr_outdated = \
1281           filter (lambda x: is_derived_class (x.__class__,
1282                                               Lilypond_snippet)
1283                             and x.texstr_is_outdated (),
1284                   chunks)
1285         png_outdated = \
1286           filter (lambda x: is_derived_class (x.__class__,
1287                                               Lilypond_snippet)
1288                             and x.png_is_outdated (),
1289                   chunks)
1290
1291         ly.progress (_ ("Writing snippets..."))
1292         map (Lilypond_snippet.write_ly, ly_outdated)
1293         ly.progress ('\n')
1294
1295         if ly_outdated:
1296                 ly.progress (_ ("Processing..."))
1297                 ly.progress ('\n')
1298                 process_snippets (process_cmd, ly_outdated, texstr_outdated, png_outdated)
1299         else:
1300                 ly.progress (_ ("All snippets are up to date..."))
1301         ly.progress ('\n')
1302
1303 def guess_format (input_filename):
1304         format = None
1305         e = os.path.splitext (input_filename)[1]
1306         if e in ext2format.keys ():
1307                 # FIXME
1308                 format = ext2format[e]
1309         else:
1310                 ly.error (_ ("cannot determine format for: %s" \
1311                              % input_filename))
1312                 ly.exit (1)
1313         return format
1314
1315 def do_file (input_filename):
1316         # Ugh.
1317         if not input_filename or input_filename == '-':
1318                 in_handle = sys.stdin
1319                 input_fullname = '<stdin>'
1320         else:
1321                 if os.path.exists (input_filename):
1322                         input_fullname = input_filename
1323                 elif format == LATEX:
1324                         # urg python interface to libkpathsea?
1325                         input_fullname = ly.read_pipe ('kpsewhich '
1326                                                        + input_filename)[:-1]
1327                 else:
1328                         input_fullname = find_file (input_filename)
1329                 in_handle = open (input_fullname)
1330
1331         if input_filename == '-':
1332                 input_base = 'stdin'
1333         else:
1334                 input_base = os.path.basename \
1335                              (os.path.splitext (input_filename)[0])
1336
1337         # Only default to stdout when filtering.
1338         if output_name == '-' or (not output_name and filter_cmd):
1339                 output_filename = '-'
1340                 output_file = sys.stdout
1341         else:
1342                 if not output_name:
1343                         output_filename = input_base + format2ext[format]
1344                 else:
1345                         if not os.path.isdir (output_name):
1346                                 os.mkdir (output_name, 0777)
1347                         output_filename = (output_name
1348                                            + '/' + input_base
1349                                            + format2ext[format])
1350
1351                 if os.path.exists (input_filename) \
1352                    and os.path.exists (output_filename) \
1353                    and os.path.samefile (output_filename, input_fullname):
1354                         ly.error (
1355                           _ ("Output would overwrite input file; use --output."))
1356                         ly.exit (2)
1357
1358                 output_file = open (output_filename, 'w')
1359                 if output_name:
1360                         os.chdir (output_name)
1361         try:
1362                 ly.progress (_ ("Reading %s...") % input_fullname)
1363                 source = in_handle.read ()
1364                 ly.progress ('\n')
1365
1366                 # FIXME: Containing blocks must be first, see
1367                 #        find_toplevel_snippets.
1368                 snippet_types = (
1369                         'multiline_comment',
1370                         'verbatim',
1371                         'lilypond_block',
1372         #               'verb',
1373                         'singleline_comment',
1374                         'lilypond_file',
1375                         'include',
1376                         'lilypond',
1377                 )
1378                 ly.progress (_ ("Dissecting..."))
1379                 chunks = find_toplevel_snippets (source, snippet_types)
1380                 ly.progress ('\n')
1381
1382                 global default_ly_options
1383                 textwidth = 0
1384                 if not default_ly_options.has_key (LINEWIDTH):
1385                         if format == LATEX:
1386                                 textwidth = get_latex_textwidth (source)
1387                                 default_ly_options[LINEWIDTH] = \
1388                                   '''%.0f\\pt''' % textwidth
1389                         elif format == TEXINFO:
1390                                 for (k, v) in texinfo_linewidths.items ():
1391                                         # FIXME: @layout is usually not in
1392                                         # chunk #0:
1393                                         #
1394                                         #  \input texinfo @c -*-texinfo-*-
1395                                         #
1396                                         # Bluntly search first K items of
1397                                         # source.
1398                                         # s = chunks[0].replacement_text ()
1399                                         if re.search (k, source[:1024]):
1400                                                 default_ly_options[LINEWIDTH] = v
1401                                                 break
1402
1403                 if filter_cmd:
1404                         output_file.writelines ([c.filter_text () \
1405                                                  for c in chunks])
1406
1407                 elif process_cmd:
1408                         do_process_cmd (chunks, input_fullname)
1409                         ly.progress (_ ("Compiling %s...") % output_filename)
1410                         output_file.writelines ([s.replacement_text () \
1411                                                  for s in chunks])
1412                         ly.progress ('\n')
1413
1414                 def process_include (snippet):
1415                         os.chdir (original_dir)
1416                         name = snippet.substring ('filename')
1417                         ly.progress (_ ("Processing include: %s") % name)
1418                         ly.progress ('\n')
1419                         do_file (name)
1420
1421                 map (process_include,
1422                      filter (lambda x: is_derived_class (x.__class__,
1423                                                          Include_snippet),
1424                              chunks))
1425         except Compile_error:
1426                 os.chdir (original_dir)
1427                 ly.progress (_ ("Removing `%s'") % output_filename)
1428                 ly.progress ('\n')
1429
1430                 os.unlink (output_filename)
1431                 raise Compile_error
1432
1433 def do_options ():
1434         global format, output_name
1435         global filter_cmd, process_cmd, verbose_p
1436
1437         (sh, long) = ly.getopt_args (option_definitions)
1438         try:
1439                 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1440         except getopt.error, s:
1441                 sys.stderr.write ('\n')
1442                 ly.error (_ ("getopt says: `%s'" % s))
1443                 sys.stderr.write ('\n')
1444                 ly.help ()
1445                 ly.exit (2)
1446
1447         for opt in options:
1448                 o = opt[0]
1449                 a = opt[1]
1450
1451                 if 0:
1452                         pass
1453                 elif o == '--filter' or o == '-F':
1454                         filter_cmd = a
1455                         process_cmd = 0
1456                 elif o == '--format' or o == '-f':
1457                         format = a
1458                         if a == 'texi-html' or a == 'texi':
1459                                 format = TEXINFO
1460                 elif o == '--tex-backend ':
1461                         backend = 'tex'
1462                 elif o == '--help' or o == '-h':
1463                         ly.help ()
1464                         sys.exit (0)
1465                 elif o == '--include' or o == '-I':
1466                         include_path.append (os.path.join (original_dir,
1467                                                            ly.abspath (a)))
1468                 elif o == '--output' or o == '-o':
1469                         output_name = a
1470                 elif o == '--outdir':
1471                         output_name = a
1472                 elif o == '--process' or o == '-P':
1473                         process_cmd = a
1474                         filter_cmd = 0
1475                 elif o == '--version' or o == '-v':
1476                         ly.identify (sys.stdout)
1477                         sys.exit (0)
1478                 elif o == '--verbose' or o == '-V':
1479                         verbose_p = 1
1480                 elif o == '--warranty' or o == '-w':
1481                         if 1 or status:
1482                                 ly.warranty ()
1483                         sys.exit (0)
1484         return files
1485
1486 def main ():
1487         files = do_options ()
1488         if not files:
1489                 ly.warning ("Need to have command line option")
1490                 ly.exit (2)
1491
1492         file = files[0]
1493         global process_cmd, format
1494         if not format:
1495                 format = guess_format (files[0])
1496
1497         formats = 'ps'
1498         if format == TEXINFO or format == HTML: 
1499                 formats += ',png' 
1500         if process_cmd == '':
1501                 process_cmd = lilypond_binary + ' --formats=%s --backend eps ' % formats
1502
1503         if process_cmd:
1504                 process_cmd += string.join ([(' -I %s' % p)
1505                                              for p in include_path])
1506
1507         ly.identify (sys.stderr)
1508         ly.setup_environment ()
1509
1510         try:
1511                 do_file (file)
1512         except Compile_error:
1513                 ly.exit (1)
1514
1515
1516 if __name__ == '__main__':
1517         main ()