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