-
Notifications
You must be signed in to change notification settings - Fork 432
Expand file tree
/
Copy pathparse-error.ts
More file actions
465 lines (413 loc) · 14.3 KB
/
parse-error.ts
File metadata and controls
465 lines (413 loc) · 14.3 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
/*
* log.ts
*
* Copyright (C) 2020-2022 Posit Software, PBC
*/
import { basename, join } from "../../../deno_ral/path.ts";
import { existsSync } from "../../../deno_ral/fs.ts";
import * as ld from "../../../core/lodash.ts";
import { lines } from "../../../core/text.ts";
// The missing font log file name
export const kMissingFontLog = "missfont.log";
// Reads log files and returns a list of search terms to use
// to find packages to install
export function findMissingFontsAndPackages(
logText: string,
dir: string,
): string[] {
// Look for missing fonts
const missingFonts = findMissingFonts(dir);
// Look in the log file itself
const missingPackages = findMissingPackages(logText);
return ld.uniq([...missingPackages, ...missingFonts]);
}
// Does the log file indicate recompilation is neeeded
export function needsRecompilation(log: string) {
if (existsSync(log)) {
const logContents = Deno.readTextFileSync(log);
// First look for an explicit request to recompile
const explicitMatches = explicitMatchers.some((matcher) => {
return logContents.match(matcher);
});
// If there are no explicit requests to re-compile
// Look for unresolved 'resolving' matches
if (explicitMatches) {
return true;
} else {
const unresolvedMatches = resolvingMatchers.some((resolvingMatcher) => {
// First see if there is a message indicating a match of something that
// might subsequently resolve
resolvingMatcher.unresolvedMatch.lastIndex = 0;
let unresolvedMatch = resolvingMatcher.unresolvedMatch.exec(
logContents,
);
const unresolvedMatches = [];
while (unresolvedMatch) {
// Now look for a message indicating that the issue
// has been resolved
const resolvedRegex = new RegExp(
resolvingMatcher.resolvedMatch.replace(
kCaptureToken,
unresolvedMatch[1],
),
"gm",
);
if (!logContents.match(resolvedRegex)) {
unresolvedMatches.push(unresolvedMatch[1]);
}
// Continue looking for other unresolved matches
unresolvedMatch = resolvingMatcher.unresolvedMatch.exec(
logContents,
);
}
if (unresolvedMatches.length > 0) {
// There is an unresolved match
return true;
} else {
// There is not an unresolved match
return false;
}
});
return !!unresolvedMatches;
}
}
return false;
}
const explicitMatchers = [
/(Rerun to get | Please \(re\)run | [rR]erun LaTeX\.)/, // explicitly request recompile
/^No file .*?.aux\.\s*$/gm, // missing aux file from a beamer run using lualatex #6226
];
// Resolving matchers are matchers that may resolve later in the log
// So inspect the for the first match, then if there is a match,
// inspect for the second match, which will indicate that the issue has
// been resolved.
// For example:
// Package marginnote Info: xpos seems to be \@mn@currxpos on input line 213. <- unpositioned element
// Package marginnote Info: xpos seems to be 367.46002pt on input line 213. <- positioned later in the log
const kCaptureToken = "${unresolvedCapture}";
const resolvingMatchers = [
{
unresolvedMatch: /^.*xpos seems to be \\@mn@currxpos.*?line ([0-9]*)\.$/gm,
resolvedMatch:
`^.*xpos seems to be [0-9]*\.[0-9]*pt.*?line ${kCaptureToken}\.$`,
},
];
// Finds PDF/UA accessibility warnings from tagpdf and DocumentMetadata
export interface PdfAccessibilityWarnings {
missingAltText: string[]; // filenames of images missing alt text
missingLanguage: boolean; // document language not set
otherWarnings: string[]; // other tagpdf warnings
}
export function findPdfAccessibilityWarnings(
logText: string,
): PdfAccessibilityWarnings {
const result: PdfAccessibilityWarnings = {
missingAltText: [],
missingLanguage: false,
otherWarnings: [],
};
// Match: Package tagpdf Warning: Alternative text for graphic is missing.
// (tagpdf) Using 'filename' instead.
// Note: tagpdf wraps long filenames across multiple (tagpdf) continuation
// lines, so we allow optional line breaks with (tagpdf) prefixes.
const altTextRegex =
/Package tagpdf Warning: Alternative text for graphic is missing\.\s*\n\(tagpdf\)\s*Using ['`]([^'`]+)['`]\s*(?:\n\(tagpdf\)\s*)?instead\./g;
let match;
while ((match = altTextRegex.exec(logText)) !== null) {
result.missingAltText.push(match[1]);
}
// Match: LaTeX DocumentMetadata Warning: The language has not been set in
if (
/LaTeX DocumentMetadata Warning: The language has not been set in/.test(
logText,
)
) {
result.missingLanguage = true;
}
// Capture any other tagpdf warnings we haven't specifically handled
const otherTagpdfRegex = /Package tagpdf Warning: ([^\n]+)/g;
while ((match = otherTagpdfRegex.exec(logText)) !== null) {
const warning = match[1];
// Skip the alt text warning we already handle specifically
if (!warning.startsWith("Alternative text for graphic is missing")) {
result.otherWarnings.push(warning);
}
}
return result;
}
// Finds missing hyphenation files (these appear as warnings in the log file)
export function findMissingHyphenationFiles(logText: string) {
//ngerman gets special cased
const filterLang = (lang: string) => {
// It seems some languages have no hyphenation files, so we just filter them out
// e.g. `lang: zh` has no hyphenation files
// https://github.com/quarto-dev/quarto-cli/issues/10291
const noHyphen = ["chinese-hans", "chinese"];
if (noHyphen.includes(lang)) {
return;
}
// NOTE Although the names of the corresponding lfd files match those in this list,
// there are some exceptions, particularly in German and Serbian. So, ngerman is
// called here german, which is the name in the CLDR and, actually, the most logical.
//
// See https://ctan.math.utah.edu/ctan/tex-archive/macros/latex/required/babel/base/babel.pdf
if (lang === "ngerman") {
return "hyphen-german";
}
return `hyphen-${lang.toLowerCase()}`;
};
const babelWarningRegex = /^Package babel Warning:/m;
const hasWarning = logText.match(babelWarningRegex);
if (hasWarning) {
const languageRegex = /^\(babel\).* language [`'](\S+)[`'].*$/m;
const languageMatch = logText.match(languageRegex);
if (languageMatch) {
return filterLang(languageMatch[1]);
}
}
// Try an alternative way of parsing
const hyphenRulesRegex =
/Package babel Info: Hyphen rules for '(.*?)' set to \\l@nil/m;
const match = logText.match(hyphenRulesRegex);
if (match) {
const language = match[1];
if (language) {
return filterLang(language);
}
}
}
// Parse a log file to find latex errors
const kErrorRegex = /^\!\s([\s\S]+)?Here is how much/m;
const kEmptyRegex = /(No pages of output)\./;
export function findLatexError(
logText: string,
stderr?: string,
): string | undefined {
const errors: string[] = [];
const match = logText.match(kErrorRegex);
if (match) {
const hint = suggestHint(logText, stderr);
if (hint) {
errors.push(`${match[1]}\n${hint}`);
} else {
errors.push(match[1]);
}
}
if (errors.length === 0) {
const emptyMatch = logText.match(kEmptyRegex);
if (emptyMatch) {
errors.push(
`${emptyMatch[1]} - the document appears to have produced no output.`,
);
}
}
return errors.join("\n");
}
// Find the index error message
const kIndexErrorRegex = /^\s\s\s--\s(.*)/m;
export function findIndexError(logText: string): string | undefined {
const match = logText.match(kIndexErrorRegex);
if (match) {
return match[1];
} else {
return undefined;
}
}
// Search the missing font log for fonts
function findMissingFonts(dir: string): string[] {
const missingFonts = [];
// Look in the missing font file for any missing fonts
const missFontLog = join(dir, kMissingFontLog);
if (existsSync(missFontLog)) {
const missFontLogText = Deno.readTextFileSync(missFontLog);
const fontSearchTerms = findInMissingFontLog(missFontLogText);
missingFonts.push(...fontSearchTerms);
}
return missingFonts;
}
const formatFontFilter = (match: string, _text: string) => {
// Remove special prefix / suffix e.g. 'file:HaranoAjiMincho-Regular.otf:-kern;jfm=ujis'
// https://github.com/quarto-dev/quarto-cli/issues/12194
const base = basename(match).replace(/^.*?:|:.*$/g, "");
// return found file directly if it has an extension
return /[.]/.test(base) ? base : fontSearchTerm(base);
};
const estoPdfFilter = (_match: string, _text: string) => {
return "epstopdf";
};
const packageMatchers = [
// Fonts
{
regex: /.*! Font [^=]+=([^ ]+).+ not loadable.*/g,
filter: formatFontFilter,
},
{
regex: /.*! .*The font "([^"]+)" cannot be found.*/g,
filter: formatFontFilter,
},
{
regex: /.*!.+ error:.+\(file ([^)]+)\): .*/g,
filter: formatFontFilter,
},
{
regex: /.*Unable to find TFM file "([^"]+)".*/g,
filter: formatFontFilter,
},
{
regex: /.*\(fontspec\)\s+The font "([^"]+)" cannot be.*/g,
filter: formatFontFilter,
},
{
regex: /.*Package widetext error: Install the ([^ ]+) package.*/g,
filter: (match: string, _text: string) => {
return `${match}.sty`;
},
},
{ regex: /.* File [`'](.+eps-converted-to.pdf)'.*/g, filter: estoPdfFilter },
{ regex: /.*xdvipdfmx:fatal: pdf_ref_obj.*/g, filter: estoPdfFilter },
{
regex: /.* (tikzlibrary[^ ]+?[.]code[.]tex).*/g,
filter: (match: string, text: string) => {
if (text.match(/! Package tikz Error:/)) {
return match;
} else {
return undefined;
}
},
},
{
regex: /module 'lua-uni-normalize' not found:/g,
filter: (_match: string, _text: string) => {
return "lua-uni-algos.lua";
},
},
{
regex: /.* Package pdfx Error: No color profile ([^\s]*).*/g,
filter: (_match: string, _text: string) => {
return "colorprofiles.sty";
},
},
{
regex: /.*No support files for \\DocumentMetadata found.*/g,
filter: (_match: string, _text: string) => {
return "latex-lab";
},
},
{
// PDF/A requires embedded color profiles - pdfmanagement-testphase needs colorprofiles
regex: /.*\(pdf backend\): cannot open file for embedding.*/g,
filter: (_match: string, _text: string) => {
return "colorprofiles";
},
},
{
regex: /.*No file ([^`'. ]+[.]fd)[.].*/g,
filter: (match: string, _text: string) => {
return match.toLowerCase();
},
},
{ regex: /.* Loading '([^']+)' aborted!.*/g },
{ regex: /.*! LaTeX Error: File [`']([^']+)' not found.*/g },
{ regex: /.* [fF]ile ['`]?([^' ]+)'? not found.*/g },
{ regex: /.*the language definition file ([^\s]*).*/g },
{
regex: /.*! Package babel Error: Unknown option [`']([^'`]+)'[.].*/g,
filter: (match: string, _text: string) => {
return `${match}.ldf`;
},
},
{ regex: /.* \\(file ([^)]+)\\): cannot open .*/g },
{ regex: /.*file [`']([^']+)' .*is missing.*/g },
{ regex: /.*! CTeX fontset [`']([^']+)' is unavailable.*/g },
{ regex: /.*: ([^:]+): command not found.*/g },
{ regex: /.*! I can't find file [`']([^']+)'.*/g },
];
function fontSearchTerm(font: string): string {
const fontPattern = font.replace(/\s+/g, "\\s*");
return `${fontPattern}(-(Bold|Italic|Regular).*)?[.](tfm|afm|mf|otf|ttf)`;
}
function findMissingPackages(logFileText: string): string[] {
const toInstall: string[] = [];
packageMatchers.forEach((packageMatcher) => {
packageMatcher.regex.lastIndex = 0;
let match = packageMatcher.regex.exec(logFileText);
while (match != null) {
const file = match[1];
// Apply the filter, if there is one
const filteredFile = packageMatcher.filter
? packageMatcher.filter(file, logFileText)
: file;
// Capture any matches
if (filteredFile) {
toInstall.push(filteredFile);
}
match = packageMatcher.regex.exec(logFileText);
}
packageMatcher.regex.lastIndex = 0;
});
// dedulicated list of packages to attempt to install
return ld.uniq(toInstall);
}
function findInMissingFontLog(missFontLogText: string): string[] {
const toInstall: string[] = [];
lines(missFontLogText).forEach((line) => {
// Trim the line
line = line.trim();
// Extract the font from the end of the line
const fontMatch = line.match(/([^\s]*)$/);
if (fontMatch && fontMatch[1].trim() !== "") {
toInstall.push(fontMatch[1]);
}
// Extract the font install command from the front of the line
// Also request that this be installed
const commandMatch = line.match(/^([^\s]*)/);
if (commandMatch && commandMatch[1].trim() !== "") {
toInstall.push(commandMatch[1]);
}
});
// deduplicated list of fonts and font install commands
return ld.uniq(toInstall);
}
const kUnicodePattern = {
regex: /\! Package inputenc Error: Unicode character/,
hint:
"Possible unsupported unicode character in this configuration. Perhaps try another LaTeX engine (e.g. XeLaTeX).",
};
const kInlinePattern = {
regex: /Missing \$ inserted\./,
hint: "You may need to $ $ around an expression in this file.",
};
const kGhostPattern = {
regex: /^\!\!\! Error: Cannot open Ghostscript for piped input/m,
hint:
"GhostScript is likely required to compile this document. Please be sure GhostScript (https://ghostscript.com) is installed and try again.",
};
const kGhostCorruptPattern = {
regex: /^GPL Ghostscript .*: Can't find initialization file gs_init.ps/m,
hint:
"GhostScript is likely required to compile this document. Please be sure GhostScript (https://ghostscript.com) is installed and configured properly and try again.",
};
const kLogOutputPatterns = [kUnicodePattern, kInlinePattern];
const kStdErrPatterns = [kGhostPattern, kGhostCorruptPattern];
function suggestHint(
logText: string,
stderr?: string,
): string | undefined {
// Check stderr for hints
const stderrHint = kStdErrPatterns.find((errPattern) =>
stderr?.match(errPattern.regex)
);
if (stderrHint) {
return stderrHint.hint;
} else {
// Check the log file for hints
const logHint = kLogOutputPatterns.find((logPattern) =>
logText.match(logPattern.regex)
);
if (logHint) {
return logHint.hint;
} else {
return undefined;
}
}
}