]> git.donarmstrong.com Git - lilypond.git/blob - scripts/lilypond-book.py
Merge branch 'master' of ssh://jomand@git.sv.gnu.org/srv/git/lilypond
[lilypond.git] / scripts / lilypond-book.py
1 #!@TARGET_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
17   *  this script is too complex. Modularize.
18   
19   *  ly-options: intertext?
20   *  --line-width?
21   *  eps in latex / eps by lilypond -b ps?
22   *  check latex parameters, twocolumn, multicolumn?
23   *  use --png --ps --pdf for making images?
24
25   *  Converting from lilypond-book source, substitute:
26    @mbinclude foo.itely -> @include foo.itely
27    \mbinput -> \input
28
29 '''
30
31 import glob
32 import md5
33 import os
34 import re
35 import stat
36 import sys
37 import tempfile
38
39 """
40 @relocate-preamble@
41 """
42
43 import lilylib as ly
44 import fontextract
45 import langdefs
46 global _;_=ly._
47
48
49 # Lilylib globals.
50 program_version = '@TOPLEVEL_VERSION@'
51 program_name = os.path.basename (sys.argv[0])
52
53 original_dir = os.getcwd ()
54 backend = 'ps'
55
56 help_summary = (
57 _ ("Process LilyPond snippets in hybrid HTML, LaTeX, texinfo or DocBook document.")
58 + '\n\n'
59 + _ ("Examples:")
60 + '''
61  lilypond-book --filter="tr '[a-z]' '[A-Z]'" %(BOOK)s
62  lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" %(BOOK)s
63  lilypond-book --process='lilypond -I include' %(BOOK)s
64 ''' % {'BOOK': _ ("BOOK")})
65
66 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
67            'Han-Wen Nienhuys <hanwen@xs4all.nl>')
68
69 ################################################################
70 def exit (i):
71     if global_options.verbose:
72         raise Exception (_ ('Exiting (%d)...') % i)
73     else:
74         sys.exit (i)
75
76 def identify ():
77     ly.encoded_write (sys.stdout, '%s (GNU LilyPond) %s\n' % (program_name, program_version))
78
79 progress = ly.progress
80
81 def warning (s):
82     ly.stderr_write (program_name + ": " + _ ("warning: %s") % s + '\n')
83
84 def error (s):
85     ly.stderr_write (program_name + ": " + _ ("error: %s") % s + '\n')
86
87 def ps_page_count (ps_name):
88     header = file (ps_name).read (1024)
89     m = re.search ('\n%%Pages: ([0-9]+)', header)
90     if m:
91         return int (m.group (1))
92     return 0
93
94 def warranty ():
95     identify ()
96     ly.encoded_write (sys.stdout, '''
97 %s
98
99 %s
100
101 %s
102 %s
103 ''' % ( _ ('Copyright (c) %s by') % '2001--2007',
104         ' '.join (authors),
105         _ ("Distributed under terms of the GNU General Public License."),
106         _ ("It comes with NO WARRANTY.")))
107
108 def get_option_parser ():
109     p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'lilypond-book',
110                               description=help_summary,
111                               add_help_option=False)
112
113     p.add_option ('-F', '--filter', metavar=_ ("FILTER"),
114                   action="store",
115                   dest="filter_cmd",
116                   help=_ ("pipe snippets through FILTER [convert-ly -n -]"),
117                   default=None)
118
119     p.add_option ('-f', '--format',
120                   help=_ ("use output format FORMAT (texi [default], texi-html, latex, html, docbook)"),
121                   action='store')
122
123     p.add_option("-h", "--help",
124                  action="help",
125                  help=_ ("show this help and exit"))
126
127     p.add_option ("-I", '--include', help=_ ("add DIR to include path"),
128                   metavar=_ ("DIR"),
129                   action='append', dest='include_path',
130                   default=[os.path.abspath (os.getcwd ())])
131
132     p.add_option ('--info-images-dir',
133                   help=_ ("format Texinfo output so that Info will "
134                           "look for images of music in DIR"),
135                   metavar=_ ("DIR"),
136                   action='store', dest='info_images_dir',
137                   default='')
138
139     p.add_option ('--latex',
140                   help=_ ("Run executable PROG instead of latex"),
141                   metavar=_ ("PROG"),
142                   action='store', dest='latex_program',
143                   default='latex')
144
145     p.add_option ('--left-padding', 
146                   metavar=_ ("PAD"),
147                   dest="padding_mm",
148                   help=_ ("pad left side of music to align music inspite of uneven bar numbers (in mm)"),
149                   type="float",
150                   default=3.0)
151     
152     p.add_option ("-o", '--output', help=_ ("write output to DIR"),
153                   metavar=_ ("DIR"),
154                   action='store', dest='output_dir',
155                   default='')
156     
157     p.add_option ('--skip-lily-check',
158                   help=_ ("do not fail if no lilypond output is found."),
159                   metavar=_ ("DIR"),
160                   action='store_true', dest='skip_lilypond_run',
161                   default=False)
162
163     p.add_option ('--skip-png-check',
164                   help=_ ("do not fail if no PNG images are found for EPS files"),
165                   metavar=_ ("DIR"),
166                   action='store_true', dest='skip_png_check',
167                   default=False)
168     
169     p.add_option ('--lily-output-dir',
170                   help=_ ("write lily-XXX files to DIR, link into --output dir."),
171                   metavar=_ ("DIR"),
172                   action='store', dest='lily_output_dir',
173                   default=None)
174     
175     p.add_option ('-P', '--process', metavar=_ ("COMMAND"),
176                   help = _ ("process ly_files using COMMAND FILE..."),
177                   action='store', 
178                   dest='process_cmd', default='')
179
180     p.add_option ('--pdf',
181                   action="store_true",
182                   dest="create_pdf",
183                   help=_ ("create PDF files for use with PDFTeX"),
184                   default=False)
185
186     p.add_option ('', '--psfonts', action="store_true", dest="psfonts",
187                   help=_ ('''extract all PostScript fonts into INPUT.psfonts for LaTeX
188 must use this with dvips -h INPUT.psfonts'''),
189                   default=None)
190
191     p.add_option ('-V', '--verbose', help=_ ("be verbose"),
192                   action="store_true",
193                   default=False,
194                   dest="verbose")
195
196     p.version = "@TOPLEVEL_VERSION@"
197     p.add_option("--version",
198                  action="version",
199                  help=_ ("show version number and exit"))
200
201     p.add_option ('-w', '--warranty',
202                   help=_ ("show warranty and copyright"),
203                   action='store_true')
204     p.add_option_group (ly.display_encode (_ ('Bugs')),
205                         description=(
206         _ ("Report bugs via")
207         + ' http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs\n'))
208     return p
209
210 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
211
212 # Only use installed binary when we are installed too.
213 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
214     lilypond_binary = 'lilypond'
215
216 global_options = None
217
218
219 default_ly_options = { 'alt': "[image of music]" }
220
221 document_language = ''
222
223 #
224 # Is this pythonic?  Personally, I find this rather #define-nesque. --hwn
225 #
226 ADDVERSION = 'addversion'
227 AFTER = 'after'
228 BEFORE = 'before'
229 DOCBOOK = 'docbook'
230 EXAMPLEINDENT = 'exampleindent'
231 FILTER = 'filter'
232 FRAGMENT = 'fragment'
233 HTML = 'html'
234 INDENT = 'indent'
235 LANG = 'lang'
236 LATEX = 'latex'
237 LAYOUT = 'layout'
238 LINE_WIDTH = 'line-width'
239 LILYQUOTE = 'lilyquote'
240 NOFRAGMENT = 'nofragment'
241 NOINDENT = 'noindent'
242 NOQUOTE = 'noquote'
243 NOTES = 'body'
244 NOTIME = 'notime'
245 OUTPUT = 'output'
246 OUTPUTIMAGE = 'outputimage'
247 PACKED = 'packed'
248 PAPER = 'paper'
249 PREAMBLE = 'preamble'
250 PRINTFILENAME = 'printfilename'
251 QUOTE = 'quote'
252 RAGGED_RIGHT = 'ragged-right'
253 RELATIVE = 'relative'
254 STAFFSIZE = 'staffsize'
255 TEXIDOC = 'texidoc'
256 TEXINFO = 'texinfo'
257 VERBATIM = 'verbatim'
258 FONTLOAD = 'fontload'
259 FILENAME = 'filename'
260 ALT = 'alt'
261
262
263 # NOTIME has no opposite so it isn't part of this dictionary.
264 # NOQUOTE is used internally only.
265 no_options = {
266     NOFRAGMENT: FRAGMENT,
267     NOINDENT: INDENT,
268 }
269
270
271 # Recognize special sequences in the input.
272 #
273 #   (?P<name>regex) -- Assign result of REGEX to NAME.
274 #   *? -- Match non-greedily.
275 #   (?m) -- Multiline regex: Make ^ and $ match at each line.
276 #   (?s) -- Make the dot match all characters including newline.
277 #   (?x) -- Ignore whitespace in patterns.
278 no_match = 'a\ba'
279 snippet_res = {
280  ##
281     DOCBOOK: {
282         'include':
283          no_match,
284
285         'lilypond':
286          r'''(?smx)
287           (?P<match>
288           <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
289
290         'lilypond_block':
291          r'''(?smx)
292           (?P<match>
293           <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
294
295         'lilypond_file':
296          r'''(?smx)
297           (?P<match>
298           <(?P<inline>(inline)?)mediaobject>\s*<imageobject.*?>\s*<imagedata\s+fileref="(?P<filename>.*?\.ly)"\s*(role="(?P<options>.*?)")?\s*(/>|>\s*</imagedata>)\s*</imageobject>\s*</(inline)?mediaobject>)''',
299
300         'multiline_comment':
301          r'''(?smx)
302           (?P<match>
303           \s*(?!@c\s+)
304           (?P<code><!--\s.*?!-->)
305           \s)''',
306
307         'singleline_comment':
308          no_match,
309
310         'verb':
311          no_match,
312
313         'verbatim':
314         no_match,
315         
316     }, 
317     ##
318     HTML: {
319         'include':
320          no_match,
321
322         'lilypond':
323          r'''(?mx)
324           (?P<match>
325           <lilypond
326            (\s*(?P<options>.*?)\s*:)?\s*
327            (?P<code>.*?)
328           />)''',
329
330         'lilypond_block':
331          r'''(?msx)
332           (?P<match>
333           <lilypond
334            \s*(?P<options>.*?)\s*
335           >
336           (?P<code>.*?)
337           </lilypond>)''',
338
339         'lilypond_file':
340          r'''(?mx)
341           (?P<match>
342           <lilypondfile
343            \s*(?P<options>.*?)\s*
344           >
345           \s*(?P<filename>.*?)\s*
346           </lilypondfile>)''',
347
348         'multiline_comment':
349          r'''(?smx)
350           (?P<match>
351           \s*(?!@c\s+)
352           (?P<code><!--\s.*?!-->)
353           \s)''',
354
355         'singleline_comment':
356          no_match,
357
358         'verb':
359          r'''(?x)
360           (?P<match>
361            (?P<code><pre>.*?</pre>))''',
362
363         'verbatim':
364          r'''(?x)
365           (?s)
366           (?P<match>
367            (?P<code><pre>\s.*?</pre>\s))''',
368     },
369
370     ##
371     LATEX: {
372         'include':
373          r'''(?smx)
374           ^[^%\n]*?
375           (?P<match>
376           \\input\s*{
377            (?P<filename>\S+?)
378           })''',
379
380         'lilypond':
381          r'''(?smx)
382           ^[^%\n]*?
383           (?P<match>
384           \\lilypond\s*(
385           \[
386            \s*(?P<options>.*?)\s*
387           \])?\s*{
388            (?P<code>.*?)
389           })''',
390
391         'lilypond_block':
392          r'''(?smx)
393           ^[^%\n]*?
394           (?P<match>
395           \\begin\s*(
396           \[
397            \s*(?P<options>.*?)\s*
398           \])?\s*{lilypond}
399            (?P<code>.*?)
400           ^[^%\n]*?
401           \\end\s*{lilypond})''',
402
403         'lilypond_file':
404          r'''(?smx)
405           ^[^%\n]*?
406           (?P<match>
407           \\lilypondfile\s*(
408           \[
409            \s*(?P<options>.*?)\s*
410           \])?\s*\{
411            (?P<filename>\S+?)
412           })''',
413
414         'multiline_comment':
415          no_match,
416
417         'singleline_comment':
418          r'''(?mx)
419           ^.*?
420           (?P<match>
421            (?P<code>
422            %.*$\n+))''',
423
424         'verb':
425          r'''(?mx)
426           ^[^%\n]*?
427           (?P<match>
428            (?P<code>
429            \\verb(?P<del>.)
430             .*?
431            (?P=del)))''',
432
433         'verbatim':
434          r'''(?msx)
435           ^[^%\n]*?
436           (?P<match>
437            (?P<code>
438            \\begin\s*{verbatim}
439             .*?
440            \\end\s*{verbatim}))''',
441     },
442
443     ##
444     TEXINFO: {
445         'include':
446          r'''(?mx)
447           ^(?P<match>
448           @include\s+
449            (?P<filename>\S+))''',
450
451         'lilypond':
452          r'''(?smx)
453           ^[^\n]*?(?!@c\s+)[^\n]*?
454           (?P<match>
455           @lilypond\s*(
456           \[
457            \s*(?P<options>.*?)\s*
458           \])?\s*{
459            (?P<code>.*?)
460           })''',
461
462         'lilypond_block':
463          r'''(?msx)
464           ^(?P<match>
465           @lilypond\s*(
466           \[
467            \s*(?P<options>.*?)\s*
468           \])?\s+?
469           ^(?P<code>.*?)
470           ^@end\s+lilypond)\s''',
471
472         'lilypond_file':
473          r'''(?mx)
474           ^(?P<match>
475           @lilypondfile\s*(
476           \[
477            \s*(?P<options>.*?)\s*
478           \])?\s*{
479            (?P<filename>\S+)
480           })''',
481
482         'multiline_comment':
483          r'''(?smx)
484           ^(?P<match>
485            (?P<code>
486            @ignore\s
487             .*?
488            @end\s+ignore))\s''',
489
490         'singleline_comment':
491          r'''(?mx)
492           ^.*
493           (?P<match>
494            (?P<code>
495            @c([ \t][^\n]*|)\n))''',
496
497     # Don't do this: It interferes with @code{@{}.
498     #        'verb': r'''(?P<code>@code{.*?})''',
499
500         'verbatim':
501          r'''(?sx)
502           (?P<match>
503            (?P<code>
504            @example
505             \s.*?
506            @end\s+example\s))''',
507     },
508 }
509
510
511
512
513 format_res = {
514     DOCBOOK: {        
515         'intertext': r',?\s*intertext=\".*?\"',
516         'option_sep': '\s*',
517     }, 
518     HTML: {
519         'intertext': r',?\s*intertext=\".*?\"',
520         'option_sep': '\s*',
521     },
522
523     LATEX: {
524         'intertext': r',?\s*intertext=\".*?\"',
525         'option_sep': '\s*,\s*',
526     },
527
528     TEXINFO: {
529         'intertext': r',?\s*intertext=\".*?\"',
530         'option_sep': '\s*,\s*',
531     },
532 }
533
534 # Options without a pattern in ly_options.
535 simple_options = [
536     EXAMPLEINDENT,
537     FRAGMENT,
538     NOFRAGMENT,
539     NOINDENT,
540     PRINTFILENAME,
541     TEXIDOC,
542     LANG,
543     VERBATIM,
544     FONTLOAD,
545     FILENAME,
546     ALT,
547     ADDVERSION
548 ]
549
550 ly_options = {
551     ##
552     NOTES: {
553         RELATIVE: r'''\relative c%(relative_quotes)s''',
554     },
555
556     ##
557     PAPER: {
558         INDENT: r'''indent = %(indent)s''',
559
560         LINE_WIDTH: r'''line-width = %(line-width)s''',
561
562         QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
563
564         LILYQUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
565
566         RAGGED_RIGHT: r'''ragged-right = ##t''',
567
568         PACKED: r'''packed = ##t''',
569     },
570
571     ##
572     LAYOUT: {
573         NOTIME: r'''
574  \context {
575   \Score
576   timing = ##f
577  }
578  \context {
579   \Staff
580   \remove Time_signature_engraver
581  }''',
582     },
583
584     ##
585     PREAMBLE: {
586         STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
587     },
588 }
589
590 output = {
591     ##
592     DOCBOOK: {                 
593         FILTER: r'''<mediaobject><textobject><programlisting language="lilypond" role="%(options)s">%(code)s</programlisting></textobject></mediaobject>''', 
594     
595         OUTPUT: r'''
596         <imageobject role="latex">
597                 <imagedata fileref="%(base)s.pdf" format="PDF"/>
598                 </imageobject>
599                 <imageobject role="html">
600                 <imagedata fileref="%(base)s.png" format="PNG"/></imageobject>''',
601     
602         VERBATIM: r'''<programlisting>%(verb)s</programlisting>''',
603     
604         PRINTFILENAME: '<textobject><simpara><ulink url="%(base)s.ly"><filename>%(filename)s</filename></ulink></simpara></textobject>'
605     },
606     ##
607     HTML: {
608         FILTER: r'''<lilypond %(options)s>
609 %(code)s
610 </lilypond>
611 ''',
612
613         AFTER: r'''
614  </a>
615 </p>''',
616
617         BEFORE: r'''<p>
618  <a href="%(base)s.ly">''',
619
620         OUTPUT: r'''
621   <img align="middle" 
622     border="0" src="%(image)s" alt="%(alt)s">''',
623
624         PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
625
626         QUOTE: r'''<blockquote>
627 %(str)s
628 </blockquote>
629 ''',
630
631         VERBATIM: r'''<pre>
632 %(verb)s</pre>''',
633     },
634
635     ##
636     LATEX: {
637         OUTPUT: r'''{%%
638 \parindent 0pt%%
639 \ifx\preLilyPondExample \undefined%%
640  \relax%%
641 \else%%
642  \preLilyPondExample%%
643 \fi%%
644 \def\lilypondbook{}%%
645 \input %(base)s-systems.tex%%
646 \ifx\postLilyPondExample \undefined%%
647  \relax%%
648 \else%%
649  \postLilyPondExample%%
650 \fi%%
651 }''',
652
653         PRINTFILENAME: '''\\texttt{%(filename)s}
654     ''',
655
656         QUOTE: r'''\begin{quotation}%(str)s
657 \end{quotation}''',
658
659         VERBATIM: r'''\noindent
660 \begin{verbatim}%(verb)s\end{verbatim}''',
661
662         FILTER: r'''\begin{lilypond}[%(options)s]
663 %(code)s
664 \end{lilypond}''',
665     },
666
667     ##
668     TEXINFO: {
669         FILTER: r'''@lilypond[%(options)s]
670 %(code)s
671 @lilypond''',
672
673         OUTPUT: r'''
674 @iftex
675 @include %(base)s-systems.texi
676 @end iftex
677 ''',
678
679         OUTPUTIMAGE: r'''@noindent
680 @ifinfo
681 @image{%(info_image_path)s,,,%(alt)s,%(ext)s}
682 @end ifinfo
683 @html
684 <p>
685  <a href="%(base)s.ly">
686   <img align="middle"
687     border="0" src="%(image)s" alt="%(alt)s">
688  </a>
689 </p>
690 @end html
691 ''',
692
693         PRINTFILENAME: '''
694 @html
695 <a href="%(base)s.ly">
696 @end html
697 @file{%(filename)s}
698 @html
699 </a>
700 @end html
701     ''',
702
703         QUOTE: r'''@quotation
704 %(str)s@end quotation
705 ''',
706
707         NOQUOTE: r'''@format
708 %(str)s@end format
709 ''',
710
711         VERBATIM: r'''@exampleindent 0
712 %(version)s@verbatim
713 %(verb)s@end verbatim
714 ''',
715
716         ADDVERSION: r'''@example
717 \version @w{"@version{}"}
718 @end example
719 '''
720     },
721 }
722
723 #
724 # Maintain line numbers.
725 #
726
727 ## TODO
728 if 0:
729     for f in [HTML, LATEX]:
730         for s in (QUOTE, VERBATIM):
731             output[f][s] = output[f][s].replace("\n"," ")
732
733
734 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
735 %%%% Options: [%(option_string)s]
736 \\include "lilypond-book-preamble.ly"
737
738
739 %% ****************************************************************
740 %% Start cut-&-pastable-section 
741 %% ****************************************************************
742
743 %(preamble_string)s
744
745 \paper {
746   #(define dump-extents #t)
747   %(font_dump_setting)s
748   %(paper_string)s
749   force-assignment = #""
750   line-width = #(- line-width (* mm  %(padding_mm)f))
751 }
752
753 \layout {
754   %(layout_string)s
755 }
756 '''
757
758 FRAGMENT_LY = r'''
759 %(notes_string)s
760 {
761
762
763 %% ****************************************************************
764 %% ly snippet contents follows:
765 %% ****************************************************************
766 %(code)s
767
768
769 %% ****************************************************************
770 %% end ly snippet
771 %% ****************************************************************
772 }
773 '''
774
775 FULL_LY = '''
776
777
778 %% ****************************************************************
779 %% ly snippet:
780 %% ****************************************************************
781 %(code)s
782
783
784 %% ****************************************************************
785 %% end ly snippet
786 %% ****************************************************************
787 '''
788
789 texinfo_line_widths = {
790     '@afourpaper': '160\\mm',
791     '@afourwide': '6.5\\in',
792     '@afourlatex': '150\\mm',
793     '@smallbook': '5\\in',
794     '@letterpaper': '6\\in',
795 }
796
797 def classic_lilypond_book_compatibility (key, value):
798     if key == 'singleline' and value == None:
799         return (RAGGED_RIGHT, None)
800
801     m = re.search ('relative\s*([-0-9])', key)
802     if m:
803         return ('relative', m.group (1))
804
805     m = re.match ('([0-9]+)pt', key)
806     if m:
807         return ('staffsize', m.group (1))
808
809     if key == 'indent' or key == 'line-width':
810         m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
811         if m:
812             f = float (m.group (1))
813             return (key, '%f\\%s' % (f, m.group (2)))
814
815     return (None, None)
816
817 def find_file (name, raise_error=True):
818     for i in global_options.include_path:
819         full = os.path.join (i, name)
820         if os.path.exists (full):
821             return full
822         
823     if raise_error:
824         error (_ ("file not found: %s") % name + '\n')
825         exit (1)
826     return ''
827
828 def verbatim_html (s):
829     return re.sub ('>', '&gt;',
830            re.sub ('<', '&lt;',
831                re.sub ('&', '&amp;', s)))
832
833 ly_var_def_re = re.compile (r'^([a-zA-Z]+)[\t ]*=', re.M)
834 ly_comment_re = re.compile (r'(%+[\t ]*)(.*)$', re.M)
835
836 def ly_comment_gettext (t, m):
837     return m.group (1) + t (m.group (2))
838
839 def verb_ly_gettext (s):
840     if not document_language:
841         return s
842     try:
843         t = langdefs.translation[document_language]
844     except:
845         return s
846
847     s = ly_comment_re.sub (lambda m: ly_comment_gettext (t, m), s)
848     
849     for v in ly_var_def_re.findall (s):
850         s = re.sub (r"(?m)(^|[' \\#])%s([^a-zA-Z])" % v,
851                     "\\1" + t (v) + "\\2",
852                     s)
853     return s
854
855 texinfo_lang_re = re.compile ('(?m)^@documentlanguage (.*?)( |$)')
856 def set_default_options (source, default_ly_options, format):
857     global document_language
858     if LINE_WIDTH not in default_ly_options:
859         if format == LATEX:
860             textwidth = get_latex_textwidth (source)
861             default_ly_options[LINE_WIDTH] = '%.0f\\pt' % textwidth
862         elif format == TEXINFO:
863             m = texinfo_lang_re.search (source)
864             if m and not m.group (1).startswith ('en'):
865                 document_language = m.group (1)
866             else:
867                 document_language = ''
868             for regex in texinfo_line_widths:
869                 # FIXME: @layout is usually not in
870                 # chunk #0:
871                 #
872                 #  \input texinfo @c -*-texinfo-*-
873                 #
874                 # Bluntly search first K items of
875                 # source.
876                 # s = chunks[0].replacement_text ()
877                 if re.search (regex, source[:1024]):
878                     default_ly_options[LINE_WIDTH] = texinfo_line_widths[regex]
879                     break
880
881 class Chunk:
882     def replacement_text (self):
883         return ''
884
885     def filter_text (self):
886         return self.replacement_text ()
887
888     def is_plain (self):
889         return False
890     
891 class Substring (Chunk):
892     """A string that does not require extra memory."""
893     def __init__ (self, source, start, end, line_number):
894         self.source = source
895         self.start = start
896         self.end = end
897         self.line_number = line_number
898         self.override_text = None
899         
900     def is_plain (self):
901         return True
902
903     def replacement_text (self):
904         if self.override_text:
905             return self.override_text
906         else:
907             return self.source[self.start:self.end]
908
909 class Snippet (Chunk):
910     def __init__ (self, type, match, format, line_number):
911         self.type = type
912         self.match = match
913         self.checksum = 0
914         self.option_dict = {}
915         self.format = format
916         self.line_number = line_number
917
918     def replacement_text (self):
919         return self.match.group ('match')
920
921     def substring (self, s):
922         return self.match.group (s)
923
924     def __repr__ (self):
925         return `self.__class__` + ' type = ' + self.type
926
927 class IncludeSnippet (Snippet):
928     def processed_filename (self):
929         f = self.substring ('filename')
930         return os.path.splitext (f)[0] + format2ext[self.format]
931
932     def replacement_text (self):
933         s = self.match.group ('match')
934         f = self.substring ('filename')
935
936         return re.sub (f, self.processed_filename (), s)
937
938 class LilypondSnippet (Snippet):
939     def __init__ (self, type, match, format, line_number):
940         Snippet.__init__ (self, type, match, format, line_number)
941         os = match.group ('options')
942         self.do_options (os, self.type)
943
944     def verb_ly (self):
945         return verb_ly_gettext (self.substring ('code'))
946
947     def ly (self):
948         contents = self.substring ('code')
949         return ('\\sourcefileline %d\n%s'
950                 % (self.line_number - 1, contents))
951
952     def full_ly (self):
953         s = self.ly ()
954         if s:
955             return self.compose_ly (s)
956         return ''
957
958     def split_options (self, option_string):
959         if option_string:
960             if self.format == HTML:
961                 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',
962                                      option_string)
963                 options = [re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)', '\g<1>\g<3>', opt)
964                            for opt in options]
965                 return options
966             else:
967                 return re.split (format_res[self.format]['option_sep'],
968                                  option_string)
969         return []
970
971     def do_options (self, option_string, type):
972         self.option_dict = {}
973
974         options = self.split_options (option_string)
975
976         for option in options:
977             if '=' in option:
978                 (key, value) = re.split ('\s*=\s*', option)
979                 self.option_dict[key] = value
980             else:
981                 if option in no_options:
982                     if no_options[option] in self.option_dict:
983                         del self.option_dict[no_options[option]]
984                 else:
985                     self.option_dict[option] = None
986
987         has_line_width = self.option_dict.has_key (LINE_WIDTH)
988         no_line_width_value = 0
989
990         # If LINE_WIDTH is used without parameter, set it to default.
991         if has_line_width and self.option_dict[LINE_WIDTH] == None:
992             no_line_width_value = 1
993             del self.option_dict[LINE_WIDTH]
994
995         for k in default_ly_options:
996             if k not in self.option_dict:
997                 self.option_dict[k] = default_ly_options[k]
998
999         if not has_line_width:
1000             if type == 'lilypond' or FRAGMENT in self.option_dict:
1001                 self.option_dict[RAGGED_RIGHT] = None
1002
1003             if type == 'lilypond':
1004                 if LINE_WIDTH in self.option_dict:
1005                     del self.option_dict[LINE_WIDTH]
1006             else:
1007                 if RAGGED_RIGHT in self.option_dict:
1008                     if LINE_WIDTH in self.option_dict:
1009                         del self.option_dict[LINE_WIDTH]
1010
1011             if QUOTE in self.option_dict or type == 'lilypond':
1012                 if LINE_WIDTH in self.option_dict:
1013                     del self.option_dict[LINE_WIDTH]
1014
1015         if not INDENT in self.option_dict:
1016             self.option_dict[INDENT] = '0\\mm'
1017
1018         # The QUOTE pattern from ly_options only emits the `line-width'
1019         # keyword.
1020         if has_line_width and QUOTE in self.option_dict:
1021             if no_line_width_value:
1022                 del self.option_dict[LINE_WIDTH]
1023             else:
1024                 del self.option_dict[QUOTE]
1025
1026     def compose_ly (self, code):
1027         if FRAGMENT in self.option_dict:
1028             body = FRAGMENT_LY
1029         else:
1030             body = FULL_LY
1031
1032         # Defaults.
1033         relative = 1
1034         override = {}
1035         # The original concept of the `exampleindent' option is broken.
1036         # It is not possible to get a sane value for @exampleindent at all
1037         # without processing the document itself.  Saying
1038         #
1039         #   @exampleindent 0
1040         #   @example
1041         #   ...
1042         #   @end example
1043         #   @exampleindent 5
1044         #
1045         # causes ugly results with the DVI backend of texinfo since the
1046         # default value for @exampleindent isn't 5em but 0.4in (or a smaller
1047         # value).  Executing the above code changes the environment
1048         # indentation to an unknown value because we don't know the amount
1049         # of 1em in advance since it is font-dependent.  Modifying
1050         # @exampleindent in the middle of a document is simply not
1051         # supported within texinfo.
1052         #
1053         # As a consequence, the only function of @exampleindent is now to
1054         # specify the amount of indentation for the `quote' option.
1055         #
1056         # To set @exampleindent locally to zero, we use the @format
1057         # environment for non-quoted snippets.
1058         override[EXAMPLEINDENT] = r'0.4\in'
1059         override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1060         override.update (default_ly_options)
1061
1062         option_list = []
1063         for (key, value) in self.option_dict.items ():
1064             if value == None:
1065                 option_list.append (key)
1066             else:
1067                 option_list.append (key + '=' + value)
1068         option_string = ','.join (option_list)
1069
1070         compose_dict = {}
1071         compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1072         for a in compose_types:
1073             compose_dict[a] = []
1074
1075         for (key, value) in self.option_dict.items ():
1076             (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
1077             if c_key:
1078                 if c_value:
1079                     warning (
1080                         _ ("deprecated ly-option used: %s=%s") % (key, value))
1081                     warning (
1082                         _ ("compatibility mode translation: %s=%s") % (c_key, c_value))
1083                 else:
1084                     warning (
1085                         _ ("deprecated ly-option used: %s") % key)
1086                     warning (
1087                         _ ("compatibility mode translation: %s") % c_key)
1088
1089                 (key, value) = (c_key, c_value)
1090
1091             if value:
1092                 override[key] = value
1093             else:
1094                 if not override.has_key (key):
1095                     override[key] = None
1096
1097             found = 0
1098             for type in compose_types:
1099                 if ly_options[type].has_key (key):
1100                     compose_dict[type].append (ly_options[type][key])
1101                     found = 1
1102                     break
1103
1104             if not found and key not in simple_options:
1105                 warning (_ ("ignoring unknown ly option: %s") % key)
1106
1107         # URGS
1108         if RELATIVE in override and override[RELATIVE]:
1109             relative = int (override[RELATIVE])
1110
1111         relative_quotes = ''
1112
1113         # 1 = central C
1114         if relative < 0:
1115             relative_quotes += ',' * (- relative)
1116         elif relative > 0:
1117             relative_quotes += "'" * relative
1118
1119         paper_string = '\n  '.join (compose_dict[PAPER]) % override
1120         layout_string = '\n  '.join (compose_dict[LAYOUT]) % override
1121         notes_string = '\n  '.join (compose_dict[NOTES]) % vars ()
1122         preamble_string = '\n  '.join (compose_dict[PREAMBLE]) % override
1123         padding_mm = global_options.padding_mm
1124         font_dump_setting = ''
1125         if FONTLOAD in self.option_dict:
1126             font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1127
1128         d = globals().copy()
1129         d.update (locals())
1130         return (PREAMBLE_LY + body) % d
1131
1132     def get_checksum (self):
1133         if not self.checksum:
1134             hash = md5.md5 (self.relevant_contents (self.full_ly ()))
1135
1136             ## let's not create too long names.
1137             self.checksum = hash.hexdigest ()[:10]
1138             
1139         return self.checksum
1140
1141     def basename (self):
1142         cs = self.get_checksum ()
1143         name = '%s/lily-%s' % (cs[:2], cs[2:10])
1144         return name
1145
1146     def write_ly (self):
1147         base = self.basename ()
1148         path = os.path.join (global_options.lily_output_dir, base)
1149         directory = os.path.split(path)[0]
1150         if not os.path.isdir (directory):
1151             os.makedirs (directory)
1152         out = file (path + '.ly', 'w')
1153         out.write (self.full_ly ())
1154         file (path + '.txt', 'w').write ('image of music')
1155
1156     def relevant_contents (self, ly):
1157         return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
1158
1159     def link_all_output_files (self, output_dir, output_dir_files, destination):
1160         existing, missing = self.all_output_files (output_dir, output_dir_files)
1161         if missing:
1162             print '\nMissing', missing
1163             raise CompileError(self.basename())
1164         for name in existing:
1165             try:
1166                 os.unlink (os.path.join (destination, name))
1167             except OSError:
1168                 pass
1169
1170             src = os.path.join (output_dir, name)
1171             dst = os.path.join (destination, name)
1172             dst_path = os.path.split(dst)[0]
1173             if not os.path.isdir (dst_path):
1174                 os.makedirs (dst_path)
1175             os.link (src, dst)
1176
1177         
1178     def all_output_files (self, output_dir, output_dir_files):
1179         """Return all files generated in lily_output_dir, a set.
1180
1181         output_dir_files is the list of files in the output directory.
1182         """
1183         result = set ()
1184         missing = set ()
1185         base = self.basename()
1186         full = os.path.join (output_dir, base)
1187         def consider_file (name):
1188             if name in output_dir_files:
1189                 result.add (name)
1190              
1191         def require_file (name):
1192             if name in output_dir_files:
1193                 result.add (name)
1194             else:
1195                 missing.add (name)
1196
1197         # UGH - junk global_options
1198         skip_lily = global_options.skip_lilypond_run
1199         for required in [base + '.ly',
1200                          base + '.txt']:
1201             require_file (required)
1202         if not skip_lily:
1203             require_file (base + '-systems.count')
1204
1205         map (consider_file, [base + '.tex',
1206                              base + '.eps',
1207                              base + '.texidoc',
1208                              base + '.texidoc' + document_language,
1209                              base + '-systems.texi',
1210                              base + '-systems.tex',
1211                              base + '-systems.pdftexi'])
1212
1213         # UGH - junk global_options
1214         if (base + '.eps' in result and self.format in (HTML, TEXINFO)
1215             and not global_options.skip_png_check):
1216             page_count = ps_page_count (full + '.eps')
1217             if page_count <= 1:
1218                 require_file (base + '.png')
1219             else:
1220                 for page in range (1, page_count + 1):
1221                     require_file (base + '-page%d.png' % page)
1222
1223         system_count = 0
1224         if not skip_lily and not missing:
1225             system_count = int(file (full + '-systems.count').read())
1226         for number in range(1, system_count + 1):
1227             systemfile = '%s-%d' % (base, number)
1228             require_file (systemfile + '.eps')
1229             consider_file (systemfile + '.pdf')
1230         
1231         return (result, missing)
1232     
1233     def is_outdated (self, output_dir, current_files):
1234         found, missing = self.all_output_files (output_dir, current_files)
1235         return missing
1236     
1237     def filter_text (self):
1238         """Run snippet bodies through a command (say: convert-ly).
1239
1240         This functionality is rarely used, and this code must have bitrot.
1241         """
1242         code = self.substring ('code')
1243         s = filter_pipe (code, global_options.filter_cmd)
1244         d = {
1245             'code': s,
1246             'options': self.match.group ('options')
1247         }
1248         # TODO
1249         return output[self.format][FILTER] % d
1250
1251     def replacement_text (self):
1252         func = LilypondSnippet.__dict__['output_' + self.format]
1253         return func (self)
1254
1255     def get_images (self):
1256         base = self.basename ()
1257
1258         single = '%(base)s.png' % vars ()
1259         multiple = '%(base)s-page1.png' % vars ()
1260         images = (single,)
1261         if (os.path.exists (multiple) 
1262             and (not os.path.exists (single)
1263                  or (os.stat (multiple)[stat.ST_MTIME]
1264                      > os.stat (single)[stat.ST_MTIME]))):
1265             count = ps_page_count ('%(base)s.eps' % vars ())
1266             images = ['%s-page%d.png' % (base, page) for page in range (1, count+1)]
1267             images = tuple (images)
1268             
1269         return images
1270
1271     def output_docbook (self):
1272         str = ''
1273         base = self.basename ()
1274         for image in self.get_images ():
1275             (base, ext) = os.path.splitext (image)
1276             str += output[DOCBOOK][OUTPUT] % vars ()
1277             str += self.output_print_filename (DOCBOOK)
1278             if (self.substring('inline') == 'inline'): 
1279                 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1280             else:
1281                 str = '<mediaobject>' + str + '</mediaobject>'
1282         if VERBATIM in self.option_dict:
1283                 verb = verbatim_html (self.verb_ly ())
1284                 str = output[DOCBOOK][VERBATIM] % vars () + str
1285         return str
1286         
1287     def output_html (self):
1288         str = ''
1289         base = self.basename ()
1290         if self.format == HTML:
1291             str += self.output_print_filename (HTML)
1292             if VERBATIM in self.option_dict:
1293                 verb = verbatim_html (self.verb_ly ())
1294                 str += output[HTML][VERBATIM] % vars ()
1295             if QUOTE in self.option_dict:
1296                 str = output[HTML][QUOTE] % vars ()
1297
1298         str += output[HTML][BEFORE] % vars ()
1299         for image in self.get_images ():
1300             (base, ext) = os.path.splitext (image)
1301             alt = self.option_dict[ALT]
1302             str += output[HTML][OUTPUT] % vars ()
1303         str += output[HTML][AFTER] % vars ()
1304         return str
1305
1306     def output_info (self):
1307         str = ''
1308         for image in self.get_images ():
1309             (base, ext) = os.path.splitext (image)
1310
1311             # URG, makeinfo implicitly prepends dot to extension.
1312             # Specifying no extension is most robust.
1313             ext = ''
1314             alt = self.option_dict[ALT]
1315             info_image_path = os.path.join (global_options.info_images_dir, base)
1316             str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1317
1318         base = self.basename ()
1319         str += output[self.format][OUTPUT] % vars ()
1320         return str
1321
1322     def output_latex (self):
1323         str = ''
1324         base = self.basename ()
1325         if self.format == LATEX:
1326             str += self.output_print_filename (LATEX)
1327             if VERBATIM in self.option_dict:
1328                 verb = self.verb_ly ()
1329                 str += (output[LATEX][VERBATIM] % vars ())
1330
1331         str += (output[LATEX][OUTPUT] % vars ())
1332
1333         ## todo: maintain breaks
1334         if 0:
1335             breaks = self.ly ().count ("\n")
1336             str += "".ljust (breaks, "\n").replace ("\n","%\n")
1337         
1338         if QUOTE in self.option_dict:
1339             str = output[LATEX][QUOTE] % vars ()
1340         return str
1341
1342     def output_print_filename (self, format):
1343         str = ''
1344         if PRINTFILENAME in self.option_dict:
1345             base = self.basename ()
1346             filename = os.path.basename (self.substring ('filename'))
1347             str = output[format][PRINTFILENAME] % vars ()
1348
1349         return str
1350
1351     def output_texinfo (self):
1352         str = self.output_print_filename (TEXINFO)
1353         base = self.basename ()
1354         if TEXIDOC in self.option_dict:
1355             texidoc = base + '.texidoc'
1356             translated_texidoc = texidoc + document_language
1357             if os.path.exists (translated_texidoc):
1358                 str += '@include %(translated_texidoc)s\n\n' % vars ()
1359             elif os.path.exists (texidoc):
1360                 str += '@include %(texidoc)s\n\n' % vars ()
1361
1362         substr = ''
1363         if VERBATIM in self.option_dict:
1364             version = ''
1365             if ADDVERSION in self.option_dict:
1366                 version = output[TEXINFO][ADDVERSION]
1367             verb = self.verb_ly ()
1368             substr = output[TEXINFO][VERBATIM] % vars ()
1369         substr += self.output_info ()
1370         if LILYQUOTE in self.option_dict:
1371             substr = output[TEXINFO][QUOTE] % {'str':substr}
1372         str += substr
1373
1374 #                str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1375 #                str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1376 #                str += ('@html\n' + self.output_html () + '\n@end html\n')
1377
1378         if QUOTE in self.option_dict:
1379             str = output[TEXINFO][QUOTE] % vars ()
1380
1381         # need par after image
1382         str += '\n'
1383
1384         return str
1385
1386 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1387 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1388
1389 class LilypondFileSnippet (LilypondSnippet):
1390     def __init__ (self, type, match, format, line_number):
1391         LilypondSnippet.__init__ (self, type, match, format, line_number)
1392         self.contents = file (find_file (self.substring ('filename'))).read ()
1393
1394     def verb_ly (self):
1395         s = self.contents
1396         s = re_begin_verbatim.split (s)[-1]
1397         s = re_end_verbatim.split (s)[0]
1398         return verb_ly_gettext (s)
1399
1400     def ly (self):
1401         name = self.substring ('filename')
1402         return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1403                 % (name, self.contents))
1404
1405
1406 snippet_type_to_class = {
1407     'lilypond_file': LilypondFileSnippet,
1408     'lilypond_block': LilypondSnippet,
1409     'lilypond': LilypondSnippet,
1410     'include': IncludeSnippet,
1411 }
1412
1413 def find_linestarts (s):
1414     nls = [0]
1415     start = 0
1416     end = len (s)
1417     while 1:
1418         i = s.find ('\n', start)
1419         if i < 0:
1420             break
1421
1422         i = i + 1
1423         nls.append (i)
1424         start = i
1425
1426     nls.append (len (s))
1427     return nls
1428
1429 def find_toplevel_snippets (input_string, format, types):
1430     res = {}
1431     for t in types:
1432         res[t] = re.compile (snippet_res[format][t])
1433
1434     snippets = []
1435     index = 0
1436     found = dict ([(t, None) for t in types])
1437
1438     line_starts = find_linestarts (input_string)
1439     line_start_idx = 0
1440     # We want to search for multiple regexes, without searching
1441     # the string multiple times for one regex.
1442     # Hence, we use earlier results to limit the string portion
1443     # where we search.
1444     # Since every part of the string is traversed at most once for
1445     # every type of snippet, this is linear.
1446
1447     while 1:
1448         first = None
1449         endex = 1 << 30
1450         for type in types:
1451             if not found[type] or found[type][0] < index:
1452                 found[type] = None
1453                 
1454                 m = res[type].search (input_string[index:endex])
1455                 if not m:
1456                     continue
1457
1458                 klass = Snippet
1459                 if type in snippet_type_to_class:
1460                     klass = snippet_type_to_class[type]
1461
1462                 start = index + m.start ('match')
1463                 line_number = line_start_idx
1464                 while (line_starts[line_number] < start):
1465                     line_number += 1
1466
1467                 line_number += 1
1468                 snip = klass (type, m, format, line_number)
1469
1470                 found[type] = (start, snip)
1471
1472             if (found[type] 
1473                 and (not first 
1474                      or found[type][0] < found[first][0])):
1475                 first = type
1476
1477                 # FIXME.
1478
1479                 # Limiting the search space is a cute
1480                 # idea, but this *requires* to search
1481                 # for possible containing blocks
1482                 # first, at least as long as we do not
1483                 # search for the start of blocks, but
1484                 # always/directly for the entire
1485                 # @block ... @end block.
1486
1487                 endex = found[first][0]
1488
1489         if not first:
1490             snippets.append (Substring (input_string, index, len (input_string), line_start_idx))
1491             break
1492
1493         while (start > line_starts[line_start_idx+1]):
1494             line_start_idx += 1
1495
1496         (start, snip) = found[first]
1497         snippets.append (Substring (input_string, index, start, line_start_idx + 1))
1498         snippets.append (snip)
1499         found[first] = None
1500         index = start + len (snip.match.group ('match'))
1501
1502     return snippets
1503
1504 def filter_pipe (input, cmd):
1505     """Pass input through cmd, and return the result."""
1506     
1507     if global_options.verbose:
1508         progress (_ ("Opening filter `%s'") % cmd)
1509
1510     (stdin, stdout, stderr) = os.popen3 (cmd)
1511     stdin.write (input)
1512     status = stdin.close ()
1513
1514     if not status:
1515         status = 0
1516         output = stdout.read ()
1517         status = stdout.close ()
1518         error = stderr.read ()
1519
1520     if not status:
1521         status = 0
1522     signal = 0x0f & status
1523     if status or (not output and error):
1524         exit_status = status >> 8
1525         error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1526         error (_ ("The error log is as follows:"))
1527         ly.stderr_write (error)
1528         ly.stderr_write (stderr.read ())
1529         exit (status)
1530
1531     if global_options.verbose:
1532         progress ('\n')
1533
1534     return output
1535
1536 def system_in_directory (cmd, directory):
1537     """Execute a command in a different directory.
1538
1539     Because of win32 compatibility, we can't simply use subprocess.
1540     """
1541     
1542     current = os.getcwd()
1543     os.chdir (directory)
1544     ly.system(cmd, be_verbose=global_options.verbose, 
1545               progress_p=1)
1546     os.chdir (current)
1547     
1548
1549 def process_snippets (cmd, snippets,
1550                       format, lily_output_dir):
1551     """Run cmd on all of the .ly files from snippets."""
1552
1553     if not snippets:
1554         return
1555     
1556     if format in (HTML, TEXINFO) and '--formats' not in cmd:
1557         cmd += ' --formats=png '
1558     elif format in (DOCBOOK) and '--formats' not in cmd:
1559         cmd += ' --formats=png,pdf '
1560
1561     checksum = snippet_list_checksum (snippets)
1562     contents = '\n'.join (['snippet-map-%d.ly' % checksum] 
1563                           + [snip.basename() + '.ly' for snip in snippets])
1564     name = os.path.join (lily_output_dir,
1565                          'snippet-names-%d.ly' % checksum)
1566     file (name, 'wb').write (contents)
1567
1568     system_in_directory (' '.join ([cmd, name]),
1569                          lily_output_dir)
1570             
1571         
1572 ###
1573 # Retrieve dimensions from LaTeX
1574 LATEX_INSPECTION_DOCUMENT = r'''
1575 \nonstopmode
1576 %(preamble)s
1577 \begin{document}
1578 \typeout{textwidth=\the\textwidth}
1579 \typeout{columnsep=\the\columnsep}
1580 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1581 \end{document}
1582 '''
1583
1584 # Do we need anything else besides `textwidth'?
1585 def get_latex_textwidth (source):
1586     m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1587     if m == None:
1588         warning (_ ("cannot find \\begin{document} in LaTeX document"))
1589         
1590         ## what's a sensible default?
1591         return 550.0
1592     
1593     preamble = source[:m.start (0)]
1594     latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1595     
1596     (handle, tmpfile) = tempfile.mkstemp('.tex')
1597     logfile = os.path.splitext (tmpfile)[0] + '.log'
1598     logfile = os.path.split (logfile)[1]
1599
1600     tmp_handle = os.fdopen (handle,'w')
1601     tmp_handle.write (latex_document)
1602     tmp_handle.close ()
1603     
1604     ly.system ('%s %s' % (global_options.latex_program, tmpfile),
1605                be_verbose=global_options.verbose)
1606     parameter_string = file (logfile).read()
1607     
1608     os.unlink (tmpfile)
1609     os.unlink (logfile)
1610
1611     columns = 0
1612     m = re.search ('columns=([0-9.]*)', parameter_string)
1613     if m:
1614         columns = int (m.group (1))
1615
1616     columnsep = 0
1617     m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1618     if m:
1619         columnsep = float (m.group (1))
1620
1621     textwidth = 0
1622     m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1623     if m:
1624         textwidth = float (m.group (1))
1625         if columns:
1626             textwidth = (textwidth - columnsep) / columns
1627
1628     return textwidth
1629
1630 def modify_preamble (chunk):
1631     str = chunk.replacement_text ()
1632     if (re.search (r"\\begin *{document}", str)
1633       and not re.search ("{graphic[sx]", str)):
1634         str = re.sub (r"\\begin{document}",
1635                r"\\usepackage{graphics}" + '\n'
1636                + r"\\begin{document}",
1637                str)
1638         chunk.override_text = str 
1639
1640
1641 format2ext = {
1642     HTML: '.html',
1643     # TEXINFO: '.texinfo',
1644     TEXINFO: '.texi',
1645     LATEX: '.tex',
1646     DOCBOOK: '.xml'
1647 }
1648
1649 class CompileError(Exception):
1650     pass
1651
1652 def snippet_list_checksum (snippets):
1653     return hash (' '.join([l.basename() for l in snippets]))
1654
1655 def write_file_map (lys, name):
1656     snippet_map = file (os.path.join (
1657         global_options.lily_output_dir,
1658         'snippet-map-%d.ly' % snippet_list_checksum (lys)), 'w')
1659
1660     snippet_map.write ("""
1661 #(define version-seen #t)
1662 #(define output-empty-score-list #f)
1663 #(ly:add-file-name-alist '(%s
1664     ))\n
1665 """ % '\n'.join(['("%s.ly" . "%s")\n' % (ly.basename (), name)
1666                  for ly in lys]))
1667
1668 def split_output_files(directory):
1669     """Returns directory entries in DIRECTORY/XX/ , where XX are hex digits.
1670
1671     Return value is a set of strings.
1672     """
1673     files = []
1674     for subdir in glob.glob (os.path.join (directory, '[a-f0-9][a-f0-9]')):
1675         base_subdir = os.path.split (subdir)[1]
1676         sub_files = [os.path.join (base_subdir, name)
1677                      for name in os.listdir (subdir)]
1678         files += sub_files
1679     return set (files)
1680
1681 def do_process_cmd (chunks, input_name, options):
1682     snippets = [c for c in chunks if isinstance (c, LilypondSnippet)]
1683
1684     output_files = split_output_files (options.lily_output_dir)
1685     outdated = [c for c in snippets if c.is_outdated (options.lily_output_dir, output_files)]
1686     
1687     write_file_map (outdated, input_name)    
1688     progress (_ ("Writing snippets..."))
1689     for snippet in outdated:
1690         snippet.write_ly()
1691     progress ('\n')
1692
1693     if outdated:
1694         progress (_ ("Processing..."))
1695         progress ('\n')
1696         process_snippets (options.process_cmd, outdated,
1697                           options.format, options.lily_output_dir)
1698
1699     else:
1700         progress (_ ("All snippets are up to date..."))
1701
1702     if options.lily_output_dir != options.output_dir:
1703         output_files = split_output_files (options.lily_output_dir)
1704         for snippet in snippets:
1705             snippet.link_all_output_files (options.lily_output_dir,
1706                                            output_files,
1707                                            options.output_dir)
1708
1709     progress ('\n')
1710
1711
1712 ###
1713 # Format guessing data
1714 ext2format = {
1715     '.html': HTML,
1716     '.itely': TEXINFO,
1717     '.latex': LATEX,
1718     '.lytex': LATEX,
1719     '.tely': TEXINFO,
1720     '.tex': LATEX,
1721     '.texi': TEXINFO,
1722     '.texinfo': TEXINFO,
1723     '.xml': HTML,
1724     '.lyxml': DOCBOOK
1725 }
1726
1727 def guess_format (input_filename):
1728     format = None
1729     e = os.path.splitext (input_filename)[1]
1730     if e in ext2format:
1731         # FIXME
1732         format = ext2format[e]
1733     else:
1734         error (_ ("cannot determine format for: %s"
1735                   % input_filename))
1736         exit (1)
1737     return format
1738
1739 def write_if_updated (file_name, lines):
1740     try:
1741         f = file (file_name)
1742         oldstr = f.read ()
1743         new_str = ''.join (lines)
1744         if oldstr == new_str:
1745             progress (_ ("%s is up to date.") % file_name)
1746             progress ('\n')
1747
1748             # this prevents make from always rerunning lilypond-book:
1749             # output file must be touched in order to be up to date
1750             os.utime (file_name, None)
1751             return
1752     except:
1753         pass
1754
1755     output_dir = os.path.dirname (file_name)
1756     if not os.path.exists (output_dir):
1757         os.makedirs (output_dir)
1758
1759     progress (_ ("Writing `%s'...") % file_name)
1760     file (file_name, 'w').writelines (lines)
1761     progress ('\n')
1762
1763
1764 def note_input_file (name, inputs=[]):
1765     ## hack: inputs is mutable!
1766     inputs.append (name)
1767     return inputs
1768
1769 def samefile (f1, f2):
1770     try:
1771         return os.path.samefile (f1, f2)
1772     except AttributeError:                # Windoze
1773         f1 = re.sub ("//*", "/", f1)
1774         f2 = re.sub ("//*", "/", f2)
1775         return f1 == f2
1776
1777 def do_file (input_filename, included=False):
1778     # Ugh.
1779     if not input_filename or input_filename == '-':
1780         in_handle = sys.stdin
1781         input_fullname = '<stdin>'
1782     else:
1783         if os.path.exists (input_filename):
1784             input_fullname = input_filename
1785         elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1786             input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1787         else:
1788             input_fullname = find_file (input_filename)
1789
1790         note_input_file (input_fullname)
1791         in_handle = file (input_fullname)
1792
1793     if input_filename == '-':
1794         input_base = 'stdin'
1795     elif included:
1796         input_base = os.path.splitext (input_filename)[0]
1797     else:
1798         input_base = os.path.basename (
1799             os.path.splitext (input_filename)[0])
1800
1801     # don't complain when global_options.output_dir is existing
1802     if not global_options.output_dir:
1803         global_options.output_dir = os.getcwd()
1804     else:
1805         global_options.output_dir = os.path.abspath(global_options.output_dir)
1806         
1807         if not os.path.isdir (global_options.output_dir):
1808             os.mkdir (global_options.output_dir, 0777)
1809         os.chdir (global_options.output_dir)
1810
1811     output_filename = os.path.join(global_options.output_dir,
1812                                    input_base + format2ext[global_options.format])
1813     if (os.path.exists (input_filename) 
1814         and os.path.exists (output_filename) 
1815         and samefile (output_filename, input_fullname)):
1816      error (
1817      _ ("Output would overwrite input file; use --output."))
1818      exit (2)
1819
1820     try:
1821         progress (_ ("Reading %s...") % input_fullname)
1822         source = in_handle.read ()
1823         progress ('\n')
1824
1825         set_default_options (source, default_ly_options, global_options.format)
1826
1827
1828         # FIXME: Containing blocks must be first, see
1829         #        find_toplevel_snippets.
1830         snippet_types = (
1831             'multiline_comment',
1832             'verbatim',
1833             'lilypond_block',
1834     #                'verb',
1835             'singleline_comment',
1836             'lilypond_file',
1837             'include',
1838             'lilypond',
1839         )
1840         progress (_ ("Dissecting..."))
1841         chunks = find_toplevel_snippets (source, global_options.format, snippet_types)
1842
1843         if global_options.format == LATEX:
1844             for c in chunks:
1845                 if (c.is_plain () and
1846                   re.search (r"\\begin *{document}", c.replacement_text())):
1847                     modify_preamble (c)
1848                     break
1849         progress ('\n')
1850
1851         if global_options.filter_cmd:
1852             write_if_updated (output_filename,
1853                      [c.filter_text () for c in chunks])
1854         elif global_options.process_cmd:
1855             do_process_cmd (chunks, input_fullname, global_options)
1856             progress (_ ("Compiling %s...") % output_filename)
1857             progress ('\n')
1858             write_if_updated (output_filename,
1859                      [s.replacement_text ()
1860                      for s in chunks])
1861         
1862         def process_include (snippet):
1863             os.chdir (original_dir)
1864             name = snippet.substring ('filename')
1865             progress (_ ("Processing include: %s") % name)
1866             progress ('\n')
1867             return do_file (name, included=True)
1868
1869         include_chunks = map (process_include,
1870                               filter (lambda x: isinstance (x, IncludeSnippet),
1871                                       chunks))
1872
1873         return chunks + reduce (lambda x, y: x + y, include_chunks, [])
1874         
1875     except CompileError:
1876         os.chdir (original_dir)
1877         progress (_ ("Removing `%s'") % output_filename)
1878         progress ('\n')
1879         raise CompileError
1880
1881 def do_options ():
1882     global global_options
1883
1884     opt_parser = get_option_parser()
1885     (global_options, args) = opt_parser.parse_args ()
1886     if global_options.format in ('texi-html', 'texi'):
1887         global_options.format = TEXINFO
1888
1889     global_options.include_path =  map (os.path.abspath, global_options.include_path)
1890     
1891     if global_options.warranty:
1892         warranty ()
1893         exit (0)
1894     if not args or len (args) > 1:
1895         opt_parser.print_help ()
1896         exit (2)
1897         
1898     return args
1899
1900 def main ():
1901     # FIXME: 85 lines of `main' macramee??
1902     files = do_options ()
1903
1904     basename = os.path.splitext (files[0])[0]
1905     basename = os.path.split (basename)[1]
1906     
1907     if not global_options.format:
1908         global_options.format = guess_format (files[0])
1909
1910     formats = 'ps'
1911     if global_options.format in (TEXINFO, HTML, DOCBOOK):
1912         formats += ',png'
1913
1914     if global_options.process_cmd == '':
1915         global_options.process_cmd = (lilypond_binary 
1916                                       + ' --formats=%s -dbackend=eps ' % formats)
1917
1918     if global_options.process_cmd:
1919         global_options.process_cmd += ' '.join ([(' -I %s' % ly.mkarg (p))
1920                                                  for p in global_options.include_path])
1921
1922     if global_options.format in (TEXINFO, LATEX):
1923         ## prevent PDF from being switched on by default.
1924         global_options.process_cmd += ' --formats=eps '
1925         if global_options.create_pdf:
1926             global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
1927     
1928     if global_options.verbose:
1929         global_options.process_cmd += " --verbose "
1930
1931     if global_options.padding_mm:
1932         global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
1933         
1934     global_options.process_cmd += " -dread-file-list -dno-strip-output-dir"
1935
1936     if global_options.lily_output_dir:
1937         global_options.lily_output_dir = os.path.abspath(global_options.lily_output_dir)
1938         if not os.path.isdir (global_options.lily_output_dir):
1939             os.makedirs (global_options.lily_output_dir)
1940     else:
1941         global_options.lily_output_dir = os.path.abspath(global_options.output_dir)
1942         
1943
1944     identify ()
1945     try:
1946         chunks = do_file (files[0])
1947     except CompileError:
1948         exit (1)
1949
1950     inputs = note_input_file ('')
1951     inputs.pop ()
1952
1953     base_file_name = os.path.splitext (os.path.basename (files[0]))[0]
1954     dep_file = os.path.join (global_options.output_dir, base_file_name + '.dep')
1955     final_output_file = os.path.join (global_options.output_dir,
1956                      base_file_name
1957                      + '.%s' % global_options.format)
1958     
1959     os.chdir (original_dir)
1960     file (dep_file, 'w').write ('%s: %s'
1961                                 % (final_output_file, ' '.join (inputs)))
1962
1963 if __name__ == '__main__':
1964     main ()