2 # -*- coding: iso-8859-1 -*-
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 five arguments:
34 # FORMAT: either 'png' or 'ppm'. The desired output format.
35 # TEXFILE: the name of the .tex file to be converted.
36 # DPI: a scale factor, passed to dvipng.
37 # FG_COLOR: the foreground color as a hexadecimal string, eg '000000'.
38 # BG_COLOR: the background color as a hexadecimal string, eg 'faf0e6'.
40 # Decomposing TEXFILE's name as DIR/BASE.tex, this script will,
41 # if executed successfully, leave in DIR:
42 # * a (possibly large) number of image files with names
44 # * a file BASE.metrics, containing info needed by LyX to position
45 # the images correctly on the screen.
47 import glob, os, re, string, sys
48 from legacy_lyxpreview2ppm import legacy_conversion
51 # Pre-compiled regular expressions.
52 hexcolor_re = re.compile("^[0-9a-fA-F]{6}$")
53 latex_file_re = re.compile("\.tex$")
57 return "Usage: %s <latex file> <dpi> <fg color> <bg color>\n"\
58 "\twhere the colors are hexadecimal strings, eg 'faf0e6'"\
63 sys.stderr.write(message + '\n')
67 def find_exe(candidates, path):
68 for prog in candidates:
69 for directory in path:
71 full_path = os.path.join(directory, prog + ".exe")
73 full_path = os.path.join(directory, prog)
75 if os.access(full_path, os.X_OK):
81 def find_exe_or_terminate(candidates, path):
82 exe = find_exe(candidates, path)
84 error("Unable to find executable from '%s'" % string.join(candidates))
90 handle = os.popen(cmd, 'r')
91 cmd_stdout = handle.read()
92 cmd_status = handle.close()
94 return cmd_status, cmd_stdout
97 def make_texcolor(hexcolor):
98 # Test that the input string contains 6 hexadecimal chars.
99 if not hexcolor_re.match(hexcolor):
100 error("Cannot convert color '%s'" % hexcolor)
102 red = float(string.atoi(hexcolor[0:2], 16)) / 255.0
103 green = float(string.atoi(hexcolor[2:4], 16)) / 255.0
104 blue = float(string.atoi(hexcolor[4:6], 16)) / 255.0
106 return "rgb %f %f %f" % (red, green, blue)
109 def extract_metrics_info(dvipng_stdout, metrics_file):
110 metrics = open(metrics_file, 'w')
111 metrics_re = re.compile("\[([0-9]+) depth=(-?[0-9]+) height=(-?[0-9]+)")
116 match = metrics_re.search(dvipng_stdout, pos)
121 # Calculate the 'ascent fraction'.
122 descent = string.atof(match.group(2))
123 ascent = string.atof(match.group(3))
125 if abs(ascent + descent) > 0.1:
126 frac = ascent / (ascent + descent)
128 metrics.write("Snippet %s %f\n" % (match.group(1), frac))
129 pos = match.end(3) + 2
134 def convert_to_ppm_format(pngtopnm, basename):
135 png_file_re = re.compile("\.png$")
137 for png_file in glob.glob("%s*.png" % basename):
138 ppm_file = png_file_re.sub(".ppm", png_file)
140 p2p_cmd = "%s %s" % (pngtopnm, png_file)
141 p2p_status, p2p_stdout = run_command(p2p_cmd)
142 if p2p_status != None:
143 error("Unable to convert %s to ppm format" % png_file)
145 ppm = open(ppm_file, 'w')
146 ppm.write(p2p_stdout)
151 # Parse and manipulate the command line arguments.
153 error(usage(argv[0]))
155 output_format = string.lower(argv[1])
157 dir, latex_file = os.path.split(argv[2])
161 dpi = string.atoi(argv[3])
162 fg_color = make_texcolor(argv[4])
163 bg_color = make_texcolor(argv[5])
165 # External programs used by the script.
166 path = string.split(os.getenv("PATH"), os.pathsep)
167 latex = find_exe_or_terminate(["pplatex", "latex2e", "latex"], path)
169 # This can go once dvipng becomes widespread.
170 dvipng = find_exe(["dvipng"], path)
172 if output_format == "ppm":
173 return legacy_conversion(argv)
175 error("The old 'dvi->ps->ppm' conversion requires "
176 "ppm as the output format")
179 if output_format == "ppm":
180 pngtopnm = find_exe_or_terminate(["pngtopnm"], path)
182 # Compile the latex file.
183 latex_call = "%s %s" % (latex, latex_file)
185 latex_status, latex_stdout = run_command(latex_call)
186 if latex_status != None:
187 error("%s failed to compile %s" \
188 % (os.path.basename(latex), latex_file))
190 # Run the dvi file through dvipng.
191 dvi_file = latex_file_re.sub(".dvi", latex_file)
192 dvipng_call = "%s -Ttight -depth -height -D %d -fg '%s' -bg '%s' %s" \
193 % (dvipng, dpi, fg_color, bg_color, dvi_file)
195 dvipng_status, dvipng_stdout = run_command(dvipng_call)
196 if dvipng_status != None:
197 error("%s failed to generate images from %s" \
198 % (os.path.basename(dvipng), dvi_file))
200 # Extract metrics info from dvipng_stdout.
201 metrics_file = latex_file_re.sub(".metrics", latex_file)
202 if not extract_metrics_info(dvipng_stdout, metrics_file):
203 error("Failed to extract metrics info from dvipng")
205 # Convert images to ppm format if necessary.
206 if output_format == "ppm":
207 convert_to_ppm_format(pngtopnm, latex_file_re.sub("", latex_file))
211 if __name__ == "__main__":