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