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