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