forked from schlamar/latexmk.py
-
Notifications
You must be signed in to change notification settings - Fork 2
/
latexmake.py
executable file
·897 lines (775 loc) · 31.6 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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
#!/usr/bin/env python3
# coding: utf-8
'''
latexmake
~~~~~~~~~
Python module for latexmake which completely automates the process of
generating a LaTeX document.
:copyright: (c) 2012-2013 by Marc Schlaich and Jan Kanis
:license: GPL version 3 or later, see LICENSE for more details.
'''
from os import path
from io import open
from collections import defaultdict
from itertools import chain
from subprocess import Popen, call
from textwrap import dedent
from hashlib import sha256
import argparse
import subprocess
import errno
import filecmp
import fnmatch
import logging
import os
import re
import shutil
import sys
import time
import copy
import errno
try:
from inotify.watcher import Watcher
from inotify import _inotify as inotify
from inotify._inotify import IN_MODIFY, IN_DELETE_SELF, IN_MOVE_SELF
except ImportError:
Watcher = None
IN_MODIFY, IN_DELETE_SELF, IN_MOVE_SELF = 2, 1024, 2048
try:
import notify2
from dbus.exceptions import DBusException
except ImportError:
notify2 = None
__author__ = 'Jan Kanis'
__version__ = '0.6dev'
__license__ = 'GPL3+'
WATCH_FILETYPES = 'tex eps jpg png pdf'.split()
def rejoin(*args):
return '|'.join('(?:'+r+')' for r in args)
BIB_PATTERN = re.compile(r'\\bibdata\{(.*)\}')
CITE_PATTERN = re.compile(r'\\citation\{(.*)\}')
BIBCITE_PATTERN = re.compile(r'\\bibcite\{(.*)\}\{(.*)\}')
BIBENTRY_PATTERN = re.compile(r'@.*\{(.*),\s')
FILE_NOT_FOUND_PATTERN = re.compile(rejoin(
r"^No file\s*(.*)\.$",
r"^! LaTeX Error: File `([^']*)' not found\.",
r".*?:\d*: LaTeX Error: File `([^']*)' not found\.",
r"^LaTeX Warning: File `([^']*)' not found",
r"^Package .* [fF]ile `([^']*)' not found",
r"Error: pdflatex \(file ([^\)]*)\): cannot find image file",
), re.M)
ERROR_PATTERN = re.compile(rejoin(
r'^! (?:.|\n)*?\nl\.\d+.*\n.*$',
# r'^! (.*\nl\..*)$',
r'^! .*$',
r'No pages of output.'
), re.M)
LATEX_RERUN_PATTERN = re.compile(rejoin(
r'LaTeX Warning: Reference .* undefined',
r'LaTeX Warning: There were undefined references\.',
r'LaTeX Warning: Label\(s\) may have changed\.',
r'Package natbib Warning: Citation .* undefined',
r'.*Warning:.*Rerun to get.*',
r'No file .*(\.toc|\.lof)\.',
# This pattern can occur when using XeLaTeX. It is only
# present in stderr and not in the log because it is
# not generated by XeLaTeX itself but by a helper
# program that is called from XeLaTeX. This happens
# when non-utf8 clean .aux or .toc files generated by
# PDFLaTeX are read in by XeLaTeX. Rerunning resolves
# it.
r'\*\* WARNING \*\* Failed to convert input string to UTF16',
))
TEXLIPSE_MAIN_PATTERN = re.compile(r'^mainTexFile=(.*)(?:\.tex)$', re.M)
LATEX_FLAGS = ['-interaction=nonstopmode', '-shell-escape', '--synctex=1']
MAX_RUNS = 5
NO_LATEX_ERROR = (
'Could not run command \'%s\'. '
'Is your latex distribution under your PATH?'
)
log = logging.getLogger(__name__)
log.addHandler(logging.StreamHandler())
WATCH_MASK = IN_MODIFY | IN_DELETE_SELF | IN_MOVE_SELF
class LatexMaker (object):
'''
Main class for generation process.
'''
def __init__(self, project_name, opt, log=None):
self.opt = opt
self.project_name = project_name
self.log = log
if self.log == None:
self.log = globals()['log']
if self.opt.command:
self.latex_cmd = self.opt.command
elif self.opt.pdf:
self.latex_cmd = 'pdflatex'
else:
self.latex_cmd = 'latex'
self.out = ''
self.exitcode = None
self.glossaries = dict()
self.latex_run_counter = 0
self.bib_file = ''
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, 'rb') as fobj:
toc_sha = sha256(fobj.read()).digest()
else:
toc_sha = ''
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_sha, gloss_files
def _is_toc_changed(self, toc_sha):
'''
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, 'rb') as fobj:
if sha256(fobj.read()).digest() != toc_sha:
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 = [e.group().replace('\r', '').strip()
for e in ERROR_PATTERN.finditer(self.out)
if e.group().strip()]
if errors:
error = ['! Errors occurred:'] + errors + [
'! See "{p}.log" and "{p}.stdout" for details.'
.format(p=self.project_name)]
if self.opt.notify:
notify('Latex error', '\n'.join(error[:10]))
self.log.error('\n'.join(error), extra={'show_on_desktop':False})
if self.opt.exit_on_error:
raise LatexMkError('\n'.join(error))
return False
elif self.exitcode != 0:
self.log.error("LaTeX exited with exitcode {}"
.format(self.exitcode, ' '.join(cmd)))
return False
return True
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 + ['-jobname', self.project_name])
cmd.extend(self.opt.texoptions)
cmd.append('{}.tex'.format(self.project_name))
self.log.debug('Running '+' '.join(cmd))
if self.opt.texoutput:
print('\n' + " beginning LaTeX output ".center(70, '=') + '\n')
# Not all relevant errors end up in the log, so we parse stdout/stderr.
# See the definition of LATEX_RERUN_PATTERN for details.
try:
# Contrary to what proc.stdout.read's help message says,
# subprocess's builtin PIPE object blocks on read until the
# subprocess is done and all the output can be returned. We want
# to handle subprocess output immediately as it becomes available
# so we use raw io operations.
pread, pwrite = os.pipe()
outfile = open(self.project_name+'.stdout', 'wb')
proc = Popen(cmd, stdout=pwrite, stderr=subprocess.STDOUT)
os.close(pwrite)
output = []
read = os.read(pread, 1024)
while read:
output.append(read)
if self.opt.texoutput:
sys.stdout.buffer.write(read)
outfile.write(read)
read = os.read(pread, 1024)
self.exitcode = proc.wait()
self.out = b''.join(output).decode('utf-8', 'replace')
except OSError as e:
_fatal_error(NO_LATEX_ERROR % self.latex_cmd, error=e)
finally:
os.close(pread)
outfile.close()
if self.opt.texoutput:
print('\n' + " end LaTeX output ".center(70, '=') + '\n')
self.latex_run_counter += 1
return self.check_errors()
def bibtex_run(self):
'''
Start bibtex run.
'''
self.log.info('Running bibtex...')
try:
with open(os.devnull, 'w') as null:
self.log.debug('Running bibtex '+self.project_name)
Popen(['bibtex', self.project_name], stdout=null).wait()
except OSError as e:
_fatal_error(NO_LATEX_ERROR % 'bibtex', error=e)
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]
self.log.debug(' '.join(cmd))
with open(os.devnull, 'w') as null:
Popen(cmd, stdout=null).wait()
except OSError as e:
_fatal_error(NO_LATEX_ERROR % 'makeindex', error=e)
gloss_changed = True
return gloss_changed
def open_preview(self):
'''
Try to open a preview of the generated document.
'''
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
)
else:
try:
# xdg-open works on most Linuxes, open on OSX
cmd = 'open' if sys.platform == 'darwin' else 'xdg-open'
call([cmd, filename])
except OSError as e:
self.log.error('Preview-Error: opening previewer failed with '
'the following message:\n' + str(e))
def need_latex_rerun(self):
'''
Test for all rerun patterns if they match the output.
'''
match = LATEX_RERUN_PATTERN.search(self.out)
if match:
self.log.debug('rerun pattern found: "{}"'.format(match.group()))
return True
return False
def run(self):
'''Run the LaTeX compilation.'''
# store files
self.old_dir = []
self.latex_run_counter = 0
if self.opt.clean:
self.old_dir = os.listdir('.')
cite_counter, toc_sha, gloss_files = self._read_latex_files()
ok = self.latex_run()
self.read_glossaries()
gloss_changed = self.makeindex_runs(gloss_files)
if gloss_changed or self._is_toc_changed(toc_sha):
ok = self.latex_run()
if self._need_bib_run(cite_counter):
self.bibtex_run()
ok = self.latex_run()
overrun = True
while (self.latex_run_counter < MAX_RUNS):
if not self.need_latex_rerun():
overrun = False
break
ok = self.latex_run()
if overrun:
self.log.error(("Error: LaTeX takes more than {} runs "+
"to converge, aborting").format(MAX_RUNS))
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.warn('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()
if ok:
msg = "{}.tex compiled\n".format(self.project_name)
self.log.info(msg)
if self.opt.notify:
notify(msg, icon='face-smile')
class PollEvent (object):
def __init__(self, path, mask):
self.path = path
self.mask = mask
class PollWatcher (object):
"""
A fallback watcher that conforms to the interface of
inotify.watcher.Watcher but uses polling.
"""
def __init__(self, sleep=2):
self.watchlist = {}
self.removed = set()
self.sleeptime = sleep
def add(self, pth, mask):
if mask != WATCH_MASK:
warnings.warn("PollWatcher.add does not support a nonstandard mask")
self.watchlist[pth] = os.path.getmtime(pth)
def path(self, pth):
if pth in self.watchlist:
return (0, IN_MODIFY)
else:
return None
def remove_path(self, pth):
del self.watchlist[pth]
self.removed.discard(pth)
def watches(self):
for path in self.watchlist.keys():
yield path, 0, IN_MODIFY
def read(self, buf=None):
"""A simple polling loop checking file's mtime"""
events = []
while not events:
for f,t in self.watchlist.items():
if f in self.removed: continue
try:
mtime = os.stat(f).st_mtime
if mtime > t:
events.append(PollEvent(f, IN_MODIFY))
self.watchlist[f] = mtime
except OSError as e:
if e.errno in (errno.EACCESS, errno.ELOOP, errno.ENOENT, errno.ENOTDIR):
events.append(PollEvent(f, IN_DELETE_SELF))
self.removed.add(f)
else:
raise
if buf == 0:
break
time.sleep(self.sleeptime)
return events
class LatexWatcher (object):
def __init__(self, project_name, args):
self.project_name = project_name
self.args = args
self.log = log
if not '-recorder' in args.texoptions:
self.args.texoptions.insert(0, '-recorder')
if self.args.watchmethod == 'inotify' and Watcher:
self.watcher = Watcher()
self.log.debug("loaded inotify watcher")
else:
self.watcher = PollWatcher()
self.log.info("inotify not available, falling back on polling watcher")
self.add_watch(args.filename)
for w in args.watchfiles:
self.add_watch(w)
maker_args = copy.copy(self.args)
maker_args.preview = False
maker_args.exit_on_error = True
self.maker = LatexMaker(self.project_name, maker_args)
def run(self):
try:
self.build()
# Open preview just once
if self.args.preview:
self.maker.open_preview()
while 1:
self.build()
except KeyboardInterrupt:
self.log.info('')
self.log.info("exiting")
def update_files(self):
old_watches = [path for path, wd, mask in self.watcher.watches()
if not path in self.args.watchfiles]
with open(self.project_name+'.fls') as record:
for l in record.readlines():
l = l.rstrip('\n')
if not l.startswith('INPUT '):
continue
if self.args.texonly and not l.endswith(self.args.watchtypes):
continue
pth = l.split(' ', 1)[1]
if not self.args.watch_system:
# currently unix only. What would the windows version look like?
spath = path.abspath(pth).lstrip(path.sep)
if spath.startswith(('usr', 'lib', 'etc')):
continue
if not self.watcher.path(pth):
# new file, add it to the watchlist
self.add_watch(pth)
else:
try:
# It's still a current watch
old_watches.remove(pth)
except ValueError:
# sometimes the same file is read multiple times
pass
# remove files that are no longer a dependency
if self.args.filename in old_watches:
raise LatexMkError(
"Filename {} is no longer present in LaTeX's list of inputs"
.format(self.args.filename))
for pth in old_watches:
self.remove_watch(pth)
def add_watch(self, pth):
self.log.debug("adding watch for "+pth)
self.watcher.add(pth,
IN_MODIFY | IN_DELETE_SELF | IN_MOVE_SELF)
def remove_watch(self, pth):
self.log.debug("removing watch for "+pth)
self.watcher.remove_path(pth)
def wait(self):
'''wait for changes to files'''
watchmask = IN_MODIFY | IN_DELETE_SELF | IN_MOVE_SELF
events = []
while not events:
try:
events = [e for e in self.watcher.read() if e.mask & watchmask]
except OSError as e:
if e.errno != errno.EINTR: raise
# wait a little since there are often multiple events close together
time.sleep(0.1)
# clear any additional events
events += [e for e in self.watcher.read(0) if e.mask & watchmask]
self.log.debug("events:"+''.join(
("\n {} {}".format(e.path, '|'.join(inotify.decode_mask(e.mask))) for e in events)))
self.log.info("file(s) changed: "+' '.join(set(e.path for e in events)))
def build(self):
try:
self.maker.run()
except LatexMkError as e:
if self.args.exit_on_error:
raise
self.update_files()
self.wait()
class LatexMkError (Exception):
pass
class NotifyHandler (logging.Handler):
'''
A Logging handler that sends messages to the Gnome notification system
using the notify2 library. Default level is WARN.
'''
def __init__(self, level=logging.WARN, *args):
logging.Handler.__init__(self, *args, level=level)
self.notification = notify2.Notification('')
self.timestamp = 0
self.messages = []
def emit(self, record):
if not getattr(record, 'show_on_desktop', True):
return
now = time.time()
if now - self.timestamp > 10:
del self.messages[:]
self.messages.append(record.getMessage())
self.notification.update(
'LatexMk error:', '\n'.join(self.messages), icon='dialog-error')
self.notification.show()
self.timestamp = now
def _fatal_error(msg, error=None):
'''
Log the error to the logger and raise a LatexMkError
'''
log.error(msg)
raise LatexMkError(msg) from error
def _parse_texlipse_config():
'''
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)
try:
with open('.texlipse') as fobj:
content = fobj.read()
except EnvironmentError as e:
_fatal_error('Could not open .texlipse file: ' + str(e), e)
match = TEXLIPSE_MAIN_PATTERN.search(content)
if match:
project_name = match.groups()[0]
log.info('Found inputfile in ".texlipse": {}.tex'.format(project_name))
return project_name
else:
_fatal_error('Parsing .texlipse file failed.')
def projectname(name):
'''
return the actual project name given a .tex or .texlipse filename
'''
if name == '.texlipse':
name = _parse_texlipse_config()
log.info('Project name is "{}"'.format(name))
if name.endswith('.tex'):
name = name[:-4]
return name
def notify(sum, msg='', icon=''):
'''
Display a notification.
For some standard icon names, see
http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html#names
'''
if notify2:
notify2.Notification(sum, msg, icon=icon).show()
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 "argparse" and pass the options to
a new instance of L{LatexMaker}.
'''
# Read description from doc, inserting the version number. Add a space
# because argparse removes empty trailing lines from the description.
doctext1, *doctext2 = dedent(__doc__).partition('\n:copyright:')
doctext = ''.join([doctext1, '\n:version: {}'.format(__version__)] + doctext2) + ' '
parser = argparse.ArgumentParser(description=doctext,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('filename', default=None, nargs='?',
help='''input filename. If omitted the current directory
will be searched for a single *.tex file. Specify
".texlipse" to find the .tex file from a *.texlipse
project file.''')
parser.add_argument('-f', dest='filename',
help='''The .tex file to watch. Same as the program's
first argument.''')
parser.add_argument('-c', '--clean',
action='store_true', dest='clean', default=False,
help='Clean all temporary files after converting.')
parser.add_argument('-q', '--quiet',
action='count', dest='quiet', default=0,
help='Don\'t print status messages to stdout. Specify '
'twice not to show error messages either.')
parser.add_argument('-d', '--debug',
action='store_const', dest='quiet', const=-1, default=0,
help='Show debugging information.')
parser.add_argument('-n', '--no-exit',
action='store_false', dest='exit_on_error', default=True,
help='Don\'t exit if error occurs.')
parser.add_argument('-N', '--notify',
action='store_true', dest='notify', default=False,
help='''Notify through the desktop environment if a
rebuild is finished and if errors occured. Currently
only available on Gnome.''')
parser.add_argument('-p', '--preview',
action='store_true', dest='preview', default=False,
help='Try to open preview of generated document.')
parser.add_argument('--dvi', action='store_false', dest='pdf',
default=True, help='use "latex" instead of pdflatex')
parser.add_argument('-t', '--tex-command', dest='command',
help='The latex compiler command to use.')
parser.add_argument('--check-cite', action='store_true', dest='check_cite',
default=False,
help='Check bibtex file for uncited entries.')
parser.add_argument('-P', '--texoutput', action='store_true', default=False,
help='Show the output of the called commands')
parser.add_argument('--pvc', '--preview-continuously',
dest='continuous', action='store_true', default=False,
help='''preview continuously. Keep running, watching the
.tex file and any .tex dependencies for changes
and rebuilding the document on changes. ''')
parser.add_argument('-w', '--watch',
dest='watch', action='store_true', default=False,
help='''Turn on all options useful for running in the
background and building the latex file on changes.
This implies --pvc, -n and -N (if available).''')
parser.add_argument('--watch-system', action='store_true', default=False,
help='''Also watch system files. By default files under
/usr and /etc are not watched for changes.''')
parser.add_argument('--watch-all',
action='store_false', default=True, dest='texonly',
help='''Also watch imported files that do not end in .tex
for changes.''')
parser.add_argument('--latex-options',
action='append', dest='texoptions', nargs='+', default=[],
help='Additional options to pass to latex.')
parser.add_argument('--makeglossaries-options',
action='append', dest='glossariesoptions', nargs='+', default=[],
help="Additional options to pass to `makeglossaries`.")
parser.add_argument('--watchfile',
dest='watchfiles', nargs='+', default=[],
help='Also watch these files for changes.')
parser.add_argument('--watchtype',
dest='watchtypes', nargs='+', default=[],
help='Also watch files with these extensions if latex uses them.')
parser.add_argument('--watchmethod',
nargs=1, choices=['inotify', 'poll'], default='inotify',
help='Specify the method used to detect file changes.')
parser.add_argument('--version', action='version',
version='%(prog)s {}'.format(__version__))
args, rest = parser.parse_known_args()
if rest:
parser.error(
'unrecognized arguments: {}. Specify at most one filename'
.format(' '.join(('"{}"'.format(r) for r in rest))))
if args.filename == None:
tex_files = fnmatch.filter(os.listdir('.'), '*.tex')
if len(tex_files) == 1:
args.filename = tex_files[0]
elif len(tex_files) == 0:
parser.error('could not find one *.tex file in current directory')
else:
parser.error('multiple *.tex files in current directory, specify only one')
if args.texoptions:
args.texoptions = [op for list in args.texoptions for op in list]
args.verbosity = \
{-1: logging.DEBUG, 0: logging.INFO,
1: logging.ERROR, 2: logging.FATAL}[min(args.quiet, 2)]
log.setLevel(args.verbosity)
log.debug('arguments: '+str(args))
args.watchtypes = tuple(WATCH_FILETYPES + args.watchtypes)
if args.watch:
args.continuous = True
args.exit_on_error = False
if notify2:
args.notify = True
if args.notify:
if notify2 is None:
parser.error("Unable to use desktop notification ('-N', '--notify'). "
"Could not load package 'notify2'.")
try:
notify2.init('LatexMake')
log.addHandler(NotifyHandler())
except DBusException as e:
log.error('Failed to initialize DBus: '+str(e))
parser.error("Unable to use desktop notification ('-N', '--notify'). "
"Failed to initialize DBus.")
try:
if args.continuous:
LatexWatcher(projectname(args.filename), args).run()
else:
LatexMaker(projectname(args.filename), args).run()
except LatexMkError as e:
# The exceptions message is already logged
log.error('! Exiting...')
sys.exit(1)
if __name__ == '__main__':
main()