]> git.donarmstrong.com Git - lilypond.git/blob - scripts/lilypond-book.py
Merge branch 'lilypond/translation' of ssh://jomand@git.sv.gnu.org/srv/git/lilypond
[lilypond.git] / scripts / lilypond-book.py
1 #!@TARGET_PYTHON@
2
3 '''
4 Example usage:
5
6 test:
7   lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
8
9 convert-ly on book:
10   lilypond-book --filter="convert-ly --no-version --from=1.6.11 -" BOOK
11
12 classic lilypond-book:
13   lilypond-book --process="lilypond" BOOK.tely
14
15 TODO:
16
17   *  this script is too complex. Modularize.
18   
19   *  ly-options: intertext?
20   *  --line-width?
21   *  eps in latex / eps by lilypond -b ps?
22   *  check latex parameters, twocolumn, multicolumn?
23   *  use --png --ps --pdf for making images?
24
25   *  Converting from lilypond-book source, substitute:
26    @mbinclude foo.itely -> @include foo.itely
27    \mbinput -> \input
28
29 '''
30
31 import glob
32 import md5
33 import os
34 import re
35 import stat
36 import sys
37 import tempfile
38
39 """
40 @relocate-preamble@
41 """
42
43 import lilylib as ly
44 import fontextract
45 import langdefs
46 global _;_=ly._
47
48 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 ly_context_id_re = re.compile ('\\\\(?:new|context)\\s+(?:[a-zA-Z]*?(?:Staff\
844 (?:Group)?|Voice|FiguredBass|FretBoards|Names|Devnull))\\s+=\\s+"?([a-zA-Z]+)"?\\s+')
845
846 def ly_comment_gettext (t, m):
847     return m.group (1) + t (m.group (2))
848
849 def verb_ly_gettext (s):
850     if not document_language:
851         return s
852     try:
853         t = langdefs.translation[document_language]
854     except:
855         return s
856
857     s = ly_comment_re.sub (lambda m: ly_comment_gettext (t, m), s)
858     
859     for v in ly_var_def_re.findall (s):
860         s = re.sub (r"(?m)(^|[' \\#])%s([^a-zA-Z])" % v,
861                     "\\1" + t (v) + "\\2",
862                     s)
863     for id in ly_context_id_re.findall (s):
864         s = re.sub (r'(\s+|")%s(\s+|")' % id,
865                     "\\1" + t (id) + "\\2",
866                     s)
867     return s
868
869 texinfo_lang_re = re.compile ('(?m)^@documentlanguage (.*?)( |$)')
870 def set_default_options (source, default_ly_options, format):
871     global document_language
872     if LINE_WIDTH not in default_ly_options:
873         if format == LATEX:
874             textwidth = get_latex_textwidth (source)
875             default_ly_options[LINE_WIDTH] = '%.0f\\pt' % textwidth
876         elif format == TEXINFO:
877             m = texinfo_lang_re.search (source)
878             if m and not m.group (1).startswith ('en'):
879                 document_language = m.group (1)
880             else:
881                 document_language = ''
882             for regex in texinfo_line_widths:
883                 # FIXME: @layout is usually not in
884                 # chunk #0:
885                 #
886                 #  \input texinfo @c -*-texinfo-*-
887                 #
888                 # Bluntly search first K items of
889                 # source.
890                 # s = chunks[0].replacement_text ()
891                 if re.search (regex, source[:1024]):
892                     default_ly_options[LINE_WIDTH] = texinfo_line_widths[regex]
893                     break
894
895 class Chunk:
896     def replacement_text (self):
897         return ''
898
899     def filter_text (self):
900         return self.replacement_text ()
901
902     def is_plain (self):
903         return False
904     
905 class Substring (Chunk):
906     """A string that does not require extra memory."""
907     def __init__ (self, source, start, end, line_number):
908         self.source = source
909         self.start = start
910         self.end = end
911         self.line_number = line_number
912         self.override_text = None
913         
914     def is_plain (self):
915         return True
916
917     def replacement_text (self):
918         if self.override_text:
919             return self.override_text
920         else:
921             return self.source[self.start:self.end]
922
923 class Snippet (Chunk):
924     def __init__ (self, type, match, format, line_number):
925         self.type = type
926         self.match = match
927         self.checksum = 0
928         self.option_dict = {}
929         self.format = format
930         self.line_number = line_number
931
932     def replacement_text (self):
933         return self.match.group ('match')
934
935     def substring (self, s):
936         return self.match.group (s)
937
938     def __repr__ (self):
939         return `self.__class__` + ' type = ' + self.type
940
941 class IncludeSnippet (Snippet):
942     def processed_filename (self):
943         f = self.substring ('filename')
944         return os.path.splitext (f)[0] + format2ext[self.format]
945
946     def replacement_text (self):
947         s = self.match.group ('match')
948         f = self.substring ('filename')
949
950         return re.sub (f, self.processed_filename (), s)
951
952 class LilypondSnippet (Snippet):
953     def __init__ (self, type, match, format, line_number):
954         Snippet.__init__ (self, type, match, format, line_number)
955         os = match.group ('options')
956         self.do_options (os, self.type)
957
958     def verb_ly (self):
959         return verb_ly_gettext (self.substring ('code'))
960
961     def ly (self):
962         contents = self.substring ('code')
963         return ('\\sourcefileline %d\n%s'
964                 % (self.line_number - 1, contents))
965
966     def full_ly (self):
967         s = self.ly ()
968         if s:
969             return self.compose_ly (s)
970         return ''
971
972     def split_options (self, option_string):
973         if option_string:
974             if self.format == HTML:
975                 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',
976                                      option_string)
977                 options = [re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)', '\g<1>\g<3>', opt)
978                            for opt in options]
979                 return options
980             else:
981                 return re.split (format_res[self.format]['option_sep'],
982                                  option_string)
983         return []
984
985     def do_options (self, option_string, type):
986         self.option_dict = {}
987
988         options = self.split_options (option_string)
989
990         for option in options:
991             if '=' in option:
992                 (key, value) = re.split ('\s*=\s*', option)
993                 self.option_dict[key] = value
994             else:
995                 if option in no_options:
996                     if no_options[option] in self.option_dict:
997                         del self.option_dict[no_options[option]]
998                 else:
999                     self.option_dict[option] = None
1000
1001         has_line_width = self.option_dict.has_key (LINE_WIDTH)
1002         no_line_width_value = 0
1003
1004         # If LINE_WIDTH is used without parameter, set it to default.
1005         if has_line_width and self.option_dict[LINE_WIDTH] == None:
1006             no_line_width_value = 1
1007             del self.option_dict[LINE_WIDTH]
1008
1009         for k in default_ly_options:
1010             if k not in self.option_dict:
1011                 self.option_dict[k] = default_ly_options[k]
1012
1013         # RELATIVE does not work without FRAGMENT;
1014         # make RELATIVE imply FRAGMENT
1015         has_relative = self.option_dict.has_key (RELATIVE)
1016         if has_relative and not self.option_dict.has_key (FRAGMENT):
1017             self.option_dict[FRAGMENT] = None
1018
1019         if not has_line_width:
1020             if type == 'lilypond' or FRAGMENT in self.option_dict:
1021                 self.option_dict[RAGGED_RIGHT] = None
1022
1023             if type == 'lilypond':
1024                 if LINE_WIDTH in self.option_dict:
1025                     del self.option_dict[LINE_WIDTH]
1026             else:
1027                 if RAGGED_RIGHT in self.option_dict:
1028                     if LINE_WIDTH in self.option_dict:
1029                         del self.option_dict[LINE_WIDTH]
1030
1031             if QUOTE in self.option_dict or type == 'lilypond':
1032                 if LINE_WIDTH in self.option_dict:
1033                     del self.option_dict[LINE_WIDTH]
1034
1035         if not INDENT in self.option_dict:
1036             self.option_dict[INDENT] = '0\\mm'
1037
1038         # The QUOTE pattern from ly_options only emits the `line-width'
1039         # keyword.
1040         if has_line_width and QUOTE in self.option_dict:
1041             if no_line_width_value:
1042                 del self.option_dict[LINE_WIDTH]
1043             else:
1044                 del self.option_dict[QUOTE]
1045
1046     def compose_ly (self, code):
1047         if FRAGMENT in self.option_dict:
1048             body = FRAGMENT_LY
1049         else:
1050             body = FULL_LY
1051
1052         # Defaults.
1053         relative = 1
1054         override = {}
1055         # The original concept of the `exampleindent' option is broken.
1056         # It is not possible to get a sane value for @exampleindent at all
1057         # without processing the document itself.  Saying
1058         #
1059         #   @exampleindent 0
1060         #   @example
1061         #   ...
1062         #   @end example
1063         #   @exampleindent 5
1064         #
1065         # causes ugly results with the DVI backend of texinfo since the
1066         # default value for @exampleindent isn't 5em but 0.4in (or a smaller
1067         # value).  Executing the above code changes the environment
1068         # indentation to an unknown value because we don't know the amount
1069         # of 1em in advance since it is font-dependent.  Modifying
1070         # @exampleindent in the middle of a document is simply not
1071         # supported within texinfo.
1072         #
1073         # As a consequence, the only function of @exampleindent is now to
1074         # specify the amount of indentation for the `quote' option.
1075         #
1076         # To set @exampleindent locally to zero, we use the @format
1077         # environment for non-quoted snippets.
1078         override[EXAMPLEINDENT] = r'0.4\in'
1079         override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1080         override.update (default_ly_options)
1081
1082         option_list = []
1083         for (key, value) in self.option_dict.items ():
1084             if value == None:
1085                 option_list.append (key)
1086             else:
1087                 option_list.append (key + '=' + value)
1088         option_string = ','.join (option_list)
1089
1090         compose_dict = {}
1091         compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1092         for a in compose_types:
1093             compose_dict[a] = []
1094
1095         for (key, value) in self.option_dict.items ():
1096             (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
1097             if c_key:
1098                 if c_value:
1099                     warning (
1100                         _ ("deprecated ly-option used: %s=%s") % (key, value))
1101                     warning (
1102                         _ ("compatibility mode translation: %s=%s") % (c_key, c_value))
1103                 else:
1104                     warning (
1105                         _ ("deprecated ly-option used: %s") % key)
1106                     warning (
1107                         _ ("compatibility mode translation: %s") % c_key)
1108
1109                 (key, value) = (c_key, c_value)
1110
1111             if value:
1112                 override[key] = value
1113             else:
1114                 if not override.has_key (key):
1115                     override[key] = None
1116
1117             found = 0
1118             for type in compose_types:
1119                 if ly_options[type].has_key (key):
1120                     compose_dict[type].append (ly_options[type][key])
1121                     found = 1
1122                     break
1123
1124             if not found and key not in simple_options:
1125                 warning (_ ("ignoring unknown ly option: %s") % key)
1126
1127         # URGS
1128         if RELATIVE in override and override[RELATIVE]:
1129             relative = int (override[RELATIVE])
1130
1131         relative_quotes = ''
1132
1133         # 1 = central C
1134         if relative < 0:
1135             relative_quotes += ',' * (- relative)
1136         elif relative > 0:
1137             relative_quotes += "'" * relative
1138
1139         paper_string = '\n  '.join (compose_dict[PAPER]) % override
1140         layout_string = '\n  '.join (compose_dict[LAYOUT]) % override
1141         notes_string = '\n  '.join (compose_dict[NOTES]) % vars ()
1142         preamble_string = '\n  '.join (compose_dict[PREAMBLE]) % override
1143         padding_mm = global_options.padding_mm
1144         font_dump_setting = ''
1145         if FONTLOAD in self.option_dict:
1146             font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1147
1148         d = globals().copy()
1149         d.update (locals())
1150         return (PREAMBLE_LY + body) % d
1151
1152     def get_checksum (self):
1153         if not self.checksum:
1154             hash = md5.md5 (self.relevant_contents (self.full_ly ()))
1155
1156             ## let's not create too long names.
1157             self.checksum = hash.hexdigest ()[:10]
1158             
1159         return self.checksum
1160
1161     def basename (self):
1162         cs = self.get_checksum ()
1163         name = '%s/lily-%s' % (cs[:2], cs[2:10])
1164         return name
1165
1166     def write_ly (self):
1167         base = self.basename ()
1168         path = os.path.join (global_options.lily_output_dir, base)
1169         directory = os.path.split(path)[0]
1170         if not os.path.isdir (directory):
1171             os.makedirs (directory)
1172         out = file (path + '.ly', 'w')
1173         out.write (self.full_ly ())
1174         file (path + '.txt', 'w').write ('image of music')
1175
1176     def relevant_contents (self, ly):
1177         return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
1178
1179     def link_all_output_files (self, output_dir, output_dir_files, destination):
1180         existing, missing = self.all_output_files (output_dir, output_dir_files)
1181         if missing:
1182             print '\nMissing', missing
1183             raise CompileError(self.basename())
1184         for name in existing:
1185             try:
1186                 os.unlink (os.path.join (destination, name))
1187             except OSError:
1188                 pass
1189
1190             src = os.path.join (output_dir, name)
1191             dst = os.path.join (destination, name)
1192             dst_path = os.path.split(dst)[0]
1193             if not os.path.isdir (dst_path):
1194                 os.makedirs (dst_path)
1195             os.link (src, dst)
1196
1197         
1198     def all_output_files (self, output_dir, output_dir_files):
1199         """Return all files generated in lily_output_dir, a set.
1200
1201         output_dir_files is the list of files in the output directory.
1202         """
1203         result = set ()
1204         missing = set ()
1205         base = self.basename()
1206         full = os.path.join (output_dir, base)
1207         def consider_file (name):
1208             if name in output_dir_files:
1209                 result.add (name)
1210              
1211         def require_file (name):
1212             if name in output_dir_files:
1213                 result.add (name)
1214             else:
1215                 missing.add (name)
1216
1217         # UGH - junk global_options
1218         skip_lily = global_options.skip_lilypond_run
1219         for required in [base + '.ly',
1220                          base + '.txt']:
1221             require_file (required)
1222         if not skip_lily:
1223             require_file (base + '-systems.count')
1224
1225         if 'ddump-profile' in global_options.process_cmd:
1226             require_file (base + '.profile')
1227         if 'dseparate-log-file' in global_options.process_cmd:
1228             require_file (base + '.log')
1229
1230         map (consider_file, [base + '.tex',
1231                              base + '.eps',
1232                              base + '.texidoc',
1233                              base + '.doctitle',
1234                              base + '-systems.texi',
1235                              base + '-systems.tex',
1236                              base + '-systems.pdftexi'])
1237         if document_language:
1238             map (consider_file,
1239                  [base + '.texidoc' + document_language,
1240                   base + '.doctitle' + document_language])
1241
1242         # UGH - junk global_options
1243         if (base + '.eps' in result and self.format in (HTML, TEXINFO)
1244             and not global_options.skip_png_check):
1245             page_count = ps_page_count (full + '.eps')
1246             if page_count <= 1:
1247                 require_file (base + '.png')
1248             else:
1249                 for page in range (1, page_count + 1):
1250                     require_file (base + '-page%d.png' % page)
1251
1252         system_count = 0
1253         if not skip_lily and not missing:
1254             system_count = int(file (full + '-systems.count').read())
1255
1256         for number in range(1, system_count + 1):
1257             systemfile = '%s-%d' % (base, number)
1258             require_file (systemfile + '.eps')
1259             consider_file (systemfile + '.pdf')
1260
1261             # We can't require signatures, since books and toplevel
1262             # markups do not output a signature.
1263             if 'ddump-signature' in global_options.process_cmd:
1264                 consider_file (systemfile + '.signature')
1265              
1266        
1267         return (result, missing)
1268     
1269     def is_outdated (self, output_dir, current_files):
1270         found, missing = self.all_output_files (output_dir, current_files)
1271         return missing
1272     
1273     def filter_text (self):
1274         """Run snippet bodies through a command (say: convert-ly).
1275
1276         This functionality is rarely used, and this code must have bitrot.
1277         """
1278         code = self.substring ('code')
1279         s = filter_pipe (code, global_options.filter_cmd)
1280         d = {
1281             'code': s,
1282             'options': self.match.group ('options')
1283         }
1284         # TODO
1285         return output[self.format][FILTER] % d
1286
1287     def replacement_text (self):
1288         func = LilypondSnippet.__dict__['output_' + self.format]
1289         return func (self)
1290
1291     def get_images (self):
1292         base = self.basename ()
1293
1294         single = '%(base)s.png' % vars ()
1295         multiple = '%(base)s-page1.png' % vars ()
1296         images = (single,)
1297         if (os.path.exists (multiple) 
1298             and (not os.path.exists (single)
1299                  or (os.stat (multiple)[stat.ST_MTIME]
1300                      > os.stat (single)[stat.ST_MTIME]))):
1301             count = ps_page_count ('%(base)s.eps' % vars ())
1302             images = ['%s-page%d.png' % (base, page) for page in range (1, count+1)]
1303             images = tuple (images)
1304             
1305         return images
1306
1307     def output_docbook (self):
1308         str = ''
1309         base = self.basename ()
1310         for image in self.get_images ():
1311             (base, ext) = os.path.splitext (image)
1312             str += output[DOCBOOK][OUTPUT] % vars ()
1313             str += self.output_print_filename (DOCBOOK)
1314             if (self.substring('inline') == 'inline'): 
1315                 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1316             else:
1317                 str = '<mediaobject>' + str + '</mediaobject>'
1318         if VERBATIM in self.option_dict:
1319                 verb = verbatim_html (self.verb_ly ())
1320                 str = output[DOCBOOK][VERBATIM] % vars () + str
1321         return str
1322         
1323     def output_html (self):
1324         str = ''
1325         base = self.basename ()
1326         if self.format == HTML:
1327             str += self.output_print_filename (HTML)
1328             if VERBATIM in self.option_dict:
1329                 verb = verbatim_html (self.verb_ly ())
1330                 str += output[HTML][VERBATIM] % vars ()
1331             if QUOTE in self.option_dict:
1332                 str = output[HTML][QUOTE] % vars ()
1333
1334         str += output[HTML][BEFORE] % vars ()
1335         for image in self.get_images ():
1336             (base, ext) = os.path.splitext (image)
1337             alt = self.option_dict[ALT]
1338             str += output[HTML][OUTPUT] % vars ()
1339         str += output[HTML][AFTER] % vars ()
1340         return str
1341
1342     def output_info (self):
1343         str = ''
1344         for image in self.get_images ():
1345             (base, ext) = os.path.splitext (image)
1346
1347             # URG, makeinfo implicitly prepends dot to extension.
1348             # Specifying no extension is most robust.
1349             ext = ''
1350             alt = self.option_dict[ALT]
1351             info_image_path = os.path.join (global_options.info_images_dir, base)
1352             str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1353
1354         base = self.basename ()
1355         str += output[self.format][OUTPUT] % vars ()
1356         return str
1357
1358     def output_latex (self):
1359         str = ''
1360         base = self.basename ()
1361         if self.format == LATEX:
1362             str += self.output_print_filename (LATEX)
1363             if VERBATIM in self.option_dict:
1364                 verb = self.verb_ly ()
1365                 str += (output[LATEX][VERBATIM] % vars ())
1366
1367         str += (output[LATEX][OUTPUT] % vars ())
1368
1369         ## todo: maintain breaks
1370         if 0:
1371             breaks = self.ly ().count ("\n")
1372             str += "".ljust (breaks, "\n").replace ("\n","%\n")
1373         
1374         if QUOTE in self.option_dict:
1375             str = output[LATEX][QUOTE] % vars ()
1376         return str
1377
1378     def output_print_filename (self, format):
1379         str = ''
1380         if PRINTFILENAME in self.option_dict:
1381             base = self.basename ()
1382             filename = os.path.basename (self.substring ('filename'))
1383             str = output[format][PRINTFILENAME] % vars ()
1384
1385         return str
1386
1387     def output_texinfo (self):
1388         str = self.output_print_filename (TEXINFO)
1389         base = self.basename ()
1390         if DOCTITLE in self.option_dict:
1391             doctitle = base + '.doctitle'
1392             translated_doctitle = doctitle + document_language
1393             if os.path.exists (translated_doctitle):
1394                 str += '@lydoctitle %s\n' % open (translated_doctitle).read ()
1395             elif os.path.exists (doctitle):
1396                 str += '@lydoctitle %s\n' % open (doctitle).read ()
1397         if TEXIDOC in self.option_dict:
1398             texidoc = base + '.texidoc'
1399             translated_texidoc = texidoc + document_language
1400             if os.path.exists (translated_texidoc):
1401                 str += '@include %(translated_texidoc)s\n\n' % vars ()
1402             elif os.path.exists (texidoc):
1403                 str += '@include %(texidoc)s\n\n' % vars ()
1404
1405         substr = ''
1406         if VERBATIM in self.option_dict:
1407             version = ''
1408             if ADDVERSION in self.option_dict:
1409                 version = output[TEXINFO][ADDVERSION]
1410             verb = self.verb_ly ()
1411             substr = output[TEXINFO][VERBATIM] % vars ()
1412         substr += self.output_info ()
1413         if LILYQUOTE in self.option_dict:
1414             substr = output[TEXINFO][QUOTE] % {'str':substr}
1415         str += substr
1416
1417 #                str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1418 #                str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1419 #                str += ('@html\n' + self.output_html () + '\n@end html\n')
1420
1421         if QUOTE in self.option_dict:
1422             str = output[TEXINFO][QUOTE] % vars ()
1423
1424         # need par after image
1425         str += '\n'
1426
1427         return str
1428
1429 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1430 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1431
1432 class LilypondFileSnippet (LilypondSnippet):
1433     def __init__ (self, type, match, format, line_number):
1434         LilypondSnippet.__init__ (self, type, match, format, line_number)
1435         self.contents = file (find_file (self.substring ('filename'))).read ()
1436
1437     def verb_ly (self):
1438         s = self.contents
1439         s = re_begin_verbatim.split (s)[-1]
1440         s = re_end_verbatim.split (s)[0]
1441         return verb_ly_gettext (s)
1442
1443     def ly (self):
1444         name = self.substring ('filename')
1445         return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1446                 % (name, self.contents))
1447
1448
1449 snippet_type_to_class = {
1450     'lilypond_file': LilypondFileSnippet,
1451     'lilypond_block': LilypondSnippet,
1452     'lilypond': LilypondSnippet,
1453     'include': IncludeSnippet,
1454 }
1455
1456 def find_linestarts (s):
1457     nls = [0]
1458     start = 0
1459     end = len (s)
1460     while 1:
1461         i = s.find ('\n', start)
1462         if i < 0:
1463             break
1464
1465         i = i + 1
1466         nls.append (i)
1467         start = i
1468
1469     nls.append (len (s))
1470     return nls
1471
1472 def find_toplevel_snippets (input_string, format, types):
1473     res = {}
1474     for t in types:
1475         res[t] = re.compile (snippet_res[format][t])
1476
1477     snippets = []
1478     index = 0
1479     found = dict ([(t, None) for t in types])
1480
1481     line_starts = find_linestarts (input_string)
1482     line_start_idx = 0
1483     # We want to search for multiple regexes, without searching
1484     # the string multiple times for one regex.
1485     # Hence, we use earlier results to limit the string portion
1486     # where we search.
1487     # Since every part of the string is traversed at most once for
1488     # every type of snippet, this is linear.
1489
1490     while 1:
1491         first = None
1492         endex = 1 << 30
1493         for type in types:
1494             if not found[type] or found[type][0] < index:
1495                 found[type] = None
1496                 
1497                 m = res[type].search (input_string[index:endex])
1498                 if not m:
1499                     continue
1500
1501                 klass = Snippet
1502                 if type in snippet_type_to_class:
1503                     klass = snippet_type_to_class[type]
1504
1505                 start = index + m.start ('match')
1506                 line_number = line_start_idx
1507                 while (line_starts[line_number] < start):
1508                     line_number += 1
1509
1510                 line_number += 1
1511                 snip = klass (type, m, format, line_number)
1512
1513                 found[type] = (start, snip)
1514
1515             if (found[type] 
1516                 and (not first 
1517                      or found[type][0] < found[first][0])):
1518                 first = type
1519
1520                 # FIXME.
1521
1522                 # Limiting the search space is a cute
1523                 # idea, but this *requires* to search
1524                 # for possible containing blocks
1525                 # first, at least as long as we do not
1526                 # search for the start of blocks, but
1527                 # always/directly for the entire
1528                 # @block ... @end block.
1529
1530                 endex = found[first][0]
1531
1532         if not first:
1533             snippets.append (Substring (input_string, index, len (input_string), line_start_idx))
1534             break
1535
1536         while (start > line_starts[line_start_idx+1]):
1537             line_start_idx += 1
1538
1539         (start, snip) = found[first]
1540         snippets.append (Substring (input_string, index, start, line_start_idx + 1))
1541         snippets.append (snip)
1542         found[first] = None
1543         index = start + len (snip.match.group ('match'))
1544
1545     return snippets
1546
1547 def filter_pipe (input, cmd):
1548     """Pass input through cmd, and return the result."""
1549     
1550     if global_options.verbose:
1551         progress (_ ("Opening filter `%s'") % cmd)
1552
1553     (stdin, stdout, stderr) = os.popen3 (cmd)
1554     stdin.write (input)
1555     status = stdin.close ()
1556
1557     if not status:
1558         status = 0
1559         output = stdout.read ()
1560         status = stdout.close ()
1561         error = stderr.read ()
1562
1563     if not status:
1564         status = 0
1565     signal = 0x0f & status
1566     if status or (not output and error):
1567         exit_status = status >> 8
1568         error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1569         error (_ ("The error log is as follows:"))
1570         ly.stderr_write (error)
1571         ly.stderr_write (stderr.read ())
1572         exit (status)
1573
1574     if global_options.verbose:
1575         progress ('\n')
1576
1577     return output
1578
1579 def system_in_directory (cmd, directory):
1580     """Execute a command in a different directory.
1581
1582     Because of win32 compatibility, we can't simply use subprocess.
1583     """
1584     
1585     current = os.getcwd()
1586     os.chdir (directory)
1587     ly.system(cmd, be_verbose=global_options.verbose, 
1588               progress_p=1)
1589     os.chdir (current)
1590     
1591
1592 def process_snippets (cmd, snippets,
1593                       format, lily_output_dir):
1594     """Run cmd on all of the .ly files from snippets."""
1595
1596     if not snippets:
1597         return
1598     
1599     if format in (HTML, TEXINFO) and '--formats' not in cmd:
1600         cmd += ' --formats=png '
1601     elif format in (DOCBOOK) and '--formats' not in cmd:
1602         cmd += ' --formats=png,pdf '
1603
1604     checksum = snippet_list_checksum (snippets)
1605     contents = '\n'.join (['snippet-map-%d.ly' % checksum] 
1606                           + [snip.basename() + '.ly' for snip in snippets])
1607     name = os.path.join (lily_output_dir,
1608                          'snippet-names-%d.ly' % checksum)
1609     file (name, 'wb').write (contents)
1610
1611     system_in_directory (' '.join ([cmd, ly.mkarg (name)]),
1612                          lily_output_dir)
1613             
1614         
1615 ###
1616 # Retrieve dimensions from LaTeX
1617 LATEX_INSPECTION_DOCUMENT = r'''
1618 \nonstopmode
1619 %(preamble)s
1620 \begin{document}
1621 \typeout{textwidth=\the\textwidth}
1622 \typeout{columnsep=\the\columnsep}
1623 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1624 \end{document}
1625 '''
1626
1627 # Do we need anything else besides `textwidth'?
1628 def get_latex_textwidth (source):
1629     m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1630     if m == None:
1631         warning (_ ("cannot find \\begin{document} in LaTeX document"))
1632         
1633         ## what's a sensible default?
1634         return 550.0
1635     
1636     preamble = source[:m.start (0)]
1637     latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1638     
1639     (handle, tmpfile) = tempfile.mkstemp('.tex')
1640     logfile = os.path.splitext (tmpfile)[0] + '.log'
1641     logfile = os.path.split (logfile)[1]
1642
1643     tmp_handle = os.fdopen (handle,'w')
1644     tmp_handle.write (latex_document)
1645     tmp_handle.close ()
1646     
1647     ly.system ('%s %s' % (global_options.latex_program, tmpfile),
1648                be_verbose=global_options.verbose)
1649     parameter_string = file (logfile).read()
1650     
1651     os.unlink (tmpfile)
1652     os.unlink (logfile)
1653
1654     columns = 0
1655     m = re.search ('columns=([0-9.]*)', parameter_string)
1656     if m:
1657         columns = int (m.group (1))
1658
1659     columnsep = 0
1660     m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1661     if m:
1662         columnsep = float (m.group (1))
1663
1664     textwidth = 0
1665     m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1666     if m:
1667         textwidth = float (m.group (1))
1668         if columns:
1669             textwidth = (textwidth - columnsep) / columns
1670
1671     return textwidth
1672
1673 def modify_preamble (chunk):
1674     str = chunk.replacement_text ()
1675     if (re.search (r"\\begin *{document}", str)
1676       and not re.search ("{graphic[sx]", str)):
1677         str = re.sub (r"\\begin{document}",
1678                r"\\usepackage{graphics}" + '\n'
1679                + r"\\begin{document}",
1680                str)
1681         chunk.override_text = str 
1682
1683
1684 format2ext = {
1685     HTML: '.html',
1686     # TEXINFO: '.texinfo',
1687     TEXINFO: '.texi',
1688     LATEX: '.tex',
1689     DOCBOOK: '.xml'
1690 }
1691
1692 class CompileError(Exception):
1693     pass
1694
1695 def snippet_list_checksum (snippets):
1696     return hash (' '.join([l.basename() for l in snippets]))
1697
1698 def write_file_map (lys, name):
1699     snippet_map = file (os.path.join (
1700         global_options.lily_output_dir,
1701         'snippet-map-%d.ly' % snippet_list_checksum (lys)), 'w')
1702
1703     snippet_map.write ("""
1704 #(define version-seen #t)
1705 #(define output-empty-score-list #f)
1706 #(ly:add-file-name-alist '(%s
1707     ))\n
1708 """ % '\n'.join(['("%s.ly" . "%s")\n' % (ly.basename (), name)
1709                  for ly in lys]))
1710
1711 def split_output_files(directory):
1712     """Returns directory entries in DIRECTORY/XX/ , where XX are hex digits.
1713
1714     Return value is a set of strings.
1715     """
1716     files = []
1717     for subdir in glob.glob (os.path.join (directory, '[a-f0-9][a-f0-9]')):
1718         base_subdir = os.path.split (subdir)[1]
1719         sub_files = [os.path.join (base_subdir, name)
1720                      for name in os.listdir (subdir)]
1721         files += sub_files
1722     return set (files)
1723
1724 def do_process_cmd (chunks, input_name, options):
1725     snippets = [c for c in chunks if isinstance (c, LilypondSnippet)]
1726
1727     output_files = split_output_files (options.lily_output_dir)
1728     outdated = [c for c in snippets if c.is_outdated (options.lily_output_dir, output_files)]
1729     
1730     write_file_map (outdated, input_name)    
1731     progress (_ ("Writing snippets..."))
1732     for snippet in outdated:
1733         snippet.write_ly()
1734     progress ('\n')
1735
1736     if outdated:
1737         progress (_ ("Processing..."))
1738         progress ('\n')
1739         process_snippets (options.process_cmd, outdated,
1740                           options.format, options.lily_output_dir)
1741
1742     else:
1743         progress (_ ("All snippets are up to date..."))
1744
1745     if options.lily_output_dir != options.output_dir:
1746         output_files = split_output_files (options.lily_output_dir)
1747         for snippet in snippets:
1748             snippet.link_all_output_files (options.lily_output_dir,
1749                                            output_files,
1750                                            options.output_dir)
1751
1752     progress ('\n')
1753
1754
1755 ###
1756 # Format guessing data
1757 ext2format = {
1758     '.html': HTML,
1759     '.itely': TEXINFO,
1760     '.latex': LATEX,
1761     '.lytex': LATEX,
1762     '.tely': TEXINFO,
1763     '.tex': LATEX,
1764     '.texi': TEXINFO,
1765     '.texinfo': TEXINFO,
1766     '.xml': HTML,
1767     '.lyxml': DOCBOOK
1768 }
1769
1770 def guess_format (input_filename):
1771     format = None
1772     e = os.path.splitext (input_filename)[1]
1773     if e in ext2format:
1774         # FIXME
1775         format = ext2format[e]
1776     else:
1777         error (_ ("cannot determine format for: %s"
1778                   % input_filename))
1779         exit (1)
1780     return format
1781
1782 def write_if_updated (file_name, lines):
1783     try:
1784         f = file (file_name)
1785         oldstr = f.read ()
1786         new_str = ''.join (lines)
1787         if oldstr == new_str:
1788             progress (_ ("%s is up to date.") % file_name)
1789             progress ('\n')
1790
1791             # this prevents make from always rerunning lilypond-book:
1792             # output file must be touched in order to be up to date
1793             os.utime (file_name, None)
1794             return
1795     except:
1796         pass
1797
1798     output_dir = os.path.dirname (file_name)
1799     if not os.path.exists (output_dir):
1800         os.makedirs (output_dir)
1801
1802     progress (_ ("Writing `%s'...") % file_name)
1803     file (file_name, 'w').writelines (lines)
1804     progress ('\n')
1805
1806
1807 def note_input_file (name, inputs=[]):
1808     ## hack: inputs is mutable!
1809     inputs.append (name)
1810     return inputs
1811
1812 def samefile (f1, f2):
1813     try:
1814         return os.path.samefile (f1, f2)
1815     except AttributeError:                # Windoze
1816         f1 = re.sub ("//*", "/", f1)
1817         f2 = re.sub ("//*", "/", f2)
1818         return f1 == f2
1819
1820 def do_file (input_filename, included=False):
1821     # Ugh.
1822     if not input_filename or input_filename == '-':
1823         in_handle = sys.stdin
1824         input_fullname = '<stdin>'
1825     else:
1826         if os.path.exists (input_filename):
1827             input_fullname = input_filename
1828         elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1829             input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1830         else:
1831             input_fullname = find_file (input_filename)
1832
1833         note_input_file (input_fullname)
1834         in_handle = file (input_fullname)
1835
1836     if input_filename == '-':
1837         input_base = 'stdin'
1838     elif included:
1839         input_base = os.path.splitext (input_filename)[0]
1840     else:
1841         input_base = os.path.basename (
1842             os.path.splitext (input_filename)[0])
1843
1844     # don't complain when global_options.output_dir is existing
1845     if not global_options.output_dir:
1846         global_options.output_dir = os.getcwd()
1847     else:
1848         global_options.output_dir = os.path.abspath(global_options.output_dir)
1849         
1850         if not os.path.isdir (global_options.output_dir):
1851             os.mkdir (global_options.output_dir, 0777)
1852         os.chdir (global_options.output_dir)
1853
1854     output_filename = os.path.join(global_options.output_dir,
1855                                    input_base + format2ext[global_options.format])
1856     if (os.path.exists (input_filename) 
1857         and os.path.exists (output_filename) 
1858         and samefile (output_filename, input_fullname)):
1859      error (
1860      _ ("Output would overwrite input file; use --output."))
1861      exit (2)
1862
1863     try:
1864         progress (_ ("Reading %s...") % input_fullname)
1865         source = in_handle.read ()
1866         progress ('\n')
1867
1868         set_default_options (source, default_ly_options, global_options.format)
1869
1870
1871         # FIXME: Containing blocks must be first, see
1872         #        find_toplevel_snippets.
1873         snippet_types = (
1874             'multiline_comment',
1875             'verbatim',
1876             'lilypond_block',
1877     #                'verb',
1878             'singleline_comment',
1879             'lilypond_file',
1880             'include',
1881             'lilypond',
1882         )
1883         progress (_ ("Dissecting..."))
1884         chunks = find_toplevel_snippets (source, global_options.format, snippet_types)
1885
1886         if global_options.format == LATEX:
1887             for c in chunks:
1888                 if (c.is_plain () and
1889                   re.search (r"\\begin *{document}", c.replacement_text())):
1890                     modify_preamble (c)
1891                     break
1892         progress ('\n')
1893
1894         if global_options.filter_cmd:
1895             write_if_updated (output_filename,
1896                      [c.filter_text () for c in chunks])
1897         elif global_options.process_cmd:
1898             do_process_cmd (chunks, input_fullname, global_options)
1899             progress (_ ("Compiling %s...") % output_filename)
1900             progress ('\n')
1901             write_if_updated (output_filename,
1902                      [s.replacement_text ()
1903                      for s in chunks])
1904         
1905         def process_include (snippet):
1906             os.chdir (original_dir)
1907             name = snippet.substring ('filename')
1908             progress (_ ("Processing include: %s") % name)
1909             progress ('\n')
1910             return do_file (name, included=True)
1911
1912         include_chunks = map (process_include,
1913                               filter (lambda x: isinstance (x, IncludeSnippet),
1914                                       chunks))
1915
1916         return chunks + reduce (lambda x, y: x + y, include_chunks, [])
1917         
1918     except CompileError:
1919         os.chdir (original_dir)
1920         progress (_ ("Removing `%s'") % output_filename)
1921         progress ('\n')
1922         raise CompileError
1923
1924 def do_options ():
1925     global global_options
1926
1927     opt_parser = get_option_parser()
1928     (global_options, args) = opt_parser.parse_args ()
1929     if global_options.format in ('texi-html', 'texi'):
1930         global_options.format = TEXINFO
1931
1932     global_options.include_path =  map (os.path.abspath, global_options.include_path)
1933     
1934     if global_options.warranty:
1935         warranty ()
1936         exit (0)
1937     if not args or len (args) > 1:
1938         opt_parser.print_help ()
1939         exit (2)
1940         
1941     return args
1942
1943 def main ():
1944     # FIXME: 85 lines of `main' macramee??
1945     files = do_options ()
1946
1947     basename = os.path.splitext (files[0])[0]
1948     basename = os.path.split (basename)[1]
1949     
1950     if not global_options.format:
1951         global_options.format = guess_format (files[0])
1952
1953     formats = 'ps'
1954     if global_options.format in (TEXINFO, HTML, DOCBOOK):
1955         formats += ',png'
1956
1957     if global_options.process_cmd == '':
1958         global_options.process_cmd = (lilypond_binary 
1959                                       + ' --formats=%s -dbackend=eps ' % formats)
1960
1961     if global_options.process_cmd:
1962         includes = global_options.include_path
1963         if global_options.lily_output_dir:
1964             # This must be first, so lilypond prefers to read .ly
1965             # files in the other lybookdb dir.
1966             includes = [os.path.abspath(global_options.lily_output_dir)] + includes
1967         global_options.process_cmd += ' '.join ([' -I %s' % ly.mkarg (p)
1968                                                  for p in includes])
1969
1970     if global_options.format in (TEXINFO, LATEX):
1971         ## prevent PDF from being switched on by default.
1972         global_options.process_cmd += ' --formats=eps '
1973         if global_options.create_pdf:
1974             global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
1975     
1976     if global_options.verbose:
1977         global_options.process_cmd += " --verbose "
1978
1979     if global_options.padding_mm:
1980         global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
1981         
1982     global_options.process_cmd += " -dread-file-list -dno-strip-output-dir"
1983
1984     if global_options.lily_output_dir:
1985         global_options.lily_output_dir = os.path.abspath(global_options.lily_output_dir)
1986         if not os.path.isdir (global_options.lily_output_dir):
1987             os.makedirs (global_options.lily_output_dir)
1988     else:
1989         global_options.lily_output_dir = os.path.abspath(global_options.output_dir)
1990         
1991
1992     identify ()
1993     try:
1994         chunks = do_file (files[0])
1995     except CompileError:
1996         exit (1)
1997
1998     inputs = note_input_file ('')
1999     inputs.pop ()
2000
2001     base_file_name = os.path.splitext (os.path.basename (files[0]))[0]
2002     dep_file = os.path.join (global_options.output_dir, base_file_name + '.dep')
2003     final_output_file = os.path.join (global_options.output_dir,
2004                      base_file_name
2005                      + '.%s' % global_options.format)
2006     
2007     os.chdir (original_dir)
2008     file (dep_file, 'w').write ('%s: %s'
2009                                 % (final_output_file, ' '.join (inputs)))
2010
2011 if __name__ == '__main__':
2012     main ()