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