-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathpaperlint.py
More file actions
executable file
·1560 lines (1348 loc) · 54.7 KB
/
paperlint.py
File metadata and controls
executable file
·1560 lines (1348 loc) · 54.7 KB
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
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import re
import sys
import os
def usage():
print("%s <file.tex/path> [-x <excluded-switch1>] [-i <included-switch1>] [-i/x <switch n, evaluated in order of specification>] [--error]" % sys.argv[0])
sys.exit(1)
if len(sys.argv) < 2:
usage()
tex_files = []
if(not sys.argv[1].endswith(".tex")):
for path, subdirs, files in os.walk(sys.argv[1]):
for f in files:
if f.endswith(".tex"):
tex_files.append(os.path.join(path,f))
else:
tex_files = [sys.argv[1]]
tex = None
tex_lines = None
tex_lines_clean = None
tex_lines_math_masked = None
tex_lines_math_texttt_masked = None
in_env = None
envs = None
FLOAT_ENVS = ["figure", "listing", "table"]
CODE_WARNING_EXCEPTIONS = {
"listing-alignment",
"listing-label",
"listing-caption",
"listing-caption-order",
"listing-float",
}
SECTION_COMMAND_RE = re.compile("\\\\(section|subsection|subsubsection|paragraph)\\*?\\{([^\\}]+)\\}")
SENTENCE_END_RE = re.compile(r"(?<!\\)[.!?](?=(?:['\")\]}]*)(?:\s|$))")
def next_file(file):
global tex, tex_lines, tex_lines_clean, tex_lines_math_masked, tex_lines_math_texttt_masked, in_env, envs
try:
tex = open(file).read()
except:
print("Could not open '%s'" % sys.argv[1])
sys.exit(1)
tex_lines = tex.split("\n")
tex_lines_clean = tex.split("\n")
tex_lines_math_masked = tex.split("\n")
tex_lines_math_texttt_masked = tex.split("\n")
in_env = {}
envs = {}
def preprocess():
global tex_lines_math_masked, tex_lines_math_texttt_masked
env = list(set(re.findall(r"\\begin\{(\w+)\*?\}", tex)))
for e in env:
in_env[e] = []
envs[e] = []
current_start = -1
begin_pattern = re.compile(r"\\begin\{%s\*?\}" % re.escape(e))
end_pattern = re.compile(r"\\end\{%s\*?\}" % re.escape(e))
for i, l in enumerate(tex_lines):
if begin_pattern.search(l):
in_env[e].append(True)
current_start = i
elif end_pattern.search(l):
in_env[e].append(False)
envs[e].append((current_start, i))
else:
if len(in_env[e]) == 0:
in_env[e].append(False)
else:
in_env[e].append(in_env[e][-1])
if "%" in tex_lines[i]:
idx = tex_lines[i].index("%")
if idx > 0 and tex_lines[i][idx - 1] != "\\":
tex_lines_clean[i] = tex_lines[i][0:max(0, (tex_lines[i].index("%") - 1))]
if tex_lines_clean[i].startswith("%"): tex_lines_clean[i] = ""
else:
tex_lines_clean[i] = tex_lines[i]
else:
tex_lines_clean[i] = tex_lines[i]
if "comment" in in_env:
for i in range(len(tex_lines_clean)):
if in_env["comment"][i]:
tex_lines_clean[i] = ""
tex_lines_math_masked = mask_math_in_lines(tex_lines_clean)
tex_lines_math_texttt_masked = [
mask_spans(line, get_command_brace_spans(line, "texttt"))
for line in tex_lines_math_masked
]
def in_any_env(line):
for e in in_env:
if in_env[e][line]:
return True
return False
def in_any_float(line):
for f in FLOAT_ENVS:
if f in in_env and in_env[f][line]:
return True
return False
def in_code(line):
if "lstlisting" in in_env:
return in_env["lstlisting"][line]
return False
def in_comment(line):
if "comment" in in_env:
return in_env["comment"][line]
return False
def in_list(line):
for env in ["itemize", "enumerate", "compactitem", "compactenum", "description"]:
if env in in_env and in_env[env][line]:
return True
return False
def in_equation(line):
if "equation" in in_env and in_env["equation"][line]:
return True
if "align" in in_env and in_env["align"][line]:
return True
if "align*" in in_env and in_env["align*"][line]:
return True
if "eqnarray" in in_env and in_env["eqnarray"][line]:
return True
if "theorem" in in_env and in_env["theorem"][line]:
return True
if "proof" in in_env and in_env["proof"][line]:
return True
if "proposition" in in_env and in_env["proposition"][line]:
return True
return False
def normalize_title(title):
return re.sub("\\s+", " ", title.strip()).lower()
def get_section_entries():
entries = []
for i, l in enumerate(tex_lines_clean):
match = SECTION_COMMAND_RE.search(l)
if match:
entries.append({
"line": i,
"level": match.group(1),
"title": match.group(2).strip(),
"span": match.span(),
"starred": "*" in match.group(0)
})
return entries
def extract_section_ranges():
entries = [e for e in get_section_entries() if e["level"] == "section"]
appendix_line = tex.find("\\appendix")
appendix_line = tex[:appendix_line].count("\n") if appendix_line != -1 else None
ranges = []
for idx, entry in enumerate(entries):
start = entry["line"] + 1
end = len(tex_lines)
for nxt in entries[idx + 1:]:
end = nxt["line"]
break
ranges.append({
"title": entry["title"],
"line": entry["line"],
"span": entry["span"],
"starred": entry["starred"],
"in_appendix": appendix_line is not None and entry["line"] > appendix_line,
"start": start,
"end": end
})
return ranges
def count_sentences(text):
stripped = text.strip()
if not stripped:
return 0
cleaned = re.sub(r"\\[A-Za-z@]+\*?(?:\[[^\]]*\])?(?:\{[^{}]*\})?", " ", stripped)
return len(SENTENCE_END_RE.findall(cleaned))
def is_paragraph_content(line):
stripped = line.strip()
if not stripped:
return False
if stripped.startswith("%"):
return False
if stripped in ["{", "}"]:
return False
if re.match("\\\\(section|subsection|subsubsection|paragraph|begin|end|item|label|caption|centering|bibliography|bibliographystyle|appendix|FloatBarrier|clearpage|cleardoublepage|maketitle|title|author|date|thanks|if|else|fi|newcommand|renewcommand|providecommand|definecolor|newlength|setlength|AtBeginDocument)\\b", stripped):
return False
return True
def get_paragraphs(start=0, end=None):
if end is None:
end = len(tex_lines_clean)
paragraphs = []
para_start = None
para_lines = []
for idx in range(start, end):
if "document" in in_env and not in_env["document"][idx]:
continue
stripped = tex_lines_clean[idx].strip()
if stripped.startswith("%"):
continue
if in_code(idx) or in_equation(idx) or in_any_float(idx):
if para_lines:
paragraphs.append((para_start, idx, " ".join(para_lines).strip()))
para_start = None
para_lines = []
continue
item_match = re.match(r"\\item(?:\s*\[[^\]]+\])?\s*(.*)", stripped)
if item_match:
if para_lines:
paragraphs.append((para_start, idx, " ".join(para_lines).strip()))
para_start = idx
para_lines = [item_match.group(1).strip()]
continue
if is_paragraph_content(tex_lines_clean[idx]):
if para_start is None:
para_start = idx
para_lines.append(stripped)
else:
if para_lines:
paragraphs.append((para_start, idx, " ".join(para_lines).strip()))
para_start = None
para_lines = []
if para_lines:
paragraphs.append((para_start, end, " ".join(para_lines).strip()))
return paragraphs
def get_math_spans(line):
spans = []
for pattern in [r"(?<!\$)\$(?!\$)(.+?)(?<!\$)\$(?!\$)", r"\\\((.+?)\\\)"]:
for match in re.finditer(pattern, line):
spans.append((match.start(), match.end(), match.group(1)))
return spans
def mask_spans(line, spans):
if not spans:
return line
chars = list(line)
for start, end in spans:
for pos in range(max(0, start), min(len(chars), end)):
chars[pos] = " "
return "".join(chars)
def get_inline_math_spans(line):
spans = []
i = 0
math_start = None
while i < len(line):
if line.startswith(r"\(", i):
if math_start is None:
math_start = i
else:
spans.append((math_start, i + 2))
math_start = None
i += 2
continue
if line[i] == "$" and (i == 0 or line[i - 1] != "\\"):
if math_start is None:
math_start = i
else:
spans.append((math_start, i + 1))
math_start = None
i += 1
return spans
def get_command_brace_spans(line, command):
spans = []
pattern = re.compile(r"\\%s\*?\{" % re.escape(command))
for match in pattern.finditer(line):
start = match.start()
pos = match.end() - 1
depth = 0
while pos < len(line):
char = line[pos]
if char == "{":
depth += 1
elif char == "}":
depth -= 1
if depth == 0:
spans.append((start, pos + 1))
break
pos += 1
return spans
def mask_math_in_lines(lines):
masked_lines = []
state = None
for line in lines:
chars = list(line)
i = 0
while i < len(line):
if state is None:
if line.startswith(r"\(", i):
chars[i:i + 2] = [" ", " "]
state = r"\("
i += 2
continue
if line.startswith(r"\[", i):
chars[i:i + 2] = [" ", " "]
state = r"\["
i += 2
continue
if line.startswith("$$", i) and (i == 0 or line[i - 1] != "\\"):
chars[i:i + 2] = [" ", " "]
state = "$$"
i += 2
continue
if line[i] == "$" and (i == 0 or line[i - 1] != "\\"):
chars[i] = " "
state = "$"
else:
if state == r"\(" and line.startswith(r"\)", i):
chars[i:i + 2] = [" ", " "]
state = None
i += 2
continue
if state == r"\[" and line.startswith(r"\]", i):
chars[i:i + 2] = [" ", " "]
state = None
i += 2
continue
if state == "$$" and line.startswith("$$", i) and (i == 0 or line[i - 1] != "\\"):
chars[i:i + 2] = [" ", " "]
state = None
i += 2
continue
if state == "$" and line[i] == "$" and (i == 0 or line[i - 1] != "\\"):
chars[i] = " "
state = None
i += 1
continue
chars[i] = " "
i += 1
masked_lines.append("".join(chars))
return masked_lines
def mask_inline_math(line):
return mask_spans(line, get_inline_math_spans(line))
def mask_inline_math_and_texttt(line):
spans = get_inline_math_spans(line)
spans.extend(get_command_brace_spans(line, "texttt"))
return mask_spans(line, spans)
def strip_explicit_math_text(content):
stripped = content
explicit_text_commands = [
"text",
"textrm",
"textit",
"textbf",
"textsf",
"texttt",
"textsc",
"mbox",
"operatorname",
"mathrm",
"mathit",
"mathbf",
"mathsf",
"mathtt",
"mathcal",
"mathbb",
"mathfrak",
]
pattern = re.compile(r"\\(?:%s)\*?\{[^{}]*\}" % "|".join(explicit_text_commands))
while True:
updated = pattern.sub(" ", stripped)
if updated == stripped:
return stripped
stripped = updated
def check_space_before_cite():
warns = []
for i, l in enumerate(tex_lines):
b = re.search("[^ ~]\\\\cite", l)
if b:
if not "\\etal\\cite" in l:
warns.append((i, "No space before \\cite", b.span(0)))
return warns
def check_float_alignment(env):
warns = []
for i, l in enumerate(tex_lines):
b = re.search(r"\\begin\{%s\}" % env, l)
if b:
if not re.search(r"%s}\[[^\]]*[htbH][^\]]*\]" % env, l):
warns.append((i, "%s without alignment: %s" % (env, l.strip()), b.span()))
return warns
def check_figure_alignment():
return check_float_alignment("figure")
def check_table_alignment():
return check_float_alignment("table")
def check_listing_alignment():
return check_float_alignment("listing")
def check_float_has_label(env):
warns = []
if env not in envs: return warns
for r in envs[env]:
label = False
for i in range(*r):
b = re.search(r"\\label\{", tex_lines[i])
if b:
label = True
if not label:
warns.append((r[0], "%s without a label" % env))
return warns
def check_float_has_caption(env):
warns = []
if env not in envs: return warns
for r in envs[env]:
label = False
for i in range(*r):
b = re.search(r"\\caption\{", tex_lines[i])
if b:
label = True
if not label:
warns.append((r[0], "%s without a caption" % env))
return warns
def check_float_caption_label_order(env):
warns = []
if env not in envs: return warns
for r in envs[env]:
label = -1
caption = -1
for i in range(*r):
b = re.search(r"\\caption\{", tex_lines[i])
if b:
caption = i
b = re.search(r"\\label\{", tex_lines[i])
if b:
label = i
if label > -1 and caption > -1 and label < caption:
warns.append((r[0], "label before caption in %s, swap for correct references" % env))
return warns
def check_no_resizebox_for_tables():
warns = []
if "table" not in envs: return warns
for r in envs["table"]:
rb = False
b = None
for i in range(*r):
b = re.search(r"\\resizebox\{", tex_lines[i])
if b:
rb = True
break
if rb:
warns.append((r[0], "table with resizebox -> use adjustbox instead"))
return warns
def check_weird_units():
warns = []
block = ["\\textwidth", "\\linewidth"]
for i, l in enumerate(tex_lines):
for b in block:
if b in l:
warns.append((i, "use \\hsize instead of %s" % b, (l.index(b), l.index(b) + len(b))))
return warns
def check_figure_has_label():
return check_float_has_label("figure")
def check_table_has_label():
return check_float_has_label("table")
def check_listing_has_label():
return check_float_has_label("listing")
def check_figure_has_caption():
return check_float_has_caption("figure")
def check_table_has_caption():
return check_float_has_caption("table")
def check_listing_has_caption():
return check_float_has_caption("listing")
def check_figure_caption_label_order():
return check_float_caption_label_order("figure")
def check_table_caption_label_order():
return check_float_caption_label_order("table")
def check_listing_caption_label_order():
return check_float_caption_label_order("listing")
def check_todos():
warns = []
for i, l in enumerate(tex_lines_clean):
if "TODO" in l:
warns.append((i, "TODO found", (l.index("TODO"), l.index("TODO") + 4)))
return warns
def check_notes():
warns = []
for i, l in enumerate(tex_lines_clean):
if "\\note" in l:
warns.append((i, "\\note found", (l.index("\\note"), l.index("\\note") + 5)))
if "\\todo" in l:
warns.append((i, "\\todo found", (l.index("\\todo"), l.index("\\todo") + 5)))
return warns
def check_math_numbers():
warns = []
for i, l in enumerate(tex_lines):
if in_code(i):
continue
n = re.search("\\$\\d+\\$", tex_lines[i])
if n and not in_any_float(i):
warns.append((i, "Number in math mode, consider using siunit instead", n.span()))
return warns
def check_math_text_mix():
warns = []
for i, l in enumerate(tex_lines_clean):
if in_code(i):
continue
for start, end, content in get_math_spans(l):
normalized = strip_explicit_math_text(content)
normalized = re.sub("\\\\[A-Za-z]+", " ", normalized)
normalized = re.sub("[\\^_{}&=+\\-*/(),.;:0-9\\s]", " ", normalized)
words = re.findall("[A-Za-z]{2,}", normalized)
prose_words = [word for word in words if word.islower()]
prose_like_words = [word for word in prose_words if len(word) >= 4]
if prose_like_words:
warns.append((i, "Text-like content in math mode, mark it explicitly with \\text{...}", (start, end)))
break
return warns
def check_units():
warns = []
unit_pattern = re.compile(r"(?<!\\)(\b\d+(?:\.\d+)?)(\s?)(ms|ns|us|s|min|h|Hz|kHz|MHz|GHz|B|KB|MB|GB|TB|bit|m|cm|mm|km|g|kg|mg|V|A|W|kW|J|N|K|mol|cd)\b")
for i, l in enumerate(tex_lines_clean):
if in_code(i):
continue
if any(cmd in l for cmd in ["\\SI{", "\\si{", "\\qty{", "\\unit{"]):
continue
masked = tex_lines_math_masked[i]
match = unit_pattern.search(masked)
if match:
before = masked[match.start() - 1] if match.start() > 0 else ""
after = masked[match.end()] if match.end() < len(masked) else ""
if before.isalnum() or before in ["-", "_"]:
continue
if after.isalnum() or after in ["-", "_"]:
continue
prefix = masked[:match.start()].rstrip()
if re.search(r"\\[A-Za-z@]+\*?(?:\{[^{}]*\})*\{$", prefix):
continue
if re.search(r"(?:^|[,\[])\s*[A-Za-z@][A-Za-z0-9@ _-]*=\s*$", prefix):
continue
if match.group(2) == "":
warns.append((i, "Unit attached to number, separate it and prefer siunitx", match.span()))
else:
warns.append((i, "Number with unit should use siunitx", match.span()))
return warns
def check_float_placement():
warns = []
for i, l in enumerate(tex_lines_clean):
match = re.search("\\\\begin\\{(%s)\\}\\[([^\\]]*[hH][^\\]]*)\\]" % "|".join(FLOAT_ENVS), l)
if match:
warns.append((i, "Float uses discouraged placement specifier [%s]" % match.group(2), match.span(2)))
return warns
def check_unused_macro():
warns = []
definitions = []
patterns = [
re.compile("\\\\newcommand\\*?\\{\\\\([A-Za-z@]+)\\}"),
re.compile("\\\\providecommand\\*?\\{\\\\([A-Za-z@]+)\\}"),
re.compile("\\\\def\\\\([A-Za-z@]+)")
]
for i, l in enumerate(tex_lines_clean):
for pattern in patterns:
match = pattern.search(l)
if match:
definitions.append((match.group(1), i, match.span(1)))
break
for name, line, span in definitions:
if len(re.findall("\\\\%s\\b" % re.escape(name), tex)) <= 1:
warns.append((line, "Macro \\%s is defined but never used" % name, span))
return warns
def check_required_sections():
warns = []
sections = {normalize_title(section["title"]) for section in extract_section_ranges()}
if "\\begin{abstract}" in tex:
sections.add("abstract")
required = ["abstract", "introduction", "conclusion"]
missing = [section.title() for section in required if section not in sections]
if missing:
warns.append((-1, "Missing required paper components: %s" % ", ".join(missing)))
return warns
def check_section_balance():
warns = []
sections = extract_section_ranges()
if len(sections) < 2:
return warns
word_counts = []
filtered_sections = [section for section in sections if not section["starred"] and not section["in_appendix"]]
if len(filtered_sections) < 2:
return warns
for section in filtered_sections:
text = " ".join(tex_lines_clean[section["start"]:section["end"]])
word_counts.append(len(re.findall("\\b\\w+\\b", text)))
sorted_counts = sorted(word_counts)
median = sorted_counts[len(sorted_counts) // 2]
if median == 0:
return warns
for section, count in zip(filtered_sections, word_counts):
if count < max(40, int(median * 0.3)):
warns.append((section["line"], "Section '%s' is extremely short compared to the rest of the paper" % section["title"], section["span"]))
elif count > max(600, int(median * 2.5)):
warns.append((section["line"], "Section '%s' is extremely long compared to the rest of the paper" % section["title"], section["span"]))
return warns
def check_deprecated():
warns = []
patterns = [
(re.compile("\\{\\\\bf\\b"), "Deprecated font switch \\bf, use \\textbf{...}"),
(re.compile("\\{\\\\it\\b"), "Deprecated font switch \\it, use \\textit{...}"),
(re.compile("\\{\\\\rm\\b"), "Deprecated font switch \\rm, use \\textrm{...}"),
(re.compile("\\{\\\\sc\\b"), "Deprecated font switch \\sc, use \\textsc{...}"),
(re.compile("\\{\\\\tt\\b"), "Deprecated font switch \\tt, use \\texttt{...}"),
(re.compile("\\$\\$"), "Deprecated display math $$...$$, use \\[...\\] or an equation environment"),
(re.compile("\\\\centerline\\b"), "Deprecated \\centerline command"),
(re.compile("\\\\epsfig\\b"), "Deprecated \\epsfig command, use \\includegraphics")
]
for i, l in enumerate(tex_lines_clean):
for pattern, message in patterns:
match = pattern.search(l)
if match:
warns.append((i, message, match.span()))
return warns
def check_package_conflict():
warns = []
packages = {}
for i, l in enumerate(tex_lines_clean):
for match in re.finditer("\\\\usepackage(?:\\[[^\\]]+\\])?\\{([^\\}]+)\\}", l):
for package in [p.strip() for p in match.group(1).split(",")]:
packages[package] = i
conflicts = [
("subfigure", "subcaption"),
("subfig", "subcaption"),
("natbib", "biblatex")
]
for left, right in conflicts:
if left in packages and right in packages:
warns.append((packages[right], "Conflicting packages loaded together: %s and %s" % (left, right)))
return warns
def check_duplicate_word():
warns = []
for i, l in enumerate(tex_lines_clean):
if in_code(i):
continue
match = re.search("\\b(\\w+)\\s+\\1\\b", l, re.IGNORECASE)
if match:
warns.append((i, "Duplicated adjacent word '%s'" % match.group(1), match.span()))
return warns
def check_paragraph_length():
warns = []
for start, end, text in get_paragraphs():
if in_list(start):
continue
if not re.search("[.!?]", text):
continue
sentence_count = count_sentences(text)
if sentence_count == 2:
warns.append((start, "Paragraph has only %d sentence%s; expected at least 3" % (sentence_count, "" if sentence_count == 1 else "s"), (0, len(tex_lines[start]))))
return warns
def check_section_length():
warns = []
for section in extract_section_ranges():
if section["starred"] or section["in_appendix"]:
continue
paragraphs = [p for p in get_paragraphs(section["start"], section["end"]) if p[0] >= section["start"] and p[0] < section["end"]]
if len(paragraphs) < 3:
warns.append((section["line"], "Section '%s' has only %d paragraph%s; expected at least 3" % (section["title"], len(paragraphs), "" if len(paragraphs) == 1 else "s"), section["span"]))
return warns
def check_subsection_count_sanity():
warns = []
sections = extract_section_ranges()
for idx, section in enumerate(sections):
if section["starred"] or section["in_appendix"]:
continue
next_line = sections[idx + 1]["line"] if idx + 1 < len(sections) else len(tex_lines)
count = 0
for line_no in range(section["start"], next_line):
if re.search("\\\\subsection\\*?\\{", tex_lines_clean[line_no]):
count += 1
if count == 1 or count > 10:
warns.append((section["line"], "Section '%s' has %d subsection%s; expected 0 or between 2 and 10" % (section["title"], count, "" if count == 1 else "s"), section["span"]))
return warns
def check_large_numbers_without_si():
warns = []
for i, l in enumerate(tex_lines):
n = re.search(r"[\s(]\d{5,}[\s),\.]", tex_lines[i])
if n and not in_any_float(i):
warns.append((i, "Large number without formating, consider using siunit", n.span()))
return warns
def check_env_not_in_float(env, float_env):
warns = []
if env in envs:
for e in envs[env]:
if (float_env not in in_env) or (not in_env[float_env][e[0]]):
warns.append((e[0], "%s not within %s environment" % (env, float_env)))
return warns
def check_listing_in_correct_float():
return check_env_not_in_float("lstlisting", "listing")
def check_tabular_in_correct_float():
return check_env_not_in_float("tabular", "table")
def check_tikz_in_correct_float():
return check_env_not_in_float("tikzpicture", "figure")
def check_comment_has_space():
warns = []
for i, l in enumerate(tex_lines):
ls = l.strip()
if "%" in ls:
if ls[0] != "%":
c = re.search("[^\\s\\\\\\}\\{%]+%", l)
if c and not in_code(i):
warns.append((i, "Comment without a whitespace before", c.span()))
return warns
def check_percent_without_siunix():
warns = []
for i, l in enumerate(tex_lines):
n = re.search("\\d+\\s*\\\\%", l)
if n:
warns.append((i, "Number with percent without siunit", n.span(0)))
return warns
def check_short_form():
warns = []
for i, l in enumerate(tex_lines_clean):
n = re.search("[^`%]\\w+'[a-rt-z]", l)
if n:
warns.append((i, "Contracted form used", n.span()))
return warns
def check_labels_referenced():
warns = []
labels = [] #re.findall("\\\\label\{([^\\}]+)\}", tex)
for i, l in enumerate(tex_lines_clean):
lab = re.search(r"\\label\{([^\}]+)\}", l)
if lab:
labels.append((lab.group(1), i, lab.span()))
for lab in labels:
found = False
for i, l in enumerate(tex_lines):
if ("ref{%s}" % lab[0]) in l:
found = True
break
if not found:
if not (lab[0].startswith("sec") or lab[0].startswith("subsec")):
warns.append((lab[1], "Label %s is not referenced" % lab[0], lab[2]))
return warns
def check_section_capitalization():
warns = []
for i, l in enumerate(tex_lines):
n = re.search("(section|paragraph)\\{([^\\}]+)\\}", l)
if n:
try:
words = n.group(2).split(" ")
for w in words:
if len(w) > 4 and w[0].islower():
warns.append((i, "Wrong capitalization of header", (l.index(w), l.index(w) + 1)))
break
except:
pass
return warns
def check_quotation():
warns = []
for i, l in enumerate(tex_lines_clean):
ws = re.search("[^\\\\]\"\\w+", l)
we = re.search("\\w+\"", l)
if (ws or we) and not in_code(i):
warns.append((i, "Wrong quotation, use `` and '' instead of \"", ws.span() if ws else we.span()))
return warns
def check_hline_in_table():
warns = []
for i, l in enumerate(tex_lines):
hl = re.search("\\\\hline", l)
if hl:
if "tabular" in in_env and in_env["tabular"]:
warns.append((i, "\\hline in table, consider using \\toprule, \\midrule, \\bottomrule.", hl.span()))
return warns
def check_space_before_punctuation():
warns = []
for i, l in enumerate(tex_lines):
s = re.search("\\s+[,.!?:;]", l)
if s and not in_any_env(i):
warns.append((i, "Spacing before punctuation", s.span()))
return warns
def check_headers_without_text():
warns = []
for i, l in enumerate(tex_lines):
n = re.search("(section|paragraph)\\{([^\\}]+)\\}", l)
if n:
nx = i
while (nx + 1) < len(tex_lines):
nx += 1
if len(tex_lines[nx].strip()) == 0: continue
if tex_lines[nx].strip().startswith("%"): continue
nn = re.search("(section|paragraph)\\{([^\\}]+)\\}", tex_lines[nx])
if nn:
warns.append((i, "Section header without text before next header", n.span()))
break
return warns
def check_one_sentence_paragraphs():
warns = []
for i, l in enumerate(tex_lines):
if i > 0 and i < len(tex_lines) - 1:
if len(tex_lines[i - 1].strip()) == 0 and len(tex_lines[i + 1].strip()) == 0 and len(tex_lines[i].strip()) > 0:
if tex_lines[i].strip().startswith("\\"): continue
if ". " in tex_lines[i]: continue
warns.append((i, "One-sentence paragraph", (0, len(tex_lines[i]))))
return warns
def check_multiple_sentences_per_line():
warns = []
for i, l in enumerate(tex_lines_clean):
p = re.search("[\\.!?]\\s+\\w+", l.rstrip())
if p and "vs." not in l.rstrip():
warns.append((i, "Multiple sentences in one line", p.span()))
return warns
def check_unbalanced_brackets():
warns = []
for i, l in enumerate(tex_lines):
if in_code(i):
continue
masked = tex_lines_math_masked[i]
if masked.count("(") != masked.count(")"):
first = min(masked.index("(") if masked.count("(") > 0 else len(masked), masked.index(")") if masked.count(")") > 0 else len(masked))
last = max(masked.rindex("(") if masked.count("(") > 0 else len(masked), masked.rindex(")") if masked.count(")") > 0 else len(masked))
warns.append((i, "Mismatch of opening and closing parenthesis", (first, last)))
return warns
def check_and_or():
warns = []
for i, l in enumerate(tex_lines):
ao = re.search("and/or", l)
if ao:
warns.append((i, "And/or discouraged in academic writing", ao.span()))
return warns
def check_ellipsis():
warns = []
for i, l in enumerate(tex_lines_clean):
el = re.search("\\w+\\.\\.\\.", l)
if el:
warns.append((i, "Ellipsis \"...\" discouraged in academic writing", el.span()))
return warns
def check_etc():
warns = []
for i, l in enumerate(tex_lines):
el = re.search("\\s+etc[\\.\\w]", l)
if el:
warns.append((i, "Unspecific \"etc\" discouraged in academic writing", el.span()))
return warns
def check_footnote():
warns = []
for i, l in enumerate(tex_lines):
fn = re.search("\\s*\\\\footnote\\{[^\\}]+\\}\\.", l)
if fn:
warns.append((i, "Footnote must be after the full stop", fn.span()))
return warns
def check_table_top_caption():
warns = []
if "table" in envs:
for table in envs["table"]:
caption = -1
tab = -1
for intab in range(*table):
if re.search("\\\\caption\\{", tex_lines[intab]):
caption = intab
if re.search("\\\\begin\\{tabular", tex_lines[intab]):
tab = intab
if tab != -1 and caption != -1 and tab < caption:
warns.append((table[0], "Table caption must be above table"))
return warns
def check_punctuation_end_of_line():
warns = []
for i, l in enumerate(tex_lines_clean):
sl = l.strip()
if len(sl) < 10: continue
if len(sl.split(" ")) < 8: continue
if in_any_float(i): continue
if "lstlisting" in in_env and in_env["lstlisting"][i]: continue
if sl.startswith("\\") or sl.startswith("%"): continue
if sl.endswith("\\\\") or sl.endswith("}"): continue
if sl.endswith(".") or sl.endswith("!") or sl.endswith("?") or sl.endswith(":") or sl.endswith(";"): continue
p = re.search("\\s*[\\w})$]+[\\.!?}{:;\\\\]\\s*$", l.rstrip())
if not p:
warns.append((i, "Line ends without punctuation", (len(l) - 2, len(l))))
return warns
def check_table_vertical_lines():
warns = []
for i, l in enumerate(tex_lines):