3 # file lyxpreview2bitmap.py
4 # This file is part of LyX, the document processor.
5 # Licence details can be found in the file COPYING.
8 # with much advice from members of the preview-latex project:
9 # David Kastrup, dak@gnu.org and
10 # Jan-Åke Larsson, jalar@mai.liu.se.
12 # Full author contact details are available in file CREDITS
14 # This script takes a LaTeX file and generates a collection of
15 # png or ppm image files, one per previewed snippet.
18 # * A latex executable;
21 # * pngtoppm (if outputing ppm format images).
23 # preview.sty and dvipng are part of the preview-latex project
24 # http://preview-latex.sourceforge.net/
26 # preview.sty can alternatively be obtained from
27 # CTAN/support/preview-latex/
30 # lyxpreview2bitmap.py png 0lyxpreview.tex 128 000000 faf0e6
32 # This script takes five arguments:
33 # FORMAT: either 'png' or 'ppm'. The desired output format.
34 # TEXFILE: the name of the .tex file to be converted.
35 # DPI: a scale factor, passed to dvipng.
36 # FG_COLOR: the foreground color as a hexadecimal string, eg '000000'.
37 # BG_COLOR: the background color as a hexadecimal string, eg 'faf0e6'.
39 # Decomposing TEXFILE's name as DIR/BASE.tex, this script will,
40 # if executed successfully, leave in DIR:
41 # * a (possibly large) number of image files with names
43 # * a file BASE.metrics, containing info needed by LyX to position
44 # the images correctly on the screen.
46 import glob, os, re, string, sys
49 # Pre-compiled regular expressions.
50 hexcolor_re = re.compile("^[0-9a-fA-F]{6}$")
51 latex_file_re = re.compile("\.tex$")
55 return "Usage: %s <latex file> <dpi> <fg color> <bg color>\n"\
56 "\twhere the colors are hexadecimal strings, eg 'faf0e6'"\
61 sys.stderr.write(message + '\n')
65 def find_exe(candidates, path):
66 for prog in candidates:
67 for directory in path:
68 full_path = os.path.join(directory, prog)
69 if os.access(full_path, os.X_OK):
75 def find_exe_or_terminate(candidates, path):
76 exe = find_exe(candidates, path)
78 error("Unable to find executable from '%s'" % string.join(candidates))
84 handle = os.popen(cmd, 'r')
85 cmd_stdout = handle.read()
86 cmd_status = handle.close()
88 return cmd_status, cmd_stdout
91 def make_texcolor(hexcolor):
92 # Test that the input string contains 6 hexadecimal chars.
93 if not hexcolor_re.match(hexcolor):
94 error("Cannot convert color '%s'" % hexcolor)
96 red = float(string.atoi(hexcolor[0:2], 16)) / 255.0
97 green = float(string.atoi(hexcolor[2:4], 16)) / 255.0
98 blue = float(string.atoi(hexcolor[4:6], 16)) / 255.0
100 return "rgb %f %f %f" % (red, green, blue)
103 def extract_metrics_info(dvipng_stdout, metrics_file):
104 metrics = open(metrics_file, 'w')
105 metrics_re = re.compile("\[([0-9]+) depth=([0-9]+) height=([0-9]+)\]")
110 match = metrics_re.search(dvipng_stdout, pos)
115 # Calculate the 'ascent fraction'.
116 descent = string.atof(match.group(2))
117 ascent = string.atof(match.group(3))
119 if abs(ascent + descent) > 0.1:
120 frac = ascent / (ascent + descent)
122 metrics.write("Snippet %s %f\n" % (match.group(1), frac))
123 pos = match.end(3) + 2
128 def convert_to_ppm_format(pngtopnm, basename):
129 png_file_re = re.compile("\.png$")
131 for png_file in glob.glob("%s*.png" % basename):
132 ppm_file = png_file_re.sub(".ppm", png_file)
134 p2p_cmd = "%s %s" % (pngtopnm, png_file)
135 p2p_status, p2p_stdout = run_command(p2p_cmd)
136 if p2p_status != None:
137 error("Unable to convert %s to ppm format" % png_file)
139 ppm = open(ppm_file, 'w')
140 ppm.write(p2p_stdout)
145 # Parse and manipulate the command line arguments.
147 error(usage(argv[0]))
149 output_format = string.lower(argv[1])
151 dir, latex_file = os.path.split(argv[2])
155 dpi = string.atoi(argv[3])
156 fg_color = make_texcolor(argv[4])
157 bg_color = make_texcolor(argv[5])
159 # External programs used by the script.
160 path = string.split(os.getenv("PATH"), os.pathsep)
161 latex = find_exe_or_terminate(["pplatex", "latex2e", "latex"], path)
162 dvipng = find_exe_or_terminate(["dvipng"], path)
164 if output_format == "ppm":
165 pngtopnm = find_exe_or_terminate(["pngtopnm"], path)
167 # Compile the latex file.
168 latex_call = "%s %s" % (latex, latex_file)
170 latex_status, latex_stdout = run_command(latex_call)
171 if latex_status != None:
172 error("%s failed to compile %s" \
173 % (os.path.basename(latex), latex_file))
175 # Run the dvi file through dvipng.
176 dvi_file = latex_file_re.sub(".dvi", latex_file)
177 dvipng_call = "%s -Ttight -depth -height -D %d -fg '%s' -bg '%s' %s" \
178 % (dvipng, dpi, fg_color, bg_color, dvi_file)
180 dvipng_status, dvipng_stdout = run_command(dvipng_call)
181 if dvipng_status != None:
182 error("%s failed to generate images from %s" \
183 % (os.path.basename(dvipng), dvi_file))
185 # Extract metrics info from dvipng_stdout.
186 metrics_file = latex_file_re.sub(".metrics", latex_file)
187 if not extract_metrics_info(dvipng_stdout, metrics_file):
188 error("Failed to extract metrics info from dvipng")
190 # Convert images to ppm format if necessary.
191 if output_format == "ppm":
192 convert_to_ppm_format(pngtopnm, latex_file_re.sub("", latex_file))
195 if __name__ == "__main__":