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