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