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 # * python 2.4 or later (subprocess module);
20 # * A latex executable;
24 # * pngtoppm (if outputing ppm format images).
26 # preview.sty and dvipng are part of the preview-latex project
27 # http://preview-latex.sourceforge.net/
29 # preview.sty can alternatively be obtained from
30 # CTAN/support/preview-latex/
33 # lyxpreview2bitmap.py --bg=faf0e6 0lyxpreview.tex
35 # This script takes one obligatory argument:
37 # <input file>: The name of the .tex file to be converted.
39 # and these optional arguments:
41 # --png, --ppm: The desired output format. Either 'png' or 'ppm'.
42 # --dpi=<res>: A scale factor, used to ascertain the resolution of the
43 # generated image which is then passed to gs.
44 # --fg=<color>: The foreground color as a hexadecimal string, eg '000000'.
45 # --bg=<color>: The background color as a hexadecimal string, eg 'faf0e6'.
46 # --latex=<exe>: The converter for latex files. Default is latex.
47 # --bibtex=<exe>: The converter for bibtex files. Default is bibtex.
48 # --lilypond: Preprocess through lilypond-book. Default is false.
49 # --lilypond-book=<exe>:
50 # The converter for lytex files. Default is lilypond-book.
52 # -d, --debug Show the output from external commands.
53 # -h, --help Show an help screen and exit.
54 # -v, --verbose Show progress messages.
56 # Decomposing TEXFILE's name as DIR/BASE.tex, this script will,
57 # if executed successfully, leave in DIR:
58 # * a (possibly large) number of image files with names
60 # * a file BASE.metrics, containing info needed by LyX to position
61 # the images correctly on the screen.
63 # What does this script do?
64 # 1) Call latex/pdflatex/xelatex/whatever (CONVERTER parameter)
65 # 2) If the output is a PDF fallback to legacy
66 # 3) Otherwise check each page of the DVI (with dv2dt) looking for
67 # PostScript literals, not well supported by dvipng. Pages
68 # containing them are passed to the legacy method in a new LaTeX file.
69 # 4) Call dvipng on the pages without PS literals
70 # 5) Join metrics info coming from both methods (legacy and dvipng)
71 # and write them to file
73 # dvipng is fast but gives problem in several cases, like with
74 # PSTricks, TikZ and other packages using PostScript literals
75 # for all these cases the legacy route is taken (step 3).
76 # Moreover dvipng can't work with PDF files, so, if the CONVERTER
77 # paramter is pdflatex we have to fallback to legacy route (step 2).
79 import getopt, glob, os, re, shutil, string, sys
81 from legacy_lyxpreview2ppm import legacy_conversion_step1
83 from lyxpreview_tools import bibtex_commands, copyfileobj, error, \
84 filter_pages, find_exe, find_exe_or_terminate, join_metrics_and_rename, \
85 latex_commands, latex_file_re, make_texcolor, mkstemp, pdflatex_commands, \
86 progress, run_command, run_latex, run_tex, warning, write_metrics_info
91 Usage: %s <options> <input file>
94 --dpi=<res>: Resolution per inch (default: 128)
95 --png, --ppm: Select the output format (default: png)
96 --fg=<color>: Foreground color (default: black, ie '000000')
97 --bg=<color>: Background color (default: white, ie 'ffffff')
98 --latex=<exe>: Specify the executable for latex (default: latex)
99 --bibtex=<exe>: Specify the executable for bibtex (default: bibtex)
100 --lilypond: Preprocess through lilypond-book (default: false)
101 --lilypond-book=<exe>:
102 The executable for lilypond-book (default: lilypond-book)
104 -d, --debug: Show the output from external commands
105 -h, --help: Show this help screen and exit
106 -v, --verbose: Show progress messages
108 The colors are hexadecimal strings, eg 'faf0e6'."""
109 return msg % prog_name
111 # Returns a list of tuples containing page number and ascent fraction
112 # extracted from dvipng output.
113 # Use write_metrics_info to create the .metrics file with this info
114 def extract_metrics_info(dvipng_stdout):
115 # "\[[0-9]+" can match two kinds of numbers: page numbers from dvipng
116 # and glyph numbers from mktexpk. The glyph numbers always match
117 # "\[[0-9]+\]" while the page number never is followed by "\]". Thus:
118 page_re = re.compile("\[([0-9]+)[^]]");
119 metrics_re = re.compile("depth=(-?[0-9]+) height=(-?[0-9]+)")
126 match = page_re.search(dvipng_stdout, pos)
129 page = match.group(1)
131 match = metrics_re.search(dvipng_stdout, pos)
136 # Calculate the 'ascent fraction'.
137 descent = string.atof(match.group(1))
138 ascent = string.atof(match.group(2))
141 if ascent >= 0 or descent >= 0:
142 if abs(ascent + descent) > 0.1:
143 frac = ascent / (ascent + descent)
149 results.append((int(page), frac))
150 pos = match.end() + 2
153 error("Failed to extract metrics info from dvipng")
158 def fix_latex_file(latex_file):
159 documentclass_re = re.compile("(\\\\documentclass\[)(1[012]pt,?)(.+)")
164 for line in open(latex_file, 'r').readlines():
165 match = documentclass_re.match(line)
171 tmp.write("%s%s\n" % (match.group(1), match.group(3)))
174 copyfileobj(tmp, open(latex_file,"wb"), 1)
179 def convert_to_ppm_format(pngtopnm, basename):
180 png_file_re = re.compile("\.png$")
182 for png_file in glob.glob("%s*.png" % basename):
183 ppm_file = png_file_re.sub(".ppm", png_file)
185 p2p_cmd = '%s "%s"' % (pngtopnm, png_file)
186 p2p_status, p2p_stdout = run_command(p2p_cmd)
188 error("Unable to convert %s to ppm format" % png_file)
190 ppm = open(ppm_file, 'w')
191 ppm.write(p2p_stdout)
194 # Returns a tuple of:
195 # ps_pages: list of page indexes of pages containing PS literals
196 # page_count: total number of pages
197 # pages_parameter: parameter for dvipng to exclude pages with PostScript
198 def find_ps_pages(dvi_file):
200 # FIXME: try with pdflatex
201 if not os.path.isfile(dvi_file):
202 error("No DVI output.")
204 # Check for PostScript specials in the dvi, badly supported by dvipng
205 # This is required for correct rendering of PSTricks and TikZ
206 dv2dt = find_exe_or_terminate(["dv2dt"])
207 dv2dt_call = '%s "%s"' % (dv2dt, dvi_file)
209 # The output from dv2dt goes to stdout
210 dv2dt_status, dv2dt_output = run_command(dv2dt_call)
211 psliteral_re = re.compile("^special[1-4] [0-9]+ '(\"|ps:)")
213 # Parse the dtl file looking for PostScript specials.
214 # Pages using PostScript specials are recorded in ps_pages and then
215 # used to create a different LaTeX file for processing in legacy mode.
220 for line in dv2dt_output.split("\n"):
222 if line.startswith("bop"):
227 if line.startswith("eop") and page_has_ps:
228 # We save in a list all the PostScript pages
229 ps_pages.append(page_index)
231 if psliteral_re.match(line) != None:
232 # Literal PostScript special detected!
235 # Create the -pp parameter for dvipng
237 if len(ps_pages) > 0 and len(ps_pages) < page_index:
238 # Don't process Postscript pages with dvipng by selecting the
239 # wanted pages through the -pp parameter. E.g., dvipng -pp 4-12,14,64
240 pages_parameter = " -pp "
244 # Use page ranges, as a list of pages could exceed command line
245 # maximum length (especially under Win32)
246 for index in xrange(1, page_index + 1):
247 if (not index in ps_pages) and skip:
248 # We were skipping pages but current page shouldn't be skipped.
249 # Add this page to -pp, it could stay alone or become the
251 pages_parameter += str(index)
252 # Save the starting index to avoid things such as "11-11"
254 # We're not skipping anymore
256 elif (index in ps_pages) and (not skip):
257 # We weren't skipping but current page should be skipped
258 if last != index - 1:
259 # If the start index of the range is the previous page
260 # then it's not a range
261 pages_parameter += "-" + str(index - 1)
264 pages_parameter += ","
268 # Remove the trailing separator
269 pages_parameter = pages_parameter.rstrip(",")
270 # We've to manage the case in which the last page is closing a range
271 if (not index in ps_pages) and (not skip) and (last != index):
272 pages_parameter += "-" + str(index)
274 return (ps_pages, page_index, pages_parameter)
285 output_format = "png"
286 script_name = argv[0]
288 # Parse and manipulate the command line arguments.
290 (opts, args) = getopt.gnu_getopt(argv[1:], "dhv", ["bibtex=", "bg=",
291 "debug", "dpi=", "fg=", "help", "latex=", "lilypond",
292 "lilypond-book=", "png", "ppm", "verbose"])
293 except getopt.GetoptError, err:
294 error("%s\n%s" % (err, usage(script_name)))
297 for opt, val in opts:
298 if opt in ("-h", "--help"):
299 print usage(script_name)
301 elif opt == "--bibtex":
305 elif opt in ("-d", "--debug"):
306 import lyxpreview_tools
307 lyxpreview_tools.debug = True
310 dpi = string.atoi(val)
312 error("Cannot convert %s to an integer value" % val)
315 elif opt == "--latex":
317 elif opt == "--lilypond":
319 elif opt == "--lilypond-book":
320 lilypond_book = [val]
321 elif opt in ("--png", "--ppm"):
322 output_format = opt[2:]
323 elif opt in ("-v", "--verbose"):
324 import lyxpreview_tools
325 lyxpreview_tools.verbose = True
327 # Determine input file
329 err = "A single input file is required, %s given" % (len(args) or "none")
330 error("%s\n%s" % (err, usage(script_name)))
333 dir, latex_file = os.path.split(input_path)
336 progress("Starting %s..." % script_name)
337 progress("Output format: %s" % output_format)
338 progress("Foreground color: %s" % fg_color)
339 progress("Background color: %s" % bg_color)
340 progress("Resolution (dpi): %s" % dpi)
341 progress("File to process: %s" % input_path)
343 # Check for the input file
344 if not os.path.exists(input_path):
345 error('File "%s" not found.' % input_path)
349 fg_color_dvipng = make_texcolor(fg_color, False)
350 bg_color_dvipng = make_texcolor(bg_color, False)
352 # External programs used by the script.
353 latex = find_exe_or_terminate(latex or latex_commands)
354 bibtex = find_exe(bibtex or bibtex_commands)
356 lilypond_book = find_exe_or_terminate(lilypond_book or
357 ["lilypond-book --safe"])
359 # These flavors of latex are known to produce pdf output
360 pdf_output = latex in pdflatex_commands
362 progress("Latex command: %s" % latex)
363 progress("Latex produces pdf output: %s" % pdf_output)
364 progress("Bibtex command: %s" % bibtex)
365 progress("Lilypond-book command: %s" % lilypond_book)
366 progress("Preprocess through lilypond-book: %s" % lilypond)
367 progress("Altering the latex file for font size and colors")
369 # Omit font size specification in latex file.
370 fix_latex_file(latex_file)
373 progress("Preprocess the latex file through %s" % lilypond_book)
375 lilypond_book += " --pdf"
376 lilypond_book += " --latex-program=%s" % latex.split()[0]
378 # Make a copy of the latex file
379 lytex_file = latex_file_re.sub(".lytex", latex_file)
380 shutil.copyfile(latex_file, lytex_file)
382 # Preprocess the latex file through lilypond-book.
383 lytex_status, lytex_stdout = run_tex(lilypond_book, lytex_file)
386 progress("Using the legacy conversion method (PDF support)")
387 return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
388 bg_color, latex, pdf_output)
390 # This can go once dvipng becomes widespread.
391 dvipng = find_exe(["dvipng"])
393 progress("Using the legacy conversion method (dvipng not found)")
394 return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
395 bg_color, latex, pdf_output)
397 dv2dt = find_exe(["dv2dt"])
399 progress("Using the legacy conversion method (dv2dt not found)")
400 return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
401 bg_color, latex, pdf_output)
404 if output_format == "ppm":
405 pngtopnm = find_exe(["pngtopnm"])
407 progress("Using the legacy conversion method (pngtopnm not found)")
408 return legacy_conversion_step1(latex_file, dpi, output_format,
409 fg_color, bg_color, latex, pdf_output)
411 # Compile the latex file.
412 latex_status, latex_stdout = run_latex(latex, latex_file, bibtex)
414 # The dvi output file name
415 dvi_file = latex_file_re.sub(".dvi", latex_file)
417 # If there's no DVI output, look for PDF and go to legacy or fail
418 if not os.path.isfile(dvi_file):
419 # No DVI, is there a PDF?
420 pdf_file = latex_file_re.sub(".pdf", latex_file)
421 if os.path.isfile(pdf_file):
422 progress("%s produced a PDF output, fallback to legacy." \
423 % (os.path.basename(latex)))
424 progress("Using the legacy conversion method (PDF support)")
425 return legacy_conversion_step1(latex_file, dpi, output_format,
426 fg_color, bg_color, latex, True)
428 error("No DVI or PDF output. %s failed." \
429 % (os.path.basename(latex)))
431 # Look for PS literals in DVI pages
432 # ps_pages: list of page indexes of pages containing PS literals
433 # page_count: total number of pages
434 # pages_parameter: parameter for dvipng to exclude pages with PostScript
435 (ps_pages, page_count, pages_parameter) = find_ps_pages(dvi_file)
437 # If all pages need PostScript, directly use the legacy method.
438 if len(ps_pages) == page_count:
439 progress("Using the legacy conversion method (PostScript support)")
440 return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
441 bg_color, latex, pdf_output)
443 # Run the dvi file through dvipng.
444 dvipng_call = '%s -Ttight -depth -height -D %d -fg "%s" -bg "%s" %s "%s"' \
445 % (dvipng, dpi, fg_color_dvipng, bg_color_dvipng, pages_parameter, dvi_file)
446 dvipng_status, dvipng_stdout = run_command(dvipng_call)
449 warning("%s failed to generate images from %s... fallback to legacy method" \
450 % (os.path.basename(dvipng), dvi_file))
451 progress("Using the legacy conversion method (dvipng failed)")
452 return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
453 bg_color, latex, pdf_output)
455 # Extract metrics info from dvipng_stdout.
456 metrics_file = latex_file_re.sub(".metrics", latex_file)
457 dvipng_metrics = extract_metrics_info(dvipng_stdout)
459 # If some pages require PostScript pass them to legacy method
460 if len(ps_pages) > 0:
461 # Create a new LaTeX file just for the snippets needing
463 legacy_latex_file = latex_file_re.sub("_legacy.tex", latex_file)
464 filter_pages(latex_file, legacy_latex_file, ps_pages)
466 # Pass the new LaTeX file to the legacy method
467 progress("Pages %s include postscript specials" % ps_pages)
468 progress("Using the legacy conversion method (PostScript support)")
469 legacy_status, legacy_metrics = legacy_conversion_step1(legacy_latex_file,
470 dpi, output_format, fg_color, bg_color, latex, pdf_output, True)
472 # Now we need to mix metrics data from dvipng and the legacy method
473 original_bitmap = latex_file_re.sub("%d." + output_format, legacy_latex_file)
474 destination_bitmap = latex_file_re.sub("%d." + output_format, latex_file)
476 # Join metrics from dvipng and legacy, and rename legacy bitmaps
477 join_metrics_and_rename(dvipng_metrics, legacy_metrics, ps_pages,
478 original_bitmap, destination_bitmap)
480 # Convert images to ppm format if necessary.
481 if output_format == "ppm":
482 convert_to_ppm_format(pngtopnm, latex_file_re.sub("", latex_file))
484 # Actually create the .metrics file
485 write_metrics_info(dvipng_metrics, metrics_file)
487 return (0, dvipng_metrics)
489 if __name__ == "__main__":
490 sys.exit(main(sys.argv)[0])