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:
70 full_path = os.path.join(directory, prog)
71 if os.access(full_path, os.X_OK):
77 def find_exe_or_terminate(candidates, path):
78 exe = find_exe(candidates, path)
80 error("Unable to find executable from '%s'" % string.join(candidates))
86 handle = os.popen(cmd, 'r')
87 cmd_stdout = handle.read()
88 cmd_status = handle.close()
90 return cmd_status, cmd_stdout
93 def make_texcolor(hexcolor):
94 # Test that the input string contains 6 hexadecimal chars.
95 if not hexcolor_re.match(hexcolor):
96 error("Cannot convert color '%s'" % hexcolor)
98 red = float(string.atoi(hexcolor[0:2], 16)) / 255.0
99 green = float(string.atoi(hexcolor[2:4], 16)) / 255.0
100 blue = float(string.atoi(hexcolor[4:6], 16)) / 255.0
102 return "rgb %f %f %f" % (red, green, blue)
105 def extract_metrics_info(dvipng_stdout, metrics_file):
106 metrics = open(metrics_file, 'w')
107 metrics_re = re.compile("\[([0-9]+) depth=(-?[0-9]+) height=(-?[0-9]+)")
112 match = metrics_re.search(dvipng_stdout, pos)
117 # Calculate the 'ascent fraction'.
118 descent = string.atof(match.group(2))
119 ascent = string.atof(match.group(3))
121 if abs(ascent + descent) > 0.1:
122 frac = ascent / (ascent + descent)
124 metrics.write("Snippet %s %f\n" % (match.group(1), frac))
125 pos = match.end(3) + 2
130 def convert_to_ppm_format(pngtopnm, basename):
131 png_file_re = re.compile("\.png$")
133 for png_file in glob.glob("%s*.png" % basename):
134 ppm_file = png_file_re.sub(".ppm", png_file)
136 p2p_cmd = "%s %s" % (pngtopnm, png_file)
137 p2p_status, p2p_stdout = run_command(p2p_cmd)
138 if p2p_status != None:
139 error("Unable to convert %s to ppm format" % png_file)
141 ppm = open(ppm_file, 'w')
142 ppm.write(p2p_stdout)
147 # Parse and manipulate the command line arguments.
149 error(usage(argv[0]))
151 output_format = string.lower(argv[1])
153 dir, latex_file = os.path.split(argv[2])
157 dpi = string.atoi(argv[3])
158 fg_color = make_texcolor(argv[4])
159 bg_color = make_texcolor(argv[5])
161 # External programs used by the script.
162 path = string.split(os.getenv("PATH"), os.pathsep)
163 latex = find_exe_or_terminate(["pplatex", "latex2e", "latex"], path)
165 # This can go once dvipng becomes widespread.
166 dvipng = find_exe(["dvipng"], path)
168 if output_format == "ppm":
169 return legacy_conversion(argv)
171 error("The old 'dvi->ps->ppm' conversion requires "
172 "ppm as the output format")
175 if output_format == "ppm":
176 pngtopnm = find_exe_or_terminate(["pngtopnm"], path)
178 # Compile the latex file.
179 latex_call = "%s %s" % (latex, latex_file)
181 latex_status, latex_stdout = run_command(latex_call)
182 if latex_status != None:
183 error("%s failed to compile %s" \
184 % (os.path.basename(latex), latex_file))
186 # Run the dvi file through dvipng.
187 dvi_file = latex_file_re.sub(".dvi", latex_file)
188 dvipng_call = "%s -Ttight -depth -height -D %d -fg '%s' -bg '%s' %s" \
189 % (dvipng, dpi, fg_color, bg_color, dvi_file)
191 dvipng_status, dvipng_stdout = run_command(dvipng_call)
192 if dvipng_status != None:
193 error("%s failed to generate images from %s" \
194 % (os.path.basename(dvipng), dvi_file))
196 # Extract metrics info from dvipng_stdout.
197 metrics_file = latex_file_re.sub(".metrics", latex_file)
198 if not extract_metrics_info(dvipng_stdout, metrics_file):
199 error("Failed to extract metrics info from dvipng")
201 # Convert images to ppm format if necessary.
202 if output_format == "ppm":
203 convert_to_ppm_format(pngtopnm, latex_file_re.sub("", latex_file))
207 if __name__ == "__main__":