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