-
Notifications
You must be signed in to change notification settings - Fork 330
/
pdf.ts
594 lines (535 loc) · 15.9 KB
/
pdf.ts
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
/*
* pdf.ts
*
* Copyright (C) 2020-2022 Posit Software, PBC
*/
import { dirname, join } from "path/mod.ts";
import { existsSync } from "fs/mod.ts";
import { PdfEngine } from "../../../config/types.ts";
import { LatexmkOptions } from "./types.ts";
import { dirAndStem } from "../../../core/path.ts";
import { ProcessResult } from "../../../core/process-types.ts";
import { hasTexLive, TexLiveContext, texLiveContext } from "./texlive.ts";
import { runBibEngine, runIndexEngine, runPdfEngine } from "./latex.ts";
import { PackageManager, packageManager } from "./pkgmgr.ts";
import {
findIndexError,
findLatexError,
findMissingFontsAndPackages,
findMissingHyphenationFiles,
kMissingFontLog,
needsRecompilation,
} from "./parse-error.ts";
import { error, info, warning } from "log/mod.ts";
import { logProgress } from "../../../core/log.ts";
export async function generatePdf(mkOptions: LatexmkOptions): Promise<string> {
if (!mkOptions.quiet) {
logProgress("\nRendering PDF");
logProgress(
`running ${mkOptions.engine.pdfEngine} - 1`,
);
}
// Get the working directory and file name stem
const [cwd, stem] = dirAndStem(mkOptions.input);
const workingDir = mkOptions.outputDir ? join(cwd, mkOptions.outputDir) : cwd;
// Ensure that working directory exists
if (!existsSync(workingDir)) {
Deno.mkdirSync(workingDir);
} else {
// Clean the working directory of any leftover artifacts
cleanup(workingDir, stem);
}
// Determine whether we support automatic updating (TexLive is available)
const allowUpdate = await hasTexLive();
mkOptions.autoInstall = mkOptions.autoInstall && allowUpdate;
// Create the TexLive context for this compilation
const texLive = await texLiveContext(mkOptions.tinyTex !== false);
// The package manager used to find and install packages
const pkgMgr = packageManager(mkOptions, texLive);
// Render the PDF, detecting whether any packages need to be installed
const response = await initialCompileLatex(
mkOptions.input,
mkOptions.engine,
pkgMgr,
texLive,
mkOptions.outputDir,
mkOptions.texInputDirs,
mkOptions.quiet,
);
const initialCompileNeedsRerun = needsRecompilation(response.log);
const indexIntermediateFile = indexIntermediate(workingDir, stem);
let indexCreated = false;
if (indexIntermediateFile) {
// When building large and complex indexes, it
// may be required to run the PDF engine again prior to building
// the index (or page numbers may be incorrect).
// See: https://github.com/rstudio/bookdown/issues/1274
info(" Re-compiling document for index");
await runPdfEngine(
mkOptions.input,
mkOptions.engine,
texLive,
mkOptions.outputDir,
mkOptions.texInputDirs,
pkgMgr,
mkOptions.quiet,
);
// Generate the index information, if needed
indexCreated = await makeIndexIntermediates(
indexIntermediateFile,
pkgMgr,
texLive,
mkOptions.engine.indexEngine,
mkOptions.engine.indexEngineOpts,
mkOptions.quiet,
);
}
// Generate the bibliography intermediaries
const bibliographyCreated = await makeBibliographyIntermediates(
mkOptions.input,
mkOptions.engine.bibEngine || "citeproc",
pkgMgr,
texLive,
mkOptions.outputDir,
mkOptions.texInputDirs,
mkOptions.quiet,
);
// Recompile the Latex if required
// we have already run the engine one time (hence subtracting one run from min and max)
const minRuns = (mkOptions.minRuns || 1) - 1;
const maxRuns = (mkOptions.maxRuns || 10) - 1;
if (
(indexCreated || bibliographyCreated || minRuns ||
initialCompileNeedsRerun) && maxRuns > 0
) {
await recompileLatexUntilComplete(
mkOptions.input,
mkOptions.engine,
pkgMgr,
mkOptions.minRuns || 1,
maxRuns,
texLive,
mkOptions.outputDir,
mkOptions.texInputDirs,
mkOptions.quiet,
);
}
// cleanup if requested
if (mkOptions.clean) {
cleanup(workingDir, stem);
}
if (!mkOptions.quiet) {
info("");
}
return mkOptions.outputDir
? join(mkOptions.outputDir, stem + ".pdf")
: join(cwd, stem + ".pdf");
}
// The first pass compilation of the latex with the ability to discover
// missing packages (and subsequently retrying the compilation)
async function initialCompileLatex(
input: string,
engine: PdfEngine,
pkgMgr: PackageManager,
texLive: TexLiveContext,
outputDir?: string,
texInputDirs?: string[],
quiet?: boolean,
) {
let packagesUpdated = false;
while (true) {
// Run the pdf engine
const response = await runPdfEngine(
input,
engine,
texLive,
outputDir,
texInputDirs,
pkgMgr,
quiet,
);
// Check whether it suceeded. We'll consider it a failure if there is an error status or output is missing despite a success status
// (PNAS Template may eat errors when missing packages exists)
// See: https://github.com/rstudio/tinytex/blob/6c0078f2c3c1319a48b71b61753f09c3ec079c0a/R/latex.R#L216
const success = response.result.code === 0 &&
(!response.output || existsSync(response.output));
if (success) {
// See whether there are warnings about hyphenation
// See (https://github.com/rstudio/tinytex/commit/0f2007426f730a6ed9d45369233c1349a69ddd29)
const logText = Deno.readTextFileSync(response.log);
const missingHyphenationFile = findMissingHyphenationFiles(logText);
if (missingHyphenationFile) {
if (await pkgMgr.installPackages([missingHyphenationFile])) {
// We installed hyphenation files, retry
continue;
} else {
writeError("missing hyphenation file", "", response.log);
return Promise.reject();
}
}
} else if (pkgMgr.autoInstall) {
// try autoinstalling
// First be sure all packages are up to date
if (!packagesUpdated) {
if (!quiet) {
logProgress("updating tlmgr");
}
await pkgMgr.updatePackages(false, true);
info("");
if (!quiet) {
logProgress("updating existing packages");
}
await pkgMgr.updatePackages(true, false);
packagesUpdated = true;
}
const logText = Deno.readTextFileSync(response.log);
// Try to find and install packages
const packagesInstalled = await findAndInstallPackages(
pkgMgr,
response.log,
response.result.stderr,
quiet,
);
if (packagesInstalled) {
// try the intial compile again
continue;
} else {
// We failed to install packages (but there are missing packages), give up
displayError(
"missing packages (automatic installation failed)",
response.log,
response.result,
);
return Promise.reject();
}
} else {
// Failed, but no auto-installation, just display the error
displayError(
"missing packages (automatic installed disabled)",
response.log,
response.result,
);
return Promise.reject();
}
// If we get here, we aren't installing packages (or we've already installed them)
return Promise.resolve(response);
}
}
function displayError(title: string, log: string, result: ProcessResult) {
if (existsSync(log)) {
// There is a log file, so read that and try to find the error
const logText = Deno.readTextFileSync(log);
writeError(
title,
findLatexError(logText, result.stderr),
log,
);
} else {
// There is no log file, just display an unknown error
writeError(title);
}
}
function indexIntermediate(dir: string, stem: string) {
const indexFile = join(dir, `${stem}.idx`);
if (existsSync(indexFile)) {
return indexFile;
} else {
return undefined;
}
}
async function makeIndexIntermediates(
indexFile: string,
pkgMgr: PackageManager,
texLive: TexLiveContext,
engine?: string,
args?: string[],
quiet?: boolean,
) {
// If there is an idx file, we need to run makeindex to create the index data
if (indexFile) {
if (!quiet) {
logProgress("making index");
}
// Make the index
try {
const response = await runIndexEngine(
indexFile,
texLive,
engine,
args,
pkgMgr,
quiet,
);
// Indexing Failed
const indexLogExists = existsSync(response.log);
if (response.result.code !== 0) {
writeError(
`result code ${response.result.code}`,
"",
response.log,
);
return Promise.reject();
} else if (indexLogExists) {
// The command succeeded, but there is an indexing error in the lgo
const logText = Deno.readTextFileSync(response.log);
const error = findIndexError(logText);
if (error) {
writeError(
`error generating index`,
error,
response.log,
);
return Promise.reject();
}
}
return true;
} catch {
writeError(
`error generating index`,
);
return Promise.reject();
}
} else {
return false;
}
}
async function makeBibliographyIntermediates(
input: string,
engine: string,
pkgMgr: PackageManager,
texLive: TexLiveContext,
outputDir?: string,
texInputDirs?: string[],
quiet?: boolean,
) {
// Generate bibliography (including potentially installing missing packages)
// By default, we'll use citeproc which requires no additional processing,
// but if the user would like to use natbib or biblatex, we do need additional
// processing (including explicitly calling the processing tool)
const bibCommand = engine === "natbib" ? "bibtex" : "biber";
const [cwd, stem] = dirAndStem(input);
while (true) {
// If biber, look for a bcf file, otherwise look for aux file
const auxBibFile = bibCommand === "biber" ? `${stem}.bcf` : `${stem}.aux`;
const auxBibPath = outputDir ? join(outputDir, auxBibFile) : auxBibFile;
const auxBibFullPath = join(cwd, auxBibPath);
if (existsSync(auxBibFullPath)) {
const auxFileData = Deno.readTextFileSync(auxBibFullPath);
const requiresProcessing = bibCommand === "biber"
? true
: containsBiblioData(auxFileData);
if (requiresProcessing) {
if (!quiet) {
logProgress("generating bibliography");
}
// If we're on windows and auto-install isn't enabled,
// fix up the aux file
//
if (Deno.build.os === "windows") {
if (bibCommand !== "biber" && !hasTexLive()) {
// See https://github.com/rstudio/tinytex/blob/b2d1bae772f3f979e77fca9fb5efda05855b39d2/R/latex.R#L284
// Strips the '.bib' from any match and returns the string without the bib extension
// Replace any '.bib' in bibdata in windows auxData
const fixedAuxFileData = auxFileData.replaceAll(
/(^\\bibdata{.+)\.bib(.*})$/gm,
(
_substr: string,
prefix: string,
postfix: string,
) => {
return prefix + postfix;
},
);
// Rewrite the corrected file
Deno.writeTextFileSync(auxBibFullPath, fixedAuxFileData);
}
}
// If natbib, only use bibtex, otherwise, could use biber or bibtex
const response = await runBibEngine(
bibCommand,
auxBibPath,
cwd,
texLive,
pkgMgr,
texInputDirs,
quiet,
);
if (response.result.code !== 0 && pkgMgr.autoInstall) {
// Biblio generation failed, see whether we should install anything to try to resolve
// Find the missing packages
const log = join(dirname(auxBibFullPath), `${stem}.blg`);
if (existsSync(log)) {
const logOutput = Deno.readTextFileSync(log);
const match = logOutput.match(/.* open style file ([^ ]+).*/);
if (match) {
const file = match[1];
if (
await findAndInstallPackages(
pkgMgr,
file,
response.result.stderr,
quiet,
)
) {
continue;
} else {
// TODO: read error out of blg file
// TODO: writeError that doesn't require logText?
writeError(`error generating bibliography`, "", log);
return Promise.reject();
}
}
}
}
return true;
}
}
return false;
}
}
async function findAndInstallPackages(
pkgMgr: PackageManager,
logFile: string,
stderr?: string,
_quiet?: boolean,
) {
if (existsSync(logFile)) {
// Read the log file itself
const logText = Deno.readTextFileSync(logFile);
const searchTerms = findMissingFontsAndPackages(logText, dirname(logFile));
if (searchTerms.length > 0) {
const packages = await pkgMgr.searchPackages(searchTerms);
if (packages.length > 0) {
const packagesInstalled = await pkgMgr.installPackages(
packages,
);
if (packagesInstalled) {
// Try again
return true;
} else {
writeError(
"package installation error",
findLatexError(logText, stderr),
logFile,
);
return Promise.reject();
}
} else {
writeError(
"no matching packages",
findLatexError(logText, stderr),
logFile,
);
return Promise.reject();
}
} else {
writeError("error", findLatexError(logText, stderr), logFile);
return Promise.reject();
}
}
return false;
}
function writeError(primary: string, secondary?: string, logFile?: string) {
error(
`\ncompilation failed- ${primary}`,
);
if (secondary) {
info(secondary);
}
if (logFile) {
info(`see ${logFile} for more information.`);
}
}
async function recompileLatexUntilComplete(
input: string,
engine: PdfEngine,
pkgMgr: PackageManager,
minRuns: number,
maxRuns: number,
texLive: TexLiveContext,
outputDir?: string,
texInputDirs?: string[],
quiet?: boolean,
) {
// Run the engine until the bibliography is fully resolved
let runCount = 0;
// convert to zero based minimum
minRuns = minRuns - 1;
while (true) {
// If we've exceeded maximum runs break
if (runCount >= maxRuns) {
if (!quiet) {
warning(
`maximum number of runs (${maxRuns}) reached`,
);
}
break;
}
if (!quiet) {
logProgress(
`running ${engine.pdfEngine} - ${runCount + 2}`,
);
}
const result = await runPdfEngine(
input,
engine,
texLive,
outputDir,
texInputDirs,
pkgMgr,
quiet,
);
if (!result.result.success) {
// Failed
displayError("Error compiling latex", result.log, result.result);
return Promise.reject();
} else {
runCount = runCount + 1;
// If we haven't reached the minimum or the bibliography still needs to be rerun
// go again.
if (
existsSync(result.log) && needsRecompilation(result.log) ||
runCount < minRuns
) {
continue;
}
break;
}
}
}
function containsBiblioData(auxData: string) {
return auxData.match(/^\\(bibdata|citation|bibstyle)\{/m);
}
function auxFile(stem: string, ext: string) {
return `${stem}.${ext}`;
}
function cleanup(workingDir: string, stem: string) {
const auxFiles = [
"log",
"idx",
"aux",
"bcf",
"blg",
"bbl",
"fls",
"out",
"lof",
"lot",
"toc",
"nav",
"snm",
"vrb",
"ilg",
"ind",
"xwm",
"brf",
"run.xml",
].map((aux) => join(workingDir, auxFile(stem, aux)));
// Also cleanup any missfont.log file
auxFiles.push(join(workingDir, kMissingFontLog));
auxFiles.forEach((auxFile) => {
if (existsSync(auxFile)) {
Deno.removeSync(auxFile);
}
});
}