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