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