]> git.lyx.org Git - lyx.git/blob - lib/scripts/lyxpreview_tools.py
Don't use widest label for numerical citations.
[lyx.git] / lib / scripts / lyxpreview_tools.py
1 #! /usr/bin/env python
2
3 # file lyxpreview_tools.py
4 # This file is part of LyX, the document processor.
5 # Licence details can be found in the file COPYING.
6
7 # author Angus Leeming
8 # Full author contact details are available in file CREDITS
9
10 # and with much help testing the code under Windows from
11 #   Paul A. Rubin, rubin@msu.edu.
12
13 # A repository of the following functions, used by the lyxpreview2xyz scripts.
14 # copyfileobj, error, find_exe, find_exe_or_terminate, make_texcolor, mkstemp,
15 # progress, run_command, run_latex, warning
16
17 # Requires python 2.4 or later (subprocess module).
18
19 import os, re, string, subprocess, sys, tempfile
20
21
22 # Control the output to stdout
23 debug = False
24 verbose = False
25
26 # Known flavors of latex and bibtex
27 bibtex_commands = ("bibtex", "bibtex8", "biber")
28 latex_commands = ("latex", "pplatex", "platex", "latex2e")
29 pdflatex_commands = ("pdflatex", "xelatex", "lualatex")
30
31 # Pre-compiled regular expressions
32 latex_file_re = re.compile(r"\.tex$")
33
34 # PATH and PATHEXT environment variables
35 path = os.environ["PATH"].split(os.pathsep)
36 extlist = ['']
37 if "PATHEXT" in os.environ:
38     extlist += os.environ["PATHEXT"].split(os.pathsep)
39 extlist.append('.py')
40
41 use_win32_modules = 0
42 if os.name == "nt":
43     use_win32_modules = 1
44     try:
45         import pywintypes
46         import win32con
47         import win32event
48         import win32file
49         import win32pipe
50         import win32process
51         import win32security
52         import winerror
53     except:
54         sys.stderr.write("Consider installing the PyWin extension modules " \
55                          "if you're irritated by windows appearing briefly.\n")
56         use_win32_modules = 0
57
58
59 def progress(message):
60     global verbose
61     if verbose:
62         sys.stdout.write("Progress: %s\n" % message)
63
64
65 def warning(message):
66     sys.stderr.write("Warning: %s\n" % message)
67
68
69 def error(message):
70     sys.stderr.write("Error: %s\n" % message)
71     sys.exit(1)
72
73
74 def make_texcolor(hexcolor, graphics):
75     # Test that the input string contains 6 hexadecimal chars.
76     hexcolor_re = re.compile("^[0-9a-fA-F]{6}$")
77     if not hexcolor_re.match(hexcolor):
78         error("Cannot convert color '%s'" % hexcolor)
79
80     red   = float(string.atoi(hexcolor[0:2], 16)) / 255.0
81     green = float(string.atoi(hexcolor[2:4], 16)) / 255.0
82     blue  = float(string.atoi(hexcolor[4:6], 16)) / 255.0
83
84     if graphics:
85         return "%f,%f,%f" % (red, green, blue)
86     else:
87         return "rgb %f %f %f" % (red, green, blue)
88
89
90 def find_exe(candidates):
91     global extlist, path
92
93     for command in candidates:
94         prog = command.split()[0]
95         for directory in path:
96             for ext in extlist:
97                 full_path = os.path.join(directory, prog + ext)
98                 if os.access(full_path, os.X_OK):
99                     # The thing is in the PATH already (or we wouldn't
100                     # have found it). Return just the basename to avoid
101                     # problems when the path to the executable contains
102                     # spaces.
103                     if full_path.lower().endswith('.py'):
104                         return command.replace(prog, '"%s" "%s"'
105                             % (sys.executable, full_path))
106                     return command
107
108     return None
109
110
111 def find_exe_or_terminate(candidates):
112     exe = find_exe(candidates)
113     if exe == None:
114         error("Unable to find executable from '%s'" % string.join(candidates))
115
116     return exe
117
118
119 def run_command_popen(cmd, stderr2stdout):
120     if os.name == 'nt':
121         unix = False
122     else:
123         unix = True
124     if stderr2stdout:
125         pipe = subprocess.Popen(cmd, shell=unix, close_fds=unix, stdin=subprocess.PIPE, \
126             stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
127         cmd_stdout = pipe.communicate()[0]
128     else:
129         pipe = subprocess.Popen(cmd, shell=unix, close_fds=unix, stdin=subprocess.PIPE, \
130             stdout=subprocess.PIPE, universal_newlines=True)
131         (cmd_stdout, cmd_stderr) = pipe.communicate()
132         if cmd_stderr:
133             sys.stderr.write(cmd_stderr)
134     cmd_status = pipe.returncode
135
136     global debug
137     if debug:
138         sys.stdout.write(cmd_stdout)
139     return cmd_status, cmd_stdout
140
141
142 def run_command_win32(cmd):
143     sa = win32security.SECURITY_ATTRIBUTES()
144     sa.bInheritHandle = True
145     stdout_r, stdout_w = win32pipe.CreatePipe(sa, 0)
146
147     si = win32process.STARTUPINFO()
148     si.dwFlags = (win32process.STARTF_USESTDHANDLES
149                   | win32process.STARTF_USESHOWWINDOW)
150     si.wShowWindow = win32con.SW_HIDE
151     si.hStdOutput = stdout_w
152
153     process, thread, pid, tid = \
154              win32process.CreateProcess(None, cmd, None, None, True,
155                                         0, None, None, si)
156     if process == None:
157         return -1, ""
158
159     # Must close the write handle in this process, or ReadFile will hang.
160     stdout_w.Close()
161
162     # Read the pipe until we get an error (including ERROR_BROKEN_PIPE,
163     # which is okay because it happens when child process ends).
164     data = ""
165     error = 0
166     while 1:
167         try:
168             hr, buffer = win32file.ReadFile(stdout_r, 4096)
169             if hr != winerror.ERROR_IO_PENDING:
170                 data = data + buffer
171
172         except pywintypes.error, e:
173             if e.args[0] != winerror.ERROR_BROKEN_PIPE:
174                 error = 1
175             break
176
177     if error:
178         return -2, ""
179
180     # Everything is okay --- the called process has closed the pipe.
181     # For safety, check that the process ended, then pick up its exit code.
182     win32event.WaitForSingleObject(process, win32event.INFINITE)
183     if win32process.GetExitCodeProcess(process):
184         return -3, ""
185
186     global debug
187     if debug:
188         sys.stdout.write(data)
189     return 0, data
190
191
192 def run_command(cmd, stderr2stdout = True):
193     progress("Running %s" % cmd)
194     if use_win32_modules:
195         return run_command_win32(cmd)
196     else:
197         return run_command_popen(cmd, stderr2stdout)
198
199
200 def get_version_info():
201     version_re = re.compile("([0-9])\.([0-9])")
202
203     match = version_re.match(sys.version)
204     if match == None:
205         error("Unable to extract version info from 'sys.version'")
206
207     return string.atoi(match.group(1)), string.atoi(match.group(2))
208
209
210 def copyfileobj(fsrc, fdst, rewind=0, length=16*1024):
211     """copy data from file-like object fsrc to file-like object fdst"""
212     if rewind:
213         fsrc.flush()
214         fsrc.seek(0)
215
216     while 1:
217         buf = fsrc.read(length)
218         if not buf:
219             break
220         fdst.write(buf)
221
222
223 class TempFile:
224     """clone of tempfile.TemporaryFile to use with python < 2.0."""
225     # Cache the unlinker so we don't get spurious errors at shutdown
226     # when the module-level "os" is None'd out.  Note that this must
227     # be referenced as self.unlink, because the name TempFile
228     # may also get None'd out before __del__ is called.
229     unlink = os.unlink
230
231     def __init__(self):
232         self.filename = tempfile.mktemp()
233         self.file = open(self.filename,"w+b")
234         self.close_called = 0
235
236     def close(self):
237         if not self.close_called:
238             self.close_called = 1
239             self.file.close()
240             self.unlink(self.filename)
241
242     def __del__(self):
243         self.close()
244
245     def read(self, size = -1):
246         return self.file.read(size)
247
248     def write(self, line):
249         return self.file.write(line)
250
251     def seek(self, offset):
252         return self.file.seek(offset)
253
254     def flush(self):
255         return self.file.flush()
256
257
258 def mkstemp():
259     """create a secure temporary file and return its object-like file"""
260     major, minor = get_version_info()
261
262     if major >= 2 and minor >= 0:
263         return tempfile.TemporaryFile()
264     else:
265         return TempFile()
266
267 def write_metrics_info(metrics_info, metrics_file):
268     metrics = open(metrics_file, 'w')
269     for metric in metrics_info:
270         metrics.write("Snippet %s %f\n" % metric)
271     metrics.close()
272
273 # Reads a .tex files and create an identical file but only with
274 # pages whose index is in pages_to_keep
275 def filter_pages(source_path, destination_path, pages_to_keep):
276     source_file = open(source_path, "r")
277     destination_file = open(destination_path, "w")
278
279     page_index = 0
280     skip_page = False
281     for line in source_file:
282         # We found a new page
283         if line.startswith("\\begin{preview}"):
284             page_index += 1
285             # If the page index isn't in pages_to_keep we don't copy it
286             skip_page = page_index not in pages_to_keep
287
288         if not skip_page:
289             destination_file.write(line)
290
291         # End of a page, we reset the skip_page bool
292         if line.startswith("\\end{preview}"):
293             skip_page = False
294
295     destination_file.close()
296     source_file.close()
297
298 # Joins two metrics list, that is a list of tuple (page_index, metric)
299 # new_page_indexes contains the original page number of the pages in new_metrics
300 # e.g. new_page_indexes[3] == 14 means that the 4th item in new_metrics is the 15th in the original counting
301 # original_bitmap and destination_bitmap are file name models used to rename the new files
302 # e.g. image_new%d.png and image_%d.png
303 def join_metrics_and_rename(original_metrics, new_metrics, new_page_indexes, original_bitmap, destination_bitmap):
304     legacy_index = 0
305     for (index, metric) in new_metrics:
306         # If the file exists we rename it
307         if os.path.isfile(original_bitmap % (index)):
308             os.rename(original_bitmap % (index), destination_bitmap % new_page_indexes[index-1])
309
310         # Extract the original page index
311         index = new_page_indexes[index-1]
312         # Goes through the array until the end is reached or the correct index is found
313         while legacy_index < len(original_metrics) and original_metrics[legacy_index][0] < index:
314             legacy_index += 1
315
316         # Add or update the metric for this page
317         if legacy_index < len(original_metrics) and original_metrics[legacy_index][0] == index:
318             original_metrics[legacy_index] = (index, metric)
319         else:
320             original_metrics.insert(legacy_index, (index, metric))
321
322
323 def run_latex(latex, latex_file, bibtex = None):
324     # Run latex
325     latex_status, latex_stdout = run_tex(latex, latex_file)
326
327     if bibtex is None:
328         return latex_status, latex_stdout
329
330     # The aux and log output file names
331     aux_file = latex_file_re.sub(".aux", latex_file)
332     log_file = latex_file_re.sub(".log", latex_file)
333
334     # Run bibtex/latex if necessary
335     progress("Checking if a bibtex run is necessary")
336     if string_in_file(r"\bibdata", aux_file):
337         bibtex_status, bibtex_stdout = run_tex(bibtex, aux_file)
338         latex_status, latex_stdout = run_tex(latex, latex_file)
339     # Rerun latex if necessary
340     progress("Checking if a latex rerun is necessary")
341     if string_in_file("Warning: Citation", log_file):
342         latex_status, latex_stdout = run_tex(latex, latex_file)
343
344     return latex_status, latex_stdout
345
346
347 def run_tex(tex, tex_file):
348     tex_call = '%s "%s"' % (tex, tex_file)
349
350     tex_status, tex_stdout = run_command(tex_call)
351     if tex_status:
352         warning("%s had problems compiling %s" \
353             % (os.path.basename(tex), tex_file))
354     return tex_status, tex_stdout
355
356
357 def string_in_file(string, infile):
358     if not os.path.isfile(infile):
359         return False
360     f = open(infile, 'r')
361     for line in f.readlines():
362         if string in line:
363             f.close()
364             return True
365     f.close()
366     return False