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