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