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