-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLaTeXChecker_v2.8.py
1705 lines (1665 loc) · 86 KB
/
LaTeXChecker_v2.8.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
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
import os
from sys import argv, executable, exit
from re import findall
from time import sleep
PLATFORM = __import__("platform").system().upper()
os.chdir(os.path.abspath(os.path.dirname(__file__)))
EXIT_SUCCESS = 0
EXIT_FAILURE = 1
CLEAR_SCREEN_COMMAND = ("CLS" if PLATFORM == "WINDOWS" else "clear") if __import__("sys").stdin.isatty() else None
STARTUP_COMMAND_FORMAT = "START \"\" \"{0}\" \"{1}\" \"{2}\"" if PLATFORM == "WINDOWS" else "\"{0}\" \"{1}\" \"{2}\"&"
class DebugLevel:
defaultCharacter = "?"
defaultName = "*"
defaultSymbol = "[?]"
defaultValue = 0
def __init__(self:object, d:dict) -> object:
self.character = d["character"] if "character" in d else DebugLevel.defaultCharacter
self.name = d["name"] if "name" in d else DebugLevel.defaultName
self.symbol = d["symbol"] if "symbol" in d else DebugLevel.defaultSymbol
self.value = d["value"] if "value" in d else DebugLevel.defaultValue
def __eq__(self:object, other:object) -> bool:
if isinstance(other, DebugLevel):
return self.value == other.value
elif isinstance(other, (int, float)):
return self.value == other
else:
return False
def __ne__(self:object, other:object) -> bool:
if isinstance(other, DebugLevel):
return self.value != other.value
elif isinstance(other, (int, float)):
return self.value != other
else:
return True
def __lt__(self:object, other:object) -> bool:
if isinstance(other, DebugLevel):
return self.value < other.value
elif isinstance(other, (int, float)):
return self.value < other
else:
raise TypeError("TypeError: '<' not supported between instances of '{0}' and '{1}'".format(type(self), type(other)))
def __le__(self:object, other:object) -> bool:
if isinstance(other, DebugLevel):
return self.value <= other.value
elif isinstance(other, (int, float)):
return self.value <= other
else:
raise TypeError("TypeError: '<=' not supported between instances of '{0}' and '{1}'".format(type(self), type(other)))
def __gt__(self:object, other:object) -> bool:
if isinstance(other, DebugLevel):
return self.value > other.value
elif isinstance(other, (int, float)):
return self.value > other
else:
raise TypeError("TypeError: '>' not supported between instances of '{0}' and '{1}'".format(type(self), type(other)))
def __ge__(self:object, other:object) -> bool:
if isinstance(other, DebugLevel):
return self.value >= other.value
elif isinstance(other, (int, float)):
return self.value >= other
else:
raise TypeError("TypeError: '>=' not supported between instances of '{0}' and '{1}'".format(type(self), type(other)))
def __bool__(self:object) -> bool:
return bool(self.value)
def __int__(self:object) -> int:
return self.value
def __str__(self:object) -> str:
return str(self.symbol)
Prompt = DebugLevel({"character":"P", "name":"Prompt", "symbol":"[P]", "value":100})
Fatal = DebugLevel({"character":"F", "name":"Fatal", "symbol":"[F]", "value":60})
Critical = DebugLevel({"character":"C", "name":"Critical", "symbol":"[C]", "value":50})
Error = DebugLevel({"character":"E", "name":"Error", "symbol":"[E]", "value":40})
Warning = DebugLevel({"character":"W", "name":"Warning", "symbol":"[W]", "value":30})
Info = DebugLevel({"character":"I", "name":"Info", "symbol":"[I]", "value":20})
Debug = DebugLevel({"character":"D", "name":"Debug", "symbol":"[D]", "value":10})
class PointerNode:
def __init__(self:object, filePath:str, parentPointerNode:object = None) -> object:
self.__filePath = os.path.abspath(str(filePath).replace("\"", "")) # must be an absolute path since __eq__ needs to use it
self.__lineIdx = 0 # the initialization value
self.__charIdx = -1 # the initialization value
self.__parentPointerNode = parentPointerNode if isinstance(parentPointerNode, PointerNode) else None
self.__children = None # initialization flag
self.__lines = None # initialization flag
def __getTxt(self:object, filePath:str, index:int = 0) -> str: # get .txt content
coding = ("utf-8", "gbk", "utf-16") # codings
if 0 <= index < len(coding): # in the range
try:
with open(filePath, "r", encoding = coding[index]) as f:
content = f.read()
return content[1:] if content.startswith("\ufeff") else content # if utf-8 with BOM, remove BOM
except (UnicodeError, UnicodeDecodeError):
return self.__getTxt(filePath, index + 1) # recursion
except:
return None
else:
return None # out of range
def initialize(self:object) -> bool:
content = self.__getTxt(self.__filePath)
if content is None:
self.__lines = None # avoid re-initialization
self.__children = None # avoid re-initialization
return False
elif content:
self.__lines = content.splitlines()
self.__children = []
return True
else:
self.__lines = [""]
self.__children = []
return True
def isInitialized(self:object) -> bool:
return isinstance(self.__lines, list) and isinstance(self.__children, list)
def hasNextChar(self:object) -> bool: # only just the status of the current pointer node
return 0 <= self.__lineIdx < len(self.__lines) and 0 <= self.__charIdx + 1 < len(self.__lines[self.__lineIdx]) if self.isInitialized() else None
def nextChar(self:object) -> bool:
bRet = self.hasNextChar() # judge if it is initialized and if there is a following character
if bRet:
self.__charIdx += 1 # increse the character count
return bRet
def hasNextLine(self:object) -> bool: # only just the status of the current pointer node
return self.__lineIdx + 1 < len(self.__lines) if self.isInitialized() else None
def nextLine(self:object) -> bool:
bRet = self.hasNextLine() # judge if it is initialized and if there is a following line
if bRet:
self.__lineIdx += 1 # increase the line count
self.__charIdx = -1 # reset the char index
return bRet
def isEOF(self:object) -> bool:
return self.__lineIdx + 1 == len(self.__lines) and self.__charIdx >= 0 and self.__charIdx + 1 == len(self.__lines[self.__lineIdx]) if self.isInitialized() else None
def getCurrentChar(self:object) -> str:
return self.__lines[self.__lineIdx][self.__charIdx] if self.isInitialized() and self.__lineIdx < len(self.__lines) and 0 <= self.__charIdx < len(self.__lines[self.__lineIdx]) else None
def getNextChar(self:object) -> str:
return self.__lines[self.__lineIdx][self.__charIdx + 1] if self.hasNextChar() else None
def getCurrentLine(self:object) -> str:
return self.__lines[self.__lineIdx] if self.isInitialized() and self.__lineIdx < len(self.__lines) else None
def getRemainingChars(self:object) -> str:
return self.__lines[self.__lineIdx][self.__charIdx + 1:] if self.isInitialized() and self.__lineIdx < len(self.__lines) else None
def addChildPointerNode(self:object, pointerNode:object) -> bool:
if isinstance(pointerNode, PointerNode) and pointerNode.isInitialized():
self.__children.append(pointerNode)
return True
else:
return False
def getFilePath(self:object) -> str:
return self.__filePath if self.isInitialized() else None
def getCurrentLocation(self:object) -> tuple:
return (self.__filePath, self.__lineIdx, self.__charIdx)
def getChildren(self:object, isReversed:bool = False) -> list:
return (self.__children[::-1] if isReversed else self.__children[::]) if self.isInitialized() else None
def __eq__(self:object, obj:str|object) -> bool:
if PLATFORM == "WINDOWS":
return isinstance(obj, PointerNode) and self.__filePath.lower() == obj.__filePath.lower() or isinstance(obj, str) and self.__filePath.lower() == obj.lower()
else:
return isinstance(obj, PointerNode) and self.__filePath == obj.__filePath or isinstance(obj, str) and self.__filePath == obj
class Pointer:
def __init__(self:object, rootFilePath:str) -> object:
absRootFilePath = os.path.abspath(str(rootFilePath).replace("\"", ""))
self.__pointerNodeStack = [] # stack (stack[0] is the root) # initialization flag
self.__pointerNodeStack.append(PointerNode(absRootFilePath)) # write separately to avoid the absence of this attribute caused by exceptions in PointerNode
self.__currentPointerNode = None # initialization flag
self.__baseFolderPath = os.path.split(absRootFilePath)[0]
self.__lastError = "Currently, there are no errors. "
def initialize(self:object) -> bool:
if self.__pointerNodeStack and self.__pointerNodeStack[0].initialize():
self.__currentPointerNode = self.__pointerNodeStack[0]
return True
else:
self.__pointerNodeStack = [self.__pointerNodeStack[0]] if self.__pointerNodeStack else [] # avoid re-initialization
self.__currentPointerNode = None # avoid re-initialization
return False
def isInitialized(self:object) -> bool:
return bool(self.__pointerNodeStack) and isinstance(self.__currentPointerNode, PointerNode)
def hasNextChar(self:object, fileSwitch:bool = True) -> bool: # in the current line including "1\input{2}3"
if self.isInitialized():
if self.__currentPointerNode.hasNextChar():
return True
elif isinstance(fileSwitch, bool) and fileSwitch:
for i in range(len(self.__pointerNodeStack) - 1, -1, -1): # check the parents constantly
if self.__pointerNodeStack[i].hasNextChar():
return True
elif not self.__pointerNodeStack[i].isEOF(): # there is a following line but there is not a following character
return False
return False # no following characters are followed / all the opened files report EOF
else:
return None # not initialized
def nextChar(self:object, fileSwitch:bool = True) -> bool:
bRet = self.hasNextChar(fileSwitch = fileSwitch) # judge if it is initialized and if there is a following character in the current line
if bRet:
while len(self.__pointerNodeStack) > 1: # no need to consider the switch again; keep the main file in the stack
if self.__pointerNodeStack[-1].nextChar():
return True
elif not self.__pointerNodeStack[-1].isEOF(): # there is a following line but there is not a following character
return False
self.__pointerNodeStack.pop()
self.__currentPointerNode = self.__pointerNodeStack[-1] # move the pointer
if self.__pointerNodeStack[0].nextChar(): # all the opened non-main files report EOF
return True
else:
return False # the main file
else:
return bRet
def hasNextLine(self:object, fileSwitch:bool = True) -> bool:
if self.isInitialized():
if self.__currentPointerNode.hasNextLine():
return True
else:
for i in range(len(self.__pointerNodeStack) - 1, -1, -1): # check the parents constantly
if self.__pointerNodeStack[i].hasNextLine():
return True
return False # all the opened files report EOF
else:
return None # not initialized
def nextLine(self:object, fileSwitch:bool = True) -> bool:
bRet = self.hasNextLine() # judge if it is initialized and if there is a following line
if bRet:
while len(self.__pointerNodeStack) > 1: # keep the main file in the stack
if self.__pointerNodeStack[-1].nextLine():
return True
self.__pointerNodeStack.pop()
self.__currentPointerNode = self.__pointerNodeStack[-1] # move the pointer
if self.__pointerNodeStack[0].nextLine(): # all the opened non-main files report the end of lines
return True
else:
return False # the main file
else:
return bRet
def getCurrentChar(self:object) -> str:
return self.__currentPointerNode.getCurrentChar() if self.isInitialized() else None
def getNextChar(self:object, fileSwitch:bool = True) -> str:
bRet = self.hasNextChar(fileSwitch = fileSwitch) # judge if it is initialized and if there is a following character in the current line
if bRet:
for i in range(len(self.__pointerNodeStack) - 1, -1, -1): # check the parents constantly
if self.__pointerNodeStack[i].hasNextChar():
return self.__pointerNodeStack[i].getNextChar()
return None # all the opened files report EOF
else:
return bRet
def getCurrentLine(self:object) -> str:
return self.__currentPointerNode.getCurrentLine() if self.isInitialized() else None
def getRemainingCharactersInTheCurrentLineOfTheCurrentFile(self:object) -> str:
return self.__currentPointerNode.getRemainingChars() if self.isInitialized() else None
def getCurrentLocation(self:object) -> tuple:
if self.isInitialized():
tp = self.__currentPointerNode.getCurrentLocation()
return (os.path.relpath(str(tp[0]), self.__baseFolderPath), tp[1], tp[2]) if isinstance(tp, tuple) else None
else:
return None
def getCurrentLocationDescription(self:object) -> str:
tp = self.getCurrentLocation()
return ("Char {0}, Line {1}, File \"{2}\"".format(tp[2], tp[1] + 1, tp[0]) if tp[2] >= 0 else "Line {1}, File \"{2}\"".format(tp[2], tp[1] + 1, tp[0])) if isinstance(tp, tuple) else None
def addPointerNode(self:object, filePath:str, canCallAgain:bool = True) -> bool:
if not self.isInitialized():
self.__lastError = "The instance of ``Pointer`` has not been initialized. "
return False
elif not isinstance(filePath, str):
self.__lastError = "The passed file path is not a string. "
return False
elif not isinstance(canCallAgain, bool):
self.__lastError = "The flag for calling the pointer node adding method function is unclear. "
return False
strippedFilePath = filePath.replace("\"", "").strip()
absFilePath = os.path.abspath(strippedFilePath if os.path.isabs(strippedFilePath) else os.path.join(self.__baseFolderPath, strippedFilePath))
if absFilePath in self.__pointerNodeStack:
self.__lastError = "The file \"{0}\" has been in the stack for resolving. Please check and make sure that there are no recursive calls. ".format(absFilePath).replace("\\", "\\\\")
return False
pointerNode = PointerNode(absFilePath, parentPointerNode = self.__currentPointerNode)
if pointerNode.initialize() and self.__currentPointerNode.addChildPointerNode(pointerNode):
self.__currentPointerNode = pointerNode
self.__pointerNodeStack.append(pointerNode)
self.__lastError = "Currently, there are no errors. "
return True
elif canCallAgain and not strippedFilePath.endswith(".bib") and not strippedFilePath.endswith(".tex"): # call again for the ``.tex`` extension added
return self.addPointerNode(strippedFilePath + ".tex", False)
else:
self.__lastError = "Failed to initialize the call to \"{0}\". ".format(absFilePath).replace("\\", "\\\\")
return False
def getLastError(self:object) -> str:
return self.__lastError
def getTree(self:object, indentationSymbol:str = "\t", indentationCount:int = 0) -> str:
if self.isInitialized() and isinstance(indentationSymbol, str) and "\r" not in indentationSymbol and "\n" not in indentationSymbol and isinstance(indentationCount, int) and indentationCount >= 0:
stack = [(self.__pointerNodeStack[0], 0)]
res = []
while stack:
node, level = stack.pop()
if node.isInitialized():
res.append("{0}{1}".format(str(indentationSymbol) * level, os.path.relpath(node.getFilePath(), self.__baseFolderPath)))
stack.extend([(n, level + 1) for n in node.getChildren(isReversed = True)])
return "\n".join(res)
else:
return None
class StructureNode:
def __init__(self:object, header:str = "", parent:object = None) -> object:
self.__header = header if isinstance(header, str) else ""
self.__footer = ""
self.__type = None # initialization flag
self.__descriptor = None
self.__children = None # initialization flag
self.__media = None # initialization flag
self.__parent = parent if isinstance(parent, StructureNode) else None
def initialize(self:object) -> bool:
if self.__header:
if "Root" == self.__header:
self.__type = "Root"
self.__descriptor = None
elif self.__header.startswith("\\begin{") and self.__header.endswith("}"):
self.__type = "Environment"
self.__descriptor = self.__header[7:-1] # cannot compile "\\begin{ equation }" in LaTeX
elif self.__header.startswith("\\documentclass"):
self.__type = "DocumentClass"
self.__descriptor = None
elif ( \
( \
self.__header.startswith("\\section{") or self.__header.startswith("\\section*{") \
or self.__header.startswith("\\subsection{") or self.__header.startswith("\\subsection*{") \
or self.__header.startswith("\\subsubsection{") or self.__header.startswith("\\subsubsection*{") \
) \
and self.__header.endswith("}") \
):
self.__type = "S" + self.__header[2:self.__header.index("{")]
self.__descriptor = self.__header[self.__header.index("{") + 1:-1].strip()
elif self.__header in ("$", "$$", "\\(", "\\["):
self.__type = "Equation"
self.__descriptor = self.__header
else:
self.__type = None # avoid re-initialization
self.__children = None # avoid re-initialization
return False
self.__children = []
self.__media = {}
return True
else:
self.__type = None # avoid re-initialization
self.__children = None # avoid re-initialization
self.__media = None # avoid re-initialization
return False
def isInitialized(self:object) -> bool:
return isinstance(self.__type, str) and isinstance(self.__children, list) and isinstance(self.__media, dict)
def addChildStructureNode(self:object, structureNode:object) -> bool:
if self.isInitialized() and isinstance(structureNode, StructureNode):
self.__children.append(structureNode)
return True
else:
return None
def isFooterAccepted(self:object, footer:str) -> bool:
if self.isInitialized() and isinstance(footer, str):
if "Root" == footer or footer.startswith("\\documentclass"):
return self.__type in ("DocumentClass", "Section", "Section*", "Subsection", "Subsection*", "Subsubsection", "Subsubsection*")
elif "\\begin{thebibliography}" == footer:
return self.__type in ("Section", "Section*", "Subsection", "Subsection*", "Subsubsection", "Subsubsection*")
elif "\\end{document}" == footer:
return self.__type in ("Section", "Section*", "Subsection", "Subsection*", "Subsubsection", "Subsubsection*") or "Environment" == self.__type and "document" == self.__descriptor
elif footer.startswith("\\end{") and footer.endswith("}"):
return (
"Environment" == self.__type and footer[5:-1] == self.__descriptor
or "document" == footer[5:-1] and self.__type in ("Section", "Section*", "Subsection", "Subsection*", "Subsubsection", "Subsubsection*")
)
elif (footer.startswith("\\section{") or footer.startswith("\\section*{") or footer.startswith("\\subsection{") or footer.startswith("\\subsection*{") or footer.startswith("\\subsubsection") or footer.startswith("\\subsubsection*")) and footer.endswith("}"):
if self.__type in ("Section", "Section*"):
return footer.startswith("\\section{") or footer.startswith("\\section*{") # only "\\section" and "\\section*" are allowed
elif self.__type in ("Subsection", "Subsection*"):
return footer.startswith("\\section{") or footer.startswith("\\section*{") or footer.startswith("\\subsection{") or footer.startswith("\\subsection*{") # >=
elif self.__type in ("Subsubsection", "Subsubsection*"):
return True # all the three are accepted
else:
return False
elif footer in ("$", "$$"):
return "Equation" == self.__type and footer == self.__descriptor
elif "\\)" == footer:
return "Equation" == self.__type and "\\(" == self.__descriptor
elif "\\]" == footer:
return "Equation" == self.__type and "\\[" == self.__descriptor
else: # Root etc.
return False
else:
return None
def setFooter(self:object, footer:str) -> bool:
bRet = self.isFooterAccepted(footer)
if bRet and self.__header not in ("DocumentClass", "Section", "Section*", "Subsection", "Subsubsection"): # the "documentclass" and section-like structures do not require footnotes
self.__footer = footer
return bRet
def addPlainText(self:object, strings:str = "") -> bool:
if self.isInitialized() and isinstance(strings, str):
if self.__children and isinstance(self.__children[-1], str): # the last node is a string
self.__children[-1] += strings
else: # create a new string
self.__children.append(strings)
else:
return None
def addMedia(self:object, mediumType:str) -> bool:
if self.isInitialized() and isinstance(mediumType, str):
self.__media.setdefault(mediumType, 0)
self.__media[mediumType] += 1
return True
else:
return None
def getType(self:object) -> str:
return self.__type # return None if it is None
def getDescriptor(self:object) -> str|None:
return self.__descriptor # return None if it is None
def getMedia(self:object, mediumType:str|tuple|list|None = None) -> int|tuple:
if self.isInitialized():
if mediumType is None:
return tuple(self.__media.items())
elif isinstance(mediumType, str):
return self.__media[mediumType] if mediumType in self.__media else 0
elif isinstance(mediumType, tuple):
return tuple((self.__media[m] if m in self.__media else 0) for m in mediumType if isinstance(m, str))
elif isinstance(mediumType, list):
return [(self.__media[m] if m in self.__media else 0) for m in mediumType if isinstance(m, str)]
else:
return None
else:
return None
def getChildren(self:object, isReversed:bool = False) -> list:
return (self.__children[::-1] if isReversed else self.__children[::]) if self.isInitialized() else None
def getParent(self:object) -> object:
return self.__parent
def __str__(self:object) -> str:
return "{0}".format(self.__type) if self.__descriptor is None else "{0}({1})".format(self.__type, self.__descriptor)
class Structure:
def __init__(self:object) -> object:
self.__rootStructureNode = None # initialization flag
self.__currentStructureNode = None # initialization flag
def initialize(self:object) -> bool:
self.__rootStructureNode = StructureNode("Root")
if self.__rootStructureNode.initialize():
self.__currentStructureNode = self.__rootStructureNode
return True
else:
self.__rootStructureNode = None # avoid re-initialization
self.__currentStructureNode = None # avoid re-initialization
return False
def isInitialized(self:object) -> bool:
return isinstance(self.__rootStructureNode, StructureNode) and isinstance(self.__currentStructureNode, StructureNode)
def addPlainText(self:object, strings:str = "") -> bool:
return self.__currentStructureNode.addPlainText(strings) if self.isInitialized() else None
def addMedia(self:object, mediumType:str) -> bool:
if isinstance(mediumType, str):
bRet = True
pStructureNode = self.__currentStructureNode
while pStructureNode != self.__rootStructureNode:
bRet = pStructureNode.addMedia(mediumType) and bRet
pStructureNode = pStructureNode.getParent()
bRet = pStructureNode.addMedia(mediumType) and bRet # the root
return bRet
else:
return False
def addStructureNode(self:object, header:str) -> bool:
if self.isInitialized() and isinstance(header, str):
while ( \
( \
( \
header.startswith("\\documentclass") or header.startswith("\\section{") or header.startswith("\\section*{") \
or header.startswith("\\subsection{") or header.startswith("\\subsection*{") \
or header.startswith("\\subsubsection{") or header.startswith("\\subsubsection*{") \
) \
and header.endswith("}") or "\\begin{thebibliography}" == header \
) and self.__currentStructureNode.isFooterAccepted(header) \
): # go back to the parent node if the footer is accepted
self.__currentStructureNode = self.__currentStructureNode.getParent()
structureNode = StructureNode(header = header, parent = self.__currentStructureNode)
if structureNode.initialize() and self.__currentStructureNode.addChildStructureNode(structureNode):
self.__currentStructureNode = structureNode
return True
else:
return False
else:
return None
def canLeaveCurrentStructureNode(self:object, footer:str) -> bool:
if self.isInitialized() and isinstance(footer, str):
return self.__currentStructureNode != self.__rootStructureNode and self.__currentStructureNode.isFooterAccepted(footer)
else:
return None
def leaveCurrentStructureNode(self:object, footer:str = "", leavingQueue:list = []) -> bool:
if isinstance(leavingQueue, list):
leavingQueue.clear()
else:
return None
bRet = self.canLeaveCurrentStructureNode(footer)
if bRet:
if footer == "\\end{document}":
while self.canLeaveCurrentStructureNode(footer):
self.__currentStructureNode.setFooter(footer)
leavingQueue.append(str(self.__currentStructureNode))
self.__currentStructureNode = self.__currentStructureNode.getParent()
else:
self.__currentStructureNode.setFooter(footer)
leavingQueue.append(str(self.__currentStructureNode))
self.__currentStructureNode = self.__currentStructureNode.getParent()
return bRet
def getCurrentStructureNodeDescription(self:object) -> str:
return str(self.__currentStructureNode) if self.isInitialized() else None
def endStructure(self:object) -> bool:
while self.canLeaveCurrentStructureNode("Root"):
self.leaveCurrentStructureNode("Root")
return self.__currentStructureNode == self.__rootStructureNode
def getMedia(self:object, mediumType:str|tuple|list|None = None, indentationSymbol:str = "\t", indentationCount:int = 0) -> str:
if self.isInitialized() and isinstance(mediumType, (str, tuple, list, None)) and isinstance(indentationSymbol, str) and "\r" not in indentationSymbol and "\n" not in indentationSymbol and isinstance(indentationCount, int) and indentationCount >= 0:
stack = [(self.__rootStructureNode, indentationCount)]
res = []
while stack:
node, level = stack.pop()
if isinstance(node, StructureNode) and node.isInitialized():
r = node.getMedia(mediumType)
if isinstance(r, int) and r >= 1: # pruning
res.append("{0}{1} -> {2}".format(indentationSymbol * level, node, r))
stack.extend([(n, level + 1) for n in node.getChildren(isReversed = True)])
return "\n".join(res)
else:
return None
def getTree(self:object, mode:str = "A", indentationSymbol:str = "\t", indentationCount:int = 0) -> str:
if self.isInitialized() and isinstance(mode, str) and mode in ("A", "B", "D") and isinstance(indentationSymbol, str) and "\r" not in indentationSymbol and "\n" not in indentationSymbol and isinstance(indentationCount, int) and indentationCount >= 0:
stack = [(self.__rootStructureNode, indentationCount)]
res = []
if "D" == mode:
while stack:
node, level = stack.pop()
if isinstance(node, str): # also shows the text
res.append("{0}Text({1})".format(indentationSymbol * level, len(node)))
elif node.isInitialized():
res.append("{0}{1}".format(indentationSymbol * level, node))
stack.extend([(n, level + 1) for n in node.getChildren(isReversed = True)])
elif "B" == mode:
while stack:
node, level = stack.pop() # only shows some necessary items
if isinstance(node, StructureNode) and node.isInitialized() and node.getType() in ("Root", "DocumentClass", "Environment", "Section", "Section*", "Subsection", "Subsection*", "Subsubsection", "Subsubsection*"):
res.append("{0}{1}".format(indentationSymbol * level, node))
stack.extend([(n, level + 1) for n in node.getChildren(isReversed = True)])
else:
while stack:
node, level = stack.pop()
if isinstance(node, StructureNode) and node.isInitialized():
nodeType = node.getType()
if nodeType in ("Root", "DocumentClass", "Section", "Section*", "Subsection", "Subsection*", "Subsubsection", "Subsubsection*"):
res.append("{0}{1}".format(indentationSymbol * level, nodeType)) # only shows the type
stack.extend([(n, level + 1) for n in node.getChildren(isReversed = True)])
elif "Environment" == nodeType:
res.append("{0}{1}".format(indentationSymbol * level, node.getDescriptor())) # only shows the descriptor
stack.extend([(n, level + 1) for n in node.getChildren(isReversed = True)])
return "\n".join(res)
else:
return None
class Checker:
def __init__(self:object, mainTexPath:str = None, debugLevel:DebugLevel|int = Debug) -> object:
self.__mainTexPath = os.path.abspath(mainTexPath.replace("\"", "")) if isinstance(mainTexPath, str) else None # transfer to the absolute path
self.__pointer = None
self.__structure = None
self.__definitions = {}
self.__labels = {}
self.__citations = {}
if isinstance(debugLevel, DebugLevel):
self.__debugLevel = debugLevel
else:
try:
self.__debugLevel = DebugLevel({"value":int(debugLevel)})
except:
self.__debugLevel = Debug
self.__print("The debug level specified is invalid. It is defaulted to {0} ({1}). ".format(self.__debugLevel.name, self.__debugLevel.value), Warning)
self.__flag = False
def __print(self:object, strings:str|object, debugLevel:DebugLevel = Info, indentationSymbol:str = "\t", indentationCount:int = 0) -> bool:
if isinstance(debugLevel, DebugLevel) and isinstance(indentationSymbol, str) and isinstance(indentationCount, int):
if debugLevel >= self.__debugLevel:
try:
print("\n".join(["{0} {1}{2}".format(debugLevel, (indentationSymbol * indentationCount if indentationCount >= 1 else ""), string) for string in str(strings).split("\n")]))
return True
except: # avoid exceptions in __str__
return None
else:
return False
else:
return None
def __input(self:object, strings:str, indentationSymbol:str = "\t", indentationCount:int = 0) -> str:
try:
return input("\n".join(["{0} {1}{2}".format(Prompt, (indentationSymbol * indentationCount if isinstance(indentationSymbol, str) and isinstance(indentationCount, int) and indentationCount >= 1 else ""), string) for string in str(strings).splitlines()]))
except KeyboardInterrupt:
print() # print an empty line
self.__print("The input process was interrupted by users. None will be returned as the default value. ", Warning)
return None
except BaseException as e:
self.__print("The input process was interrupted by the following exceptions. ", Error)
self.__print(e, Error, indentationCount = 1)
return None
def __skipSpaces(self:object, lineSwitch:bool = True) -> bool:
if isinstance(lineSwitch, bool):
while self.__pointer.hasNextChar(fileSwitch = False) and self.__pointer.getNextChar(fileSwitch = False) in (" ", "\t"): # skip spaces in the current line
self.__pointer.nextChar(fileSwitch = False)
if self.__pointer.hasNextChar(fileSwitch = False): # remaining non-space characters exist
return True
elif lineSwitch: # allow a line separator
if self.__pointer.hasNextLine(fileSwitch = False):
self.__pointer.nextLine(fileSwitch = False)
while self.__pointer.hasNextChar(fileSwitch = False) and self.__pointer.getNextChar(fileSwitch = False) in (" ", "\t"): # skip spaces in the following line
self.__pointer.nextChar(fileSwitch = False)
if self.__pointer.hasNextChar(fileSwitch = False):
return True
else:
self.__print("There should be only at most a line between the command definition command and the command but there are two more at {0}. ".format(self.__pointer.getCurrentLocationDescription()), Error)
return False
else:
self.__print("While scanning the command, the file reports an EOF signal at {0}. ".format(self.__pointer.getCurrentLocationDescription()), Error)
return False
else:
self.__print("There should be non-space characters at the end of the line at {0}. ".format(self.__pointer.getCurrentLocationDescription()), Error)
else:
return None
def __fetchBraces(self:object, fileSwitch:bool = False) -> str:
if not isinstance(fileSwitch, bool) or not self.__pointer.hasNextChar(fileSwitch = fileSwitch):
return (False, "")
if "{" == self.__pointer.getNextChar(fileSwitch = fileSwitch):
layer, mainBody = 1, "{"
self.__pointer.nextChar(fileSwitch = fileSwitch)
while True:
if self.__pointer.hasNextChar(fileSwitch = fileSwitch):
ch = self.__pointer.getNextChar(fileSwitch = fileSwitch)
mainBody += ch
if "\\" == ch:
if self.__pointer.hasNextChar(fileSwitch = fileSwitch):
self.__pointer.nextChar(fileSwitch = fileSwitch)
mainBody += self.__pointer.getCurrentChar()
elif self.__pointer.hasNextLine(fileSwitch = fileSwitch):
self.__pointer.nextLine(fileSwitch = fileSwitch)
mainBody += "\n"
else:
self.__print("A missing \"}\" is detected when scanning the main body at {0}. ".format(self.__pointer.getCurrentLocationDescription()), Error)
return False
elif "{" == ch:
layer += 1
elif "}" == ch:
layer -= 1
if 0 == layer:
break
elif "%" == ch:
if self.__pointer.hasNextLine(fileSwitch = fileSwitch):
self.__pointer.nextLine(fileSwitch = fileSwitch)
else:
self.__print("There are not following lines after the \"%\" symbol at {0}. ".format(self.__pointer.getCurrentLocationDescription()), Error)
return False
self.__pointer.nextChar(fileSwitch = fileSwitch)
elif self.__pointer.hasNextLine(fileSwitch = fileSwitch):
self.__pointer.nextLine(fileSwitch = fileSwitch)
mainBody += "\n"
else:
self.__print("An EOF signal is reported during scanning the main body at {0}. ".format(self.__pointer.getCurrentLocationDescription()), Error)
return (False, mainBody)
return (True, mainBody)
else:
self.__pointer.nextChar(fileSwitch = fileSwitch)
return (True, self.__pointer.getCurrentChar())
def __convertEscaped(self:object, string:str) -> str:
if isinstance(string, str):
vec = list(string)
d = {"\\":"\\\\", "\"":"\\\"", "\'":"\\\'", "\a":"\\a", "\b":"\\b", "\f":"\\f", "\n":"\\n", "\r":"\\r", "\t":"\\t", "\v":"\\v"}
for i, ch in enumerate(vec):
if ch in d:
vec[i] = d[ch]
elif not ch.isprintable():
vec[i] = "\\x" + hex(ord(ch))[2:]
return "".join(vec)
else:
return str(string)
def __handleBibTeX(self:object) -> bool:
while True:
if self.__pointer.hasNextChar(fileSwitch = False) and "@" == self.__pointer.getNextChar(fileSwitch = False):
# Citation #
line = self.__pointer.getCurrentLine()
if "{" in line and "," in line:
citation = line[line.index("{") + 1:line.index(",")]
else:
self.__print("A line starting with \"@\" contains unexpected citation information at {0}. ".format(self.__pointer.getCurrentLocationDescription()), Warning)
if self.__pointer.hasNextLine(fileSwitch = False):
self.__pointer.nextLine(fileSwitch = False)
continue # stop reading citation content and operating the dict
else:
self.__pointer.nextLine() # will switch to the parent pointer
return True
# Citation Content #
citationContent = ""
while self.__pointer.hasNextLine(fileSwitch = False):
self.__pointer.nextLine(fileSwitch = False)
if self.__pointer.hasNextChar(fileSwitch = False) and "}" == self.__pointer.getNextChar(fileSwitch = False):
citationContent = citationContent[:-1] # remove the last "\n"
break
else:
citationContent += self.__pointer.getCurrentLine().strip() + "\n"
# Handle Dict #
if citation in self.__citations:
if self.__citations[citation][0] is None:
self.__citations[citation][0] = citationContent
elif isinstance(self.__citations[citation][0], list):
self.__citations[citation][0].append(citationContent)
self.__print( \
"The citation \"{0}\" has already been defined {1} but is defined again at {2}. ".format( \
self.__convertEscaped(citation), "twice" if 2 == length else "for {0} times".format(length), self.__pointer.getCurrentLocationDescription() \
), Warning \
)
else:
self.__citations[citation][0] = [self.__citations[citation][0], citationContent]
self.__print("The citation \"{0}\" has already existed but is defined again at {1}. ".format(self.__convertEscaped(citation), self.__pointer.getCurrentLocationDescription()), Warning)
else:
self.__citations[citation] = [citationContent, 0] # [citationContent, citeCount]
self.__print("A new citation \"{0}\" is added by BibTeX at {1}. ".format(self.__convertEscaped(citation), self.__pointer.getCurrentLocationDescription()), Debug)
if self.__pointer.hasNextLine(fileSwitch = False):
self.__pointer.nextLine(fileSwitch = False)
else:
self.__pointer.nextLine() # will switch to the parent pointer
return True
def __resolve(self:object) -> bool:
self.__pointer = Pointer(self.__mainTexPath)
self.__structure = Structure()
self.__definitions.clear()
self.__labels.clear()
self.__citations.clear()
self.__flag = False
if not self.__pointer.initialize():
self.__print("Failed to initialize the main tex file. Please check if the file can be read. ", Error)
return False
if not self.__structure.initialize():
self.__print("Failed to initialize the root structure node. ", Error)
return False
buffer = "" # can also use a flag to control the buffer like {0:"plainTextBuffer", 1:"commandBuffer", 2:"mandatoryArgumentBuffer", 3:"optionalArguementBuffer"}
stack = [] # indicate the layer of {}
isLeftPart = True # indicate the "$" or "$$" got is the left part or not
while True:
if self.__pointer.hasNextChar(): # if there is a character following the current character in this line
self.__pointer.nextChar() # move to the next character
ch = self.__pointer.getCurrentChar() # get the currenct character
if "\\" == ch: # use the active modes
if self.__pointer.hasNextChar(fileSwitch = False):
if self.__pointer.getNextChar(fileSwitch = False) in ("(", "["):
self.__structure.addStructureNode("\\" + self.__pointer.getNextChar(fileSwitch = False))
self.__pointer.nextChar(fileSwitch = False)
elif self.__pointer.getNextChar(fileSwitch = False) in (")", "]"):
if not (self.__structure.canLeaveCurrentStructureNode("\\" + self.__pointer.getNextChar(fileSwitch = False)) and self.__structure.leaveCurrentStructureNode("\\" + self.__pointer.getNextChar(fileSwitch = False))):
self.__print("Cannot end the current environment ({0}) with command \"{1}\" at {2}. ".format(self.__structure.getCurrentStructureNodeDescription(), buffer, self.__pointer.getCurrentLocationDescription()), Error)
return False
else:
buffer = "\\" # initial a buffer to obtain the command
while self.__pointer.hasNextChar(fileSwitch = False): # fetch the whole command
ch = self.__pointer.getNextChar(fileSwitch = False)
if "A" <= ch <= "Z" or "a" <= ch <= "z":
buffer += ch
self.__pointer.nextChar(fileSwitch = False)
else:
break
if buffer in ("\\section", "\\subsection", "\\subsubsection") and self.__pointer.hasNextChar(fileSwitch = False) and "*" == self.__pointer.getNextChar(fileSwitch = False): # section*-like structures
buffer += "*"
self.__pointer.nextChar(fileSwitch = False)
if "\\" == buffer: # "\\"
if "0" <= ch <= "9": # e.g. "\\0" (ch must be defined since judging whether there is a following character is done before)
self.__pointer.nextChar(fileSwitch = False) # for printing purposes
self.__print("A command should only contain letters but it does not at {0}. ".format(self.__pointer.getCurrentLocationDescription()), Error)
return False
else: # e.g. "\\%" (absorb the next character)
self.__pointer.nextChar(fileSwitch = False)
self.__structure.addStructureNode("\\" + self.__pointer.getCurrentChar())
elif "\\documentclass" == buffer:
if self.__structure.addStructureNode(buffer):
self.__print("A new structure node [{0}] is added. ".format(self.__structure.getCurrentStructureNodeDescription()), Debug)
else:
self.__print("Failed to initialize a new structure node via \"{0}\" at {1}. ".format(buffer, self.__pointer.getCurrentLocationDescription()), Error)
return False
elif buffer in ("\\begin", "\\bibliography", "\\end", "\\input", "\\section", "\\section*", "\\subsection", "\\subsection*", "\\subsubsection", "\\subsubsection*"):
commandName = buffer[1:] # for judging environments
if not self.__skipSpaces():
return False
flag, mainBody = self.__fetchBraces()
buffer = "\\" + commandName + mainBody if mainBody.startswith("{") else "\\" + commandName + "{" + mainBody + "}"
if "begin" == commandName:
if self.__structure.addStructureNode(buffer):
self.__print("A new structure node [{0}] is added. ".format(self.__structure.getCurrentStructureNodeDescription()), Debug)
if buffer == "\\begin{thebibliography}":
self.__pointer.nextChar()
if not self.__skipSpaces():
return False
self.__pointer.nextChar()
ch = self.__pointer.getCurrentChar()
if "{" == ch:
layerCount = 1
while layerCount:
if self.__pointer.hasNextChar():
self.__pointer.nextChar()
ch = self.__pointer.getCurrentChar()
if "{" == ch:
layerCount += 1
elif "}" == ch:
layerCount -= 1
elif "\\" == ch:
if self.__pointer.hasNextChar():
self.__pointer.nextChar()
elif self.__pointer.hasNextLine():
self.__pointer.nextLine()
else:
self.__print( \
"An EOF signal is reported while scanning the escaped placeholder(s) in the \"{{}}\" for the \"\\begin{thebibliography}\" command at {0}. ".format( \
self.__pointer.getCurrentLocationDescription() \
), Error \
)
return False
elif self.__pointer.hasNextLine():
self.__pointer.nextLine()
else:
self.__print( \
"An EOF signal is reported while scanning the non-escaped placeholder(s) in the \"{{}}\" for the \"\\begin{thebibliography}\" command at {0}. ".format( \
self.__pointer.getCurrentLocationDescription() \
), Error \
)
else:
if "\\" == ch: # handle the placeholder in the form of "\\#"
if self.__pointer.hasNextChar():
self.__pointer.nextChar()
elif self.__pointer.hasNextLine():
self.__pointer.nextLine()
else:
self.__print("An EOF signal is reported while scanning the character after \"\\\" at {0}. ".format(self.__pointer.getCurrentLocationDescription()), Error)
return False
while True:
if self.__pointer.hasNextChar():
ch = self.__pointer.getNextChar()
if ch in (" ", "\t"):
self.__pointer.nextChar()
elif "\\" == ch:
remainingLine = self.__pointer.getRemainingCharactersInTheCurrentLineOfTheCurrentFile()
if remainingLine.startswith("\\bibitem"):
break
else:
self.__print( \
"Without a pair of \"{{}}\" surrounded, the \"\\bibitem\" command instead of others should be right after the placeholder at {0}. ".format( \
self.__pointer.getCurrentLocationDescription() \
), Error \
)
else:
self.__print( \
"Without a pair of \"{{}}\" surrounded, the \"\\bibitem\" command should be right after the placeholder at {0}. ".format( \
self.__pointer.getCurrentLocationDescription() \
), Error \
)
return False
elif self.__pointer.hasNextLine():
self.__pointer.nextLine()
else:
self.__print("An EOF signal is reported while scanning the citations at {0}. ".format(self.__pointer.getCurrentLocationDescription()), Error)
return False
else:
self.__print("Failed to initialize a new structure node via \"{0}\" at {1}. ".format(buffer, self.__pointer.getCurrentLocationDescription()), Error)
return False
elif "bibliography" == commandName:
if self.__pointer.addPointerNode(buffer[buffer.index("{") + 1:-1]) or self.__pointer.addPointerNode(buffer[buffer.index("{") + 1:-1] + ".bib"):
self.__print("A new Bib pointer node \"{0}\" is added. ".format(self.__pointer.getCurrentLocation()[0]), Debug)
if self.__handleBibTeX():
break # break the loop for fetching the string within the {} to avoid moving to the next character repeatedly
else:
return False
else:
self.__print("Failed to add a Bib pointer node at {0}. Details are as follows. \n{1}".format(self.__pointer.getCurrentLocationDescription(), self.__pointer.getLastError()), Warning)
elif "end" == commandName:
if self.__structure.canLeaveCurrentStructureNode(buffer):
leavingQueue = []
self.__structure.leaveCurrentStructureNode(buffer, leavingQueue = leavingQueue)
if len(leavingQueue) >= 2:
self.__print("With \"{0}\": ".format(buffer), Debug)
for nodeDescription in leavingQueue:
self.__print("Leave current structure node [{0}]. ".format(nodeDescription), Debug, indentationCount = 1)
else:
self.__print("Leave current structure node [{0}] with \"{1}\". ".format(leavingQueue[0], buffer), Debug)
else:
self.__print( \
"Cannot end the current environment [{0}] with command \"{1}\" at {2}. ".format( \
self.__structure.getCurrentStructureNodeDescription(), buffer, self.__pointer.getCurrentLocationDescription() \
), Error \
)
return False
elif "input" == commandName:
if self.__pointer.addPointerNode(buffer[buffer.index("{") + 1:-1]):
self.__print("A new TeX pointer node \"{0}\" is added. ".format(self.__pointer.getCurrentLocation()[0]), Debug)
else:
self.__print("Failed to add a TeX pointer node at {0}. Details are as follows. ".format(self.__pointer.getCurrentLocationDescription()), Warning)
self.__print(self.__pointer.getLastError(), Warning, indentationCount = 1)
else:
self.__structure.addStructureNode(buffer)
elif buffer in ("\\bibitem", "\\label", "\\ref", "\\eqref"):
if not self.__skipSpaces():
return False
# Fetch #
self.__pointer.nextChar(fileSwitch = False)
if "{" == self.__pointer.getCurrentChar():
label = ""
while True:
if self.__pointer.hasNextChar(fileSwitch = False):
self.__pointer.nextChar(fileSwitch = False)
ch = self.__pointer.getCurrentChar()
if ch in ("\\", "{"):
self.__print( \
"An unexpected character \"{0}\" appears while scanning the {1} at {2}. ".format( \
self.__convertEscaped(ch), "citation" if "\\bibitem" == buffer else "label", self.__pointer.getCurrentLocationDescription() \
), Error \
)
return False
elif "}" == ch:
break
else:
label += ch
elif self.__pointer.hasNextLine(fileSwitch = False):
self.__pointer.nextLine(fileSwitch = False)
label += "\n"
while self.__pointer.hasNextChar(fileSwitch = False) and self.__pointer.getNextChar(fileSwitch = False) in (" ", "\t"):
self.__pointer.nextChar(fileSwitch = False)
citation += self.__pointer.getCurrentChar()
if not self.__pointer.hasNextChar(fileSwitch = False):
self.__print("Two or more consecutive line breaks are not allowed during the label scanning at {0}. ".format(self.__pointer.getCurrentLocationDescription()), Error)
return False
else:
self.__print("An EOF signal is reported while scanning the label at {0}. ".format(self.__pointer.getCurrentLocationDescription()), Error)
return False
elif "\\label" == buffer and self.__structure.getCurrentStructureNodeDescription() in ("Environment(equation)", "Environment(equation*)"):
self.__print("Must use a \"{{\" to follow the \"\\label\" command in the equation environment at {0}. ".format(self.__pointer.getCurrentLocationDescription()), Error)
return False
else:
label = self.__pointer.getCurrentChar()
# Handle #
if "\\bibitem" == buffer:
# Environment Check #
if "Environment(thebibliography)" != self.__structure.getCurrentStructureNodeDescription():
self.__print("The command \"\\bibitem\" should only be used in the \"thebibliography\" environment. ", Warning)
# return False
# Fetch Citation Content #
citationContent = ""
while True:
if self.__pointer.hasNextChar():
ch = self.__pointer.getNextChar()
if "\\" == ch:
remainingLine = self.__pointer.getRemainingCharactersInTheCurrentLineOfTheCurrentFile()
if remainingLine.startswith("\\begin") or remainingLine.startswith("\\bibitem") or remainingLine.startswith("\\end"):
break
else:
citationContent += "\\"
self.__pointer.nextChar()
if self.__pointer.hasNextChar(): # ``hasNextLine`` will be handled in the new loop automatically
self.__pointer.nextChar()
citationContent += self.__pointer.getCurrentChar()
elif "&" == ch:
citationContent += "&"
self.__print("Please use \"\\&\" in the citation content at {0}. ".format(self.__pointer.getCurrentLocationDescription()), Warning)
else:
citationContent += ch
self.__pointer.nextChar()
elif self.__pointer.hasNextLine():
self.__pointer.nextLine()
citationContent += "\n"
# Handle Dict #
if label in self.__citations:
if self.__citations[label][0] is None:
self.__citations[label][0] = citationContent
elif isinstance(self.__citations[label][0], list):
length = len(self.__citations[label][0])
self.__print( \
"The citation \"{0}\" has already been defined {1} but is defined again at {2}. ".format( \
self.__convertEscaped(label), "twice" if 2 == length else "for {0} times".format(length), self.__pointer.getCurrentLocationDescription() \
), Warning \
)
else:
self.__citations[label][0] = [self.__citations[label][0], False]
self.__print("The citation \"{0}\" has already existed but is defined again at {1}. ".format(self.__convertEscaped(label), self.__pointer.getCurrentLocationDescription()), Warning)
else:
self.__citations[label] = [citationContent, 0] # [citationContent, citeCount]
self.__print("A new citation \"{0}\" is added via the \"\\bibitem\" command at {1}. ".format(self.__convertEscaped(label), self.__pointer.getCurrentLocationDescription()), Debug)
elif "\\label" == buffer:
if label in self.__labels:
if self.__labels[label][0] is None:
self.__labels[label][0] = self.__structure.getCurrentStructureNodeDescription()
elif isinistance(self.__labels[label][0], list):
length = len(self.__labels[label][0])
self.__print( \
"The label \"{0}\" has already been defined {1} but is defined again at {2}. ".format( \
self.__convertEscaped(label), "twice" if 2 == length else "for {0} times".format(length), self.__pointer.getCurrentLocationDescription() \
), Warning \
)
self.__labels[label][0].append(self.__pointer.getCurrentLocationDescription())
else:
self.__labels[label][0] = [self.__labels[label][0], self.__pointer.getCurrentLocationDescription()]
self.__print("The label \"{0}\" has already existed but is defined again at {1}. ".format(self.__convertEscaped(label), self.__pointer.getCurrentLocationDescription()), Warning)
else:
self.__labels[label] = [self.__structure.getCurrentStructureNodeDescription(), 0, 0] # [type, refCount, eqrefCount]
self.__print("A new label \"{0}\" is added at {1}. ".format(self.__convertEscaped(label), self.__pointer.getCurrentLocationDescription()), Debug)
else:
if label in self.__labels:
self.__labels[label][2 if "\\eqref" == buffer else 1] += 1
elif "\\eqref" == buffer: