1 # -*- coding: utf-8 -*-
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 # * python 2.4 or later (subprocess module);
19 # * A latex executable;
23 # * pngtoppm (if outputing ppm format images).
25 # preview.sty and dvipng are part of the preview-latex project
26 # http://preview-latex.sourceforge.net/
28 # preview.sty can alternatively be obtained from
29 # CTAN/support/preview-latex/
32 # lyxpreview2bitmap.py --bg=faf0e6 0lyxpreview.tex
34 # This script takes one obligatory argument:
36 # <input file>: The name of the .tex file to be converted.
38 # and these optional arguments:
40 # --png, --ppm: The desired output format. Either 'png' or 'ppm'.
41 # --dpi=<res>: A scale factor, used to ascertain the resolution of the
42 # generated image which is then passed to gs.
43 # --fg=<color>: The foreground color as a hexadecimal string, eg '000000'.
44 # --bg=<color>: The background color as a hexadecimal string, eg 'faf0e6'.
45 # --latex=<exe>: The converter for latex files. Default is latex.
46 # --bibtex=<exe>: The converter for bibtex files. Default is bibtex.
47 # --lilypond: Preprocess through lilypond-book. Default is false.
48 # --lilypond-book=<exe>:
49 # The converter for lytex files. Default is lilypond-book.
51 # -d, --debug Show the output from external commands.
52 # -h, --help Show an help screen and exit.
53 # -v, --verbose Show progress messages.
55 # Decomposing TEXFILE's name as DIR/BASE.tex, this script will,
56 # if executed successfully, leave in DIR:
57 # * a (possibly large) number of image files with names
59 # * a file BASE.metrics, containing info needed by LyX to position
60 # the images correctly on the screen.
62 # What does this script do?
63 # 1) Call latex/pdflatex/xelatex/whatever (CONVERTER parameter)
64 # 2) If the output is a PDF fallback to legacy
65 # 3) Otherwise check each page of the DVI (with dv2dt) looking for
66 # PostScript literals, not well supported by dvipng. Pages
67 # containing them are passed to the legacy method in a new LaTeX file.
68 # 4) Call dvipng on the pages without PS literals
69 # 5) Join metrics info coming from both methods (legacy and dvipng)
70 # and write them to file
72 # dvipng is fast but gives problem in several cases, like with
73 # PSTricks, TikZ and other packages using PostScript literals
74 # for all these cases the legacy route is taken (step 3).
75 # Moreover dvipng can't work with PDF files, so, if the CONVERTER
76 # paramter is pdflatex we have to fallback to legacy route (step 2).
78 import getopt, glob, os, re, shutil, string, sys
80 from legacy_lyxpreview2ppm import legacy_conversion_step1
82 from lyxpreview_tools import bibtex_commands, check_latex_log, copyfileobj, \
83 error, filter_pages, find_exe, find_exe_or_terminate, \
84 join_metrics_and_rename, latex_commands, latex_file_re, make_texcolor, \
85 mkstemp, pdflatex_commands, progress, run_command, run_latex, run_tex, \
86 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))
142 # This is an empty image, forbid its display
144 elif ascent >= 0 or descent >= 0:
145 if abs(ascent + descent) > 0.1:
146 frac = ascent / (ascent + descent)
152 results.append((int(page), frac))
153 pos = match.end() + 2
156 error("Failed to extract metrics info from dvipng")
161 def fix_latex_file(latex_file, pdf_output):
162 documentclass_re = re.compile("(\\\\documentclass\[)(1[012]pt,?)(.+)")
163 usepackage_re = re.compile("\\\\usepackage")
164 userpreamble_re = re.compile("User specified LaTeX commands")
165 enduserpreamble_re = re.compile("\\\\makeatother")
166 begindoc_re = re.compile("\\\\begin\{document\}")
174 for line in open(latex_file, 'r').readlines():
182 if begindoc_re.match(line) != None:
185 if not pdf_output and not usepkg:
186 if userpreamble_re.search(line) != None:
188 elif enduserpreamble_re.search(line) != None:
190 if usepackage_re.match(line) != None and in_user_preamble:
193 tmp.write("\\def\\t@a{microtype}\n")
194 tmp.write("\\let\\oldusepkg\\usepackage\n")
195 tmp.write("\\def\\usepackage{\\@ifnextchar[\\@usepkg{\\@usepkg[]}}\n")
196 tmp.write("\\def\\@usepkg[#1]#2{\\@ifnextchar[")
197 tmp.write("{\\@@usepkg[#1]{#2}}{\\@@usepkg[#1]{#2}[]}}\n")
198 tmp.write("\\def\@@usepkg[#1]#2[#3]{\\def\\t@b{#2}")
199 tmp.write("\\ifx\\t@a\\t@b\\else\\oldusepkg[#1]{#2}[#3]\\fi}\n")
203 match = documentclass_re.match(line)
209 tmp.write("%s%s\n" % (match.group(1), match.group(3)))
212 copyfileobj(tmp, open(latex_file,"wb"), 1)
217 def convert_to_ppm_format(pngtopnm, basename):
218 png_file_re = re.compile("\.png$")
220 for png_file in glob.glob("%s*.png" % basename):
221 ppm_file = png_file_re.sub(".ppm", png_file)
223 p2p_cmd = '%s "%s"' % (pngtopnm, png_file)
224 p2p_status, p2p_stdout = run_command(p2p_cmd)
226 error("Unable to convert %s to ppm format" % png_file)
228 ppm = open(ppm_file, 'w')
229 ppm.write(p2p_stdout)
232 # Returns a tuple of:
233 # ps_pages: list of page indexes of pages containing PS literals
234 # pdf_pages: list of page indexes of pages requiring running pdflatex
235 # page_count: total number of pages
236 # pages_parameter: parameter for dvipng to exclude pages with PostScript/PDF
237 def find_ps_pages(dvi_file):
239 # FIXME: try with pdflatex
240 if not os.path.isfile(dvi_file):
241 error("No DVI output.")
243 # Check for PostScript specials in the dvi, badly supported by dvipng,
244 # and inclusion of PDF/PNG/JPG files.
245 # This is required for correct rendering of PSTricks and TikZ
246 dv2dt = find_exe_or_terminate(["dv2dt"])
247 dv2dt_call = '%s "%s"' % (dv2dt, dvi_file)
249 # The output from dv2dt goes to stdout
250 dv2dt_status, dv2dt_output = run_command(dv2dt_call)
251 psliteral_re = re.compile("^special[1-4] [0-9]+ '(\"|ps:)")
252 hyperref_re = re.compile("^special[1-4] [0-9]+ 'ps:.*/DEST pdfmark")
253 pdffile_re = re.compile("^special[1-4] [0-9]+ 'PSfile=.*\\.(pdf|png|jpg|jpeg|PDF|PNG|JPG|JPEG)")
255 # Parse the dtl file looking for PostScript specials and pdflatex files.
256 # Pages using PostScript specials or pdflatex files are recorded in
257 # ps_pages or pdf_pages, respectively, and then used to create a
258 # different LaTeX file for processing in legacy mode.
259 # If hyperref is detected, the corresponding page is recorded in pdf_pages.
267 for line in dv2dt_output.split("\n"):
269 if line.startswith("bop"):
275 if line.startswith("eop") and (page_has_ps or page_has_pdf):
276 # We save in a list all the PostScript/PDF pages
278 ps_pages.append(page_index)
280 pdf_pages.append(page_index)
281 ps_or_pdf_pages.append(page_index)
283 if psliteral_re.match(line) != None:
284 # Literal PostScript special detected!
285 # If hyperref is detected, put this page on the pdf pages list
286 if hyperref_re.match(line) != None:
291 elif pdffile_re.match(line) != None:
292 # Inclusion of pdflatex image file detected!
295 # Create the -pp parameter for dvipng
297 if len(ps_or_pdf_pages) > 0 and len(ps_or_pdf_pages) < page_index:
298 # Don't process Postscript/PDF pages with dvipng by selecting the
299 # wanted pages through the -pp parameter. E.g., dvipng -pp 4-12,14,64
300 pages_parameter = " -pp "
304 # Use page ranges, as a list of pages could exceed command line
305 # maximum length (especially under Win32)
306 for index in xrange(1, page_index + 1):
307 if (not index in ps_or_pdf_pages) and skip:
308 # We were skipping pages but current page shouldn't be skipped.
309 # Add this page to -pp, it could stay alone or become the
311 pages_parameter += str(index)
312 # Save the starting index to avoid things such as "11-11"
314 # We're not skipping anymore
316 elif (index in ps_or_pdf_pages) and (not skip):
317 # We weren't skipping but current page should be skipped
318 if last != index - 1:
319 # If the start index of the range is the previous page
320 # then it's not a range
321 pages_parameter += "-" + str(index - 1)
324 pages_parameter += ","
328 # Remove the trailing separator
329 pages_parameter = pages_parameter.rstrip(",")
330 # We've to manage the case in which the last page is closing a range
331 if (not index in ps_or_pdf_pages) and (not skip) and (last != index):
332 pages_parameter += "-" + str(index)
334 return (ps_pages, pdf_pages, page_index, pages_parameter)
345 output_format = "png"
346 script_name = argv[0]
348 # Parse and manipulate the command line arguments.
350 (opts, args) = getopt.gnu_getopt(argv[1:], "dhv", ["bibtex=", "bg=",
351 "debug", "dpi=", "fg=", "help", "latex=", "lilypond",
352 "lilypond-book=", "png", "ppm", "verbose"])
353 except getopt.GetoptError, err:
354 error("%s\n%s" % (err, usage(script_name)))
357 for opt, val in opts:
358 if opt in ("-h", "--help"):
359 print usage(script_name)
361 elif opt == "--bibtex":
365 elif opt in ("-d", "--debug"):
366 import lyxpreview_tools
367 lyxpreview_tools.debug = True
370 dpi = string.atoi(val)
372 error("Cannot convert %s to an integer value" % val)
375 elif opt == "--latex":
377 elif opt == "--lilypond":
379 elif opt == "--lilypond-book":
380 lilypond_book = [val]
381 elif opt in ("--png", "--ppm"):
382 output_format = opt[2:]
383 elif opt in ("-v", "--verbose"):
384 import lyxpreview_tools
385 lyxpreview_tools.verbose = True
387 # Determine input file
389 err = "A single input file is required, %s given" % (len(args) or "none")
390 error("%s\n%s" % (err, usage(script_name)))
393 dir, latex_file = os.path.split(input_path)
396 progress("Starting %s..." % script_name)
397 progress("Output format: %s" % output_format)
398 progress("Foreground color: %s" % fg_color)
399 progress("Background color: %s" % bg_color)
400 progress("Resolution (dpi): %s" % dpi)
401 progress("File to process: %s" % input_path)
403 # Check for the input file
404 if not os.path.exists(input_path):
405 error('File "%s" not found.' % input_path)
409 fg_color_dvipng = make_texcolor(fg_color, False)
410 bg_color_dvipng = make_texcolor(bg_color, False)
412 # External programs used by the script.
413 latex = find_exe_or_terminate(latex or latex_commands)
414 bibtex = find_exe(bibtex or bibtex_commands)
416 lilypond_book = find_exe_or_terminate(lilypond_book or
417 ["lilypond-book --safe"])
419 # These flavors of latex are known to produce pdf output
420 pdf_output = latex in pdflatex_commands
422 progress("Latex command: %s" % latex)
423 progress("Latex produces pdf output: %s" % pdf_output)
424 progress("Bibtex command: %s" % bibtex)
425 progress("Lilypond-book command: %s" % lilypond_book)
426 progress("Preprocess through lilypond-book: %s" % lilypond)
427 progress("Altering the latex file for font size and colors")
429 # Omit font size specification in latex file and make sure that
430 # the microtype package doesn't cause issues in dvi mode.
431 fix_latex_file(latex_file, pdf_output)
434 progress("Preprocess the latex file through %s" % lilypond_book)
436 lilypond_book += " --pdf"
437 lilypond_book += " --latex-program=%s" % latex.split()[0]
439 # Make a copy of the latex file
440 lytex_file = latex_file_re.sub(".lytex", latex_file)
441 shutil.copyfile(latex_file, lytex_file)
443 # Preprocess the latex file through lilypond-book.
444 lytex_status, lytex_stdout = run_tex(lilypond_book, lytex_file)
447 progress("Using the legacy conversion method (PDF support)")
448 return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
449 bg_color, latex, pdf_output)
451 # This can go once dvipng becomes widespread.
452 dvipng = find_exe(["dvipng"])
454 progress("Using the legacy conversion method (dvipng not found)")
455 return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
456 bg_color, latex, pdf_output)
458 dv2dt = find_exe(["dv2dt"])
460 progress("Using the legacy conversion method (dv2dt not found)")
461 return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
462 bg_color, latex, pdf_output)
465 if output_format == "ppm":
466 pngtopnm = find_exe(["pngtopnm"])
468 progress("Using the legacy conversion method (pngtopnm not found)")
469 return legacy_conversion_step1(latex_file, dpi, output_format,
470 fg_color, bg_color, latex, pdf_output)
472 # Compile the latex file.
474 latex_status, latex_stdout = run_latex(latex, latex_file, bibtex)
476 progress("Will try to recover from %s failure" % latex)
477 error_pages = check_latex_log(latex_file_re.sub(".log", latex_file))
479 # The dvi output file name
480 dvi_file = latex_file_re.sub(".dvi", latex_file)
482 # If there's no DVI output, look for PDF and go to legacy or fail
483 if not os.path.isfile(dvi_file):
484 # No DVI, is there a PDF?
485 pdf_file = latex_file_re.sub(".pdf", latex_file)
486 if os.path.isfile(pdf_file):
487 progress("%s produced a PDF output, fallback to legacy." \
488 % (os.path.basename(latex)))
489 progress("Using the legacy conversion method (PDF support)")
490 return legacy_conversion_step1(latex_file, dpi, output_format,
491 fg_color, bg_color, latex, True)
493 error("No DVI or PDF output. %s failed." \
494 % (os.path.basename(latex)))
496 # Look for PS literals or inclusion of pdflatex files in DVI pages
497 # ps_pages: list of indexes of pages containing PS literals
498 # pdf_pages: list of indexes of pages requiring running pdflatex
499 # page_count: total number of pages
500 # pages_parameter: parameter for dvipng to exclude pages with PostScript
501 (ps_pages, pdf_pages, page_count, pages_parameter) = find_ps_pages(dvi_file)
503 # If all pages need PostScript or pdflatex, directly use the legacy method.
504 if len(ps_pages) == page_count:
505 progress("Using the legacy conversion method (PostScript support)")
506 return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
507 bg_color, latex, pdf_output)
508 elif len(pdf_pages) == page_count:
509 progress("Using the legacy conversion method (PDF support)")
510 return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
511 bg_color, "pdflatex", True)
513 # Run the dvi file through dvipng.
514 dvipng_call = '%s -Ttight -depth -height -D %d -fg "%s" -bg "%s" %s "%s"' \
515 % (dvipng, dpi, fg_color_dvipng, bg_color_dvipng, pages_parameter, dvi_file)
516 dvipng_status, dvipng_stdout = run_command(dvipng_call)
519 warning("%s failed to generate images from %s... fallback to legacy method" \
520 % (os.path.basename(dvipng), dvi_file))
521 progress("Using the legacy conversion method (dvipng failed)")
522 return legacy_conversion_step1(latex_file, dpi, output_format, fg_color,
523 bg_color, latex, pdf_output)
525 # Extract metrics info from dvipng_stdout.
526 metrics_file = latex_file_re.sub(".metrics", latex_file)
527 dvipng_metrics = extract_metrics_info(dvipng_stdout)
529 # If some pages require PostScript pass them to legacy method
530 if len(ps_pages) > 0:
531 # Create a new LaTeX file just for the snippets needing
533 legacy_latex_file = latex_file_re.sub("_legacy.tex", latex_file)
534 filter_pages(latex_file, legacy_latex_file, ps_pages)
536 # Pass the new LaTeX file to the legacy method
537 progress("Pages %s include postscript specials" % ps_pages)
538 progress("Using the legacy conversion method (PostScript support)")
539 legacy_status, legacy_metrics = legacy_conversion_step1(legacy_latex_file,
540 dpi, output_format, fg_color, bg_color, latex, pdf_output, True)
542 # Now we need to mix metrics data from dvipng and the legacy method
543 original_bitmap = latex_file_re.sub("%d." + output_format, legacy_latex_file)
544 destination_bitmap = latex_file_re.sub("%d." + output_format, latex_file)
546 # Join metrics from dvipng and legacy, and rename legacy bitmaps
547 join_metrics_and_rename(dvipng_metrics, legacy_metrics, ps_pages,
548 original_bitmap, destination_bitmap)
550 # If some pages require running pdflatex pass them to legacy method
551 if len(pdf_pages) > 0:
552 # Create a new LaTeX file just for the snippets needing
554 legacy_latex_file = latex_file_re.sub("_legacy.tex", latex_file)
555 filter_pages(latex_file, legacy_latex_file, pdf_pages)
557 # Pass the new LaTeX file to the legacy method
558 progress("Pages %s require processing with pdflatex" % pdf_pages)
559 progress("Using the legacy conversion method (PDF support)")
560 legacy_status, legacy_metrics = legacy_conversion_step1(legacy_latex_file,
561 dpi, output_format, fg_color, bg_color, "pdflatex", True, True)
563 # Now we need to mix metrics data from dvipng and the legacy method
564 original_bitmap = latex_file_re.sub("%d." + output_format, legacy_latex_file)
565 destination_bitmap = latex_file_re.sub("%d." + output_format, latex_file)
567 # Join metrics from dvipng and legacy, and rename legacy bitmaps
568 join_metrics_and_rename(dvipng_metrics, legacy_metrics, pdf_pages,
569 original_bitmap, destination_bitmap)
571 # Invalidate metrics for pages that produced errors
572 if len(error_pages) > 0:
574 for index in error_pages:
575 if index not in ps_pages and index not in pdf_pages:
576 dvipng_metrics.pop(index - 1)
577 dvipng_metrics.insert(index - 1, (index, -1.0))
580 warning("Failed to produce %d preview snippet(s)" % error_count)
582 # Convert images to ppm format if necessary.
583 if output_format == "ppm":
584 convert_to_ppm_format(pngtopnm, latex_file_re.sub("", latex_file))
586 # Actually create the .metrics file
587 write_metrics_info(dvipng_metrics, metrics_file)
589 return (0, dvipng_metrics)
591 if __name__ == "__main__":
592 sys.exit(main(sys.argv)[0])