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 ('', '', 'read-lys', _ ("don't write ly files.")),
125 (_ ("FILE"), 'o', 'outname', _ ("filename main output file")),
126 (_ ("FILE"), '', 'outdir', _ ("where to place generated files")),
127 (_ ('RES'), '', 'preview-resolution',
128 _ ("set the resolution of the preview to RES")),
129 ('', 'V', 'verbose', _ ("verbose")),
130 ('', 'v', 'version', _ ("print version information")),
131 ('', 'w', 'warranty', _ ("show warranty and copyright")),
134 # format specific strings, ie. regex-es for input, and % strings for output
138 include_path = [os.getcwd ()]
141 #lilypond_binary = 'valgrind --suppressions=/home/hanwen/usr/src/guile-1.6.supp --num-callers=10 /home/hanwen/usr/src/lilypond/lily/out/lilypond'
143 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
145 # only use installed binary when we're installed too.
146 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
147 lilypond_binary = 'lilypond'
151 ly2dvi_binary = os.path.join ('@bindir@', 'ly2dvi')
153 # only use installed binary when we're installed too.
154 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
155 ly2dvi_binary = 'ly2dvi'
160 g_here_dir = os.getcwd ()
163 g_force_music_fontsize = 0
173 default_music_fontsize = 16
174 default_text_fontsize = 12
177 ################################################################
178 # Dimension handling for LaTeX.
182 self.m_document_preamble = []
186 def find_latex_dims (self):
188 fname = os.path.join (g_outdir, "lily-tmp.tex")
190 fname = "lily-tmp.tex"
192 f = open (fname, "w")
194 error ("Error creating temporary file '%s'" % fname)
196 for s in self.m_document_preamble:
201 \typeout{\columnsep \the\columnsep}
202 \typeout{\textwidth \the\textwidth}
207 re_dim = re.compile (r"\\(\w+)\s+(\d+\.\d+)")
209 cmd = "latex '\\nonstopmode \input %s'" % fname
210 # Ugh. (La)TeX writes progress and error messages on stdout
212 cmd += ' 1>/dev/stderr'
213 status = ly.system (cmd, ignore_error = 1)
214 signal = 0xf & status
215 exit_status = status >> 8
218 ly.error (_ ("LaTeX failed."))
219 ly.error (_ ("The error log is as follows:"))
223 lns = open ('lily-tmp.log').readlines ()
228 sys.stderr.write (ln)
229 if re.match ('^!', ln):
236 countdown = countdown -1
238 sys.stderr.write (" ... (further messages elided)...\n")
241 lns = open ('lily-tmp.log').readlines ()
243 ln = string.strip (ln)
244 m = re_dim.match (ln)
246 if m.groups ()[0] in ('textwidth', 'columnsep'):
247 self.__dict__['m_%s' % m.groups ()[0]] = float (m.groups ()[1])
251 os.remove (os.path.splitext (fname)[0]+".aux")
252 os.remove (os.path.splitext (fname)[0]+".log")
256 if not self.__dict__.has_key ('m_textwidth'):
259 def get_linewidth (self):
260 if self.m_num_cols == 1:
263 w = (self.m_textwidth - self.m_columnsep)/2
264 if self.m_multicols > 1:
265 return (w - self.m_columnsep* (self.m_multicols-1)) \
272 self.m_papersize = 'letterpaper'
274 def get_linewidth (self):
275 return html_linewidths[self.m_papersize][self.m_fontsize]
279 self.m_papersize = 'letterpaper'
281 def get_linewidth (self):
282 return texi_linewidths[self.m_papersize][self.m_fontsize]
288 def em2pt (x, fontsize = 10):
289 return {10: 10.00002, 11: 10.8448, 12: 11.74988}[fontsize] * x
290 def ex2pt (x, fontsize = 10):
291 return {10: 4.30554, 11: 4.7146, 12: 5.16667}[fontsize] * x
296 dimension_conversion_dict ={
298 'cm': lambda x: mm2pt (10*x),
305 # Convert numeric values, with or without specific dimension, to floats.
307 def conv_dimen_to_float (value):
308 if type (value) == type (""):
309 m = re.match ("([0-9.]+)(cm|in|pt|mm|em|ex)",value)
312 num = string.atof (m.group (1))
313 conv = dimension_conversion_dict[m.group (2)]
317 elif re.match ("^[0-9.]+$",value):
318 value = float (value)
323 'afourpaper': {12: mm2pt (160)},
324 'afourwide': {12: in2pt (6.5)},
325 'afourlatex': {12: mm2pt (150)},
326 'smallbook': {12: in2pt (5)},
327 'letterpaper': {12: in2pt (6)}}
330 'afourpaper': {12: mm2pt (160)},
331 'afourwide': {12: in2pt (6.5)},
332 'afourlatex': {12: mm2pt (150)},
333 'smallbook': {12: in2pt (5)},
334 'letterpaper': {12: in2pt (6)}}
337 ################################################################
338 # How to output various structures.
344 'output-filename' : r'''
347 <pre>%s</pre></a>:''',
348 'output-lilypond-fragment': '''<lilypond%s>
349 \context Staff\context Voice{ %s }
351 'output-noinline': r'''
352 <!-- generated: %(fn)s.png !-->
356 # Verbatim text is always finished with \n. FIXME: For HTML,
357 # this newline should be removed.
358 'output-verbatim': r'''<pre>
360 # Verbatim text is always finished with \n. FIXME: For HTML,
361 # this newline should be removed.
362 'output-small-verbatim': r'''<font size=-1><pre>
364 ## Ugh we need to differentiate on origin:
365 ## lilypond-block origin wants an extra <p>, but
366 ## inline music doesn't.
367 ## possibly other center options?
369 <a href="%(fn)s.png">
370 <img align="center" valign="center" border="0" src="%(fn)s.png" alt="[picture of music]"></a>
377 'output-lilypond-fragment' : r'''\begin[eps,singleline,%s]{lilypond}
384 'output-filename' : r'''\verb+%s+:\\
389 # verbatim text is always finished with \n
390 'output-verbatim': r'''\begin{verbatim}
393 # verbatim text is always finished with \n
394 'output-small-verbatim': r'''{\small\begin{verbatim}
397 'output-default-post': "\\def\postLilypondExample{}\n",
398 'output-default-pre': "\\def\preLilypondExample{}\n",
399 'usepackage-graphics': '\\usepackage{graphics}\n',
400 'output-eps': '\\noindent\\parbox{\\lilypondepswidth{%(fn)s.eps}}{\includegraphics{%(fn)s}}',
401 'output-noinline': r'''
402 %% generated: %(fn)s.eps
404 'output-latex-quoted': r'''{\preLilypondExample
406 \postLilypondExample}''',
407 'output-latex-noquote': r'''{\parindent 0pt
410 \postLilypondExample}''',
411 'pagebreak': r'\pagebreak',
418 'output-filename' : r'''@ifnothtml
425 'output-lilypond-fragment': '''@lilypond[%s]
426 \context Staff\context Voice{ %s }
428 'output-noinline': r'''
429 @c generated: %(fn)s.png
432 # verbatim text is always finished with \n
433 'output-small-verbatim': r'''@smallexample
436 # verbatim text is always finished with \n
437 'output-verbatim': r'''@example
440 # do some tweaking: @ is needed in some ps stuff.
442 # ugh, the <p> below breaks inline images...
443 'output-texi-noquote': r'''@tex
451 <p><a href="%(fn)s.png">
452 <img border=0 src="%(fn)s.png" alt="[picture of music]">
456 'output-texi-quoted': r'''@quotation
464 <a href="%(fn)s.png">
465 <img border=0 src="%(fn)s.png" alt="[picture of music]">
474 def output_verbatim (body, small):
477 body = re.sub ('&', '&', body)
478 body = re.sub ('>', '>', body)
479 body = re.sub ('<', '<', body)
480 elif format == 'texi':
481 # clumsy workaround for python 2.2 pre bug.
482 body = re.sub ('@', '@@', body)
483 body = re.sub ('{', '@{', body)
484 body = re.sub ('}', '@}', body)
487 key = 'output-small-verbatim'
489 key = 'output-verbatim'
490 return get_output (key) % body
493 ################################################################
494 # Recognize special sequences in the input
497 # Warning: This uses extended regular expressions. Tread with care.
501 # (?P<name>regex) -- assign result of REGEX to NAME
502 # *? -- match non-greedily.
503 # (?m) -- multiline regex: make ^ and $ match at each line
504 # (?s) -- make the dot match all characters including newline
510 'preamble-end': no_match,
511 'landscape': no_match,
512 'verbatim': r'''(?s)(?P<code><pre>\s.*?</pre>\s)''',
513 'verb': r'''(?P<code><pre>.*?</pre>)''',
514 'lilypond-file': r'(?m)(?P<match><lilypondfile(?P<options>[^>]+)?>\s*(?P<filename>[^<]+)\s*</lilypondfile>)',
515 'lilypond' : '(?m)(?P<match><lilypond((?P<options>[^:]*):)(?P<code>.*?)/>)',
516 'lilypond-block': r'''(?ms)(?P<match><lilypond(?P<options>[^>]+)?>(?P<code>.*?)</lilypond>)''',
517 'option-sep' : '\s*',
518 'intertext': r',?\s*intertext=\".*?\"',
519 'multiline-comment': r"(?sm)\s*(?!@c\s+)(?P<code><!--\s.*?!-->)\s",
520 'singleline-comment': no_match,
522 'multicols': no_match,
523 'ly2dvi': r'(?m)(?P<match><ly2dvifile(?P<options>[^>]+)?>\s*(?P<filename>[^<]+)\s*</ly2dvifile>)',
527 'input': r'(?m)^[^%\n]*?(?P<match>\\mbinput{?([^}\t \n}]*))',
528 'include': r'(?m)^[^%\n]*?(?P<match>\\mbinclude{(?P<filename>[^}]+)})',
529 'option-sep' : ',\s*',
530 'header': r"\n*\\documentclass\s*(\[.*?\])?",
531 'preamble-end': r'(?P<code>\\begin\s*{document})',
532 'verbatim': r"(?s)(?P<code>\\begin\s*{verbatim}.*?\\end{verbatim})",
533 'verb': r"(?P<code>\\verb(?P<del>.).*?(?P=del))",
534 'lilypond-file': r'(?m)^[^%\n]*?(?P<match>\\lilypondfile\s*(\[(?P<options>.*?)\])?\s*\{(?P<filename>.+)})',
535 'lilypond' : r'(?m)^[^%\n]*?(?P<match>\\lilypond\s*(\[(?P<options>.*?)\])?\s*{(?P<code>.*?)})',
536 'lilypond-block': r"(?sm)^[^%\n]*?(?P<match>\\begin\s*(\[(?P<options>.*?)\])?\s*{lilypond}(?P<code>.*?)\\end{lilypond})",
537 'def-post-re': r"\\def\\postLilypondExample",
538 'def-pre-re': r"\\def\\preLilypondExample",
539 'usepackage-graphics': r"\usepackage\s*{graphics}",
540 'intertext': r',?\s*intertext=\".*?\"',
541 'multiline-comment': no_match,
542 'singleline-comment': r"(?m)^.*?(?P<match>(?P<code>^%.*$\n+))",
543 'numcols': r"(?P<code>\\(?P<num>one|two)column)",
544 'multicols': r"(?P<code>\\(?P<be>begin|end)\s*{multicols}({(?P<num>\d+)?})?)",
549 # why do we have distinction between @mbinclude and @include?
552 'include': '(?m)^[^%\n]*?(?P<match>@mbinclude[ \n\t]+(?P<filename>[^\t \n]*))',
555 'preamble-end': no_match,
556 'landscape': no_match,
557 'verbatim': r'''(?s)(?P<code>@example\s.*?@end example\s)''',
558 'verb': r'''(?P<code>@code{.*?})''',
559 'lilypond-file': '(?m)^(?P<match>@lilypondfile(\[(?P<options>[^]]*)\])?{(?P<filename>[^}]+)})',
560 'lilypond' : '(?m)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?{(?P<code>.*?)})',
561 'lilypond-block': r'''(?ms)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?\s(?P<code>.*?)@end lilypond)\s''',
562 'option-sep' : ',\s*',
563 'intertext': r',?\s*intertext=\".*?\"',
564 'multiline-comment': r"(?sm)^\s*(?!@c\s+)(?P<code>@ignore\s.*?@end ignore)\s",
565 'singleline-comment': r"(?m)^.*?(?P<match>(?P<code>@c.*$\n+))",
567 'multicols': no_match,
573 for r in re_dict.keys ():
576 for k in olddict.keys ():
578 newdict[k] = re.compile (olddict[k])
580 print 'invalid regexp: %s' % olddict[k]
582 ## we'd like to catch and reraise a more
583 ## detailed error, but alas, the exceptions
584 ## changed across the 1.5/2.1 boundary.
600 def get_output (name):
601 return output_dict[format][name]
604 return re_dict[format][name]
606 def bounding_box_dimensions (fname):
608 fname = os.path.join (g_outdir, fname)
612 error ("Error opening `%s'" % fname)
614 s = re.search ('%%BoundingBox: ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)', str)
617 gs = map (lambda x: string.atoi (x), s.groups ())
618 return (int (gs[2] - gs[0] + 0.5),
619 int (gs[3] - gs[1] + 0.5))
624 sys.stderr.write ("\n\n" + str + "\nExiting ... \n\n")
628 def compose_full_body (body, opts):
629 '''Construct the lilypond code to send to Lilypond.
630 Add stuff to BODY using OPTS as options.'''
631 music_size = default_music_fontsize
632 if g_force_music_fontsize:
633 music_size = g_force_music_fontsize
638 if not g_force_music_fontsize:
639 m = re.match ('([0-9]+)pt', o)
641 music_size = string.atoi (m.group (1))
643 m = re.match ('indent=([-.0-9]+)(cm|in|mm|pt)', o)
645 f = float (m.group (1))
646 indent = 'indent = %f\\%s' % (f, m.group (2))
648 m = re.match ('linewidth=([-.0-9]+)(cm|in|mm|pt)', o)
650 f = float (m.group (1))
651 linewidth = 'linewidth = %f\\%s' % (f, m.group (2))
653 if re.search ('\\\\score', body):
657 if 'fragment' in opts:
659 if 'nofragment' in opts:
662 if is_fragment and not 'multiline' in opts:
663 opts.append ('singleline')
665 if 'singleline' in opts:
667 linewidth = 'raggedright = ##t'
669 indent = 'indent = 0.0\mm'
672 l = paperguru.get_linewidth ()
673 linewidth = 'linewidth = %f\pt' % l
675 if 'noindent' in opts:
676 indent = 'indent = 0.0\mm'
682 \remove Time_signature_engraver
687 m= re.search ('relative(.*)', o)
691 v = string.atoi (m.group (1))
698 pitch = pitch + '\,' * v
700 pitch = pitch + '\'' * v
702 body = '\\relative %s { %s }' % (pitch, body)
714 optstring = string.join (opts, ' ')
715 optstring = re.sub ('\n', ' ', optstring)
717 %% Generated automatically by: lilypond-book.py
719 \include "paper%d.ly"
725 ''' % (optstring, music_size, linewidth, indent, notime) + body
727 # ughUGH not original options
730 def scan_html_preamble (chunks):
733 def scan_latex_preamble (chunks):
734 # First we want to scan the \documentclass line
735 # it should be the first non-comment line.
736 # The only thing we really need to know about the \documentclass line
737 # is if there are one or two columns to begin with.
740 if chunks[idx][0] == 'ignore':
743 m = get_re ('header').match (chunks[idx][1])
745 error ("Latex documents must start with a \documentclass command")
747 options = re.split (',[\n \t]*', m.group (1)[1:-1])
750 if 'twocolumn' in options:
751 paperguru.m_num_cols = 2
755 # Then we add everything before \begin{document} to
756 # paperguru.m_document_preamble so that we can later write this header
757 # to a temporary file in find_latex_dims() to find textwidth.
758 while idx < len (chunks) and chunks[idx][0] != 'preamble-end':
759 if chunks[idx] == 'ignore':
762 paperguru.m_document_preamble.append (chunks[idx][1])
765 if len (chunks) == idx:
766 error ("Didn't find end of preamble (\\begin{document})")
768 paperguru.find_latex_dims ()
770 def scan_texi_preamble (chunks):
771 # this is not bulletproof..., it checks the first 10 chunks
772 for c in chunks[:10]:
774 for s in ('afourpaper', 'afourwide', 'letterpaper',
775 'afourlatex', 'smallbook'):
776 if string.find (c[1], "@%s" % s) != -1:
777 paperguru.m_papersize = s
780 def scan_preamble (chunks):
783 scan_html_preamble (chunks)
784 elif format == 'latex':
785 scan_latex_preamble (chunks)
786 elif format == 'texi':
787 scan_texi_preamble (chunks)
790 def completize_preamble (chunks):
792 if format != 'latex':
794 pre_b = post_b = graphics_b = None
796 if chunk[0] == 'preamble-end':
798 if chunk[0] == 'input':
799 m = get_re ('def-pre-re').search (chunk[1])
802 if chunk[0] == 'input':
803 m = get_re ('def-post-re').search (chunk[1])
807 if chunk[0] == 'input':
808 m = get_re ('usepackage-graphics').search (chunk[1])
812 while x < len (chunks) and chunks[x][0] != 'preamble-end':
815 if x == len (chunks):
819 chunks.insert (x, ('input', get_output ('output-default-pre')))
821 chunks.insert (x, ('input', get_output ('output-default-post')))
823 chunks.insert (x, ('input', get_output ('usepackage-graphics')))
829 def find_file (name):
831 Search the include path for NAME. If found, return the (CONTENTS, PATH) of the file.
835 return (sys.stdin.read (), '<stdin>')
838 for a in include_path:
840 nm = os.path.join (a, name)
843 read_files.append (nm)
848 sys.stderr.write ("Reading `%s'\n" % nm)
849 return (f.read (), nm)
851 error ("File not found `%s'\n" % name)
854 def do_ignore (match_object):
855 return [('ignore', match_object.group ('code'))]
856 def do_preamble_end (match_object):
857 return [('preamble-end', match_object.group ('code'))]
859 def make_verbatim (match_object):
860 return [('verbatim', match_object.group ('code'))]
862 def make_verb (match_object):
863 return [('verb', match_object.group ('code'))]
865 def do_include_file (m):
867 return [('input', get_output ('pagebreak'))] \
868 + read_doc_file (m.group ('filename')) \
869 + [('input', get_output ('pagebreak'))]
871 def do_input_file (m):
872 return read_doc_file (m.group ('filename'))
874 def make_lilypond (m):
875 if m.group ('options'):
876 options = m.group ('options')
879 return [('input', get_output ('output-lilypond-fragment') %
880 (options, m.group ('code')))]
882 def make_lilypond_file (m):
885 Find @lilypondfile{bla.ly} occurences and substitute bla.ly
886 into a @lilypond .. @end lilypond block.
890 if m.group ('options'):
891 options = get_re ('option-sep').split (m.group ('options'))
894 (content, nm) = find_file (m.group ('filename'))
895 options.append ("filename=%s" % nm)
897 return [('lilypond', content, options)]
899 def make_ly2dvi_block (m):
902 Find <ly2dvifile .. >
905 return [('ly2dvi', m.group ('filename'), m.group ('options'))]
908 def make_lilypond_block (m):
912 if m.group ('options'):
913 options = get_re ('option-sep').split (m.group ('options'))
916 options = filter (lambda s: s != '', options)
917 return [('lilypond', m.group ('code'), options)]
922 if format != 'latex':
924 if m.group ('num') == 'one':
925 return [('numcols', m.group ('code'), 1)]
926 if m.group ('num') == 'two':
927 return [('numcols', m.group ('code'), 2)]
929 def do_multicols (m):
931 if format != 'latex':
933 if m.group ('be') == 'begin':
934 return [('multicols', m.group ('code'), int (m.group ('num')))]
936 return [('multicols', m.group ('code'), 1)]
939 def chop_chunks (chunks, re_name, func, use_match=0):
945 m = get_re (re_name).search (str)
947 newchunks.append (('input', str))
951 newchunks.append (('input', str[:m.start ('match')]))
953 newchunks.append (('input', str[:m.start (0)]))
954 #newchunks.extend (func (m))
955 # python 1.5 compatible:
956 newchunks = newchunks + func (m)
957 str = str [m.end (0):]
962 def determine_format (str):
965 html = re.search ('(?i)<[dh]tml', str[:200])
966 latex = re.search (r'''\\document''', str[:200])
967 texi = re.search ('@node|@setfilename', str[:200])
972 if html and not latex and not texi:
974 elif latex and not html and not texi:
976 elif texi and not html and not latex:
979 error ("can't determine format, please specify")
983 if paperguru == None:
986 elif format == 'latex':
988 elif format == 'texi':
994 def read_doc_file (filename):
995 '''Read the input file, find verbatim chunks and do \input and \include
997 (str, path) = find_file (filename)
998 determine_format (str)
1000 chunks = [('input', str)]
1002 # we have to check for verbatim before doing include,
1003 # because we don't want to include files that are mentioned
1004 # inside a verbatim environment
1005 chunks = chop_chunks (chunks, 'verbatim', make_verbatim)
1007 chunks = chop_chunks (chunks, 'verb', make_verb)
1008 chunks = chop_chunks (chunks, 'multiline-comment', do_ignore)
1010 chunks = chop_chunks (chunks, 'include', do_include_file, 1)
1011 chunks = chop_chunks (chunks, 'input', do_input_file, 1)
1015 taken_file_names = {}
1017 def unique_file_name (body):
1018 return 'lily-' + `abs (hash (body))`
1020 def schedule_lilypond_block (chunk):
1021 '''Take the body and options from CHUNK, figure out how the
1022 real .ly should look, and what should be left MAIN_STR (meant
1023 for the main file). The .ly is written, and scheduled in
1026 Return: a chunk (TYPE_STR, MAIN_STR, OPTIONS, TODO, BASE)
1028 TODO has format [basename, extension, extension, ... ]
1030 (type, body, opts) = chunk
1031 assert type == 'lilypond'
1032 file_body = compose_full_body (body, opts)
1033 ## Hmm, we should hash only lilypond source, and skip the
1036 basename = unique_file_name (file_body)
1038 m = re.search ('filename="(.*?)"', o)
1040 basename = m.group (1)
1041 if not taken_file_names.has_key (basename):
1042 taken_file_names[basename] = 0
1044 taken_file_names[basename] = taken_file_names[basename] + 1
1045 basename = basename + "-%i" % taken_file_names[basename]
1047 update_file (file_body, os.path.join (g_outdir, basename) + '.ly')
1048 needed_filetypes = ['tex']
1050 if format == 'html' or g_make_html:
1051 needed_filetypes.append ('eps')
1052 needed_filetypes.append ('png')
1053 if 'eps' in opts and not ('eps' in needed_filetypes):
1054 needed_filetypes.append ('eps')
1056 pathbase = os.path.join (g_outdir, basename)
1057 def f (base, ext1, ext2):
1058 a = os.path.isfile (base + ext2)
1059 if (os.path.isfile (base + ext1) and
1060 os.path.isfile (base + ext2) and
1061 os.stat (base+ext1)[stat.ST_MTIME] >
1062 os.stat (base+ext2)[stat.ST_MTIME]) or \
1063 not os.path.isfile (base + ext2):
1066 if 'tex' in needed_filetypes and f (pathbase, '.ly', '.tex'):
1068 if 'eps' in needed_filetypes and f (pathbase, '.tex', '.eps'):
1070 if 'png' in needed_filetypes and f (pathbase, '.eps', '.png'):
1074 if 'printfilename' in opts:
1076 m= re.match ("filename=(.*)", o)
1078 newbody = newbody + get_output ("output-filename") % (m.group (1), basename + '.ly', m.group (1))
1082 if 'smallverbatim' in opts:
1083 newbody = newbody + output_verbatim (body, 1)
1084 elif 'verbatim' in opts:
1085 newbody = newbody + output_verbatim (body, 0)
1088 m = re.search ('intertext="(.*?)"', o)
1090 newbody = newbody + "\n"
1091 if format == 'texi':
1092 newbody = newbody + "@noindent\n"
1093 elif format == 'latex':
1094 newbody = newbody + "\\noindent\n"
1095 newbody = newbody + m.group (1) + "\n"
1097 if 'noinline' in opts:
1098 s = 'output-noinline'
1099 elif format == 'latex':
1104 s = 'output-latex-quoted'
1106 s = 'output-latex-noquote'
1107 elif format == 'texi':
1109 s = 'output-texi-quoted'
1111 s = 'output-texi-noquote'
1112 else: # format == 'html'
1114 newbody = newbody + get_output (s) % {'fn': basename }
1115 return ('lilypond', newbody, opts, todo, basename)
1120 def process_lilypond_blocks (chunks):#ugh rename
1122 # Count sections/chapters.
1124 if c[0] == 'lilypond':
1125 c = schedule_lilypond_block (c)
1126 elif c[0] == 'numcols':
1127 paperguru.m_num_cols = c[2]
1128 elif c[0] == 'multicols':
1129 paperguru.m_multicols = c[2]
1130 newchunks.append (c)
1133 def process_ly2dvi_blocks (chunks):
1135 def process_ly2dvi_block (chunk):
1138 Run ly2dvi script on filename specified in CHUNK.
1139 This is only supported for HTML output.
1141 In HTML output it will leave a download menu with ps/pdf/midi etc. in
1142 a separate HTML file, and a title + preview in the main html file,
1143 linking to the menu.
1146 (tag, name, opts) = chunk
1147 assert format == 'html'
1148 (content, original_name) = find_file (name)
1150 original_name = os.path.basename (original_name)
1152 base = unique_file_name (content)
1153 outname = base + '.ly'
1154 changed = update_file (content, outname)
1156 preview = base + ".png"
1157 if changed or not os.path.isfile (preview):
1159 ly.system ('%s --preview --postscript --verbose %s ' % (ly2dvi_binary, base) )
1161 ly.make_page_images (base)
1162 ly.system ('gzip -9 - < %s.ps > %s.ps.gz' % (base, base))
1165 b = os.stat(fn)[stat.ST_SIZE]
1167 return '%d bytes' % b
1169 return '%d kb' % (b >> 10)
1171 return '%d mb' % (b >> 20)
1174 'pdf' : "Print (PDF, %s)",
1175 'ps.gz' : "Print (gzipped PostScript, %s)",
1176 'png' : "View (PNG, %s)",
1177 'midi' : "Listen (MIDI, %s)",
1178 'ly' : "View source code (%s)",
1182 page_files = glob.glob ('%s-page*.png' % base)
1184 for p in string.split (page_files, '\n'):
1186 if os.path.isfile (p):
1188 page = re.sub ('.*page([0-9])+.*', 'View page \\1 (PNG picture, %s)\n', p)
1190 menu += '<li><a href="%s">%s</a>' % (p, page)
1192 ext_order = ['ly', 'pdf', 'ps.gz', 'midi']
1195 print 'checking,' , fn
1196 if not os.path.isfile (fn):
1199 entry = exts[e] % size_str (fn)
1201 ## TODO: do something like
1202 ## this for texinfo/latex as well ?
1204 menu += '<li><a href="%s">%s</a>\n\n' % (fn, entry)
1207 explanatory_para = """The pictures are 90dpi
1208 anti-aliased snapshots of the printed output, in PNG format. Both PDF and PS
1209 use scalable fonts and should look OK at any resolution."""
1212 <title>LilyPond example %s</title>
1218 <ul>%s</ul>''' % (original_name,original_name, preview, explanatory_para, menu)
1220 open (base + '.html','w'). write (separate_menu)
1222 inline_menu = '<p/><a href="%s.html"><img src="%s"><p/></a>' % (base, original_name, preview)
1224 return ('ly2dvi', inline_menu)
1228 if c[0] == 'ly2dvi':
1229 c = process_ly2dvi_block (c)
1230 newchunks.append (c)
1234 def compile_all_files (chunks):
1241 if c[0] != 'lilypond':
1250 if base + '.ly' not in tex:
1251 tex.append (base + '.ly')
1252 elif e == 'png' and g_do_pictures:
1258 # fixme: be sys-independent.
1260 if g_outdir and x[0] != '/' :
1261 x = os.path.join (g_here_dir, x)
1264 incs = map (incl_opt, include_path)
1265 lilyopts = string.join (incs)
1267 lilyopts += ' --dependencies'
1269 lilyopts += ' --dep-prefix=' + g_outdir + '/'
1270 lilyopts += ' --header=texidoc'
1271 texfiles = string.join (tex)
1272 cmd = string.join ((lilypond_binary, lilyopts, g_extra_opts,
1274 ly.system (cmd, ignore_error = 0, progress_p = 1)
1277 # Ugh, fixing up dependencies for .tex generation
1280 depfiles=map (lambda x: re.sub ('(.*)\.ly', '\\1.dep',
1287 text=re.sub ('\n([^:\n]*):',
1288 '\n' + foutn + ':', text)
1294 cmd = r"latex '\nonstopmode \input %s'" % file
1295 # Ugh. (La)TeX writes progress and error messages on stdout
1296 # Redirect to stderr
1297 cmd += ' 1>/dev/stderr'
1299 ly.system ("dvips -E -o %s.eps %s" % (file, file))
1302 map (ly.make_preview, png)
1306 def update_file (body, name):
1308 write the body if it has changed. Return whether BODY has changed.
1319 f = open (name , 'w')
1326 def write_deps (fn, target, chunks):
1328 sys.stderr.write ('Writing `%s\'\n' % os.path.join (g_outdir, fn))
1329 f = open (os.path.join (g_outdir, fn), 'w')
1330 f.write ('%s%s: ' % (g_dep_prefix, target))
1331 for d in read_files:
1335 ## There used to be code to write .tex dependencies, but
1336 ## that is silly: lilypond-book has its own dependency scheme
1337 ## to ensure that all lily-XXX.tex files are there
1344 def check_texidoc (chunks):
1347 if c[0] == 'lilypond':
1348 (type, body, opts, todo, basename) = c;
1349 pathbase = os.path.join (g_outdir, basename)
1350 if os.path.isfile (pathbase + '.texidoc') \
1351 and 'notexidoc' not in opts:
1352 body = '\n@include %s.texidoc\n' % basename + body
1353 c = (type, body, opts, todo, basename)
1358 ## what's this? Docme --hwn
1360 def fix_epswidth (chunks):
1363 if c[0] != 'lilypond' or 'eps' not in c[2]:
1364 newchunks.append (c)
1369 m = re.match ('magnification=([0-9.]+)', o)
1371 mag = string.atof (m.group (1))
1373 def replace_eps_dim (match, lmag = mag):
1374 filename = match.group (1)
1375 dims = bounding_box_dimensions (filename)
1377 return '%fpt' % (dims[0] *lmag)
1379 body = re.sub (r'''\\lilypondepswidth{(.*?)}''', replace_eps_dim, c[1])
1380 newchunks.append (('lilypond', body, c[2], c[3], c[4]))
1385 ##docme: why global?
1388 def do_file (input_filename):
1389 chunks = read_doc_file (input_filename)
1390 chunks = chop_chunks (chunks, 'ly2dvi', make_ly2dvi_block, 1)
1391 chunks = chop_chunks (chunks, 'lilypond', make_lilypond, 1)
1392 chunks = chop_chunks (chunks, 'lilypond-file', make_lilypond_file, 1)
1393 chunks = chop_chunks (chunks, 'lilypond-block', make_lilypond_block, 1)
1394 chunks = chop_chunks (chunks, 'singleline-comment', do_ignore, 1)
1395 chunks = chop_chunks (chunks, 'preamble-end', do_preamble_end)
1396 chunks = chop_chunks (chunks, 'numcols', do_columns)
1397 chunks = chop_chunks (chunks, 'multicols', do_multicols)
1399 #for c in chunks: print "c:", c;
1401 scan_preamble (chunks)
1402 chunks = process_lilypond_blocks (chunks)
1403 chunks = process_ly2dvi_blocks (chunks)
1406 global g_run_lilypond
1408 compile_all_files (chunks)
1409 chunks = fix_epswidth (chunks)
1412 if format == 'texi':
1413 chunks = check_texidoc (chunks)
1416 chunks = completize_preamble (chunks)
1421 my_outname = outname
1422 elif input_filename == '-' or input_filename == "/dev/stdin":
1425 my_outname = os.path.basename (os.path.splitext (input_filename)[0]) + '.' + format
1426 my_depname = my_outname + '.dep'
1428 if my_outname == '-' or my_outname == '/dev/stdout':
1434 foutn = os.path.join (g_outdir, my_outname)
1435 sys.stderr.write ("Writing `%s'\n" % foutn)
1436 fout = open (foutn, 'w')
1443 write_deps (my_depname, foutn, chunks)
1447 (sh, long) = ly.getopt_args (option_definitions)
1448 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1450 except getopt.error, msg:
1451 sys.stderr.write ('\n')
1452 ly.error (_ ("getopt says: `%s\'" % s))
1453 sys.stderr.write ('\n')
1462 if o == '--include' or o == '-I':
1463 include_path.append (a)
1464 elif o == '--version' or o == '-v':
1465 ly.identify (sys.stdout)
1467 elif o == '--verbose' or o == '-V':
1469 elif o == '--format' or o == '-f':
1471 if a == 'texi-html':
1474 elif o == '--outname' or o == '-o':
1477 sys.stderr.write ("Lilypond-book is confused by --outname on multiple files")
1480 elif o == '--help' or o == '-h':
1483 elif o == '--no-lily' or o == '-n':
1485 elif o == '--preview-resolution':
1486 preview_resolution = string.atoi (a)
1487 elif o == '--dependencies' or o == '-M':
1489 elif o == '--default-music-fontsize':
1490 default_music_fontsize = string.atoi (a)
1491 elif o == '--default-lilypond-fontsize':
1492 print "--default-lilypond-fontsize is deprecated, use --default-music-fontsize"
1493 default_music_fontsize = string.atoi (a)
1494 elif o == '--extra-options':
1496 elif o == '--force-music-fontsize':
1497 g_force_music_fontsize = string.atoi (a)
1498 elif o == '--force-lilypond-fontsize':
1499 print "--force-lilypond-fontsize is deprecated, use --default-lilypond-fontsize"
1500 g_force_music_fontsize = string.atoi (a)
1501 elif o == '--dep-prefix':
1503 elif o == '--no-pictures':
1505 elif o == '--no-music':
1507 elif o == '--read-lys':
1509 elif o == '--outdir':
1511 elif o == '--warranty' or o == '-w':
1512 #status = os.system ('lilypond -w')
1517 ly.identify (sys.stderr)
1520 if os.path.isfile (g_outdir):
1521 error ("outdir is a file: %s" % g_outdir)
1522 if not os.path.exists (g_outdir):
1527 ly.error (_ ("no files specified on command line"))
1530 ly.setup_environment ()
1532 for input_filename in files:
1533 do_file (input_filename)
1537 # Petr, ik zou willen dat ik iets zinvoller deed,
1538 # maar wat ik kan ik doen, het verandert toch niets?