]> git.lyx.org Git - lyx.git/blob - lib/scripts/lyxpreview2bitmap.py
Natbib authoryear uses (Ref1; Ref2) by default.
[lyx.git] / lib / scripts / lyxpreview2bitmap.py
1 #! /usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 # file lyxpreview2bitmap.py
5 # This file is part of LyX, the document processor.
6 # Licence details can be found in the file COPYING.
7
8 # author Angus Leeming
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.
12
13 # Full author contact details are available in file CREDITS
14
15 # This script takes a LaTeX file and generates a collection of
16 # png or ppm image files, one per previewed snippet.
17
18 # Pre-requisites:
19 # * python 2.4 or later (subprocess module);
20 # * A latex executable;
21 # * preview.sty;
22 # * dvipng;
23 # * dv2dt;
24 # * pngtoppm (if outputing ppm format images).
25
26 # preview.sty and dvipng are part of the preview-latex project
27 # http://preview-latex.sourceforge.net/
28
29 # preview.sty can alternatively be obtained from
30 # CTAN/support/preview-latex/
31
32 # Example usage:
33 # lyxpreview2bitmap.py --bg=faf0e6 0lyxpreview.tex
34
35 # This script takes one obligatory argument:
36 #
37 #   <input file>:  The name of the .tex file to be converted.
38 #
39 # and these optional arguments:
40 #
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.
51 #
52 #   -d, --debug    Show the output from external commands.
53 #   -h, --help     Show an help screen and exit.
54 #   -v, --verbose  Show progress messages.
55
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
59 #   like BASE[0-9]+.png
60 # * a file BASE.metrics, containing info needed by LyX to position
61 #   the images correctly on the screen.
62
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
72
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).
78
79 import getopt, glob, os, re, shutil, string, sys
80
81 from legacy_lyxpreview2ppm import legacy_conversion_step1
82
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
87
88
89 def usage(prog_name):
90     msg = """
91 Usage: %s <options> <input file>
92
93 Options:
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)
103
104   -d, --debug:   Show the output from external commands
105   -h, --help:    Show this help screen and exit
106   -v, --verbose: Show progress messages
107
108 The colors are hexadecimal strings, eg 'faf0e6'."""
109     return msg % prog_name
110
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]+)")
120
121     success = 0
122     page = ""
123     pos = 0
124     results = []
125     while 1:
126         match = page_re.search(dvipng_stdout, pos)
127         if match == None:
128             break
129         page = match.group(1)
130         pos = match.end()
131         match = metrics_re.search(dvipng_stdout, pos)
132         if match == None:
133             break
134         success = 1
135
136         # Calculate the 'ascent fraction'.
137         descent = string.atof(match.group(1))
138         ascent  = string.atof(match.group(2))
139
140         frac = 0.5
141         if ascent >= 0 or descent >= 0:
142             if abs(ascent + descent) > 0.1:
143                 frac = ascent / (ascent + descent)
144
145             # Sanity check
146             if frac < 0:
147                 frac = 0.5
148
149         results.append((int(page), frac))
150         pos = match.end() + 2
151
152     if success == 0:
153         error("Failed to extract metrics info from dvipng")
154
155     return results
156
157
158 def fix_latex_file(latex_file):
159     documentclass_re = re.compile("(\\\\documentclass\[)(1[012]pt,?)(.+)")
160
161     tmp = mkstemp()
162
163     changed = 0
164     for line in open(latex_file, 'r').readlines():
165         match = documentclass_re.match(line)
166         if match == None:
167             tmp.write(line)
168             continue
169
170         changed = 1
171         tmp.write("%s%s\n" % (match.group(1), match.group(3)))
172
173     if changed:
174         copyfileobj(tmp, open(latex_file,"wb"), 1)
175
176     return changed
177
178
179 def convert_to_ppm_format(pngtopnm, basename):
180     png_file_re = re.compile("\.png$")
181
182     for png_file in glob.glob("%s*.png" % basename):
183         ppm_file = png_file_re.sub(".ppm", png_file)
184
185         p2p_cmd = '%s "%s"' % (pngtopnm, png_file)
186         p2p_status, p2p_stdout = run_command(p2p_cmd)
187         if p2p_status:
188             error("Unable to convert %s to ppm format" % png_file)
189
190         ppm = open(ppm_file, 'w')
191         ppm.write(p2p_stdout)
192         os.remove(png_file)
193
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):
199     # latex failed
200     # FIXME: try with pdflatex
201     if not os.path.isfile(dvi_file):
202         error("No DVI output.")
203
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)
208
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:)")
212
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.
216     page_has_ps = False
217     page_index = 0
218     ps_pages = []
219
220     for line in dv2dt_output.split("\n"):
221         # New page
222         if line.startswith("bop"):
223             page_has_ps = False
224             page_index += 1
225
226         # End of page
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)
230
231         if psliteral_re.match(line) != None:
232             # Literal PostScript special detected!
233             page_has_ps = True
234
235     # Create the -pp parameter for dvipng
236     pages_parameter = ""
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 "
241         skip = True
242         last = -1
243
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
250                 # start of a range.
251                 pages_parameter += str(index)
252                 # Save the starting index to avoid things such as "11-11"
253                 last = index
254                 # We're not skipping anymore
255                 skip = False
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)
262
263                 # Add a separator
264                 pages_parameter += ","
265                 # Now we're skipping
266                 skip = True
267
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)
273
274     return (ps_pages, page_index, pages_parameter)
275
276 def main(argv):
277     # Set defaults.
278     dpi = 128
279     fg_color = "000000"
280     bg_color = "ffffff"
281     bibtex = None
282     latex = None
283     lilypond = False
284     lilypond_book = None
285     output_format = "png"
286     script_name = argv[0]
287
288     # Parse and manipulate the command line arguments.
289     try:
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)))
295
296     opts.reverse()
297     for opt, val in opts:
298         if opt in ("-h", "--help"):
299             print usage(script_name)
300             sys.exit(0)
301         elif opt == "--bibtex":
302             bibtex = [val]
303         elif opt == "--bg":
304             bg_color = val
305         elif opt in ("-d", "--debug"):
306             import lyxpreview_tools
307             lyxpreview_tools.debug = True
308         elif opt == "--dpi":
309             try:
310                 dpi = string.atoi(val)
311             except:
312                 error("Cannot convert %s to an integer value" % val)
313         elif opt == "--fg":
314             fg_color = val
315         elif opt == "--latex":
316             latex = [val]
317         elif opt == "--lilypond":
318             lilypond = True
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
326
327     # Determine input file
328     if len(args) != 1:
329         err = "A single input file is required, %s given" % (len(args) or "none")
330         error("%s\n%s" % (err, usage(script_name)))
331
332     input_path = args[0]
333     dir, latex_file = os.path.split(input_path)
334
335     # Echo the settings
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)
342
343     # Check for the input file
344     if not os.path.exists(input_path):
345         error('File "%s" not found.' % input_path)
346     if len(dir) != 0:
347         os.chdir(dir)
348
349     fg_color_dvipng = make_texcolor(fg_color, False)
350     bg_color_dvipng = make_texcolor(bg_color, False)
351
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)
355     if lilypond:
356         lilypond_book = find_exe_or_terminate(lilypond_book or
357             ["lilypond-book --safe"])
358
359     # These flavors of latex are known to produce pdf output
360     pdf_output = latex in pdflatex_commands
361
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")
368
369     # Omit font size specification in latex file.
370     fix_latex_file(latex_file)
371
372     if lilypond:
373         progress("Preprocess the latex file through %s" % lilypond_book)
374         if pdf_output:
375             lilypond_book += " --pdf"
376         lilypond_book += " --latex-program=%s" % latex.split()[0]
377
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)
381
382         # Preprocess the latex file through lilypond-book.
383         lytex_status, lytex_stdout = run_tex(lilypond_book, lytex_file)
384
385     if pdf_output:
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)
389
390     # This can go once dvipng becomes widespread.
391     dvipng = find_exe(["dvipng"])
392     if dvipng == None:
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)
396
397     dv2dt = find_exe(["dv2dt"])
398     if dv2dt == None:
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)
402
403     pngtopnm = ""
404     if output_format == "ppm":
405         pngtopnm = find_exe(["pngtopnm"])
406         if pngtopnm == None:
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)
410
411     # Compile the latex file.
412     latex_status, latex_stdout = run_latex(latex, latex_file, bibtex)
413
414     # The dvi output file name
415     dvi_file = latex_file_re.sub(".dvi", latex_file)
416
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)
427         else:
428             error("No DVI or PDF output. %s failed." \
429                 % (os.path.basename(latex)))
430
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)
436
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)
442
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)
447
448     if dvipng_status:
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)
454
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)
458
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
462         # the legacy method
463         legacy_latex_file = latex_file_re.sub("_legacy.tex", latex_file)
464         filter_pages(latex_file, legacy_latex_file, ps_pages)
465
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)
471
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)
475
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)
479
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))
483
484     # Actually create the .metrics file
485     write_metrics_info(dvipng_metrics, metrics_file)
486
487     return (0, dvipng_metrics)
488
489 if __name__ == "__main__":
490     sys.exit(main(sys.argv)[0])