-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathlatexmake.py
executable file
·497 lines (421 loc) · 15.7 KB
/
latexmake.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
#!/usr/bin/env python
# coding: utf-8
'''
latexmake
~~~~~~~~~
Python module for latexmk.py which completely automates
the process of generating a LaTeX document.
:copyright: (c) 2013 by Marc Schlaich
:license: MIT, see LICENSE for more details.
'''
from __future__ import with_statement
from collections import defaultdict
from itertools import chain
from optparse import OptionParser
from subprocess import Popen, call
import codecs
import filecmp
import fnmatch
import logging
import os
import re
import shutil
import sys
import time
__author__ = 'Marc Schlaich'
__version__ = '0.5dev'
__license__ = 'MIT'
BIB_PATTERN = re.compile(r'\\bibdata\{(.*)\}')
CITE_PATTERN = re.compile(r'\\citation\{(.*)\}')
BIBCITE_PATTERN = re.compile(r'\\bibcite\{(.*)\}\{(.*)\}')
BIBENTRY_PATTERN = re.compile(r'@.*\{(.*),\s')
ERROR_PATTTERN = re.compile(r'(?:^! (.*\nl\..*)$)|(?:^! (.*)$)|'
'(No pages of output.)', re.M)
LATEX_RERUN_PATTERNS = [re.compile(pattr) for pattr in
[r'LaTeX Warning: Reference .* undefined',
r'LaTeX Warning: There were undefined references\.',
r'LaTeX Warning: Label\(s\) may have changed\.',
r'No file .*(\.toc|\.lof)\.']]
TEXLIPSE_MAIN_PATTERN = re.compile(r'^mainTexFile=(.*)(?:\.tex)$', re.M)
LATEX_FLAGS = ['-interaction=nonstopmode', '-shell-escape', '--synctex=1']
MAX_RUNS = 4
NO_LATEX_ERROR = (
'Could not run command "%s". '
'Is your latex distribution under your PATH?'
)
class LatexMaker(object):
'''
Main class for generation process.
'''
def __init__(self, project_name, opt):
self.opt = opt
self.log = self._setup_logger()
if project_name == '.texlipse':
self.project_name = self._parse_texlipse_config()
else:
self.project_name = project_name
if self.project_name.endswith('.tex'):
self.project_name = self.project_name[:-4]
if self.opt.pdf:
self.latex_cmd = 'pdflatex'
else:
self.latex_cmd = 'latex'
self.out = ''
self.glossaries = dict()
self.latex_run_counter = 0
self.bib_file = ''
def _setup_logger(self):
'''Set up a logger.'''
log = logging.getLogger('latexmk.py')
handler = logging.StreamHandler()
log.addHandler(handler)
if self.opt.verbose:
log.setLevel(logging.INFO)
return log
def _parse_texlipse_config(self):
'''
Read the project name from the texlipse
config file ".texlipse".
'''
# If Eclipse's workspace refresh, the
# ".texlipse"-File will be newly created,
# so try again after short sleep if
# the file is still missing.
if not os.path.isfile('.texlipse'):
time.sleep(0.1)
if not os.path.isfile('.texlipse'):
self.log.error('! Fatal error: File .texlipse is missing.')
self.log.error('! Exiting...')
sys.exit(1)
with open('.texlipse') as fobj:
content = fobj.read()
match = TEXLIPSE_MAIN_PATTERN.search(content)
if match:
project_name = match.groups()[0]
self.log.info('Found inputfile in ".texlipse": %s.tex'
% project_name)
return project_name
else:
self.log.error('! Fatal error: Parsing .texlipse failed.')
self.log.error('! Exiting...')
sys.exit(1)
def _read_latex_files(self):
'''
Check if some latex output files exist
before first latex run, process them and return
the generated data.
- Parsing *.aux for citations counter and
existing glossaries.
- Getting content of files to detect changes.
- *.toc file
- all available glossaries files
'''
if os.path.isfile('%s.aux' % self.project_name):
cite_counter = self.generate_citation_counter()
self.read_glossaries()
else:
cite_counter = {'%s.aux' % self.project_name:
defaultdict(int)}
fname = '%s.toc' % self.project_name
if os.path.isfile(fname):
with open(fname) as fobj:
toc_file = fobj.read()
else:
toc_file = ''
gloss_files = dict()
for gloss in self.glossaries:
ext = self.glossaries[gloss][1]
filename = '%s.%s' % (self.project_name, ext)
if os.path.isfile(filename):
with open(filename) as fobj:
gloss_files[gloss] = fobj.read()
return cite_counter, toc_file, gloss_files
def _is_toc_changed(self, toc_file):
'''
Test if the *.toc file has changed during
the first latex run.
'''
fname = '%s.toc' % self.project_name
if os.path.isfile(fname):
with open(fname) as fobj:
if fobj.read() != toc_file:
return True
def _need_bib_run(self, old_cite_counter):
'''
Determine if you need to run "bibtex".
1. Check if *.bib exists.
2. Check latex output for hints.
3. Test if the numbers of citations changed
during first latex run.
4. Examine *.bib for changes.
'''
with open('%s.aux' % self.project_name) as fobj:
match = BIB_PATTERN.search(fobj.read())
if not match:
return False
else:
self.bib_file = match.group(1)
if not os.path.isfile('%s.bib' % self.bib_file):
self.log.warning('Could not find *.bib file.')
return False
if (re.search('No file %s.bbl.' % self.project_name, self.out) or
re.search('LaTeX Warning: Citation .* undefined', self.out)):
return True
if old_cite_counter != self.generate_citation_counter():
return True
if os.path.isfile('%s.bib.old' % self.bib_file):
new = '%s.bib' % self.bib_file
old = '%s.bib.old' % self.bib_file
if not filecmp.cmp(new, old):
return True
def read_glossaries(self):
'''
Read all existing glossaries in the main aux-file.
'''
filename = '%s.aux' % self.project_name
with open(filename) as fobj:
main_aux = fobj.read()
pattern = r'\\@newglossary\{(.*)\}\{.*\}\{(.*)\}\{(.*)\}'
for match in re.finditer(pattern, main_aux):
name, ext_i, ext_o = match.groups()
self.glossaries[name] = (ext_i, ext_o)
def check_errors(self):
'''
Check if errors occured during a latex run by
scanning the output.
'''
errors = ERROR_PATTTERN.findall(self.out)
# "errors" is a list of tuples
if errors:
self.log.error('! Errors occurred:')
self.log.error('\n'.join(
[error.replace('\r', '').strip() for error
in chain(*errors) if error.strip()]
))
self.log.error('! See "%s.log" for details.' % self.project_name)
if self.opt.exit_on_error:
self.log.error('! Exiting...')
sys.exit(1)
def generate_citation_counter(self):
'''
Generate dictionary with the number of citations in all
included files. If this changes after the first latex run,
you have to run "bibtex".
'''
cite_counter = dict()
filename = '%s.aux' % self.project_name
with open(filename) as fobj:
main_aux = fobj.read()
cite_counter[filename] = _count_citations(filename)
for match in re.finditer(r'\\@input\{(.*.aux)\}', main_aux):
filename = match.groups()[0]
try:
counter = _count_citations(filename)
except IOError:
pass
else:
cite_counter[filename] = counter
return cite_counter
def latex_run(self):
'''
Start latex run.
'''
self.log.info('Running %s...' % self.latex_cmd)
cmd = [self.latex_cmd]
cmd.extend(LATEX_FLAGS)
cmd.append('%s.tex' % self.project_name)
try:
with open(os.devnull, 'w') as null:
Popen(cmd, stdout=null, stderr=null).wait()
except OSError:
self.log.error(NO_LATEX_ERROR % self.latex_cmd)
self.latex_run_counter += 1
fname = '%s.log' % self.project_name
with codecs.open(fname, 'r', 'utf-8', 'replace') as fobj:
self.out = fobj.read()
self.check_errors()
def bibtex_run(self):
'''
Start bibtex run.
'''
self.log.info('Running bibtex...')
try:
with open(os.devnull, 'w') as null:
Popen(['bibtex', self.project_name], stdout=null).wait()
except OSError:
self.log.error(NO_LATEX_ERROR % 'bibtex')
sys.exit(1)
shutil.copy('%s.bib' % self.bib_file,
'%s.bib.old' % self.bib_file)
def makeindex_runs(self, gloss_files):
'''
Check for each glossary if it has to be regenerated
with "makeindex".
@return: True if "makeindex" was called.
'''
gloss_changed = False
for gloss in self.glossaries:
make_gloss = False
ext_i, ext_o = self.glossaries[gloss]
fname_in = '%s.%s' % (self.project_name, ext_i)
fname_out = '%s.%s' % (self.project_name, ext_o)
if re.search('No file %s.' % fname_in, self.out):
make_gloss = True
if not os.path.isfile(fname_out):
make_gloss = True
else:
with open(fname_out) as fobj:
try:
if gloss_files[gloss] != fobj.read():
make_gloss = True
except KeyError:
make_gloss = True
if make_gloss:
self.log.info('Running makeindex (%s)...' % gloss)
try:
cmd = ['makeindex', '-q', '-s',
'%s.ist' % self.project_name,
'-o', fname_in, fname_out]
with open(os.devnull, 'w') as null:
Popen(cmd, stdout=null).wait()
except OSError:
self.log.error(NO_LATEX_ERROR % 'makeindex')
sys.exit(1)
gloss_changed = True
return gloss_changed
def open_preview(self):
'''
Try to open a preview of the generated document.
Currently only supported on Windows.
'''
self.log.info('Opening preview...')
if self.opt.pdf:
ext = 'pdf'
else:
ext = 'dvi'
filename = '%s.%s' % (self.project_name, ext)
if sys.platform == 'win32':
try:
os.startfile(filename)
except OSError:
self.log.error(
'Preview-Error: Extension .%s is not linked to a '
'specific application!' % ext
)
elif sys.platform == 'darwin':
call(['open', filename])
else:
self.log.error(
'Preview-Error: Preview function is currently not '
'supported on Linux.'
)
def need_latex_rerun(self):
'''
Test for all rerun patterns if they match the output.
'''
for pattern in LATEX_RERUN_PATTERNS:
if pattern.search(self.out):
return True
return False
def run(self):
'''Run the LaTeX compilation.'''
# store files
self.old_dir = []
if self.opt.clean:
self.old_dir = os.listdir('.')
cite_counter, toc_file, gloss_files = self._read_latex_files()
self.latex_run()
self.read_glossaries()
gloss_changed = self.makeindex_runs(gloss_files)
if gloss_changed or self._is_toc_changed(toc_file):
self.latex_run()
if self._need_bib_run(cite_counter):
self.bibtex_run()
self.latex_run()
while (self.latex_run_counter < MAX_RUNS):
if not self.need_latex_rerun():
break
self.latex_run()
if self.opt.check_cite:
cites = set()
with open('%s.aux' % self.project_name) as fobj:
aux_content = fobj.read()
for match in BIBCITE_PATTERN.finditer(aux_content):
name = match.groups()[0]
cites.add(name)
with open('%s.bib' % self.bib_file) as fobj:
bib_content = fobj.read()
for match in BIBENTRY_PATTERN.finditer(bib_content):
name = match.groups()[0]
if name not in cites:
self.log.info('Bib entry not cited: "%s"' % name)
if self.opt.clean:
ending = '.dvi'
if self.opt.pdf:
ending = '.pdf'
for fname in os.listdir('.'):
if not (fname in self.old_dir or fname.endswith(ending)):
try:
os.remove(fname)
except IOError:
pass
if self.opt.preview:
self.open_preview()
def _count_citations(aux_file):
'''
Counts the citations in an aux-file.
@return: defaultdict(int) - {citation_name: number, ...}
'''
counter = defaultdict(int)
with open(aux_file) as fobj:
content = fobj.read()
for match in CITE_PATTERN.finditer(content):
name = match.groups()[0]
counter[name] += 1
return counter
def main():
'''
Set up "optparse" and pass the options to
a new instance of L{LatexMaker}.
'''
prog = 'latexmk.py'
version = __version__
usage = '%prog [options] [filename]'
# Read description from doc
doc_text = ''
for line in __doc__.splitlines():
if line.find('#') == 0:
break
doc_text += ' %s\n' % line
parser = OptionParser(prog=prog, usage=usage, version=version)
parser.add_option('-c', '--clean',
action='store_true', dest='clean', default=False,
help='clean all temporary files after converting')
parser.add_option('-q', '--quiet',
action='store_false', dest='verbose', default=True,
help='don\'t print status messages to stdout')
parser.add_option('-n', '--no-exit',
action='store_false', dest='exit_on_error', default=True,
help='don\'t exit if error occurs')
parser.add_option('-p', '--preview',
action='store_true', dest='preview', default=False,
help='try to open preview of generated document')
parser.add_option('--dvi', action='store_false', dest='pdf',
default=True, help='use "latex" instead of pdflatex')
parser.add_option('--check-cite', action='store_true', dest='check_cite',
default=False,
help='check bibtex file for uncited entries')
opt, args = parser.parse_args()
if len(args) == 0:
tex_files = fnmatch.filter(os.listdir(os.getcwd()), '*.tex')
if len(tex_files) == 1:
name = tex_files[0]
else:
parser.error('could not find a single *.tex file in current dir')
elif len(args) == 1:
name = args[0]
else:
parser.error('incorrect number of arguments')
LatexMaker(name, opt).run()
if __name__ == '__main__':
main()