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