-
Notifications
You must be signed in to change notification settings - Fork 434
Expand file tree
/
Copy pathformat-pdf.ts
More file actions
1388 lines (1268 loc) · 41.3 KB
/
format-pdf.ts
File metadata and controls
1388 lines (1268 loc) · 41.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
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
/*
* format-pdf.ts
*
* Copyright (C) 2020-2022 Posit Software, PBC
*/
import { basename, extname, join } from "../../deno_ral/path.ts";
import { mergeConfigs } from "../../core/config.ts";
import { texSafeFilename } from "../../core/tex.ts";
import {
kBibliography,
kCapBottom,
kCapLoc,
kCapTop,
kCitationLocation,
kCiteMethod,
kClassOption,
kDefaultImageExtension,
kDocumentClass,
kEcho,
kFigCapLoc,
kFigDpi,
kFigFormat,
kFigHeight,
kFigWidth,
kHeaderIncludes,
kKeepTex,
kLang,
kNumberSections,
kPaperSize,
kPdfEngine,
kPdfStandard,
kPdfStandardApplied,
kReferenceLocation,
kShiftHeadingLevelBy,
kTblCapLoc,
kTopLevelDivision,
kWarning,
pdfStandardEnv,
} from "../../config/constants.ts";
import { warning } from "../../deno_ral/log.ts";
import { asArray } from "../../core/array.ts";
import { Format, FormatExtras, PandocFlags } from "../../config/types.ts";
import { createFormat } from "../formats-shared.ts";
import { RenderedFile, RenderServices } from "../../command/render/types.ts";
import { ProjectConfig, ProjectContext } from "../../project/types.ts";
import { BookExtension } from "../../project/types/book/book-shared.ts";
import { readLines } from "io/read-lines";
import { TempContext } from "../../core/temp.ts";
import { isLatexPdfEngine, pdfEngine } from "../../config/pdf.ts";
import { formatResourcePath } from "../../core/resources.ts";
import { kTemplatePartials } from "../../command/render/template.ts";
import { copyTo } from "../../core/copy.ts";
import { kCodeAnnotations } from "../html/format-html-shared.ts";
import { safeModeFromFile } from "../../deno_ral/fs.ts";
import { hasLevelOneHeadings as hasL1Headings } from "../../core/lib/markdown-analysis/level-one-headings.ts";
export function pdfFormat(): Format {
return mergeConfigs(
createPdfFormat("PDF"),
{
extensions: {
book: pdfBookExtension,
},
},
);
}
export function beamerFormat(): Format {
return createFormat(
"Beamer",
"pdf",
createPdfFormat("Beamer", false, false),
{
execute: {
[kFigWidth]: 10,
[kFigHeight]: 7,
[kEcho]: false,
[kWarning]: false,
},
classoption: ["notheorems"],
},
);
}
export function latexFormat(displayName: string): Format {
return createFormat(
displayName,
"tex",
mergeConfigs(
createPdfFormat(displayName),
{
extensions: {
book: {
onSingleFilePreRender: (
format: Format,
_config?: ProjectConfig,
) => {
// If we're targeting LaTeX output, be sure to keep
// the supporting files around (since we're not building
// them into a PDF)
format.render[kKeepTex] = true;
return format;
},
formatOutputDirectory: () => {
return "book-latex";
},
},
},
},
),
);
}
function createPdfFormat(
displayName: string,
autoShiftHeadings = true,
koma = true,
): Format {
return createFormat(
displayName,
"pdf",
{
execute: {
[kFigWidth]: 5.5,
[kFigHeight]: 3.5,
[kFigFormat]: "pdf",
[kFigDpi]: 300,
},
pandoc: {
[kPdfEngine]: "lualatex",
standalone: true,
variables: {
graphics: true,
tables: true,
},
[kDefaultImageExtension]: "pdf",
},
metadata: {
["block-headings"]: true,
},
formatExtras: async (
_input: string,
markdown: string,
flags: PandocFlags,
format: Format,
_libDir: string,
services: RenderServices,
) => {
const extras: FormatExtras = {};
// only apply extras if this is latex (as opposed to context)
const engine = pdfEngine(format.pandoc, format.render, flags);
if (!isLatexPdfEngine(engine)) {
return extras;
}
// Post processed for dealing with latex output
extras.postprocessors = [
pdfLatexPostProcessor(flags, format, services.temp),
];
// user may have overridden koma, check for that here
const documentclass = format.metadata[kDocumentClass] as
| string
| undefined;
const usingCustomTemplates = format.pandoc.template !== undefined ||
format.metadata[kTemplatePartials] !== undefined;
if (
usingCustomTemplates ||
(documentclass &&
![
"srcbook",
"scrreprt",
"scrreport",
"scrartcl",
"scrarticle",
].includes(
documentclass,
))
) {
koma = false;
}
// default to KOMA article class. we do this here rather than
// above so that projectExtras can override us
if (koma) {
// determine caption options
const captionOptions = [];
const tblCaploc = tblCapLocation(format);
captionOptions.push(
tblCaploc === kCapTop ? "tableheading" : "tablesignature",
);
if (figCapLocation(format) === kCapTop) {
captionOptions.push("figureheading");
}
// establish default class options
const defaultClassOptions = ["DIV=11"];
if (format.metadata[kLang] !== "de") {
defaultClassOptions.push("numbers=noendperiod");
}
// determine class options (filter by options already set by the user)
const userClassOptions = format.metadata[kClassOption] as
| string[]
| undefined;
const classOptions = defaultClassOptions.filter((option) => {
if (Array.isArray(userClassOptions)) {
const name = option.split("=")[0];
return !userClassOptions.some((userOption) =>
String(userOption).startsWith(name + "=")
);
} else {
return true;
}
});
const headerIncludes = [];
headerIncludes.push(
"\\KOMAoption{captions}{" + captionOptions.join(",") + "}",
);
extras.metadata = {
[kDocumentClass]: "scrartcl",
[kClassOption]: classOptions,
[kPaperSize]: "letter",
[kHeaderIncludes]: headerIncludes,
};
}
// Provide a custom template for this format
// Partials can be the one from Quarto division
const partialNamesQuarto: string[] = [
"babel-lang",
"before-bib",
"biblio",
"biblio-config",
"citations",
"doc-class",
"graphics",
"after-body",
"before-body",
"pandoc",
"tables",
"tightlist",
"before-title",
"title",
"toc",
];
// or the one from Pandoc division (since Pandoc 3.6.3)
const partialNamesPandoc: string[] = [
"after-header-includes",
"common",
"document-metadata",
"font-settings",
"fonts",
"hypersetup",
"passoptions",
];
const createTemplateContext = function (
to: string,
partialNamesQuarto: string[],
partialNamesPandoc: string[],
) {
return {
template: formatResourcePath(to, "pandoc/template.tex"),
partials: [
...partialNamesQuarto.map((name) => {
return formatResourcePath(to, `pandoc/${name}.tex`);
}),
...partialNamesPandoc.map((name) => {
return formatResourcePath(to, `pandoc/${name}.latex`);
}),
],
};
};
// Beamer doesn't use document-metadata partial (its template doesn't include it)
const beamerPartialNamesPandoc = partialNamesPandoc.filter(
(name) => name !== "document-metadata",
);
extras.templateContext = createTemplateContext(
displayName === "Beamer" ? "beamer" : "pdf",
partialNamesQuarto,
displayName === "Beamer"
? beamerPartialNamesPandoc
: partialNamesPandoc,
);
// Don't shift the headings if we see any H1s (we can't shift up any longer)
const hasLevelOneHeadings = await hasL1Headings(markdown);
// pdfs with no other heading level oriented options get their heading level shifted by -1
if (
!hasLevelOneHeadings &&
autoShiftHeadings &&
(flags?.[kNumberSections] === true ||
format.pandoc[kNumberSections] === true) &&
flags?.[kTopLevelDivision] === undefined &&
format.pandoc?.[kTopLevelDivision] === undefined &&
flags?.[kShiftHeadingLevelBy] === undefined &&
format.pandoc?.[kShiftHeadingLevelBy] === undefined
) {
extras.pandoc = {
[kShiftHeadingLevelBy]: -1,
};
}
// pdfs with document class scrbook get number sections turned on
// https://github.com/quarto-dev/quarto-cli/issues/2369
extras.pandoc = extras.pandoc || {};
if (
documentclass === "scrbook" &&
format.pandoc[kNumberSections] !== false &&
flags[kNumberSections] !== false
) {
extras.pandoc[kNumberSections] = true;
}
// Handle pdf-standard option for PDF/A, PDF/UA, PDF/X conformance
const pdfStandard = asArray(
format.render?.[kPdfStandard] ?? format.metadata?.[kPdfStandard] ??
pdfStandardEnv(),
);
if (pdfStandard.length > 0) {
const { version, standards, needsTagging } =
normalizePdfStandardForLatex(pdfStandard);
// Set pdfstandard as a map if there are standards or a version
if (standards.length > 0 || version) {
extras.pandoc.variables = extras.pandoc.variables || {};
const pdfstandardMap: Record<string, unknown> = {};
if (standards.length > 0) {
pdfstandardMap.standards = standards;
}
if (version) {
pdfstandardMap.version = version;
}
if (needsTagging) {
pdfstandardMap.tagging = true;
}
extras.pandoc.variables["pdfstandard"] = pdfstandardMap;
}
// Store applied standards in metadata for verapdf validation
// (only standards that LaTeX actually supports, not the original list)
if (standards.length > 0) {
extras.metadata = extras.metadata || {};
extras.metadata[kPdfStandardApplied] = standards;
}
}
return extras;
},
},
);
}
const pdfBookExtension: BookExtension = {
selfContainedOutput: true,
onSingleFilePostRender: (
project: ProjectContext,
renderedFile: RenderedFile,
) => {
// if we have keep-tex then rename the input tex file to match the final output
// file (but make sure it has a tex-friendly filename)
if (renderedFile.format.render[kKeepTex]) {
const finalOutputFile = renderedFile.file!;
const texOutputFile =
texSafeFilename(basename(finalOutputFile, extname(finalOutputFile))) +
".tex";
Deno.renameSync(
join(project.dir, "index.tex"),
join(project.dir, texOutputFile),
);
}
},
};
type LineProcessor = (line: string) => string | undefined;
function pdfLatexPostProcessor(
flags: PandocFlags,
format: Format,
temp: TempContext,
) {
return async (output: string) => {
const lineProcessors: LineProcessor[] = [
sidecaptionLineProcessor(),
calloutFloatHoldLineProcessor(),
tableColumnMarginLineProcessor(),
guidsProcessor(),
];
if (format.pandoc[kCiteMethod] === "biblatex") {
lineProcessors.push(bibLatexBibligraphyRefsDivProcessor());
} else if (format.pandoc[kCiteMethod] === "natbib") {
lineProcessors.push(
natbibBibligraphyRefsDivProcessor(
format.metadata[kBibliography] as string[] | undefined,
),
);
}
const marginCites = format.metadata[kCitationLocation] === "margin";
const renderedCites = {};
if (marginCites) {
// Based upon the cite method, post process the file to
// process unresolved citations
if (format.pandoc[kCiteMethod] === "biblatex") {
lineProcessors.push(suppressBibLatexBibliographyLineProcessor());
lineProcessors.push(bibLatexCiteLineProcessor());
} else if (format.pandoc[kCiteMethod] === "natbib") {
lineProcessors.push(suppressNatbibBibliographyLineProcessor());
lineProcessors.push(natbibCiteLineProcessor());
} else {
// If this is using the pandoc default citeproc, we need to
// do a more complex processing, since it is generating raw latex
// for the citations (not running a tool in the pdf chain to
// generate the bibliography). As a result, we first read the
// rendered bibliography, indexing the entring and removing it
// from the latex, then we run a second pass where we use that index
// to replace cites with the rendered versions.
lineProcessors.push(
indexAndSuppressPandocBibliography(renderedCites),
cleanReferencesChapter(),
);
}
}
// Move longtable captions below if requested
if (tblCapLocation(format) === kCapBottom) {
lineProcessors.push(longtableBottomCaptionProcessor());
}
// If enabled, switch to sidenote footnotes
if (marginRefs(flags, format)) {
// Replace notes with side notes
lineProcessors.push(sideNoteLineProcessor());
}
lineProcessors.push(captionFootnoteLineProcessor());
if (
format.metadata[kCodeAnnotations] as boolean !== false &&
format.metadata[kCodeAnnotations] as string !== "none"
) {
lineProcessors.push(codeAnnotationPostProcessor());
lineProcessors.push(codeListAnnotationPostProcessor());
}
lineProcessors.push(tableSidenoteProcessor());
// This is pass 1
await processLines(output, lineProcessors, temp);
// This is pass 2; we need these to happen after the first pass
const pass2Processors: LineProcessor[] = [
longTableSidenoteProcessor(),
];
if (Object.keys(renderedCites).length > 0) {
pass2Processors.push(placePandocBibliographyEntries(renderedCites));
}
await processLines(output, pass2Processors, temp);
};
}
function tblCapLocation(format: Format) {
return format.metadata[kTblCapLoc] || format.metadata[kCapLoc] || kCapTop;
}
function figCapLocation(format: Format) {
return format.metadata[kFigCapLoc] || format.metadata[kCapLoc] || kCapBottom;
}
function marginRefs(flags: PandocFlags, format: Format) {
return format.pandoc[kReferenceLocation] === "margin" ||
flags[kReferenceLocation] === "margin";
}
// Processes the lines of an input file, processing each line
// and replacing the input file with the processed output file
async function processLines(
inputFile: string,
lineProcessors: LineProcessor[],
temp: TempContext,
) {
// The temp file we generate into
const outputFile = temp.createFile({ suffix: ".tex" });
const file = await Deno.open(inputFile);
// Preserve the existing permissions as we'll replace
const mode = safeModeFromFile(inputFile);
try {
for await (const line of readLines(file)) {
let processedLine: string | undefined = line;
// Give each processor a shot at the line
for (const processor of lineProcessors) {
if (processedLine !== undefined) {
processedLine = processor(processedLine);
}
}
// skip lines that a processor has 'eaten'
if (processedLine !== undefined) {
Deno.writeTextFileSync(outputFile, processedLine + "\n", {
append: true,
mode,
});
}
}
} finally {
file.close();
// Always overwrite the input file with an incompletely processed file
// which should make debugging the error easier (I hope)
copyTo(outputFile, inputFile);
}
}
const kBeginScanRegex = /^%quartopost-sidecaption-206BE349/;
const kEndScanRegex = /^%\/quartopost-sidecaption-206BE349/;
const sidecaptionLineProcessor = () => {
let state: "scanning" | "replacing" = "scanning";
return (line: string): string | undefined => {
switch (state) {
case "scanning":
if (line.match(kBeginScanRegex)) {
state = "replacing";
return kbeginLongTablesideCap;
} else {
return line;
}
case "replacing":
if (line.match(kEndScanRegex)) {
state = "scanning";
return kEndLongTableSideCap;
} else {
return line;
}
}
};
};
// Reads the first command encountered as a balanced command
// (e.g. \caption{...} or \footnote{...}) and returns
// the complete command
//
// This expects the latex string to start with the command
const readBalancedCommand = (latex: string) => {
let braceCount = 0;
let entered = false;
const chars: string[] = [];
for (let i = 0; i < latex.length; i++) {
const char = latex.charAt(i);
if (char === "{") {
braceCount++;
entered = true;
} else if (char === "}") {
braceCount--;
}
chars.push(char);
if (entered && braceCount === 0) {
break;
}
}
return chars.join("");
};
// Process element caption footnotes on a latex string
// This expects a latex elements with a `\caption{}`
//
// It will extract footnotes from the caption and replace
// them with a footnote mark and position the footnote
// below the latex element (e.g. it will remove the footnote
// from the element and then return the footnote below
// the element)
const processElementCaptionFootnotes = (latexFigure: string) => {
const footnoteMark = "\\footnote{";
const captionMark = "\\caption{";
// Contents holds the final contents that will be returned
// after being joined. This function will append to contents
// to build up the final output
const contents: string[] = [];
// Read up to the caption itself
const captionIndex = latexFigure.indexOf(captionMark);
if (captionIndex > -1) {
// Slice off the figure up to the caption
contents.push(latexFigure.substring(0, captionIndex));
const captionStartStr = latexFigure.slice(captionIndex);
// Read the caption
const captionLatex = readBalancedCommand(captionStartStr);
const figureSuffix = captionStartStr.slice(captionLatex.length);
// Slice off the command prefix and suffix
let captionContents = captionLatex.slice(
captionMark.length,
captionLatex.length - 1,
);
// Deal with footnotes in the caption
let footNoteIndex = captionContents.indexOf(footnoteMark);
if (footNoteIndex > -1) {
// Caption text will not have any footnotes in it
const captionText: string[] = [];
// Caption with note will have footnotemarks in it
const captionWithNote: string[] = [];
// The footnotes that we found along the way
const footNotes: string[] = [];
while (footNoteIndex > -1) {
// capture any prefix
const prefix = captionContents.substring(0, footNoteIndex);
captionContents = captionContents.slice(footNoteIndex);
// push the prefix onto the captions
captionText.push(prefix);
captionWithNote.push(prefix);
// process the footnote
const footnoteLatex = readBalancedCommand(captionContents);
captionContents = captionContents.slice(footnoteLatex.length);
footNoteIndex = captionContents.indexOf(footnoteMark);
// Capture the footnote and place a footnote mark in the caption
captionWithNote.push("\\footnotemark{}");
footNotes.push(
footnoteLatex.slice(footnoteMark.length, footnoteLatex.length - 1),
);
}
// Push any leftovers onto the caption contents
captionText.push(captionContents);
captionWithNote.push(captionContents);
// push the caption onto the contents
contents.push(
`\\caption[${captionText.join("")}]{${captionWithNote.join("")}}`,
);
// push the suffix onto the contents
contents.push(figureSuffix);
// push the footnotes on the contents
contents.push("\n");
// Add a proper footnote counter offset, if necessary
if (footNotes.length > 1) {
contents.push(`\\addtocounter{footnote}{-${footNotes.length - 1}}`);
}
for (let i = 0; i < footNotes.length; i++) {
contents.push(`\\footnotetext{${footNotes[i]}}`);
if (footNotes.length > 1 && i < footNotes.length - 1) {
contents.push(`\\addtocounter{footnote}{1}`);
}
}
return contents.join("");
} else {
// No footnotes in the caption, just leave it alone
return latexFigure;
}
} else {
// No caption means just let it go
return latexFigure;
}
};
const kMatchLongTableSize = /^(.*)p{\(\\columnwidth - (\d+\\tabcolsep\).*$)/;
const kStartLongTable = /^\\begin{longtable}/;
const kEndLongTable = /^\\end{longtable}/;
const guidsProcessor = () => {
let state: "looking-for-definition-start" | "looking-for-definition-end" =
"looking-for-definition-start";
const guidDefinitions: [string, string][] = [];
let guidBeingProcessed: string | undefined;
let guidContents: string[] = [];
return (line: string): string | undefined => {
switch (state) {
case "looking-for-definition-start": {
if (line.startsWith("%quarto-define-uuid: ")) {
state = "looking-for-definition-end";
line = line.replace(/^%quarto-define-uuid:\s*/, "");
guidBeingProcessed = line.trim();
return undefined;
}
for (const [key, value] of guidDefinitions) {
line = line.replaceAll(key, value);
}
return line;
}
case "looking-for-definition-end": {
if (line === "%quarto-end-define-uuid") {
state = "looking-for-definition-start";
if (guidBeingProcessed === undefined) {
throw new Error("guidBeingProcessed is undefined");
}
guidDefinitions.push([
guidBeingProcessed,
guidContents.join("").trim(),
]);
guidContents = [];
guidBeingProcessed = undefined;
return undefined;
} else {
guidContents.push(line);
return undefined;
}
}
}
};
};
const tableColumnMarginLineProcessor = () => {
let state: "looking-for-boundaries" | "looking-for-tables" | "processing" =
"looking-for-boundaries";
return (line: string): string | undefined => {
switch (state) {
case "looking-for-boundaries": {
if (line === "% quarto-tables-in-margin-AB1927C9:begin") {
state = "looking-for-tables";
return undefined;
}
return line;
}
case "looking-for-tables": {
if (line.match(kStartLongTable)) {
state = "processing";
return line;
} else if (line === "% quarto-tables-in-margin-AB1927C9:end") {
state = "looking-for-boundaries";
return undefined;
}
return line;
}
case "processing": {
if (line.match(kEndLongTable)) {
state = "looking-for-tables";
return line;
} else {
const match = line.match(kMatchLongTableSize);
if (match) {
return `${
match[1]
}p{(\\marginparwidth + \\marginparsep + \\columnwidth - ${
match[2]
}`;
} else {
return line;
}
}
}
default: {
return line;
}
}
};
};
const captionFootnoteLineProcessor = () => {
let state: "scanning" | "capturing" = "scanning";
let capturedLines: string[] = [];
return (line: string): string | undefined => {
switch (state) {
case "scanning":
if (line.match(/^\\begin{figure}.*$/)) {
state = "capturing";
capturedLines = [line];
return undefined;
} else {
return line;
}
case "capturing":
capturedLines.push(line);
if (line.match(/^\\end{figure}%*$/)) {
state = "scanning";
// read the whole figure and clear any capture state
const lines = capturedLines.join("\n");
capturedLines = [];
// Process the captions and relocate footnotes
return processElementCaptionFootnotes(lines);
} else {
return undefined;
}
}
};
};
const processSideNotes = (endMarker: string) => {
return (latexLongTable: string) => {
const sideNoteMarker = "\\sidenote{\\footnotesize ";
let strProcessing = latexLongTable;
const strOutput: string[] = [];
const sidenotes: string[] = [];
let sidenotePos = strProcessing.indexOf(sideNoteMarker);
while (sidenotePos > -1) {
strOutput.push(strProcessing.substring(0, sidenotePos));
const remainingStr = strProcessing.substring(
sidenotePos + sideNoteMarker.length,
);
let escaped = false;
let sideNoteEnd = -1;
for (let i = 0; i < remainingStr.length; i++) {
const ch = remainingStr[i];
if (ch === "\\") {
escaped = true;
} else {
if (!escaped && ch === "}") {
sideNoteEnd = i;
break;
} else {
escaped = false;
}
}
}
if (sideNoteEnd > -1) {
strOutput.push("\\sidenotemark{}");
const contents = remainingStr.substring(0, sideNoteEnd);
sidenotes.push(contents);
strProcessing = remainingStr.substring(sideNoteEnd + 1);
sidenotePos = strProcessing.indexOf(sideNoteMarker);
} else {
strOutput.push(remainingStr);
}
}
// Ensure that we inject sidenotes after the longtable
const endTable = endMarker;
const endPos = strProcessing.indexOf(endTable);
const prefix = strProcessing.substring(0, endPos + endTable.length);
const suffix = strProcessing.substring(
endPos + endTable.length,
strProcessing.length,
);
strOutput.push(prefix);
for (const note of sidenotes) {
strOutput.push(`\\sidenotetext{${note}}\n`);
}
if (suffix) {
strOutput.push(suffix);
}
return strOutput.join("");
};
};
const processLongTableSidenotes = processSideNotes("\\end{longtable}");
const processTableSidenotes = processSideNotes("\\end{table}");
const sideNoteProcessor = (
beginRegex: RegExp,
endRegex: RegExp,
callback: (str: string) => string,
) => {
return () => {
let state: "scanning" | "capturing" = "scanning";
let capturedLines: string[] = [];
return (line: string): string | undefined => {
switch (state) {
case "scanning":
if (line.match(beginRegex)) {
state = "capturing";
capturedLines = [line];
return undefined;
} else {
return line;
}
case "capturing":
capturedLines.push(line);
if (line.match(endRegex)) {
state = "scanning";
// read the whole figure and clear any capture state
const lines = capturedLines.join("\n");
capturedLines = [];
// Process the captions and relocate footnotes
return callback(lines);
} else {
return undefined;
}
}
};
};
};
const longTableSidenoteProcessor = sideNoteProcessor(
/^\\begin{longtable}.*$/,
/^\\end{longtable}%*$/,
processLongTableSidenotes,
);
const tableSidenoteProcessor = sideNoteProcessor(
/^\\begin{table}.*$/,
/^\\end{table}%*$/,
processTableSidenotes,
);
const calloutFloatHoldLineProcessor = () => {
let state: "scanning" | "replacing" = "scanning";
return (line: string): string | undefined => {
switch (state) {
case "scanning":
if (line.match(/^\\begin{tcolorbox}/)) {
state = "replacing";
return line;
} else {
return line;
}
case "replacing":
if (line.match(/^\\end{tcolorbox}/)) {
state = "scanning";
return line;
} else if (line.match(/^\\begin{figure}$/)) {
return "\\begin{figure}[H]";
} else if (line.match(/^\\begin{codelisting}$/)) {
return "\\begin{codelisting}[H]";
} else {
return line;
}
}
};
};
const kQuartoBibPlaceholderRegex = "%bib-loc-124C8010";
const bibLatexBibligraphyRefsDivProcessor = () => {
let hasRefsDiv = false;
return (line: string): string | undefined => {
if (line === kQuartoBibPlaceholderRegex) {
if (!hasRefsDiv) {
hasRefsDiv = true;
return "\\printbibliography[heading=none]";
} else {
// already seen a refs div, just ignore this one
return undefined;
}
} else if (hasRefsDiv && line.match(/^\\printbibliography$/)) {
return undefined;
} else {
return line;
}
};
};
const natbibBibligraphyRefsDivProcessor = (bibs?: string[]) => {
let hasRefsDiv = false;
return (line: string): string | undefined => {
if (line === kQuartoBibPlaceholderRegex) {
if (bibs && !hasRefsDiv) {
hasRefsDiv = true;
return `\\renewcommand{\\bibsection}{}\n\\bibliography{${
bibs.join(",")
}}`;
} else {
// already seen a refs div, just ignore this one
return undefined;
}
} else if (hasRefsDiv && line.match(/^\s*\\bibliography{.*}$/)) {
return undefined;
} else {
return line;
}
};
};
// Removes the biblatex \printbibiliography command
const suppressBibLatexBibliographyLineProcessor = () => {
return (line: string): string | undefined => {
if (line.match(/^\\printbibliography$/)) {
return "";
}
return line;
};
};
// Replaces the natbib bibligography declaration with a version
// that will not be printed in the PDF
const suppressNatbibBibliographyLineProcessor = () => {
return (line: string): string | undefined => {
return line.replace(/^\s*\\bibliography{(.*)}$/, (_match, bib) => {
return `\\newsavebox\\mytempbib
\\savebox\\mytempbib{\\parbox{\\textwidth}{\\bibliography{${bib}}}}`;
});
};
};