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