-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathtexlogsieve
More file actions
executable file
·7112 lines (5861 loc) · 226 KB
/
texlogsieve
File metadata and controls
executable file
·7112 lines (5861 loc) · 226 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 texlua
-- texlogsieve - filter and summarize LaTeX log files
--
-- Copyright (C) 2021-2026 Nelson Lago <lago@ime.usp.br>
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <https://www.gnu.org/licenses/>.
--
-- Code etc: https://gitlab.com/lago/texlogsieve
--[[
----------------
THE TeX LOG FILE
----------------
TeX uses three low-level commands for logging:
1. \message -> outputs to both the console and the log file (most
low-level TeX messages, such as open/close files, shipouts etc.
behave *more or less* as if they were generated by \message)
2. \write with an unallocated stream identifier (typically, 0) ->
also outputs to both the console and the log file.
2. \write with a negative stream identifier (typically, -1) -> outputs
to the log file only
\write and \message behave differently:
* Normally, \write appends a line feed character (LF) to the text, so
a sequence of \write commands results in multiple lines.
* \message checks whether the last thing that was sent out was another
\message; if so, it adds a space character and outputs the text (both
the previous text and the new one are on the same line, separated by
a space), otherwise it just outputs the text (in this case, the new
text is at the beginning of a line). Note, however, that there are
some \message's that are not separated by spaces, such as "))".
Also, in most cases (I could not figure out when this fails, but it
happens often), if \message realizes the new text will not fit in
the current line (the line would exceed max_print_line characters),
instead of wrapping the line as usual, it may output a LF and start
the text on a new line.
* \write also checks if the last thing that was sent out was a message;
if so, it sends LF before the text, so that it starts at the
beginning of a line (it also sends LF after the text too, as always)
Therefore, in the console, text output with \write always appears on a
new line. A sequence of calls to \message also always starts on a new
line, but the texts of all of them appear on the same line, separated
by spaces.
However, things get messy in the log file. Basically, \message and
\write0 modify the same filedescriptor, while \write-1 modifies a
different filedescriptor. This means \message and \write0 are unaware
of \write-1 and vice-versa. As a result, the spaces and LFs that are
added according to what is output to the console get mixed up with what
is written only to the log file with \write-1. Therefore, there may be
unexpected empty lines or lines that start with a space character in
the log file.
The LaTeX command \GenericInfo uses \write-1, while \GenericWarning
uses \write0. TeX and LaTeX also define \wlog, which is an alias for
\write-1; LaTeX defines \typeout, which is an alias for \write0. Some
packages define their own aliases; for example, pgfcore.code.tex does
\def\pgf@typeout{\immediate\write0}, graphics.sty does \let\Gin@log\wlog,
etc. Package infwarerr provides a compatibility layer for the LaTeX
standard logging commands, so that they can be used both in LaTeX and
in plain TeX, as \@PackageInfo, \@ClassWarning etc.
With that in mind, we will consider that there are five kinds of message
in the LaTeX log file:
* Ordinary messages -> messages that start at the beginning of the line
and end at the end of the line (they are created with \write), such as
Document Class: book 2019/08/27 v1.4j Standard LaTeX document class
For additional information on amsmath, use the `?' option.
\openout4 = `somefile'.
* Short messages -> messages that may begin/end anywhere on a line,
because the line they are in may contain multiple messages of
this type (they are created with \message), such as
ASCII Hyphenation patterns for American English
) (/usr/share/texlive/texmf-dist/tex/generic/iftex/iftex.sty
-> these mean 'close last file' and 'open file .../iftex.sty'
(/usr/share/texlive/texmf-dist/tex/latex/etoolbox/etoolbox.sty)
-> these mean 'open file .../etoolbox.sty' and 'close last file'
(which is etoolbox.sty, obviously)
))
-> these mean 'close the last two files'
[1] [2] [3]
-> these mean 'shipout pages 1, 2, and 3'
* Multiline messages -> messages that start at the beginning of a line,
continue for a few lines and end at the end of a line (the programmer
explicitly used multiple \write commands, a single \write command
with embedded newline characters, or single/multiple \message
commands with leading/trailing newline characters), such as
Package biblatex Info: Automatic encoding selection.
(biblatex) Assuming data encoding 'utf8'.
*************************************
* Using libertinus math *
*************************************
**********************
* No checksum found! *
**********************
(from ydoc-doc.sty)
* "Best-effort" multiline messages -> similar to the previous ones,
but created using multiple \message commands or a single one with
embedded newline characters but no leading and/or trailing newline
characters. They *usually* begin at the beginning of the line and
end at the end of the line because, as mentioned before, TeX usually
inserts a line break if the line would not fit otherwise. However,
that is not always true, especially if max_print_line is large.
Therefore, sometimes the message may begin in the middle of a line
and/or the various lines may be strung together or wrapped.
Examples:
*****************************************************************
GFS-Solomos style file by A. Tsolomitis
*****************************************************************
(from gfssolomos.sty)
=============== Entering putframe ====================
\pagegoal =635.97621pt, \pagetotal =368.07768pt.
(from exam.cls)
* Error messages -> when an error occurs, TeX usually writes something
like "! Some error" followed by lines that resemble a stack trace of
where the error occurred. For example, this input:
Some text \blah, something else
would result in
! Undefined control sequence.
l.5 Some text \blah
, something else
With option -file-line-error, the exclamation is replaced by an
indication like "filename:linenum:".
The "stack trace" is comprised of pairs of lines. In each pair,
the first line indicates the content in a given line leading up
to the error, while the second one shows the subsequent content of
that line. The first line is at most half_error_line characters long
(default 50) and the second line is at most error_line characters
long (default 79). The second line is indented to start after the
end of the first, as in the example above. If the content of either
segment does not fit, a part of it (the beginning for the first line
and the end for the second line) may be replaced by "...". error_line
must be < 255 and half_error_line must be < error_line -15. If
error_line >= max_print_line or half_error_line >= max_print_line,
TeX does line wrapping as usual (see below). If either is exactly
max_print_line (which is true for the default values), things get
confusing, so TeX may add a blank line when wrapping.
By default, LaTeX only shows the first and last pairs of lines of the
"stack trace" (if only one pair of lines is relevant, then obviously
only this pair is shown). The number of additional, intermediate pairs
of lines shown is determined by \errorcontextlines: if it is zero, no
additional lines are shown, but LaTeX prints "..." indicating they
were omitted. If it is -1 (the default), they are not shown and there
is no "..." indication.
LaTeX errors are similar, but usually follow the format
! LaTeX/Package/Class BLAH Error: some description
See the BLAH documentation for explanation.
Type H <return> for immediate help.
...
l.5 First error line
second error line
In errorstop mode, such errors are followed by a "?" prompt.
Finally, runaway arguments have a different format:
Runaway argument?
some text\ETC.
! SOMETHING ended...
To complicate things, TeX by default wraps (breaks) any line longer
than max_print_line characters (by default, 79). Since some messages
may be output together on a single line, even short messages may be
broken across lines. At the same time, there are quite a few ordinary
lines that in practice happen to be max_print_line characters long,
which makes detecting line wrapping a real challenge. And, just to
make things more interesting, sometimes there is a blank line between
the wrapped line and its continuation line.
pdfTeX (and, I suppose, traditional TeX) counts characters as bytes to
choose where to wrap a line. XeTeX, however, counts utf-8 characters
(I do not know whether that's code points or graphemes), so we need to
take that into consideration.
LuaTeX adds some extra complications: for no apparent reason, it wraps
some lines at max_print_line characters and others at max_print_line +1
characters. It also sometimes "forgets" to wrap a line. And more! It
does not break a line in the middle of a multibyte UTF-8 character.
That is obviously a good idea, but it counts the line length in bytes,
like pdfTeX, which means some lines may be broken at lengths smaller
than max_print_line. While this may seem rare, it can happen when parts
of the document text are included in the log, as is the case with
over/underfull box messages.
So, if at all possible, it is a very good idea to set max_print_line
to a really large value (such as 100,000), effectively disabling line
wrapping. It was useful in the 1980s, but not anymore (your terminal or
editor wraps automatically). Likewise, error_line and half_error_line
should be, respectively, 254 and 238 (more about these values here:
https://tex.stackexchange.com/a/525972).
----------------------
HOW THIS PROGRAM WORKS
----------------------
To read this section, pretend for a moment that TeX does not wrap long
lines.
We have a set of handlers, i.e., objects that process specific kinds
of message. Each handler checks if a given line matches some patterns
to decide whether it is supposed to process it (return true) or not
(return false).
There is a loop that, at each iteration, reads a new line from the log
file with moreData() and uses chooseHandler() to call each handler in
turn until one of them processes that line. After the right handler
does its thing, it sends the message to the output, erases this input
line and returns true, which causes the loop to restart, skipping the
remaining handlers.
The loop may behave a little differently in two cases:
1. If the handler processes just a part of the input line, which may
happen if the line contains multiple short messages, it removes
the processed data from the line and leaves the rest. At the next
iteration, no new data is read: the loop processes the remaining
material from the same line.
2. If the handler processes the input and expects specific lines of
content to follow, it can preset itself as the next handler,
temporarily bypassing the choice step.
When the line (or part of it) is not recognized by any handler, it is
appended to unrecognizedBuffer. We may sometimes concatenate multiple
text chunks together here because, during processing, we may break the
line into chunks when in fact it comprises a single message. In any
case, we know for sure that the message (or messages) currently in
unrecognizedBuffer is complete when either (1) we identify the next
short message in the line or (2) we proceed to the next input line.
When either happens, we send the buffer to the output.
We know most messages, but not all, start at the beginning of a line.
Therefore, we keep two sets of handlers: beginningOfLineHandlers and
anywhereHandlers. We use the boolean atBeginningOfLine to know when
we may skip trying the beginningOfLineHandlers.
We mentioned that the handler "sends the message to the output". The
handler actually creates a Message object and calls the dispatch()
function to send that object to a coroutine that handles output. The
coroutine aggregates messages by page, generates summaries for some
kinds of message (for example, it may list all undefined references
together) and prints out the report in different formats.
Sometimes we need to be able to check the content of the next line
to decide what to do about the current line (for example, different
messages may begin with a line like "**********"). So, we do not only
read one line from the input at each iteration; instead, we have a
buffer with the next few lines. When the current line has been
completely processed, moreData() simply refills the buffer and calls
Lines:gotoNextLine(), which makes the next line (line 1) become the
current line (line 0), the following line (line 2) become the next
line (line 1) etc.
That would be all if TeX did not wrap long lines, but it does. To unwrap
lines when needed, we (1) check that the line is max_print_lines long;
if so, we (2) check whether the next line is the beginning of a known
message; if it is not, we (3) check whether unwrapping lines makes us
recognize a message that was not identified without unwrapping. Because
of 3, we do this in each of the handlers and not beforehand. To unwrap
a line, we simply join the current line with the next one from the
buffer.
Note that, if you reconfigure the variable max_print_line to a value
larger than 9999 (which is a good thing to do), this program assumes
(quite reasonably) that there is no line wrapping.
------------
THE HANDLERS
------------
We want to be able to explicitly recognize as much messages as possible
(and leave the least amount possible for the unrecognizedBuffer) for at
least three reasons:
1. A character such as "(", ")", "[", or "]" in an unrecognized message
may confuse the program (these chars may indicate open/close file
and begin/end shipout). If it is part of a known message, it will
not be mistaken for an open/close file etc.
2. By default, TeX wraps lines longer than max_print_line characters,
and unwrapping them involves making sure that the following line
is not the start of a new message. For this to be reliable,
unknown messages should be kept to a minimum.
3. We can assign severity levels to known messages; unknown messages
must always be handled as high-severity, polluting the output.
At each iteration, chooseHandler() calls doit() for every handler. The
handler returns true to signal that chooseHandler() should proceed to
the next iteration. It does that if it did "something" to change the
status for the next iteration:
* It processed a complete message in this iteration (i.e., the whole
message was contained in the current line);
* It processed the message partially and defined nextHandler;
* It finalized the processing of a previous partial message (i.e., it
realized the message has ended). This only happens if the handler
was previously set as nextHandler. When this happens, it sometimes
does nothing with the content of the current line, only outputs the
complete message. Still, when the loop restarts, it will no longer
be the nextHandler (and that is "something").
A handler must provide:
1. A doit() method that returns true or false to indicate whether it
actually did something with the current line or not.
2. A canDoit(position) method that returns true or false to indicate
whether the handler can/should process the line given by "position"
(we use this to identify wrapped lines, as explained later).
3. An init() method to do any necessary setup after the command line
has been read (it is ok to do nothing). The easiest way to do this
is to "inherit" from HandlerPrototype.
4. For handlers that deal with messages that can appear in the middle
of a line, a lookahead(position) method to indicate whether there is
a message that the handler can/should process in the line indicated
by "position" when there is something else in the line before that
message.
Besides true/false, canDoit() also returns a table with extra data. In
some cases, this table is empty; in others, the handler's doit() method
knows what to do with it. There are two places outside the handler
itself where this data is used:
1. In handleUnrecognizedMessage(), where we call lookahead() and use
the value of "first" that should be embedded in this table.
2. In Lines:noHandlersForNextLine(), where we treat openParensHandler
and openSquareBracketHandler specially and read file/page data from
them.
A simple handler:
-----------------
exampleHandler = {}
exampleHandler.pattern = '^%s*L3 programming layer %b<>'
function exampleHandler:init()
end
function exampleHandler:canDoit(position)
if position == nil then position = 0 end
local line = Lines:get(position)
if line == nil then return false, {} end
local first, last = string.find(line, self.pattern)
if first == nil then return false
return true, {first = first, last = last}
end
function exampleHandler:doit()
local myTurn, data = self:canDoit()
if not myTurn then return false end
flushUnrecognizedMessages()
local msg = Message:new()
msg.severity = DEBUG
msg.content = string.sub(Lines.current, 1, data.last)
dispatch(msg)
Lines:handledChars(data.last)
return true
end
function exampleHandler:lookahead(position)
local tmp = self.pattern
self.pattern = string.sub(self.pattern, 2) -- remove leading '^'
local result, data = self:canDoit()
self.pattern = tmp
-- Only return true if whatever matches
-- is not at the beginning of the line
if result and data.first == 1 then return false, {} end
return result, data
end
There are two special handlers, which we use as prototypes
(https://www.lua.org/pil/16.1.html ) and derive some other handlers
from:
- stringsHandler - handles a list of predefined multiline strings
that may or may not begin at the beginning of a line and may or may
not end at the end of a line. We identify where the last line of
the message ends and remove that from the input line, leaving the
rest for the next handler. In general, the pattern we look for in
each line should match the whole line and should not end with
something like ".*", unless we are absolutely sure that (1) each line
always ends at the end of the line and (2) the line is short enough
that it is never wrapped (which also implies that the first line
always starts at the start of the line). This handler is quite
complex because it has to deal with many different scenarios. We
derive other handlers from the basic prototype so that we can assign
different severity levels to each one. Derived handlers differ from
the prototype only by severity level and the set of patterns to
search for.
- genericLatexHandler -> handles the multiline messages generated by
the \PackageInfo, \ClassWarning etc. LaTeX commands. The handler
does not need to know in advance the text for all these messages;
it looks for generic patterns instead and extracts from the message
itself the name of the package and severity level. It is able to
identify multiline messages by checking if the following lines are
prefixed with a specific pattern, so it can also handle messages
with an unknown number of lines. We derive other handlers from the
basic prototype because, for each kind of message, we use a different
set of pattern captures, and we need to treat these differently.
Derived handlers differ from the prototype by the set of patterns
to search for and by the unpackData() method, which deals with the
specific pattern captures.
----------------
UNWRAPPING LINES
----------------
As mentioned, each handler has a canDoit(position) method, where
"position" is the line number in the Lines input buffer (0 is the
current line, 1 is the next line etc.). As expected, doit() calls
canDoit() to check whether it should proceed of not. However, that
is not all: if canDoit() fails to find a match, it checks whether the
line might be a wrapped line. To detect a wrapped line, canDoit()
uses Lines:seemsWrapped() to do three things:
1. Check that the line is the "right" size (in Lines:wrappingLength())
2. Check that the next line is not the beginning of a known message
(in Lines:noHandlersForNextLine())
3. Check whether unwrapping the line actually gives us something, i.e.,
the unwrapped line matches something that its two separate parts
did not.
The problem is in step (2): this entails calling canDoit() from all
handlers on the following line, which means that it may be called many
times and may even call itself on a different line. Therefore, it is
essential that canDoit() have no side effects, i.e., it should not set
any state besides the return values. For the same reason, canDoit()
cannot alter the content of the Lines buffer when it tries to unwrap a
line; it should only use temporary variables instead (not only that:
if unwrapping does not yield a match, we do not want to do it either).
canDoit() may, however, return a "hint" about the line wrapping - either
the text or the pattern that finally matched. Some handlers do that and,
in doit(), take the string or pattern found by canDoit() and unwrap
lines until finding a match to that string or pattern. Others cannot do
this due to various reasons and need to repeat the work already done
by canDoit() (the code is different, however).
Note also that some handlers, such as underOverFullBoxHandler and
genericLatexHandler, cannot do (3), as they do not know in advance
how the end of a given message should look like. The bottom line is,
line unwrapping is done in many different ways according to context.
Finally, this all means that we may call canDoit() from all handlers on
a given line many times. This gets really bad with stringsHandler: for
a sequence of k consecutive lines that are max_print_line long, this
handler alone is O(n^{k+1}), where n is the number of patterns that it
checks for (around 40). A previous implementation proved this to be
impractical, so we work around this problem with memoization.
-----------------------------------------
DETAILS ABOUT UNDER/OVERFULL BOX MESSAGES
-----------------------------------------
These are actually several different messages:
Overfull \[hv]box (Npt too wide) SOMEWHERE
Underfull \[hv]box (badness N) SOMEWHERE
Possible SOMEWHEREs:
1. detected at line N
-> this is something like a makebox (horizontal) or parbox (vertical)
with an explicit size argument. For hboxes, this is followed by
the offending text.
2. has occurred while \output is active
-> If horizontal, this is probably in a header, footer or something
similar; if vertical, the vertical glues got too stretched. For
hboxes, this is followed by the offending text.
3. in alignment at lines LINE NUMBERS
-> the problematic box is part of a tabular or math alignment
environment. The lines correspond to the whole align structure,
not only the problematic box. This should only appear as an
horizontal problem. This is followed by the offending text, but
it is more often than not just a bunch of "[]" to indicate nested
boxes
4. in paragraph at lines LINE NUMBERS
-> "Normal" text. This also only appears as an horizontal problem.
This is followed by the offending text, which may include a
few "[]" for whatsits, glues etc. In particular, the text often
begins with "[]", indicating the left margin glue.
In the log file, all under/overfull box messages are followed by a
description of the boxes involved. This is *not* normally included in
the console output (but it may be, depending on \tracingonline). The
level of detail of this description is controlled by \showboxdepth
and \showboxbreadth. The default for these in LaTeX is -1, which means
this description is omitted and replaced by "[]", so it looks like this:
Underfull \vbox (badness 10000) detected at line 128
[] <-- this is the description
If the message includes the offending text, the description comes
after it:
Underfull \hbox (badness 3417) in paragraph at lines 128--128
[]\T1/LibertinusSerif-TLF/b/n/14.4 (+20) Some document text...
[] <-- this is the description
If there is no offending text, the description may appear in the same
line as the under/overfull box message (both are \message's). The
offending text, if any, always starts at the beginning of a line and
ends at the end of a line (but may be wrapped).
About the description: https://tex.stackexchange.com/a/367589
This all means that handling these messages from a pipe is different
than from the log file, because in the log file you know there will
be a "[]" after the message. What we do here is check whether that
string is there; if it is, we remove it.
under/overfull messages that do not include the offending text are
\message's and, therefore, there may be extra text (such as a shipout)
on the same line.
--]]
--[[ ##################################################################### ]]--
--[[ ################ INIT, MAIN LOOP, CHOOSING HANDLER ################## ]]--
--[[ ##################################################################### ]]--
DEBUG = 0
INFO = 1
WARNING = 2
CRITICAL = 3
UNKNOWN = 4
RED = '\x1B[31m'
YELLOW = '\x1B[33m'
GREEN = '\x1B[32m'
BRIGHT = '\x1B[37;1m'
BGREEN = '\x1B[32;1m'
RESET_COLOR = '\x1B[0m'
function main(arg)
initializeKpse()
processCommandLine(arg)
initializeGlobals()
registerHandlers()
registerSummaries()
convertFilterStringsToPatterns()
detectEngine()
while moreData() do
if nextHandler == nil then
chooseHandler()
else
handler = nextHandler
nextHandler = nil
handler:doit()
end
end
-- dispatch remaining messages, if any
if nextHandler then nextHandler:flush() end
flushUnrecognizedMessages()
dispatch(nil) -- end the output coroutine
end
function moreData()
-- Refill the buffer. A simple experiment suggests 8 lines
-- is enough, but why not use a higher value?
while Lines:numLines() < 15 do
tmp = logfile:read("*line")
if tmp == nil then break end
-- If we are running in a unix-like OS but the files we are
-- processing were generated in Windows, lua may leave a \r
-- character at the end of the line; if this happens, remove it
local _, last = string.find(tmp, '\r$')
if last ~= nil then tmp = string.sub(tmp, 1, last -1) end
-- Do not skip blank lines here, we need to do it in Lines:append()
Lines:append(tmp)
end
-- if there is remaining data from the previous iteration,
-- we leave everything as-is for it to be processed now
local tmp = Lines.current
if tmp ~= nil and tmp ~= "" then return true end
-- proceed to the next line
flushUnrecognizedMessages()
Lines:gotoNextLine()
return Lines.current ~= nil
end
--[[
chooseHandler() never tries to process more than one message in a single
iteration for at least three reasons:
* There may be no more data available on the current line, so we
need to call moreData();
* Maybe the next handler is one that we have already tried in this
iteration; skipping it and trying others may fail;
* Maybe the handler that last processed the data predefined the next
handler, and we should not interfere with that.
--]]
function chooseHandler()
-- Some messages can only appear at the beginning of a line
if Lines.atBeginningOfLine then
for _, candidateHandler in ipairs(beginningOfLineHandlers) do
if candidateHandler:doit() then return end
end
end
-- Others may appear anywhere
for _, candidateHandler in ipairs(anywhereHandlers) do
if candidateHandler:doit() then return end
end
-- No handler succeeded, which means this is an unrecognized message
-- (or a fragment of one); Add to unrecognizedBuffer.
handleUnrecognizedMessage()
end
function handleUnrecognizedMessage()
-- Before sending this to the unrecognizedBuffer, check if
-- there is another known message later on this same line.
-- NOTE: check the comment before closeParensHandler:lookahead().
local last = string.len(Lines.current)
for _, handler in ipairs(anywhereHandlers) do
local match, data = handler:lookahead()
if match and data.first -1 < last then last = data.first -1 end
end
unrecognizedBuffer = unrecognizedBuffer .. string.sub(Lines.current, 1, last)
Lines:handledChars(last)
end
function flushUnrecognizedMessages()
unrecognizedBuffer = trim(unrecognizedBuffer)
if unrecognizedBuffer == "" then return end
local msg = Message:new()
msg.content = unrecognizedBuffer
dispatch(msg)
unrecognizedBuffer = ""
end
-- Setup initial status (lots of globals, sue me)
function initializeGlobals()
-- Chunks of text that were not recognized by any handler
unrecognizedBuffer = ""
-- The user may choose to silence some files. When one of these is
-- opened/closed, this is set to true or false accordingly. The value
-- is then used by Message:new()
mute = false
-- List of files that TeX had open at a given time during processing
openFiles = Stack:new()
-- "List" of currently active shipouts. There is only ever one shipout
-- active at any time, but we borrow the design of openFiles because
-- there may be "[" and "]" characters that do not correspond to any
-- shipout, so we use this to keep track of them.
shipouts = Stack:new()
-- Counter, so we know the physical page number
numShipouts = 0
-- map physicalPage (from numShipouts) to latexPage (LaTeX counter)
latexPages = {}
-- After printing each message, the output coroutine stores them in
-- currentPageMessages. When it receives a shipout message, it traverses
-- currentPageMessages adding the page number it just learned about to
-- each of the messages and clears currentPageMessages. This serves two
-- purposes: it allows us to include the page numbers in the summaries
-- and it allows us to include the page number in page-delay mode.
currentPageMessages = {}
-- The objects representing the summary for each kind of message are
-- stored in summaries, so after all messages are processed we can just
-- traverse this list calling :toString() and get all the summaries. The
-- summaries are also used to suppress repeated messages. This table is
-- populated by registerSummaries().
summaries = {}
-- All handlers should be in either of these. They are populated by
-- registerHandlers().
beginningOfLineHandlers = {}
anywhereHandlers = {}
-- Does the log file have wrapped lines?
-- This may be changed by initializeKpse().
badLogfile = true
-- When we detect one of the many "please rerun LaTeX"
-- messages, this is set to true (used in showSummary)
SHOULD_RERUN_LATEX = false
-- Have we reached the beginning of the epilogue yet?
EPILOGUE = false
-- If there were parse errors, we should say so in showSummary
PARSE_ERROR = false
-- Did we detect any error messages?
ERRORS_DETECTED = false
-- detectEngine() may set one of these to true
LUATEX = false
XETEX = false
-- When we print a message that is the first from a given filename,
-- we announce the filename first. This is used to detect the change
-- in file - used by showFileBanner()
lastFileBanner = ""
-- Should we print "No important messages to show" at the end?
nothingWasPrinted = true
end
function initializeKpse()
-- In texlua, the texconfig table (the table that records some TeX
-- config variables) is not initialized automatically; we need to
-- call this to initialize it so we can read "max_print_line". If
-- I understand things correctly, the name used here affects the
-- loaded configuration options: using a name such as "texlogsieve"
-- would allow us to add custom options to texmf.cnf. But since
-- all we want to do is search for files and read the value of
-- "max_print_line", let's just pretend we are luatex.
kpse.set_program_name("luatex")
max_print_line = tonumber(kpse.var_value("max_print_line"))
if max_print_line ~= nil and max_print_line > 9999 then
badLogfile = false
else
badLogfile = true
end
end
function registerHandlers()
table.insert(beginningOfLineHandlers, pseudoErrorHandler)
table.insert(beginningOfLineHandlers, errorHandler)
table.insert(beginningOfLineHandlers, citationHandler)
table.insert(beginningOfLineHandlers, referenceHandler)
table.insert(beginningOfLineHandlers, labelHandler)
table.insert(beginningOfLineHandlers, unusedLabelHandler)
table.insert(beginningOfLineHandlers, genericLatexHandler)
table.insert(beginningOfLineHandlers, latex23MessageHandler)
table.insert(beginningOfLineHandlers, genericLatexVariantIHandler)
table.insert(beginningOfLineHandlers, genericLatexVariantIIHandler)
table.insert(beginningOfLineHandlers, providesHandler)
table.insert(beginningOfLineHandlers, geometryDetailsHandler)
table.insert(beginningOfLineHandlers, epilogueHandler)
table.insert(beginningOfLineHandlers, underOverFullBoxHandler)
table.insert(beginningOfLineHandlers, utf8FontMapHandler)
table.insert(beginningOfLineHandlers, missingCharHandler)
table.insert(beginningOfLineHandlers, beginningOfLineDebugStringsHandler)
table.insert(beginningOfLineHandlers, beginningOfLineInfoStringsHandler)
table.insert(beginningOfLineHandlers, beginningOfLineWarningStringsHandler)
table.insert(beginningOfLineHandlers, beginningOfLineCriticalStringsHandler)
table.insert(beginningOfLineHandlers, scontentsHandler)
table.insert(anywhereHandlers, anywhereDebugStringsHandler)
table.insert(anywhereHandlers, anywhereInfoStringsHandler)
table.insert(anywhereHandlers, anywhereWarningStringsHandler)
table.insert(anywhereHandlers, anywhereCriticalStringsHandler)
table.insert(anywhereHandlers, fpHandler) -- before open/closeParensHandler!
table.insert(anywhereHandlers, openParensHandler)
table.insert(anywhereHandlers, closeParensHandler)
table.insert(anywhereHandlers, openSquareBracketHandler)
table.insert(anywhereHandlers, closeSquareBracketHandler)
table.insert(anywhereHandlers, extraFilesHandler)
for _, handler in ipairs(beginningOfLineHandlers) do
handler:init()
end
for _, handler in ipairs(anywhereHandlers) do
handler:init()
end
end
function registerSummaries()
table.insert(summaries, underOverSummary)
table.insert(summaries, missingCharSummary)
table.insert(summaries, repetitionsSummary)
table.insert(summaries, unusedLabelsSummary)
table.insert(summaries, citationsSummary)
table.insert(summaries, referencesSummary)
table.insert(summaries, labelsSummary)
end
function convertFilterStringsToPatterns()
local tmp = {}
for _, pattern in ipairs(SEMISILENCE_FILES) do
table.insert(tmp, globtopattern(pattern))
end
SEMISILENCE_FILES = tmp
tmp = {}
for _, pattern in ipairs(SILENCE_FILES_RECURSIVE) do
table.insert(tmp, globtopattern(pattern))
end
SILENCE_FILES_RECURSIVE = tmp
tmp = {}
for _, str in ipairs(SILENCE_STRINGS) do
local pat = stringToPattern(str)
table.insert(tmp, pat)
end
SILENCE_STRINGS = tmp
tmp = {}
for _, str in ipairs(SILENCE_PKGS) do
local pat = stringToPattern(str)
table.insert(tmp, pat)
end
SILENCE_PKGS = tmp
tmp = {}
for _, str in ipairs(FORCED_DEBUG) do
local pat = stringToPattern(str)
table.insert(tmp, pat)
end
FORCED_DEBUG = tmp
tmp = {}
for _, str in ipairs(FORCED_INFO) do
local pat = stringToPattern(str)
table.insert(tmp, pat)
end
FORCED_INFO = tmp
tmp = {}
for _, str in ipairs(FORCED_WARNING) do
local pat = stringToPattern(str)
table.insert(tmp, pat)
end
FORCED_WARNING = tmp
tmp = {}
for _, str in ipairs(FORCED_CRITICAL) do
local pat = stringToPattern(str)
table.insert(tmp, pat)
end
FORCED_CRITICAL = tmp
end
function detectEngine()
local line = logfile:read("*line")
if line == nil then return end
if string.find(string.lower(line), '^this is lua') then
LUATEX = true
elseif string.find(string.lower(line), '^this is xe') then
XETEX = true
end
-- leave the line for normal processing
Lines:append(line)
end
helpmsg = [[
Usage: texlogsieve [OPTION]... [INPUT FILE]
texlogsieve reads a LaTeX log file (or the standard input), filters
out less relevant messages, and displays a summary report.
texlogsieve reads additional options from the texlogsieverc file
if it exists anywhere in the TeX path (for example, in the current
directory).
Options:
--page-delay, --no-page-delay enable/disable grouping
messages by page before display
--summary, --no-summary enable/disable final summary
--only-summary no filtering, only final summary
--shipouts, --no-shipouts enable/disable reporting shipouts
--file-banner, --no-file-banner Show/suppress "From file ..." banners
--repetitions, --no-repetitions allow/prevent repeated messages
--be-redundant, --no-be-redundant present/suppress ordinary messages
that will also appear in the summary
--box-detail, --no-box-detail include/exclude full under/overfull
boxes information in the summary
--ref-detail, --no-ref-detail include/exclude full undefined refs
information in the summary
--cite-detail, --no-cite-detail include/exclude full undefined
citations information in the summary
--summary-detail, --no-summary-detail toggle box-detail, ref-detail, and
cite-detail at once
--heartbeat, --no-heartbeat enable/disable progress gauge
--color, --no-color enable/disable colored output
--tips, --no-tips enable/disable suggesting fixes
-l LEVEL, --minlevel=LEVEL filter out messages with severity
level lower than [LEVEL]. Valid
levels are DEBUG, INFO, WARNING,
CRITICAL, and UNKNOWN
-u, --unwrap-only no filtering or summary, only
unwrap long, wrapped lines
--silence-package=PKGNAME suppress messages from package
PKGNAME; can be used multiple times
--silence-string=EXCERPT suppress messages containing text
EXCERPT; can be used multiple times
--silence-file=FILENAME suppress messages generated during
processing of FILENAME; can be used
multiple times
--semisilence-file=FILENAME similar to --silence-file, but not
recursive
--add-debug-message=MESSAGE add new recognizable DEBUG message
--add-info-message=MESSAGE add new recognizable INFO message
--add-warning-message=MESSAGE add new recognizable WARNING message
--add-critical-message=MESSAGE add new recognizable CRITICAL message
--set-to-level-debug=EXCERPT reset severity of messages containing
text EXCERPT to DEBUG; can be used
multiple times
--set-to-level-info=EXCERPT reset severity of messages containing
text EXCERPT to INFO; can be used
multiple times
--set-to-level-warning=EXCERPT reset severity of messages containing
text EXCERPT to WARNING; can be used
multiple times
--set-to-level-critical=EXCERPT reset severity of messages containing
text EXCERPT to CRITICAL; can be used
multiple times
-c cfgfile, --config-file=cfgfile read options from given config file
in addition to default config files
-v, --verbose Display info on texlogsieve config
-h, --help give this help list
--version print program version]]
versionmsg = [[
texlogsieve 1.6.1
Copyright (C) 2021-2026 Nelson Lago <lago@ime.usp.br>
License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.