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