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