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