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, legacy_extract_metrics_info
54 from lyxpreview_tools import copyfileobj, error, find_exe, \
55 find_exe_or_terminate, make_texcolor, mkstemp, run_command, warning, \
59 # Pre-compiled regular expressions.
60 latex_file_re = re.compile("\.tex$")
64 return "Usage: %s <format> <latex file> <dpi> <fg color> <bg color>\n"\
65 "\twhere the colors are hexadecimal strings, eg 'faf0e6'"\
68 # Returns a list of tuples containing page number and ascent fraction
69 # extracted from dvipng output.
70 # Use write_metrics_info to create the .metrics file with this info
71 def extract_metrics_info(dvipng_stdout):
72 # "\[[0-9]+" can match two kinds of numbers: page numbers from dvipng
73 # and glyph numbers from mktexpk. The glyph numbers always match
74 # "\[[0-9]+\]" while the page number never is followed by "\]". Thus:
75 page_re = re.compile("\[([0-9]+)[^]]");
76 metrics_re = re.compile("depth=(-?[0-9]+) height=(-?[0-9]+)")
83 match = page_re.search(dvipng_stdout, pos)
88 match = metrics_re.search(dvipng_stdout, pos)
93 # Calculate the 'ascent fraction'.
94 descent = string.atof(match.group(1))
95 ascent = string.atof(match.group(2))
98 if ascent >= 0 or descent >= 0:
99 if abs(ascent + descent) > 0.1:
100 frac = ascent / (ascent + descent)
106 results.append((page, frac))
107 pos = match.end() + 2
110 error("Failed to extract metrics info from dvipng")
115 def color_pdf(latex_file, bg_color):
116 use_preview_pdf_re = re.compile("(\s*\\\\usepackage\[[^]]+)(pdftex\]{preview})")
122 for line in open(latex_file, 'r').readlines():
123 match = use_preview_pdf_re.match(line)
128 tmp.write(" \\usepackage{color}\n" \
129 " \\pagecolor[rgb]{%s}\n" \
131 % (bg_color, match.group()))
135 # Unable to open the file, but do nothing here because
136 # the calling function will act on the value of 'success'.
137 warning('Warning in color_pdf! Unable to open "%s"' % latex_file)
138 warning(`sys.exc_type` + ',' + `sys.exc_value`)
141 copyfileobj(tmp, open(latex_file,"wb"), 1)
146 def convert_to_ppm_format(pngtopnm, basename):
147 png_file_re = re.compile("\.png$")
149 for png_file in glob.glob("%s*.png" % basename):
150 ppm_file = png_file_re.sub(".ppm", png_file)
152 p2p_cmd = '%s "%s"' % (pngtopnm, png_file)
153 p2p_status, p2p_stdout = run_command(p2p_cmd)
154 if p2p_status != None:
155 error("Unable to convert %s to ppm format" % png_file)
157 ppm = open(ppm_file, 'w')
158 ppm.write(p2p_stdout)
163 # Parse and manipulate the command line arguments.
164 if len(argv) != 6 and len(argv) != 7:
165 error(usage(argv[0]))
167 output_format = string.lower(argv[1])
169 dir, latex_file = os.path.split(argv[2])
173 dpi = string.atoi(argv[3])
174 fg_color = make_texcolor(argv[4], False)
175 bg_color = make_texcolor(argv[5], False)
177 bg_color_gr = make_texcolor(argv[5], True)
179 # External programs used by the script.
180 path = string.split(os.environ["PATH"], os.pathsep)
184 latex = find_exe_or_terminate(["latex", "pplatex", "platex", "latex2e"], path)
186 lilypond_book = find_exe_or_terminate(["lilypond-book"], path)
188 # Make a copy of the latex file
189 lytex_file = latex_file_re.sub(".lytex", latex_file)
190 shutil.copyfile(latex_file, lytex_file)
192 # Preprocess the latex file through lilypond-book.
193 lytex_call = '%s --safe --latex-program=%s "%s"' % (lilypond_book, latex, lytex_file)
194 lytex_status, lytex_stdout = run_command(lytex_call)
195 if lytex_status != None:
196 warning("%s failed to compile %s" \
197 % (os.path.basename(lilypond_book), lytex_file))
198 warning(lytex_stdout)
200 # This can go once dvipng becomes widespread.
201 dvipng = find_exe(["dvipng"], path)
203 # The data is input to legacy_conversion in as similar
204 # as possible a manner to that input to the code used in
206 vec = [ argv[0], argv[2], argv[3], argv[1], argv[4], argv[5], latex ]
207 return legacy_conversion(vec)
210 if output_format == "ppm":
211 pngtopnm = find_exe_or_terminate(["pngtopnm"], path)
213 # Move color information for PDF into the latex file.
214 if not color_pdf(latex_file, bg_color_gr):
215 error("Unable to move color info into the latex file")
217 # Compile the latex file.
218 latex_call = '%s "%s"' % (latex, latex_file)
220 latex_status, latex_stdout = run_command(latex_call)
221 if latex_status != None:
222 warning("%s had problems compiling %s" \
223 % (os.path.basename(latex), latex_file))
224 warning(latex_stdout)
226 if latex == "xelatex":
227 warning("Using XeTeX")
228 # FIXME: skip unnecessary dvips trial in legacy_conversion_step2
229 return legacy_conversion_step2(latex_file, dpi, output_format)
231 # The dvi output file name
232 dvi_file = latex_file_re.sub(".dvi", latex_file)
234 # Check for PostScript specials in the dvi, badly supported by dvipng
235 # This is required for correct rendering of PSTricks and TikZ
236 dv2dt = find_exe_or_terminate(["dv2dt"], path)
237 dv2dt_call = '%s "%s"' % (dv2dt, dvi_file)
239 # The output from dv2dt goes to stdout
240 dv2dt_status, dv2dt_output = run_command(dv2dt_call)
241 psliteral_re = re.compile("^special[1-4] [0-9]+ '(\"|ps:)")
243 # Parse the dtl file looking for PostScript specials.
244 # Pages using PostScript specials are recorded in ps_pages and then
245 # used to create a different LaTeX file for processing in legacy mode.
250 for line in dv2dt_output.split("\n"):
252 if line.startswith("bop"):
257 if line.startswith("eop") and page_has_ps:
258 # We save in a list all the PostScript pages
259 ps_pages.append(page_index)
261 if psliteral_re.match(line) != None:
262 # Literal PostScript special detected!
266 if len(ps_pages) == page_index:
267 # All pages need PostScript, so directly use the legacy method.
268 vec = [argv[0], argv[2], argv[3], argv[1], argv[4], argv[5], latex]
269 return legacy_conversion(vec)
270 elif len(ps_pages) > 0:
271 # Don't process Postscript pages with dvipng by selecting the
272 # wanted pages through the -pp parameter. E.g., dvipng -pp 4-12,14,64
273 pages_parameter = " -pp "
277 # Use page ranges, as a list of pages could exceed command line
278 # maximum length (especially under Win32)
279 for index in xrange(1, page_index + 1):
280 if (not index in ps_pages) and skip:
281 # We were skipping pages but current page shouldn't be skipped.
282 # Add this page to -pp, it could stay alone or become the
284 pages_parameter += str(index)
285 # Save the starting index to avoid things such as "11-11"
287 # We're not skipping anymore
289 elif (index in ps_pages) and (not skip):
290 # We weren't skipping but current page should be skipped
291 if last != index - 1:
292 # If the start index of the range is the previous page
293 # then it's not a range
294 pages_parameter += "-" + str(index - 1)
297 pages_parameter += ","
301 # Remove the trailing separator
302 pages_parameter = pages_parameter.rstrip(",")
303 # We've to manage the case in which the last page is closing a range
304 if (not index in ps_pages) and (not skip) and (last != index):
305 pages_parameter += "-" + str(index)
307 # Run the dvi file through dvipng.
308 dvipng_call = '%s -Ttight -depth -height -D %d -fg "%s" -bg "%s" %s "%s"' \
309 % (dvipng, dpi, fg_color, bg_color, pages_parameter, dvi_file)
310 dvipng_status, dvipng_stdout = run_command(dvipng_call)
312 if dvipng_status != None:
313 warning("%s failed to generate images from %s ... looking for PDF" \
314 % (os.path.basename(dvipng), dvi_file))
315 # FIXME: skip unnecessary dvips trial in legacy_conversion_step2
316 return legacy_conversion_step2(latex_file, dpi, output_format)
318 if len(ps_pages) > 0:
319 # Some pages require PostScript.
320 # Create a new LaTeX file just for the snippets needing
322 original_latex = open(latex_file, "r")
323 legacy_latex_file = latex_file_re.sub("_legacy.tex", latex_file)
324 legacy_latex = open(legacy_latex_file, "w")
328 for line in original_latex:
329 if line.startswith("\\begin{preview}"):
331 # Skips all pages processed by dvipng
332 skip_page = page_index not in ps_pages
335 legacy_latex.write(line)
337 if line.startswith("\\end{preview}"):
341 original_latex.close()
343 # Pass the new LaTeX file to the legacy method
344 vec = [ argv[0], latex_file_re.sub("_legacy.tex", argv[2]), \
345 argv[3], argv[1], argv[4], argv[5], latex ]
346 legacy_conversion(vec, True)
348 # Now we need to mix metrics data from dvipng and the legacy method
349 metrics_file = latex_file_re.sub(".metrics", latex_file)
351 dvipng_metrics = extract_metrics_info(dvipng_stdout)
352 legacy_metrics = legacy_extract_metrics_info(latex_file_re.sub("_legacy.log", latex_file))
354 # Check whether a page is present in dvipng_metrics, otherwise
355 # add it getting the metrics from legacy_metrics
357 for i in range(page_index):
358 # If we exceed the array bounds or the dvipng_metrics doesn't
359 # match the current one, this page belongs to the legacy method
360 if (i > len(dvipng_metrics) - 1) or (dvipng_metrics[i][0] != str(i + 1)):
363 # Add this metric from the legacy output
364 dvipng_metrics.insert(i, (str(i + 1), legacy_metrics[legacy_index][1]))
365 # Legacy output filename
366 legacy_output = os.path.join(dir, latex_file_re.sub("_legacy%s.%s" %
367 (legacy_metrics[legacy_index][0], output_format), latex_file))
369 # Check whether legacy method actually created the file
370 if os.path.isfile(legacy_output):
371 # Rename the file by removing the "_legacy" suffix
372 # and adjusting the index
373 bitmap_output = os.path.join(dir, latex_file_re.sub("%s.%s" %
374 (str(i + 1), output_format), latex_file))
375 os.rename(legacy_output, bitmap_output)
377 # Actually create the .metrics file
378 write_metrics_info(dvipng_metrics, metrics_file)
380 # Extract metrics info from dvipng_stdout.
381 # In this case we just used dvipng, so no special metrics
382 # handling is needed.
383 metrics_file = latex_file_re.sub(".metrics", latex_file)
384 write_metrics_info(extract_metrics_info(dvipng_stdout), metrics_file)
386 # Convert images to ppm format if necessary.
387 if output_format == "ppm":
388 convert_to_ppm_format(pngtopnm, latex_file_re.sub("", latex_file))
393 if __name__ == "__main__":