2 # file lyxpreview_tools.py
3 # This file is part of LyX, the document processor.
4 # Licence details can be found in the file COPYING.
7 # Full author contact details are available in file CREDITS
9 # and with much help testing the code under Windows from
10 # Paul A. Rubin, rubin@msu.edu.
12 # A repository of the following functions, used by the lyxpreview2xyz scripts.
13 # copyfileobj, error, find_exe, find_exe_or_terminate, make_texcolor,
14 # progress, run_command, run_latex, warning
16 # Requires python 2.4 or later (subprocess module).
18 import os, re, subprocess, sys, tempfile
21 # Control the output to stdout
25 # Known flavors of latex and bibtex
26 bibtex_commands = ("bibtex", "bibtex8", "biber")
27 latex_commands = ("latex", "pplatex", "platex", "latex2e")
28 pdflatex_commands = ("pdflatex", "xelatex", "lualatex")
30 # Pre-compiled regular expressions
31 latex_file_re = re.compile(r"\.tex$")
33 # PATH and PATHEXT environment variables
34 path = os.environ["PATH"].split(os.pathsep)
36 if "PATHEXT" in os.environ:
37 extlist += os.environ["PATHEXT"].split(os.pathsep)
53 sys.stderr.write("Consider installing the PyWin extension modules " \
54 "if you're irritated by windows appearing briefly.\n")
58 def progress(message):
61 sys.stdout.write("Progress: %s\n" % message)
65 sys.stderr.write("Warning: %s\n" % message)
69 sys.stderr.write("Error: %s\n" % message)
73 def make_texcolor(hexcolor, graphics):
74 # Test that the input string contains 6 hexadecimal chars.
75 hexcolor_re = re.compile(b"^[0-9a-fA-F]{6}$")
76 if not hexcolor_re.match(hexcolor):
77 error("Cannot convert color '%s'" % hexcolor)
79 red = float(int(hexcolor[0:2], 16)) / 255.0
80 green = float(int(hexcolor[2:4], 16)) / 255.0
81 blue = float(int(hexcolor[4:6], 16)) / 255.0
84 return b"%f,%f,%f" % (red, green, blue)
86 return b"rgb %f %f %f" % (red, green, blue)
89 def find_exe(candidates):
92 for command in candidates:
93 prog = command.split()[0]
94 for directory in path:
96 full_path = os.path.join(directory, prog + ext)
97 if os.access(full_path, os.X_OK):
98 # The thing is in the PATH already (or we wouldn't
99 # have found it). Return just the basename to avoid
100 # problems when the path to the executable contains
102 if full_path.lower().endswith('.py'):
103 return command.replace(prog, '"%s" "%s"'
104 % (sys.executable, full_path))
110 def find_exe_or_terminate(candidates):
111 exe = find_exe(candidates)
113 error("Unable to find executable from '%s'" % " ".join(candidates))
118 def run_command_popen(cmd, stderr2stdout):
124 pipe = subprocess.Popen(cmd, shell=unix, close_fds=unix, stdin=subprocess.PIPE, \
125 stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
126 cmd_stdout = pipe.communicate()[0]
128 pipe = subprocess.Popen(cmd, shell=unix, close_fds=unix, stdin=subprocess.PIPE, \
129 stdout=subprocess.PIPE, universal_newlines=True)
130 (cmd_stdout, cmd_stderr) = pipe.communicate()
132 sys.stderr.write(cmd_stderr)
133 cmd_status = pipe.returncode
137 sys.stdout.write(cmd_stdout)
138 return cmd_status, cmd_stdout
141 def run_command_win32(cmd):
142 sa = win32security.SECURITY_ATTRIBUTES()
143 sa.bInheritHandle = True
144 stdout_r, stdout_w = win32pipe.CreatePipe(sa, 0)
146 si = win32process.STARTUPINFO()
147 si.dwFlags = (win32process.STARTF_USESTDHANDLES
148 | win32process.STARTF_USESHOWWINDOW)
149 si.wShowWindow = win32con.SW_HIDE
150 si.hStdOutput = stdout_w
152 process, thread, pid, tid = \
153 win32process.CreateProcess(None, cmd, None, None, True,
158 # Must close the write handle in this process, or ReadFile will hang.
161 # Read the pipe until we get an error (including ERROR_BROKEN_PIPE,
162 # which is okay because it happens when child process ends).
167 hr, buffer = win32file.ReadFile(stdout_r, 4096)
168 if hr != winerror.ERROR_IO_PENDING:
171 except pywintypes.error as e:
172 if e.args[0] != winerror.ERROR_BROKEN_PIPE:
179 # Everything is okay --- the called process has closed the pipe.
180 # For safety, check that the process ended, then pick up its exit code.
181 win32event.WaitForSingleObject(process, win32event.INFINITE)
182 if win32process.GetExitCodeProcess(process):
187 sys.stdout.write(data)
191 def run_command(cmd, stderr2stdout = True):
192 progress("Running %s" % cmd)
193 if use_win32_modules:
194 return run_command_win32(cmd)
196 return run_command_popen(cmd, stderr2stdout)
199 def copyfileobj(fsrc, fdst, rewind=0, length=16*1024):
200 """copy data from file-like object fsrc to file-like object fdst"""
206 buf = fsrc.read(length)
212 def write_metrics_info(metrics_info, metrics_file):
213 metrics = open(metrics_file, 'w')
214 for metric in metrics_info:
215 metrics.write("Snippet %s %f\n" % metric)
219 # Reads a .tex files and create an identical file but only with
220 # pages whose index is in pages_to_keep
221 def filter_pages(source_path, destination_path, pages_to_keep):
222 def_re = re.compile(b"(\\\\newcommandx|\\\\renewcommandx|\\\\global\\\\long\\\\def)(\\[a-zA-Z]+)(.+)")
223 source_file = open(source_path, "rb")
224 destination_file = open(destination_path, "wb")
229 for line in source_file:
230 # We found a new page
231 if line.startswith(b"\\begin{preview}"):
233 # If the page index isn't in pages_to_keep we don't copy it
234 skip_page = page_index not in pages_to_keep
237 match = def_re.match(line)
239 definecmd = match.group(1)
240 macroname = match.group(2)
241 if not macroname in macros:
242 macros.append(macroname)
243 if definecmd == b"\\renewcommandx":
244 line = line.replace(definecmd, b"\\newcommandx")
245 destination_file.write(line)
247 # End of a page, we reset the skip_page bool
248 if line.startswith(b"\\end{preview}"):
251 destination_file.close()
254 # Joins two metrics list, that is a list of tuple (page_index, metric)
255 # new_page_indexes contains the original page number of the pages in new_metrics
256 # e.g. new_page_indexes[3] == 14 means that the 4th item in new_metrics is the 15th in the original counting
257 # original_bitmap and destination_bitmap are file name models used to rename the new files
258 # e.g. image_new%d.png and image_%d.png
259 def join_metrics_and_rename(original_metrics, new_metrics, new_page_indexes, original_bitmap, destination_bitmap):
261 for (index, metric) in new_metrics:
262 # If the file exists we rename it
263 if os.path.isfile(original_bitmap % (index)):
264 os.rename(original_bitmap % (index), destination_bitmap % new_page_indexes[index-1])
266 # Extract the original page index
267 index = new_page_indexes[index-1]
268 # Goes through the array until the end is reached or the correct index is found
269 while legacy_index < len(original_metrics) and original_metrics[legacy_index][0] < index:
272 # Add or update the metric for this page
273 if legacy_index < len(original_metrics) and original_metrics[legacy_index][0] == index:
274 original_metrics[legacy_index] = (index, metric)
276 original_metrics.insert(legacy_index, (index, metric))
279 def run_latex(latex, latex_file, bibtex = None):
281 latex_status, latex_stdout = run_tex(latex, latex_file)
284 return latex_status, latex_stdout
286 # The aux and log output file names
287 aux_file = latex_file_re.sub(".aux", latex_file)
288 log_file = latex_file_re.sub(".log", latex_file)
290 # Run bibtex/latex if necessary
291 progress("Checking if a bibtex run is necessary")
292 if string_in_file(r"\bibdata", aux_file):
293 bibtex_status, bibtex_stdout = run_tex(bibtex, aux_file)
294 latex_status, latex_stdout = run_tex(latex, latex_file)
295 # Rerun latex if necessary
296 progress("Checking if a latex rerun is necessary")
297 if string_in_file("Warning: Citation", log_file):
298 latex_status, latex_stdout = run_tex(latex, latex_file)
300 return latex_status, latex_stdout
303 def run_tex(tex, tex_file):
304 tex_call = '%s "%s"' % (tex, tex_file)
306 tex_status, tex_stdout = run_command(tex_call)
308 progress("Warning: %s had problems compiling %s" \
309 % (os.path.basename(tex), tex_file))
310 return tex_status, tex_stdout
313 def string_in_file(string, infile):
314 if not os.path.isfile(infile):
316 f = open(infile, 'rb')
317 for line in f.readlines():
318 if string.encode() in line:
325 # Returns a list of indexes of pages giving errors extracted from the latex log
326 def check_latex_log(log_file):
328 error_re = re.compile(b"^! ")
329 snippet_re = re.compile(b"^Preview: Snippet ")
330 data_re = re.compile(b"([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)")
336 for line in open(log_file, 'rb').readlines():
338 match = error_re.match(line)
343 match = snippet_re.match(line)
348 match = data_re.search(line)
350 error("Unexpected data in %s\n%s" % (log_file, line))
352 error_pages.append(int(match.group(1)))
355 warning('check_latex_log: Unable to open "%s"' % log_file)
356 warning(repr(sys.exc_info()[0]) + ',' + repr(sys.exc_info()[1]))