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