2 # -*- coding: utf-8 -*-
4 # file lyxpreview2bitmap.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 # lyxpreview2bitmap.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, 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 # This can go once dvipng becomes widespread.
181 dvipng = find_exe(["dvipng"], path)
183 # The data is input to legacy_conversion in as similar
184 # as possible a manner to that input to the code used in
186 vec = [ argv[0], argv[2], argv[3], argv[1], argv[4], argv[5], latex ]
187 return legacy_conversion(vec)
190 if output_format == "ppm":
191 pngtopnm = find_exe_or_terminate(["pngtopnm"], path)
193 # Move color information for PDF into the latex file.
194 if not color_pdf(latex_file, bg_color_gr):
195 error("Unable to move color info into the latex file")
197 # Compile the latex file.
198 latex_call = '%s "%s"' % (latex, latex_file)
200 latex_status, latex_stdout = run_command(latex_call)
201 if latex_status != None:
202 warning("%s failed to compile %s" \
203 % (os.path.basename(latex), latex_file))
205 if latex == "xelatex":
206 warning("Using XeTeX")
207 # FIXME: skip unnecessary dvips trial in legacy_conversion_step2
208 return legacy_conversion_step2(latex_file, dpi, output_format)
210 # Run the dvi file through dvipng.
211 dvi_file = latex_file_re.sub(".dvi", latex_file)
212 dvipng_call = '%s -Ttight -depth -height -D %d -fg "%s" -bg "%s" "%s"' \
213 % (dvipng, dpi, fg_color, bg_color, dvi_file)
215 dvipng_status, dvipng_stdout = run_command(dvipng_call)
216 if dvipng_status != None:
217 warning("%s failed to generate images from %s ... looking for PDF" \
218 % (os.path.basename(dvipng), dvi_file))
219 # FIXME: skip unnecessary dvips trial in legacy_conversion_step2
220 return legacy_conversion_step2(latex_file, dpi, output_format)
222 # Extract metrics info from dvipng_stdout.
223 metrics_file = latex_file_re.sub(".metrics", latex_file)
224 if not extract_metrics_info(dvipng_stdout, metrics_file):
225 error("Failed to extract metrics info from dvipng")
227 # Convert images to ppm format if necessary.
228 if output_format == "ppm":
229 convert_to_ppm_format(pngtopnm, latex_file_re.sub("", latex_file))
234 if __name__ == "__main__":