2 # vim: set noexpandtab:
4 # * junk --outdir for--output
5 # * Figure out clean set of options.
7 # * texinfo: add support for @pagesize
9 # todo: dimension handling (all the x2y) is clumsy. (tca: Thats
10 # because the values are taken directly from texinfo.tex,
11 # geometry.sty and article.cls. Give me a hint, and I'll
15 # TODO: magnification support should also work for texinfo -> html: eg. add as option to dvips.
20 # This is a slightly hairy program. The general approach is as follows
21 # The input string is chopped up in chunks, i.e. , a list of tuples
23 # with the format (TAG_STR, MAIN_STR, OPTIONS, TODO, BASE)
25 # This list is build step by step: first ignore and verbatim commands are handled,
26 # delivering a list of chunks.
28 # then all chunks containing lilypnod commands are chopped up
30 # when all chunks have their final form, all bodies from lilypond blocks are
31 # extracted, and if applicable, written do disk and run through lilypond.
35 # This is was the idea for handling of comments:
38 # Multiline comments, @ignore .. @end ignore is scanned for
39 # in read_doc_file, and the chunks are marked as 'ignore', so
40 # lilypond-book will not touch them any more. The content of the
41 # chunks are written to the output file. Also 'include' and 'input'
42 # regex has to check if they are commented out.
45 # Then it is scanned for 'lilypond', 'lilypond-file' and 'lilypond-block'.
46 # These three regex's has to check if they are on a commented line,
47 # % for latex, @c for texinfo.
49 # Then lines that are commented out with % (latex) and @c (Texinfo)
50 # are put into chunks marked 'ignore'. This cannot be done before
51 # searching for the lilypond-blocks because % is also the comment character
54 # The the rest of the rexeces are searched for. They don't have to test
55 # if they are on a commented out line.
62 ################################################################
63 # Users of python modules should include this snippet
64 # and customize variables below.
66 # We'll suffer this path init stuff as long as we don't install our
67 # python packages in <prefix>/lib/pythonx.y (and don't kludge around
68 # it as we do with teTeX on Red Hat Linux: set some environment var
69 # (PYTHONPATH) in profile)
71 # If set, LILYPONDPREFIX must take prevalence
72 # if datadir is not set, we're doing a build and LILYPONDPREFIX
73 import getopt, os, sys
74 datadir = '@local_lilypond_datadir@'
75 if not os.path.isdir (datadir):
76 datadir = '@lilypond_datadir@'
77 if os.environ.has_key ('LILYPONDPREFIX') :
78 datadir = os.environ['LILYPONDPREFIX']
79 while datadir[-1] == os.sep:
82 sys.path.insert (0, os.path.join (datadir, 'python'))
85 #if __name__ == '__main__':
92 program_name = 'lilypond-book'
95 original_dir = os.getcwd ()
96 #temp_dir = os.path.join (original_dir, '%s.dir' % program_name)
100 preview_resolution = 90
103 ## ly2dvi: silly name?
104 ## do -P or -p by default?
105 ##help_summary = _ ("Run LilyPond using LaTeX for titling")
106 help_summary = _ ("Process LilyPond snippets in hybrid html, LaTeX or texinfo document")
107 copyright = ('Tom Cato Amundsen <tca@gnu.org>',
108 'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
110 option_definitions = [
111 (_ ("EXT"), 'f', 'format', _ ("use output format EXT (texi [default], texi-html, latex, html)")),
112 (_ ("DIM"), '', 'default-music-fontsize', _ ("default fontsize for music. DIM is assumed to be in points")),
113 (_ ("DIM"), '', 'default-lilypond-fontsize', _ ("deprecated, use --default-music-fontsize")),
114 (_ ("OPT"), '', 'extra-options', _ ("pass OPT quoted to the lilypond command line")),
115 (_ ("DIM"), '', 'force-music-fontsize', _ ("force fontsize for all inline lilypond. DIM is assumed be to in points")),
116 (_ ("DIM"), '', 'force-lilypond-fontsize', _ ("deprecated, use --force-music-fontsize")),
117 ('', 'h', 'help', _ ("this help")),
118 (_ ("DIR"), 'I', 'include', _ ("include path")),
119 ('', 'M', 'dependencies', _ ("write dependencies")),
120 (_ ("PREF"), '', 'dep-prefix', _ ("prepend PREF before each -M dependency")),
121 ('', 'n', 'no-lily', _ ("don't run lilypond")),
122 ('', '', 'no-pictures', _ ("don't generate pictures")),
123 ('', '', 'no-music', _ ("strip all lilypond blocks from output")),
124 (_ ("FILE"), 'o', 'outname', _ ("filename main output file")),
125 (_ ("FILE"), '', 'outdir', _ ("where to place generated files")),
126 (_ ('RES'), '', 'preview-resolution',
127 _ ("set the resolution of the preview to RES")),
128 ('', 'V', 'verbose', _ ("verbose")),
129 ('', 'v', 'version', _ ("print version information")),
130 ('', 'w', 'warranty', _ ("show warranty and copyright")),
133 # format specific strings, ie. regex-es for input, and % strings for output
137 include_path = [os.getcwd ()]
140 #lilypond_binary = 'valgrind --suppressions=/home/hanwen/usr/src/guile-1.6.supp --num-callers=10 /home/hanwen/usr/src/lilypond/lily/out/lilypond'
142 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
144 # only use installed binary when we're installed too.
145 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
146 lilypond_binary = 'lilypond'
150 ly2dvi_binary = os.path.join ('@bindir@', 'ly2dvi')
152 # only use installed binary when we're installed too.
153 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
154 ly2dvi_binary = 'ly2dvi'
159 g_here_dir = os.getcwd ()
162 g_force_music_fontsize = 0
171 default_music_fontsize = 16
172 default_text_fontsize = 12
175 ################################################################
176 # Dimension handling for LaTeX.
180 self.m_document_preamble = []
184 def find_latex_dims (self):
186 fname = os.path.join (g_outdir, "lily-tmp.tex")
188 fname = "lily-tmp.tex"
190 f = open (fname, "w")
192 error ("Error creating temporary file '%s'" % fname)
194 for s in self.m_document_preamble:
199 \typeout{\columnsep \the\columnsep}
200 \typeout{\textwidth \the\textwidth}
205 re_dim = re.compile (r"\\(\w+)\s+(\d+\.\d+)")
207 cmd = "latex '\\nonstopmode \input %s'" % fname
208 # Ugh. (La)TeX writes progress and error messages on stdout
210 cmd += ' 1>/dev/stderr'
211 status = ly.system (cmd, ignore_error = 1)
212 signal = 0xf & status
213 exit_status = status >> 8
216 ly.error (_ ("LaTeX failed."))
217 ly.error (_ ("The error log is as follows:"))
221 lns = open ('lily-tmp.log').readlines ()
226 sys.stderr.write (ln)
227 if re.match ('^!', ln):
234 countdown = countdown -1
236 sys.stderr.write (" ... (further messages elided)...\n")
239 lns = open ('lily-tmp.log').readlines ()
241 ln = string.strip (ln)
242 m = re_dim.match (ln)
244 if m.groups ()[0] in ('textwidth', 'columnsep'):
245 self.__dict__['m_%s' % m.groups ()[0]] = float (m.groups ()[1])
249 os.remove (os.path.splitext (fname)[0]+".aux")
250 os.remove (os.path.splitext (fname)[0]+".log")
254 if not self.__dict__.has_key ('m_textwidth'):
257 def get_linewidth (self):
258 if self.m_num_cols == 1:
261 w = (self.m_textwidth - self.m_columnsep)/2
262 if self.m_multicols > 1:
263 return (w - self.m_columnsep* (self.m_multicols-1)) \
270 self.m_papersize = 'letterpaper'
272 def get_linewidth (self):
273 return html_linewidths[self.m_papersize][self.m_fontsize]
277 self.m_papersize = 'letterpaper'
279 def get_linewidth (self):
280 return texi_linewidths[self.m_papersize][self.m_fontsize]
286 def em2pt (x, fontsize = 10):
287 return {10: 10.00002, 11: 10.8448, 12: 11.74988}[fontsize] * x
288 def ex2pt (x, fontsize = 10):
289 return {10: 4.30554, 11: 4.7146, 12: 5.16667}[fontsize] * x
294 dimension_conversion_dict ={
296 'cm': lambda x: mm2pt (10*x),
303 # Convert numeric values, with or without specific dimension, to floats.
305 def conv_dimen_to_float (value):
306 if type (value) == type (""):
307 m = re.match ("([0-9.]+)(cm|in|pt|mm|em|ex)",value)
310 num = string.atof (m.group (1))
311 conv = dimension_conversion_dict[m.group (2)]
315 elif re.match ("^[0-9.]+$",value):
316 value = float (value)
321 'afourpaper': {12: mm2pt (160)},
322 'afourwide': {12: in2pt (6.5)},
323 'afourlatex': {12: mm2pt (150)},
324 'smallbook': {12: in2pt (5)},
325 'letterpaper': {12: in2pt (6)}}
328 'afourpaper': {12: mm2pt (160)},
329 'afourwide': {12: in2pt (6.5)},
330 'afourlatex': {12: mm2pt (150)},
331 'smallbook': {12: in2pt (5)},
332 'letterpaper': {12: in2pt (6)}}
335 ################################################################
336 # How to output various structures.
342 'output-filename' : r'''
345 <pre>%s</pre></a>:''',
346 'output-lilypond-fragment': '''<lilypond%s>
347 \context Staff\context Voice{ %s }
349 'output-noinline': r'''
350 <!-- generated: %(fn)s.png !-->
354 # Verbatim text is always finished with \n. FIXME: For HTML,
355 # this newline should be removed.
356 'output-verbatim': r'''<pre>
358 # Verbatim text is always finished with \n. FIXME: For HTML,
359 # this newline should be removed.
360 'output-small-verbatim': r'''<font size=-1><pre>
362 ## Ugh we need to differentiate on origin:
363 ## lilypond-block origin wants an extra <p>, but
364 ## inline music doesn't.
365 ## possibly other center options?
368 <img align="center" valign="center" border="0" src="%(fn)s.png" alt="[picture of music]"></a>
375 'output-lilypond-fragment' : r'''\begin[eps,singleline,%s]{lilypond}
382 'output-filename' : r'''\verb+%s+:\\
387 # verbatim text is always finished with \n
388 'output-verbatim': r'''\begin{verbatim}
391 # verbatim text is always finished with \n
392 'output-small-verbatim': r'''{\small\begin{verbatim}
395 'output-default-post': "\\def\postLilypondExample{}\n",
396 'output-default-pre': "\\def\preLilypondExample{}\n",
397 'usepackage-graphics': '\\usepackage{graphics}\n',
398 'output-eps': '\\noindent\\parbox{\\lilypondepswidth{%(fn)s.eps}}{\includegraphics{%(fn)s}}',
399 'output-noinline': r'''
400 %% generated: %(fn)s.eps
402 'output-latex-quoted': r'''{\preLilypondExample
404 \postLilypondExample}''',
405 'output-latex-noquote': r'''{\parindent 0pt
408 \postLilypondExample}''',
409 'pagebreak': r'\pagebreak',
416 'output-filename' : r'''@ifnothtml
423 'output-lilypond-fragment': '''@lilypond[%s]
424 \context Staff\context Voice{ %s }
426 'output-noinline': r'''
427 @c generated: %(fn)s.png
430 # verbatim text is always finished with \n
431 'output-small-verbatim': r'''@smallexample
434 # verbatim text is always finished with \n
435 'output-verbatim': r'''@example
438 # do some tweaking: @ is needed in some ps stuff.
440 # ugh, the <p> below breaks inline images...
441 'output-texi-noquote': r'''@tex
449 <p><a href="%(fn)s.ly">
450 <img border=0 src="%(fn)s.png" alt="[picture of music]">
454 'output-texi-quoted': r'''@quotation
463 <img border=0 src="%(fn)s.png" alt="[picture of music]">
472 def output_verbatim (body, small):
475 body = re.sub ('&', '&', body)
476 body = re.sub ('>', '>', body)
477 body = re.sub ('<', '<', body)
478 elif format == 'texi':
479 # clumsy workaround for python 2.2 pre bug.
480 body = re.sub ('@', '@@', body)
481 body = re.sub ('{', '@{', body)
482 body = re.sub ('}', '@}', body)
485 key = 'output-small-verbatim'
487 key = 'output-verbatim'
488 return get_output (key) % body
491 ################################################################
492 # Recognize special sequences in the input
495 # Warning: This uses extended regular expressions. Tread with care.
499 # (?P<name>regex) -- assign result of REGEX to NAME
500 # *? -- match non-greedily.
501 # (?m) -- multiline regex: make ^ and $ match at each line
502 # (?s) -- make the dot match all characters including newline
508 'preamble-end': no_match,
509 'landscape': no_match,
510 'verbatim': r'''(?s)(?P<code><pre>\s.*?</pre>\s)''',
511 'verb': r'''(?P<code><pre>.*?</pre>)''',
512 'lilypond-file': r'(?m)(?P<match><lilypondfile(?P<options>[^>]+)?>\s*(?P<filename>[^<]+)\s*</lilypondfile>)',
513 'lilypond' : '(?m)(?P<match><lilypond((?P<options>[^:]*):)(?P<code>.*?)/>)',
514 'lilypond-block': r'''(?ms)(?P<match><lilypond(?P<options>[^>]+)?>(?P<code>.*?)</lilypond>)''',
515 'option-sep' : '\s*',
516 'intertext': r',?\s*intertext=\".*?\"',
517 'multiline-comment': r"(?sm)\s*(?!@c\s+)(?P<code><!--\s.*?!-->)\s",
518 'singleline-comment': no_match,
520 'multicols': no_match,
521 'ly2dvi': r'(?m)(?P<match><ly2dvifile(?P<options>[^>]+)?>\s*(?P<filename>[^<]+)\s*</ly2dvifile>)',
525 'input': r'(?m)^[^%\n]*?(?P<match>\\mbinput{?([^}\t \n}]*))',
526 'include': r'(?m)^[^%\n]*?(?P<match>\\mbinclude{(?P<filename>[^}]+)})',
527 'option-sep' : ',\s*',
528 'header': r"\n*\\documentclass\s*(\[.*?\])?",
529 'preamble-end': r'(?P<code>\\begin\s*{document})',
530 'verbatim': r"(?s)(?P<code>\\begin\s*{verbatim}.*?\\end{verbatim})",
531 'verb': r"(?P<code>\\verb(?P<del>.).*?(?P=del))",
532 'lilypond-file': r'(?m)^[^%\n]*?(?P<match>\\lilypondfile\s*(\[(?P<options>.*?)\])?\s*\{(?P<filename>.+)})',
533 'lilypond' : r'(?m)^[^%\n]*?(?P<match>\\lilypond\s*(\[(?P<options>.*?)\])?\s*{(?P<code>.*?)})',
534 'lilypond-block': r"(?sm)^[^%\n]*?(?P<match>\\begin\s*(\[(?P<options>.*?)\])?\s*{lilypond}(?P<code>.*?)\\end{lilypond})",
535 'def-post-re': r"\\def\\postLilypondExample",
536 'def-pre-re': r"\\def\\preLilypondExample",
537 'usepackage-graphics': r"\usepackage\s*{graphics}",
538 'intertext': r',?\s*intertext=\".*?\"',
539 'multiline-comment': no_match,
540 'singleline-comment': r"(?m)^.*?(?P<match>(?P<code>^%.*$\n+))",
541 'numcols': r"(?P<code>\\(?P<num>one|two)column)",
542 'multicols': r"(?P<code>\\(?P<be>begin|end)\s*{multicols}({(?P<num>\d+)?})?)",
547 # why do we have distinction between @mbinclude and @include?
550 'include': '(?m)^[^%\n]*?(?P<match>@mbinclude[ \n\t]+(?P<filename>[^\t \n]*))',
553 'preamble-end': no_match,
554 'landscape': no_match,
555 'verbatim': r'''(?s)(?P<code>@example\s.*?@end example\s)''',
556 'verb': r'''(?P<code>@code{.*?})''',
557 'lilypond-file': '(?m)^(?P<match>@lilypondfile(\[(?P<options>[^]]*)\])?{(?P<filename>[^}]+)})',
558 'lilypond' : '(?m)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?{(?P<code>.*?)})',
559 'lilypond-block': r'''(?ms)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?\s(?P<code>.*?)@end lilypond)\s''',
560 'option-sep' : ',\s*',
561 'intertext': r',?\s*intertext=\".*?\"',
562 'multiline-comment': r"(?sm)^\s*(?!@c\s+)(?P<code>@ignore\s.*?@end ignore)\s",
563 'singleline-comment': r"(?m)^.*?(?P<match>(?P<code>@c.*$\n+))",
565 'multicols': no_match,
571 for r in re_dict.keys ():
574 for k in olddict.keys ():
576 newdict[k] = re.compile (olddict[k])
578 print 'invalid regexp: %s' % olddict[k]
580 ## we'd like to catch and reraise a more
581 ## detailed error, but alas, the exceptions
582 ## changed across the 1.5/2.1 boundary.
598 def get_output (name):
599 return output_dict[format][name]
602 return re_dict[format][name]
604 def bounding_box_dimensions (fname):
606 fname = os.path.join (g_outdir, fname)
610 error ("Error opening `%s'" % fname)
612 s = re.search ('%%BoundingBox: ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)', str)
615 gs = map (lambda x: string.atoi (x), s.groups ())
616 return (int (gs[2] - gs[0] + 0.5),
617 int (gs[3] - gs[1] + 0.5))
622 sys.stderr.write ("\n\n" + str + "\nExiting ... \n\n")
626 def compose_full_body (body, opts):
627 '''Construct the lilypond code to send to Lilypond.
628 Add stuff to BODY using OPTS as options.'''
629 music_size = default_music_fontsize
630 if g_force_music_fontsize:
631 music_size = g_force_music_fontsize
636 if not g_force_music_fontsize:
637 m = re.match ('([0-9]+)pt', o)
639 music_size = string.atoi (m.group (1))
641 m = re.match ('indent=([-.0-9]+)(cm|in|mm|pt)', o)
643 f = float (m.group (1))
644 indent = 'indent = %f\\%s' % (f, m.group (2))
646 m = re.match ('linewidth=([-.0-9]+)(cm|in|mm|pt)', o)
648 f = float (m.group (1))
649 linewidth = 'linewidth = %f\\%s' % (f, m.group (2))
651 if re.search ('\\\\score', body):
655 if 'fragment' in opts:
657 if 'nofragment' in opts:
660 if is_fragment and not 'multiline' in opts:
661 opts.append ('singleline')
663 if 'singleline' in opts:
665 linewidth = 'raggedright = ##t'
667 indent = 'indent = 0.0\mm'
670 l = paperguru.get_linewidth ()
671 linewidth = 'linewidth = %f\pt' % l
673 if 'noindent' in opts:
674 indent = 'indent = 0.0\mm'
680 \remove Time_signature_engraver
685 m= re.search ('relative(.*)', o)
689 v = string.atoi (m.group (1))
696 pitch = pitch + '\,' * v
698 pitch = pitch + '\'' * v
700 body = '\\relative %s { %s }' % (pitch, body)
712 optstring = string.join (opts, ' ')
713 optstring = re.sub ('\n', ' ', optstring)
715 %% Generated automatically by: lilypond-book.py
717 \include "paper%d.ly"
723 ''' % (optstring, music_size, linewidth, indent, notime) + body
725 # ughUGH not original options
728 def scan_html_preamble (chunks):
731 def scan_latex_preamble (chunks):
732 # First we want to scan the \documentclass line
733 # it should be the first non-comment line.
734 # The only thing we really need to know about the \documentclass line
735 # is if there are one or two columns to begin with.
738 if chunks[idx][0] == 'ignore':
741 m = get_re ('header').match (chunks[idx][1])
743 error ("Latex documents must start with a \documentclass command")
745 options = re.split (',[\n \t]*', m.group (1)[1:-1])
748 if 'twocolumn' in options:
749 paperguru.m_num_cols = 2
753 # Then we add everything before \begin{document} to
754 # paperguru.m_document_preamble so that we can later write this header
755 # to a temporary file in find_latex_dims() to find textwidth.
756 while idx < len (chunks) and chunks[idx][0] != 'preamble-end':
757 if chunks[idx] == 'ignore':
760 paperguru.m_document_preamble.append (chunks[idx][1])
763 if len (chunks) == idx:
764 error ("Didn't find end of preamble (\\begin{document})")
766 paperguru.find_latex_dims ()
768 def scan_texi_preamble (chunks):
769 # this is not bulletproof..., it checks the first 10 chunks
770 for c in chunks[:10]:
772 for s in ('afourpaper', 'afourwide', 'letterpaper',
773 'afourlatex', 'smallbook'):
774 if string.find (c[1], "@%s" % s) != -1:
775 paperguru.m_papersize = s
778 def scan_preamble (chunks):
781 scan_html_preamble (chunks)
782 elif format == 'latex':
783 scan_latex_preamble (chunks)
784 elif format == 'texi':
785 scan_texi_preamble (chunks)
788 def completize_preamble (chunks):
790 if format != 'latex':
792 pre_b = post_b = graphics_b = None
794 if chunk[0] == 'preamble-end':
796 if chunk[0] == 'input':
797 m = get_re ('def-pre-re').search (chunk[1])
800 if chunk[0] == 'input':
801 m = get_re ('def-post-re').search (chunk[1])
805 if chunk[0] == 'input':
806 m = get_re ('usepackage-graphics').search (chunk[1])
810 while x < len (chunks) and chunks[x][0] != 'preamble-end':
813 if x == len (chunks):
817 chunks.insert (x, ('input', get_output ('output-default-pre')))
819 chunks.insert (x, ('input', get_output ('output-default-post')))
821 chunks.insert (x, ('input', get_output ('usepackage-graphics')))
827 def find_file (name):
829 Search the include path for NAME. If found, return the (CONTENTS, PATH) of the file.
833 return (sys.stdin.read (), '<stdin>')
836 for a in include_path:
838 nm = os.path.join (a, name)
841 read_files.append (nm)
846 sys.stderr.write ("Reading `%s'\n" % nm)
847 return (f.read (), nm)
849 error ("File not found `%s'\n" % name)
852 def do_ignore (match_object):
853 return [('ignore', match_object.group ('code'))]
854 def do_preamble_end (match_object):
855 return [('preamble-end', match_object.group ('code'))]
857 def make_verbatim (match_object):
858 return [('verbatim', match_object.group ('code'))]
860 def make_verb (match_object):
861 return [('verb', match_object.group ('code'))]
863 def do_include_file (m):
865 return [('input', get_output ('pagebreak'))] \
866 + read_doc_file (m.group ('filename')) \
867 + [('input', get_output ('pagebreak'))]
869 def do_input_file (m):
870 return read_doc_file (m.group ('filename'))
872 def make_lilypond (m):
873 if m.group ('options'):
874 options = m.group ('options')
877 return [('input', get_output ('output-lilypond-fragment') %
878 (options, m.group ('code')))]
880 def make_lilypond_file (m):
883 Find @lilypondfile{bla.ly} occurences and substitute bla.ly
884 into a @lilypond .. @end lilypond block.
888 if m.group ('options'):
889 options = get_re ('option-sep').split (m.group ('options'))
892 (content, nm) = find_file (m.group ('filename'))
893 options.append ("filename=%s" % nm)
895 return [('lilypond', content, options)]
897 def make_ly2dvi_block (m):
900 Find <ly2dvifile .. >
903 return [('ly2dvi', m.group ('filename'), m.group ('options'))]
906 def make_lilypond_block (m):
910 if m.group ('options'):
911 options = get_re ('option-sep').split (m.group ('options'))
914 options = filter (lambda s: s != '', options)
915 return [('lilypond', m.group ('code'), options)]
920 if format != 'latex':
922 if m.group ('num') == 'one':
923 return [('numcols', m.group ('code'), 1)]
924 if m.group ('num') == 'two':
925 return [('numcols', m.group ('code'), 2)]
927 def do_multicols (m):
929 if format != 'latex':
931 if m.group ('be') == 'begin':
932 return [('multicols', m.group ('code'), int (m.group ('num')))]
934 return [('multicols', m.group ('code'), 1)]
937 def chop_chunks (chunks, re_name, func, use_match=0):
943 m = get_re (re_name).search (str)
945 newchunks.append (('input', str))
949 newchunks.append (('input', str[:m.start ('match')]))
951 newchunks.append (('input', str[:m.start (0)]))
952 #newchunks.extend (func (m))
953 # python 1.5 compatible:
954 newchunks = newchunks + func (m)
955 str = str [m.end (0):]
960 def determine_format (str):
963 html = re.search ('(?i)<[dh]tml', str[:200])
964 latex = re.search (r'''\\document''', str[:200])
965 texi = re.search ('@node|@setfilename', str[:200])
970 if html and not latex and not texi:
972 elif latex and not html and not texi:
974 elif texi and not html and not latex:
977 error ("can't determine format, please specify")
981 if paperguru == None:
984 elif format == 'latex':
986 elif format == 'texi':
992 def read_doc_file (filename):
993 '''Read the input file, find verbatim chunks and do \input and \include
995 (str, path) = find_file (filename)
996 determine_format (str)
998 chunks = [('input', str)]
1000 # we have to check for verbatim before doing include,
1001 # because we don't want to include files that are mentioned
1002 # inside a verbatim environment
1003 chunks = chop_chunks (chunks, 'verbatim', make_verbatim)
1005 chunks = chop_chunks (chunks, 'verb', make_verb)
1006 chunks = chop_chunks (chunks, 'multiline-comment', do_ignore)
1008 chunks = chop_chunks (chunks, 'include', do_include_file, 1)
1009 chunks = chop_chunks (chunks, 'input', do_input_file, 1)
1013 taken_file_names = {}
1015 def unique_file_name (body):
1016 return 'lily-' + `abs (hash (body))`
1018 def schedule_lilypond_block (chunk):
1019 '''Take the body and options from CHUNK, figure out how the
1020 real .ly should look, and what should be left MAIN_STR (meant
1021 for the main file). The .ly is written, and scheduled in
1024 Return: a chunk (TYPE_STR, MAIN_STR, OPTIONS, TODO, BASE)
1026 TODO has format [basename, extension, extension, ... ]
1028 (type, body, opts) = chunk
1029 assert type == 'lilypond'
1030 file_body = compose_full_body (body, opts)
1031 ## Hmm, we should hash only lilypond source, and skip the
1034 basename = unique_file_name (file_body)
1036 m = re.search ('filename="(.*?)"', o)
1038 basename = m.group (1)
1039 if not taken_file_names.has_key (basename):
1040 taken_file_names[basename] = 0
1042 taken_file_names[basename] = taken_file_names[basename] + 1
1043 basename = basename + "-%i" % taken_file_names[basename]
1044 update_file (file_body, os.path.join (g_outdir, basename) + '.ly')
1045 needed_filetypes = ['tex']
1047 if format == 'html' or g_make_html:
1048 needed_filetypes.append ('eps')
1049 needed_filetypes.append ('png')
1050 if 'eps' in opts and not ('eps' in needed_filetypes):
1051 needed_filetypes.append ('eps')
1053 pathbase = os.path.join (g_outdir, basename)
1054 def f (base, ext1, ext2):
1055 a = os.path.isfile (base + ext2)
1056 if (os.path.isfile (base + ext1) and
1057 os.path.isfile (base + ext2) and
1058 os.stat (base+ext1)[stat.ST_MTIME] >
1059 os.stat (base+ext2)[stat.ST_MTIME]) or \
1060 not os.path.isfile (base + ext2):
1063 if 'tex' in needed_filetypes and f (pathbase, '.ly', '.tex'):
1065 if 'eps' in needed_filetypes and f (pathbase, '.tex', '.eps'):
1067 if 'png' in needed_filetypes and f (pathbase, '.eps', '.png'):
1071 if 'printfilename' in opts:
1073 m= re.match ("filename=(.*)", o)
1075 newbody = newbody + get_output ("output-filename") % (m.group (1), basename + '.ly', m.group (1))
1079 if 'smallverbatim' in opts:
1080 newbody = newbody + output_verbatim (body, 1)
1081 elif 'verbatim' in opts:
1082 newbody = newbody + output_verbatim (body, 0)
1085 m = re.search ('intertext="(.*?)"', o)
1087 newbody = newbody + "\n"
1088 if format == 'texi':
1089 newbody = newbody + "@noindent\n"
1090 elif format == 'latex':
1091 newbody = newbody + "\\noindent\n"
1092 newbody = newbody + m.group (1) + "\n"
1094 if 'noinline' in opts:
1095 s = 'output-noinline'
1096 elif format == 'latex':
1101 s = 'output-latex-quoted'
1103 s = 'output-latex-noquote'
1104 elif format == 'texi':
1106 s = 'output-texi-quoted'
1108 s = 'output-texi-noquote'
1109 else: # format == 'html'
1111 newbody = newbody + get_output (s) % {'fn': basename }
1112 return ('lilypond', newbody, opts, todo, basename)
1117 def process_lilypond_blocks (chunks):#ugh rename
1119 # Count sections/chapters.
1121 if c[0] == 'lilypond':
1122 c = schedule_lilypond_block (c)
1123 elif c[0] == 'numcols':
1124 paperguru.m_num_cols = c[2]
1125 elif c[0] == 'multicols':
1126 paperguru.m_multicols = c[2]
1127 newchunks.append (c)
1130 def process_ly2dvi_blocks (chunks):
1132 def process_ly2dvi_block (chunk):
1135 Run ly2dvi script on filename specified in CHUNK.
1136 This is only supported for HTML output.
1138 In HTML output it will leave a download menu with ps/pdf/midi etc. in
1139 a separate HTML file, and a title + preview in the main html file,
1140 linking to the menu.
1143 (tag, name, opts) = chunk
1144 assert format == 'html'
1145 (content, original_name) = find_file (name)
1147 original_name = os.path.basename (original_name)
1149 base = unique_file_name (content)
1150 outname = base + '.ly'
1151 changed = update_file (content, outname)
1153 preview = base + ".png"
1154 if changed or not os.path.isfile (preview):
1156 ly.system ('%s --preview --postscript --verbose %s ' % (ly2dvi_binary, base) )
1158 ly.make_page_images (base)
1159 ly.system ('gzip -9 - < %s.ps > %s.ps.gz' % (base, base))
1162 b = os.stat(fn)[stat.ST_SIZE]
1164 return '%d bytes' % b
1166 return '%d kb' % (b >> 10)
1168 return '%d mb' % (b >> 20)
1171 'pdf' : "Print (PDF, %s)",
1172 'ps.gz' : "Print (gzipped PostScript, %s)",
1173 'png' : "View (PNG, %s)",
1174 'midi' : "Listen (MIDI, %s)",
1175 'ly' : "View source code (%s)",
1179 page_files = glob.glob ('%s-page*.png' % base)
1181 for p in string.split (page_files, '\n'):
1183 if os.path.isfile (p):
1185 page = re.sub ('.*page([0-9])+.*', 'View page \\1 (PNG picture, %s)\n', p)
1187 menu += '<li><a href="%s">%s</a>' % (p, page)
1189 ext_order = ['ly', 'pdf', 'ps.gz', 'midi']
1192 print 'checking,' , fn
1193 if not os.path.isfile (fn):
1196 entry = exts[e] % size_str (fn)
1198 ## TODO: do something like
1199 ## this for texinfo/latex as well ?
1201 menu += '<li><a href="%s">%s</a>\n\n' % (fn, entry)
1204 explanatory_para = """The pictures are 90dpi
1205 anti-aliased snapshots of the printed output, in PNG format. Both PDF and PS
1206 use scalable fonts and should look OK at any resolution."""
1209 <title>LilyPond example %s</title>
1215 <ul>%s</ul>''' % (original_name,original_name, preview, explanatory_para, menu)
1217 open (base + '.html','w'). write (separate_menu)
1219 inline_menu = '<p/><a href="%s.html"><img src="%s"><p/></a>' % (base, original_name, preview)
1221 return ('ly2dvi', inline_menu)
1225 if c[0] == 'ly2dvi':
1226 c = process_ly2dvi_block (c)
1227 newchunks.append (c)
1231 def compile_all_files (chunks):
1238 if c[0] != 'lilypond':
1247 if base + '.ly' not in tex:
1248 tex.append (base + '.ly')
1249 elif e == 'png' and g_do_pictures:
1255 # fixme: be sys-independent.
1257 if g_outdir and x[0] != '/' :
1258 x = os.path.join (g_here_dir, x)
1261 incs = map (incl_opt, include_path)
1262 lilyopts = string.join (incs)
1264 lilyopts += ' --dependencies'
1266 lilyopts += ' --dep-prefix=' + g_outdir + '/'
1267 lilyopts += ' --header=texidoc'
1268 texfiles = string.join (tex)
1269 cmd = string.join ((lilypond_binary, lilyopts, g_extra_opts,
1271 ly.system (cmd, ignore_error = 0, progress_p = 1)
1274 # Ugh, fixing up dependencies for .tex generation
1277 depfiles=map (lambda x: re.sub ('(.*)\.ly', '\\1.dep',
1284 text=re.sub ('\n([^:\n]*):',
1285 '\n' + foutn + ':', text)
1291 cmd = r"latex '\nonstopmode \input %s'" % file
1292 # Ugh. (La)TeX writes progress and error messages on stdout
1293 # Redirect to stderr
1294 cmd += ' 1>/dev/stderr'
1296 ly.system ("dvips -E -o %s.eps %s" % (file, file))
1299 map (ly.make_preview, png)
1303 def update_file (body, name):
1305 write the body if it has changed. Return whether BODY has changed.
1316 f = open (name , 'w')
1323 def write_deps (fn, target, chunks):
1325 sys.stderr.write ('Writing `%s\'\n' % os.path.join (g_outdir, fn))
1326 f = open (os.path.join (g_outdir, fn), 'w')
1327 f.write ('%s%s: ' % (g_dep_prefix, target))
1328 for d in read_files:
1332 ## There used to be code to write .tex dependencies, but
1333 ## that is silly: lilypond-book has its own dependency scheme
1334 ## to ensure that all lily-XXX.tex files are there
1341 def check_texidoc (chunks):
1344 if c[0] == 'lilypond':
1345 (type, body, opts, todo, basename) = c;
1346 pathbase = os.path.join (g_outdir, basename)
1347 if os.path.isfile (pathbase + '.texidoc') \
1348 and 'notexidoc' not in opts:
1349 body = '\n@include %s.texidoc\n' % basename + body
1350 c = (type, body, opts, todo, basename)
1355 ## what's this? Docme --hwn
1357 def fix_epswidth (chunks):
1360 if c[0] != 'lilypond' or 'eps' not in c[2]:
1361 newchunks.append (c)
1366 m = re.match ('magnification=([0-9.]+)', o)
1368 mag = string.atof (m.group (1))
1370 def replace_eps_dim (match, lmag = mag):
1371 filename = match.group (1)
1372 dims = bounding_box_dimensions (filename)
1374 return '%fpt' % (dims[0] *lmag)
1376 body = re.sub (r'''\\lilypondepswidth{(.*?)}''', replace_eps_dim, c[1])
1377 newchunks.append (('lilypond', body, c[2], c[3], c[4]))
1382 ##docme: why global?
1385 def do_file (input_filename):
1386 chunks = read_doc_file (input_filename)
1387 chunks = chop_chunks (chunks, 'ly2dvi', make_ly2dvi_block, 1)
1388 chunks = chop_chunks (chunks, 'lilypond', make_lilypond, 1)
1389 chunks = chop_chunks (chunks, 'lilypond-file', make_lilypond_file, 1)
1390 chunks = chop_chunks (chunks, 'lilypond-block', make_lilypond_block, 1)
1391 chunks = chop_chunks (chunks, 'singleline-comment', do_ignore, 1)
1392 chunks = chop_chunks (chunks, 'preamble-end', do_preamble_end)
1393 chunks = chop_chunks (chunks, 'numcols', do_columns)
1394 chunks = chop_chunks (chunks, 'multicols', do_multicols)
1396 #for c in chunks: print "c:", c;
1398 scan_preamble (chunks)
1399 chunks = process_lilypond_blocks (chunks)
1400 chunks = process_ly2dvi_blocks (chunks)
1403 global g_run_lilypond
1405 compile_all_files (chunks)
1406 chunks = fix_epswidth (chunks)
1409 if format == 'texi':
1410 chunks = check_texidoc (chunks)
1413 chunks = completize_preamble (chunks)
1418 my_outname = outname
1419 elif input_filename == '-' or input_filename == "/dev/stdin":
1422 my_outname = os.path.basename (os.path.splitext (input_filename)[0]) + '.' + format
1423 my_depname = my_outname + '.dep'
1425 if my_outname == '-' or my_outname == '/dev/stdout':
1431 foutn = os.path.join (g_outdir, my_outname)
1432 sys.stderr.write ("Writing `%s'\n" % foutn)
1433 fout = open (foutn, 'w')
1440 write_deps (my_depname, foutn, chunks)
1444 (sh, long) = ly.getopt_args (option_definitions)
1445 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1447 except getopt.error, msg:
1448 sys.stderr.write ('\n')
1449 ly.error (_ ("getopt says: `%s\'" % s))
1450 sys.stderr.write ('\n')
1459 if o == '--include' or o == '-I':
1460 include_path.append (a)
1461 elif o == '--version' or o == '-v':
1462 ly.identify (sys.stdout)
1464 elif o == '--verbose' or o == '-V':
1466 elif o == '--format' or o == '-f':
1468 if a == 'texi-html':
1471 elif o == '--outname' or o == '-o':
1474 sys.stderr.write ("Lilypond-book is confused by --outname on multiple files")
1477 elif o == '--help' or o == '-h':
1480 elif o == '--no-lily' or o == '-n':
1482 elif o == '--preview-resolution':
1483 preview_resolution = string.atoi (a)
1484 elif o == '--dependencies' or o == '-M':
1486 elif o == '--default-music-fontsize':
1487 default_music_fontsize = string.atoi (a)
1488 elif o == '--default-lilypond-fontsize':
1489 print "--default-lilypond-fontsize is deprecated, use --default-music-fontsize"
1490 default_music_fontsize = string.atoi (a)
1491 elif o == '--extra-options':
1493 elif o == '--force-music-fontsize':
1494 g_force_music_fontsize = string.atoi (a)
1495 elif o == '--force-lilypond-fontsize':
1496 print "--force-lilypond-fontsize is deprecated, use --default-lilypond-fontsize"
1497 g_force_music_fontsize = string.atoi (a)
1498 elif o == '--dep-prefix':
1500 elif o == '--no-pictures':
1502 elif o == '--no-music':
1504 elif o == '--outdir':
1506 elif o == '--warranty' or o == '-w':
1507 #status = os.system ('lilypond -w')
1512 ly.identify (sys.stderr)
1515 if os.path.isfile (g_outdir):
1516 error ("outdir is a file: %s" % g_outdir)
1517 if not os.path.exists (g_outdir):
1522 ly.error (_ ("no files specified on command line"))
1525 ly.setup_environment ()
1527 for input_filename in files:
1528 do_file (input_filename)
1532 # Petr, ik zou willen dat ik iets zinvoller deed,
1533 # maar wat ik kan ik doen, het verandert toch niets?