2 # -*- coding: utf-8 -*-
4 # file lyxpreview-lytex2bitmap.py
5 # This file is part of LyX, the document processor.
6 # Licence details can be found in the file COPYING.
9 # with much advice from members of the preview-latex project:
10 # David Kastrup, dak@gnu.org and
11 # Jan-Åke Larsson, jalar@mai.liu.se.
13 # Full author contact details are available in file CREDITS
15 # This script takes a LaTeX file and generates a collection of
16 # png or ppm image files, one per previewed snippet.
19 # * A latex executable;
22 # * pngtoppm (if outputing ppm format images).
24 # preview.sty and dvipng are part of the preview-latex project
25 # http://preview-latex.sourceforge.net/
27 # preview.sty can alternatively be obtained from
28 # CTAN/support/preview-latex/
31 # lyxpreview-lytex2bitmap.py png 0lyxpreview.tex 128 000000 faf0e6
33 # This script takes six arguments:
34 # FORMAT: The desired output format. Either 'png' or 'ppm'.
35 # TEXFILE: the name of the .tex file to be converted.
36 # DPI: a scale factor, used to ascertain the resolution of the
37 # generated image which is then passed to gs.
38 # FG_COLOR: the foreground color as a hexadecimal string, eg '000000'.
39 # BG_COLOR: the background color as a hexadecimal string, eg 'faf0e6'.
40 # CONVERTER: the converter (optional). Default is latex.
42 # Decomposing TEXFILE's name as DIR/BASE.tex, this script will,
43 # if executed successfully, leave in DIR:
44 # * a (possibly large) number of image files with names
46 # * a file BASE.metrics, containing info needed by LyX to position
47 # the images correctly on the screen.
49 import glob, os, re, shutil, string, sys
51 from legacy_lyxpreview2ppm import legacy_conversion, \
52 legacy_conversion_step2
54 from lyxpreview_tools import copyfileobj, error, find_exe, \
55 find_exe_or_terminate, make_texcolor, mkstemp, run_command, warning
58 # Pre-compiled regular expressions.
59 latex_file_re = re.compile("\.tex$")
63 return "Usage: %s <format> <latex file> <dpi> <fg color> <bg color>\n"\
64 "\twhere the colors are hexadecimal strings, eg 'faf0e6'"\
68 def extract_metrics_info(dvipng_stdout, metrics_file):
69 metrics = open(metrics_file, 'w')
70 # "\[[0-9]+" can match two kinds of numbers: page numbers from dvipng
71 # and glyph numbers from mktexpk. The glyph numbers always match
72 # "\[[0-9]+\]" while the page number never is followed by "\]". Thus:
73 page_re = re.compile("\[([0-9]+)[^]]");
74 metrics_re = re.compile("depth=(-?[0-9]+) height=(-?[0-9]+)")
80 match = page_re.search(dvipng_stdout, pos)
85 match = metrics_re.search(dvipng_stdout, pos)
90 # Calculate the 'ascent fraction'.
91 descent = string.atof(match.group(1))
92 ascent = string.atof(match.group(2))
95 if ascent >= 0 or descent >= 0:
96 if abs(ascent + descent) > 0.1:
97 frac = ascent / (ascent + descent)
103 metrics.write("Snippet %s %f\n" % (page, frac))
104 pos = match.end() + 2
109 def color_pdf(latex_file, bg_color):
110 use_preview_pdf_re = re.compile("(\s*\\\\usepackage\[[^]]+)(pdftex\]{preview})")
116 for line in open(latex_file, 'r').readlines():
117 match = use_preview_pdf_re.match(line)
122 tmp.write(" \\usepackage{color}\n" \
123 " \\pagecolor[rgb]{%s}\n" \
125 % (bg_color, match.group()))
129 # Unable to open the file, but do nothing here because
130 # the calling function will act on the value of 'success'.
131 warning('Warning in color_pdf! Unable to open "%s"' % latex_file)
132 warning(`sys.exc_type` + ',' + `sys.exc_value`)
135 copyfileobj(tmp, open(latex_file,"wb"), 1)
140 def convert_to_ppm_format(pngtopnm, basename):
141 png_file_re = re.compile("\.png$")
143 for png_file in glob.glob("%s*.png" % basename):
144 ppm_file = png_file_re.sub(".ppm", png_file)
146 p2p_cmd = '%s "%s"' % (pngtopnm, png_file)
147 p2p_status, p2p_stdout = run_command(p2p_cmd)
148 if p2p_status != None:
149 error("Unable to convert %s to ppm format" % png_file)
151 ppm = open(ppm_file, 'w')
152 ppm.write(p2p_stdout)
157 # Parse and manipulate the command line arguments.
158 if len(argv) != 6 and len(argv) != 7:
159 error(usage(argv[0]))
161 output_format = string.lower(argv[1])
163 dir, latex_file = os.path.split(argv[2])
167 dpi = string.atoi(argv[3])
168 fg_color = make_texcolor(argv[4], False)
169 bg_color = make_texcolor(argv[5], False)
171 bg_color_gr = make_texcolor(argv[5], True)
173 # External programs used by the script.
174 path = string.split(os.environ["PATH"], os.pathsep)
178 latex = find_exe_or_terminate(["latex", "pplatex", "platex", "latex2e"], path)
180 lilypond_book = find_exe_or_terminate(["lilypond-book"], path)
182 # Make a copy of the latex file
183 lytex_file = latex_file_re.sub(".lytex", latex_file)
184 shutil.copyfile(latex_file, lytex_file)
186 # Preprocess the latex file through lilypond-book.
187 lytex_call = '%s --latex-program=%s "%s"' % (lilypond_book, latex, lytex_file)
188 lytex_status, lytex_stdout = run_command(lytex_call)
189 if lytex_status != None:
190 warning("%s failed to compile %s" \
191 % (os.path.basename(lilypond_book), lytex_file))
192 warning(lytex_stdout)
194 # This can go once dvipng becomes widespread.
195 dvipng = find_exe(["dvipng"], path)
197 # The data is input to legacy_conversion in as similar
198 # as possible a manner to that input to the code used in
200 vec = [ argv[0], argv[2], argv[3], argv[1], argv[4], argv[5], latex ]
201 return legacy_conversion(vec)
204 if output_format == "ppm":
205 pngtopnm = find_exe_or_terminate(["pngtopnm"], path)
207 # Move color information for PDF into the latex file.
208 if not color_pdf(latex_file, bg_color_gr):
209 error("Unable to move color info into the latex file")
211 # Compile the latex file.
212 latex_call = '%s "%s"' % (latex, latex_file)
214 latex_status, latex_stdout = run_command(latex_call)
215 if latex_status != None:
216 warning("%s failed to compile %s" \
217 % (os.path.basename(latex), latex_file))
218 warning(latex_stdout)
220 if latex == "xelatex":
221 warning("Using XeTeX")
222 # FIXME: skip unnecessary dvips trial in legacy_conversion_step2
223 return legacy_conversion_step2(latex_file, dpi, output_format)
225 # Run the dvi file through dvipng.
226 dvi_file = latex_file_re.sub(".dvi", latex_file)
227 dvipng_call = '%s -Ttight -depth -height -D %d -fg "%s" -bg "%s" "%s"' \
228 % (dvipng, dpi, fg_color, bg_color, dvi_file)
230 dvipng_status, dvipng_stdout = run_command(dvipng_call)
231 if dvipng_status != None:
232 warning("%s failed to generate images from %s ... looking for PDF" \
233 % (os.path.basename(dvipng), dvi_file))
234 # FIXME: skip unnecessary dvips trial in legacy_conversion_step2
235 return legacy_conversion_step2(latex_file, dpi, output_format)
237 # Extract metrics info from dvipng_stdout.
238 metrics_file = latex_file_re.sub(".metrics", latex_file)
239 if not extract_metrics_info(dvipng_stdout, metrics_file):
240 error("Failed to extract metrics info from dvipng")
242 # Convert images to ppm format if necessary.
243 if output_format == "ppm":
244 convert_to_ppm_format(pngtopnm, latex_file_re.sub("", latex_file))
249 if __name__ == "__main__":