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 color_pdf(latex_file, bg_color, fg_color):
159 use_preview_pdf_re = re.compile("(\s*\\\\usepackage\[[^]]+)((pdftex|xetex)\]{preview})")
164 if fg_color != "0.000000,0.000000,0.000000":
165 fg = ' \\AtBeginDocument{\\let\\oldpreview\\preview\\renewcommand\\preview{\\oldpreview\\color[rgb]{%s}}}\n' % (fg_color)
169 for line in open(latex_file, 'r').readlines():
170 match = use_preview_pdf_re.match(line)
175 tmp.write(" \\usepackage{color}\n" \
176 " \\pagecolor[rgb]{%s}\n" \
179 % (bg_color, fg, match.group()))
183 # Unable to open the file, but do nothing here because
184 # the calling function will act on the value of 'success'.
185 warning('Warning in color_pdf! Unable to open "%s"' % latex_file)
186 warning(`sys.exc_type` + ',' + `sys.exc_value`)
189 copyfileobj(tmp, open(latex_file,"wb"), 1)
194 def fix_latex_file(latex_file):
195 documentclass_re = re.compile("(\\\\documentclass\[)(1[012]pt,?)(.+)")
200 for line in open(latex_file, 'r').readlines():
201 match = documentclass_re.match(line)
207 tmp.write("%s%s\n" % (match.group(1), match.group(3)))
210 copyfileobj(tmp, open(latex_file,"wb"), 1)
215 def convert_to_ppm_format(pngtopnm, basename):
216 png_file_re = re.compile("\.png$")
218 for png_file in glob.glob("%s*.png" % basename):
219 ppm_file = png_file_re.sub(".ppm", png_file)
221 p2p_cmd = '%s "%s"' % (pngtopnm, png_file)
222 p2p_status, p2p_stdout = run_command(p2p_cmd)
224 error("Unable to convert %s to ppm format" % png_file)
226 ppm = open(ppm_file, 'w')
227 ppm.write(p2p_stdout)
230 # Returns a tuple of:
231 # ps_pages: list of page indexes of pages containing PS literals
232 # page_count: total number of pages
233 # pages_parameter: parameter for dvipng to exclude pages with PostScript
234 def find_ps_pages(dvi_file):
236 # FIXME: try with pdflatex
237 if not os.path.isfile(dvi_file):
238 error("No DVI output.")
240 # Check for PostScript specials in the dvi, badly supported by dvipng
241 # This is required for correct rendering of PSTricks and TikZ
242 dv2dt = find_exe_or_terminate(["dv2dt"])
243 dv2dt_call = '%s "%s"' % (dv2dt, dvi_file)
245 # The output from dv2dt goes to stdout
246 dv2dt_status, dv2dt_output = run_command(dv2dt_call)
247 psliteral_re = re.compile("^special[1-4] [0-9]+ '(\"|ps:)")
249 # Parse the dtl file looking for PostScript specials.
250 # Pages using PostScript specials are recorded in ps_pages and then
251 # used to create a different LaTeX file for processing in legacy mode.
256 for line in dv2dt_output.split("\n"):
258 if line.startswith("bop"):
263 if line.startswith("eop") and page_has_ps:
264 # We save in a list all the PostScript pages
265 ps_pages.append(page_index)
267 if psliteral_re.match(line) != None:
268 # Literal PostScript special detected!
271 # Create the -pp parameter for dvipng
273 if len(ps_pages) > 0 and len(ps_pages) < page_index:
274 # Don't process Postscript pages with dvipng by selecting the
275 # wanted pages through the -pp parameter. E.g., dvipng -pp 4-12,14,64
276 pages_parameter = " -pp "
280 # Use page ranges, as a list of pages could exceed command line
281 # maximum length (especially under Win32)
282 for index in xrange(1, page_index + 1):
283 if (not index in ps_pages) and skip:
284 # We were skipping pages but current page shouldn't be skipped.
285 # Add this page to -pp, it could stay alone or become the
287 pages_parameter += str(index)
288 # Save the starting index to avoid things such as "11-11"
290 # We're not skipping anymore
292 elif (index in ps_pages) and (not skip):
293 # We weren't skipping but current page should be skipped
294 if last != index - 1:
295 # If the start index of the range is the previous page
296 # then it's not a range
297 pages_parameter += "-" + str(index - 1)
300 pages_parameter += ","
304 # Remove the trailing separator
305 pages_parameter = pages_parameter.rstrip(",")
306 # We've to manage the case in which the last page is closing a range
307 if (not index in ps_pages) and (not skip) and (last != index):
308 pages_parameter += "-" + str(index)
310 return (ps_pages, page_index, pages_parameter)
321 output_format = "png"
322 script_name = argv[0]
324 # Parse and manipulate the command line arguments.
326 (opts, args) = getopt.gnu_getopt(argv[1:], "dhv", ["bibtex=", "bg=",
327 "debug", "dpi=", "fg=", "help", "latex=", "lilypond",
328 "lilypond-book=", "png", "ppm", "verbose"])
329 except getopt.GetoptError, err:
330 error("%s\n%s" % (err, usage(script_name)))
333 for opt, val in opts:
334 if opt in ("-h", "--help"):
335 print usage(script_name)
337 elif opt == "--bibtex":
341 elif opt in ("-d", "--debug"):
342 import lyxpreview_tools
343 lyxpreview_tools.debug = True
346 dpi = string.atoi(val)
348 error("Cannot convert %s to an integer value" % val)
351 elif opt == "--latex":
353 elif opt == "--lilypond":
355 elif opt == "--lilypond-book":
356 lilypond_book = [val]
357 elif opt in ("--png", "--ppm"):
358 output_format = opt[2:]
359 elif opt in ("-v", "--verbose"):
360 import lyxpreview_tools
361 lyxpreview_tools.verbose = True
363 # Determine input file
365 err = "A single input file is required, %s given" % (len(args) or "none")
366 error("%s\n%s" % (err, usage(script_name)))
369 dir, latex_file = os.path.split(input_path)
372 progress("Starting %s..." % script_name)
373 progress("Output format: %s" % output_format)
374 progress("Foreground color: %s" % fg_color)
375 progress("Background color: %s" % bg_color)
376 progress("Resolution (dpi): %s" % dpi)
377 progress("File to process: %s" % input_path)
379 # Check for the input file
380 if not os.path.exists(input_path):
381 error('File "%s" not found.' % input_path)
385 fg_color_dvipng = make_texcolor(fg_color, False)
386 bg_color_dvipng = make_texcolor(bg_color, False)
388 fg_color_gr = make_texcolor(fg_color, True)
389 bg_color_gr = make_texcolor(bg_color, True)
391 # External programs used by the script.
392 latex = find_exe_or_terminate(latex or latex_commands)
393 bibtex = find_exe(bibtex or bibtex_commands)
395 lilypond_book = find_exe_or_terminate(lilypond_book or
396 ["lilypond-book --safe"])
398 # These flavors of latex are known to produce pdf output
399 pdf_output = latex in pdflatex_commands
401 progress("Latex command: %s" % latex)
402 progress("Latex produces pdf output: %s" % pdf_output)
403 progress("Bibtex command: %s" % bibtex)
404 progress("Lilypond-book command: %s" % lilypond_book)
405 progress("Preprocess through lilypond-book: %s" % lilypond)
406 progress("Altering the latex file for font size and colors")
408 # Omit font size specification in latex file.
409 if not fix_latex_file(latex_file):
410 warning("Unable to remove font size from the latex file")
413 progress("Preprocess the latex file through %s" % lilypond_book)
415 lilypond_book += " --pdf"
416 lilypond_book += " --latex-program=%s" % latex.split()[0]
418 # Make a copy of the latex file
419 lytex_file = latex_file_re.sub(".lytex", latex_file)
420 shutil.copyfile(latex_file, lytex_file)
422 # Preprocess the latex file through lilypond-book.
423 lytex_status, lytex_stdout = run_tex(lilypond_book, lytex_file)
426 progress("Using the legacy conversion method (PDF support)")
427 return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
428 bg_color, latex, pdf_output)
430 # This can go once dvipng becomes widespread.
431 dvipng = find_exe(["dvipng"])
433 progress("Using the legacy conversion method (dvipng not found)")
434 return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
435 bg_color, latex, pdf_output)
437 dv2dt = find_exe(["dv2dt"])
439 progress("Using the legacy conversion method (dv2dt not found)")
440 return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
441 bg_color, latex, pdf_output)
444 if output_format == "ppm":
445 pngtopnm = find_exe(["pngtopnm"])
447 progress("Using the legacy conversion method (pngtopnm not found)")
448 return legacy_conversion_step1(latex_file, dpi, output_format,
449 fg_color, bg_color, latex, pdf_output)
451 # Move color information for PDF into the latex file.
452 if not color_pdf(latex_file, bg_color_gr, fg_color_gr):
453 warning("Unable to move color info into the latex file")
455 # Compile the latex file.
456 latex_status, latex_stdout = run_latex(latex, latex_file, bibtex)
458 # The dvi output file name
459 dvi_file = latex_file_re.sub(".dvi", latex_file)
461 # If there's no DVI output, look for PDF and go to legacy or fail
462 if not os.path.isfile(dvi_file):
463 # No DVI, is there a PDF?
464 pdf_file = latex_file_re.sub(".pdf", latex_file)
465 if os.path.isfile(pdf_file):
466 progress("%s produced a PDF output, fallback to legacy." \
467 % (os.path.basename(latex)))
468 progress("Using the legacy conversion method (PDF support)")
469 return legacy_conversion_step1(latex_file, dpi, output_format,
470 fg_color, bg_color, latex, True)
472 error("No DVI or PDF output. %s failed." \
473 % (os.path.basename(latex)))
475 # Look for PS literals in DVI pages
476 # ps_pages: list of page indexes of pages containing PS literals
477 # page_count: total number of pages
478 # pages_parameter: parameter for dvipng to exclude pages with PostScript
479 (ps_pages, page_count, pages_parameter) = find_ps_pages(dvi_file)
481 # If all pages need PostScript, directly use the legacy method.
482 if len(ps_pages) == page_count:
483 progress("Using the legacy conversion method (PostScript support)")
484 return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
485 bg_color, latex, pdf_output)
487 # Run the dvi file through dvipng.
488 dvipng_call = '%s -Ttight -depth -height -D %d -fg "%s" -bg "%s" %s "%s"' \
489 % (dvipng, dpi, fg_color_dvipng, bg_color_dvipng, pages_parameter, dvi_file)
490 dvipng_status, dvipng_stdout = run_command(dvipng_call)
493 warning("%s failed to generate images from %s... fallback to legacy method" \
494 % (os.path.basename(dvipng), dvi_file))
495 progress("Using the legacy conversion method (dvipng failed)")
496 return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
497 bg_color, latex, pdf_output)
499 # Extract metrics info from dvipng_stdout.
500 metrics_file = latex_file_re.sub(".metrics", latex_file)
501 dvipng_metrics = extract_metrics_info(dvipng_stdout)
503 # If some pages require PostScript pass them to legacy method
504 if len(ps_pages) > 0:
505 # Create a new LaTeX file just for the snippets needing
507 legacy_latex_file = latex_file_re.sub("_legacy.tex", latex_file)
508 filter_pages(latex_file, legacy_latex_file, ps_pages)
510 # Pass the new LaTeX file to the legacy method
511 progress("Pages %s include postscript specials" % ps_pages)
512 progress("Using the legacy conversion method (PostScript support)")
513 legacy_status, legacy_metrics = legacy_conversion_step1(legacy_latex_file,
514 dpi, output_format, fg_color, bg_color, latex, pdf_output, True)
516 # Now we need to mix metrics data from dvipng and the legacy method
517 original_bitmap = latex_file_re.sub("%d." + output_format, legacy_latex_file)
518 destination_bitmap = latex_file_re.sub("%d." + output_format, latex_file)
520 # Join metrics from dvipng and legacy, and rename legacy bitmaps
521 join_metrics_and_rename(dvipng_metrics, legacy_metrics, ps_pages,
522 original_bitmap, destination_bitmap)
524 # Convert images to ppm format if necessary.
525 if output_format == "ppm":
526 convert_to_ppm_format(pngtopnm, latex_file_re.sub("", latex_file))
528 # Actually create the .metrics file
529 write_metrics_info(dvipng_metrics, metrics_file)
531 return (0, dvipng_metrics)
533 if __name__ == "__main__":
534 sys.exit(main(sys.argv)[0])