-
Notifications
You must be signed in to change notification settings - Fork 351
/
Copy pathpandoc.ts
1761 lines (1586 loc) · 53.8 KB
/
pandoc.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
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
/*
* pandoc.ts
*
* Copyright (C) 2020-2022 Posit Software, PBC
*/
import { basename, dirname, isAbsolute, join } from "../../deno_ral/path.ts";
import { info } from "../../deno_ral/log.ts";
import { ensureDir, existsSync, expandGlobSync } from "../../deno_ral/fs.ts";
import { parse as parseYml, stringify } from "../../core/yaml.ts";
import { copyTo } from "../../core/copy.ts";
import { decodeBase64, encodeBase64 } from "encoding/base64";
import * as ld from "../../core/lodash.ts";
import { Document } from "../../core/deno-dom.ts";
import { execProcess } from "../../core/process.ts";
import { dirAndStem, normalizePath } from "../../core/path.ts";
import { mergeConfigs } from "../../core/config.ts";
import { quartoConfig } from "../../core/quarto.ts";
import {
Format,
FormatExtras,
FormatPandoc,
kBodyEnvelope,
kDependencies,
kHtmlFinalizers,
kHtmlPostprocessors,
kMarkdownAfterBody,
kTextHighlightingMode,
} from "../../config/types.ts";
import {
isAstOutput,
isBeamerOutput,
isEpubOutput,
isHtmlDocOutput,
isHtmlFileOutput,
isHtmlOutput,
isIpynbOutput,
isLatexOutput,
isMarkdownOutput,
isRevealjsOutput,
isTypstOutput,
} from "../../config/format.ts";
import {
isIncludeMetadata,
isQuartoMetadata,
metadataGetDeep,
} from "../../config/metadata.ts";
import { pandocBinaryPath, resourcePath } from "../../core/resources.ts";
import { pandocAutoIdentifier } from "../../core/pandoc/pandoc-id.ts";
import {
partitionYamlFrontMatter,
readYamlFromMarkdown,
} from "../../core/yaml.ts";
import { ProjectContext } from "../../project/types.ts";
import {
deleteProjectMetadata,
projectIsBook,
projectIsWebsite,
} from "../../project/project-shared.ts";
import { deleteCrossrefMetadata } from "../../project/project-crossrefs.ts";
import {
getPandocArg,
havePandocArg,
kQuartoForwardedMetadataFields,
removePandocArgs,
} from "./flags.ts";
import {
generateDefaults,
pandocDefaultsMessage,
writeDefaultsFile,
} from "./defaults.ts";
import { filterParamsJson, removeFilterParams } from "./filters.ts";
import {
kAbstract,
kAbstractTitle,
kAuthor,
kAuthors,
kClassOption,
kColorLinks,
kColumns,
kDate,
kDateFormat,
kDateModified,
kDocumentClass,
kEmbedResources,
kFigResponsive,
kFilterParams,
kFontPaths,
kFormatResources,
kFrom,
kHighlightStyle,
kHtmlMathMethod,
kIncludeAfterBody,
kIncludeBeforeBody,
kIncludeInHeader,
kInstitute,
kInstitutes,
kKeepSource,
kLatexAutoMk,
kLinkColor,
kMath,
kMetadataFormat,
kNotebooks,
kNotebookView,
kNumberOffset,
kNumberSections,
kPageTitle,
kQuartoInternal,
kQuartoTemplateParams,
kQuartoVarsKey,
kQuartoVersion,
kResources,
kRevealJsScripts,
kSectionTitleAbstract,
kSelfContained,
kSyntaxDefinitions,
kTemplate,
kTheme,
kTitle,
kTitlePrefix,
kTocLocation,
kTocTitle,
kTocTitleDocument,
kTocTitleWebsite,
kVariables,
} from "../../config/constants.ts";
import { TempContext } from "../../core/temp.ts";
import { discoverResourceRefs, fixEmptyHrefs } from "../../core/html.ts";
import { kDefaultHighlightStyle } from "./constants.ts";
import {
HtmlPostProcessor,
HtmlPostProcessResult,
PandocOptions,
RunPandocResult,
} from "./types.ts";
import { crossrefFilterActive } from "./crossref.ts";
import { overflowXPostprocessor } from "./layout.ts";
import {
codeToolsPostprocessor,
formatHasCodeTools,
keepSourceBlock,
} from "./codetools.ts";
import { pandocMetadataPath } from "./render-paths.ts";
import { Metadata } from "../../config/types.ts";
import { resourcesFromMetadata } from "./resources.ts";
import { resolveSassBundles } from "./pandoc-html.ts";
import {
cleanTemplatePartialMetadata,
kTemplatePartials,
readPartials,
resolveTemplatePartialPaths,
stageTemplate,
} from "./template.ts";
import {
kYamlMetadataBlock,
pandocFormatWith,
parseFormatString,
splitPandocFormatString,
} from "../../core/pandoc/pandoc-formats.ts";
import { cslNameToString, parseAuthor } from "../../core/author.ts";
import { logLevel } from "../../core/log.ts";
import { cacheCodePage, clearCodePageCache } from "../../core/windows.ts";
import { textHighlightThemePath } from "../../quarto-core/text-highlighting.ts";
import { resolveAndFormatDate, resolveDate } from "../../core/date.ts";
import { katexPostProcessor } from "../../format/html/format-html-math.ts";
import {
readAndInjectDependencies,
writeDependencies,
} from "./pandoc-dependencies-html.ts";
import {
processFormatResources,
writeFormatResources,
} from "./pandoc-dependencies-resources.ts";
import { withTiming } from "../../core/timing.ts";
import {
requiresShortcodeUnescapePostprocessor,
shortcodeUnescapePostprocessor,
} from "../../format/markdown/format-markdown.ts";
import { kRevealJSPlugins } from "../../extension/constants.ts";
import { kCitation } from "../../format/html/format-html-shared.ts";
import { cslDate } from "../../core/csl.ts";
import {
createMarkdownPipeline,
MarkdownPipelineHandler,
} from "../../core/markdown-pipeline.ts";
import { getEnv } from "../../../package/src/util/utils.ts";
import {
BrandFontBunny,
BrandFontFile,
BrandFontGoogle,
} from "../../resources/types/schema-types.ts";
import { kFieldCategories } from "../../project/types/website/listing/website-listing-shared.ts";
import { isWindows } from "../../deno_ral/platform.ts";
import { appendToCombinedLuaProfile } from "../../core/performance/perfetto-utils.ts";
import { makeTimedFunctionAsync } from "../../core/performance/function-times.ts";
import { walkJson } from "../../core/json.ts";
// in case we are running multiple pandoc processes
// we need to make sure we capture all of the trace files
let traceCount = 0;
const handleCombinedLuaProfiles = (
source: string,
paramsJson: Record<string, unknown>,
temp: TempContext,
) => {
const beforePandocHooks: (() => unknown)[] = [];
const afterPandocHooks: (() => unknown)[] = [];
const tmp = temp.createFile();
const combinedProfile = Deno.env.get("QUARTO_COMBINED_LUA_PROFILE");
if (combinedProfile) {
beforePandocHooks.push(() => {
paramsJson["lua-profiler-output"] = tmp;
});
afterPandocHooks.push(() => {
appendToCombinedLuaProfile(
source,
tmp,
combinedProfile,
);
});
}
return {
before: beforePandocHooks,
after: afterPandocHooks,
};
};
function captureRenderCommand(
args: Deno.RunOptions,
temp: TempContext,
outputDir: string,
) {
Deno.mkdirSync(outputDir, { recursive: true });
const newArgs = [
args.cmd[0],
...args.cmd.slice(1).map((_arg) => {
const arg = _arg as string; // we know it's a string, TypeScript doesn't somehow
if (!arg.startsWith(temp.baseDir)) {
return arg;
}
const newArg = join(outputDir, basename(arg));
if (arg.match(/^.*quarto\-defaults.*.yml$/)) {
// we need to correct the defaults YML because it contains a reference to a template in a temp directory
const ymlDefaults = Deno.readTextFileSync(arg);
const defaults = parseYml(ymlDefaults);
const templateDirectory = dirname(defaults.template);
const newTemplateDirectory = join(
outputDir,
basename(templateDirectory),
);
copyTo(templateDirectory, newTemplateDirectory);
defaults.template = join(
newTemplateDirectory,
basename(defaults.template),
);
const defaultsOutputFile = join(outputDir, basename(arg));
Deno.writeTextFileSync(defaultsOutputFile, stringify(defaults));
return defaultsOutputFile;
}
Deno.copyFileSync(arg, newArg);
return newArg;
}),
] as typeof args.cmd;
// now we need to correct entries in filterParams
const filterParams = JSON.parse(
new TextDecoder().decode(decodeBase64(args.env!["QUARTO_FILTER_PARAMS"])),
);
walkJson(
filterParams,
(v: unknown) => typeof v === "string" && v.startsWith(temp.baseDir),
(_v: unknown) => {
const v = _v as string;
const newV = join(outputDir, basename(v));
Deno.copyFileSync(v, newV);
return newV;
},
);
Deno.writeTextFileSync(
join(outputDir, "render-command.json"),
JSON.stringify(
{
...args,
args: newArgs,
env: {
...args.env,
"QUARTO_FILTER_PARAMS": encodeBase64(JSON.stringify(filterParams)),
},
},
undefined,
2,
),
);
}
export async function runPandoc(
options: PandocOptions,
sysFilters: string[],
): Promise<RunPandocResult | null> {
const beforePandocHooks: (() => unknown)[] = [];
const afterPandocHooks: (() => unknown)[] = [];
const setupPandocHooks = (
hooks: { before: (() => unknown)[]; after: (() => unknown)[] },
) => {
beforePandocHooks.push(...hooks.before);
afterPandocHooks.push(...hooks.after);
};
const pandocEnv: { [key: string]: string } = {};
const setupPandocEnv = () => {
pandocEnv["QUARTO_FILTER_PARAMS"] = encodeBase64(
JSON.stringify(paramsJson),
);
const traceFilters = pandocMetadata?.["_quarto"]?.["trace-filters"] ||
Deno.env.get("QUARTO_TRACE_FILTERS");
if (traceFilters) {
// in case we are running multiple pandoc processes
// we need to make sure we capture all of the trace files
let traceCountSuffix = "";
if (traceCount > 0) {
traceCountSuffix = `-${traceCount}`;
}
++traceCount;
if (traceFilters === true) {
pandocEnv["QUARTO_TRACE_FILTERS"] = "quarto-filter-trace.json" +
traceCountSuffix;
} else {
pandocEnv["QUARTO_TRACE_FILTERS"] = traceFilters + traceCountSuffix;
}
}
// https://github.com/quarto-dev/quarto-cli/issues/8274
// do not use the default LUA_CPATH, as it will cause pandoc to
// load the system lua libraries, which may not be compatible with
// the lua version we are using
if (Deno.env.get("QUARTO_LUA_CPATH") !== undefined) {
pandocEnv["LUA_CPATH"] = getEnv("QUARTO_LUA_CPATH");
} else {
pandocEnv["LUA_CPATH"] = "";
}
};
// compute cwd for render
const cwd = dirname(options.source);
// build the pandoc command (we'll feed it the input on stdin)
const cmd = [pandocBinaryPath(), "+RTS", "-K512m", "-RTS"];
// build command line args
const args = [...options.args];
// propagate debug
if (logLevel() === "DEBUG") {
args.push("--verbose");
args.push("--trace");
}
// propagate quiet
if (options.flags?.quiet || logLevel() === "ERROR") {
args.push("--quiet");
}
// merge in any extra metadata
if (options.metadata) {
options.format.metadata = mergeConfigs(
options.format.metadata,
options.metadata,
);
}
// save args and metadata so we can print them (we may subsequently edit them)
const printArgs = [...args];
let printMetadata = {
...options.format.metadata,
crossref: {
...(options.format.metadata.crossref || {}),
},
...options.flags?.metadata,
} as Metadata;
const cleanQuartoTestsMetadata = (metadata: Metadata) => {
// remove any metadata that is only used for testing
if (metadata["_quarto"] && typeof metadata["_quarto"] === "object") {
delete (metadata._quarto as { [key: string]: unknown })?.tests;
if (Object.keys(metadata._quarto).length === 0) {
delete metadata._quarto;
}
}
};
// remove some metadata that are used as parameters to our lua filters
const cleanMetadataForPrinting = (metadata: Metadata) => {
delete metadata.params;
delete metadata[kQuartoInternal];
delete metadata[kQuartoVarsKey];
delete metadata[kQuartoVersion];
delete metadata[kFigResponsive];
delete metadata[kQuartoTemplateParams];
delete metadata[kRevealJsScripts];
deleteProjectMetadata(metadata);
deleteCrossrefMetadata(metadata);
removeFilterParams(metadata);
// Don't print empty reveal-js plugins
if (
metadata[kRevealJSPlugins] &&
(metadata[kRevealJSPlugins] as Array<unknown>).length === 0
) {
delete metadata[kRevealJSPlugins];
}
// Don't print _quarto.tests
// This can cause issue on regex test for printed output
cleanQuartoTestsMetadata(metadata);
};
cleanMetadataForPrinting(printMetadata);
// Forward flags metadata into the format
kQuartoForwardedMetadataFields.forEach((field) => {
if (options.flags?.pandocMetadata?.[field]) {
options.format.metadata[field] = options.flags.pandocMetadata[field];
}
});
// generate defaults and capture defaults to be printed
let allDefaults = (await generateDefaults(options)) || {};
let printAllDefaults = ld.cloneDeep(allDefaults) as FormatPandoc;
// capture any filterParams in the FormatExtras
const formatFilterParams = {} as Record<string, unknown>;
// Note whether we should be forcing math on for this render
const forceMath = options.format.metadata[kMath];
delete options.format.metadata[kMath];
// the "ojs" filter is a special value that results in us
// just signaling our standard filter chain that the ojs
// filter should be active
const kOJSFilter = "ojs";
if (sysFilters.includes(kOJSFilter)) {
formatFilterParams[kOJSFilter] = true;
sysFilters = sysFilters.filter((filter) => filter !== kOJSFilter);
}
// pass the format language along to filter params
formatFilterParams["language"] = options.format.language;
// if there is no toc title then provide the appropirate default
if (
!options.format.metadata[kTocTitle] && !isAstOutput(options.format.pandoc)
) {
options.format.metadata[kTocTitle] = options.format.language[
(projectIsWebsite(options.project) && !projectIsBook(options.project) &&
isHtmlOutput(options.format.pandoc, true))
? kTocTitleWebsite
: kTocTitleDocument
];
}
// if toc-location is set, enable the TOC as well
if (
options.format.metadata[kTocLocation] &&
options.format.pandoc.toc === undefined
) {
options.format.pandoc.toc = true;
}
// if there is an abtract then forward abtract-title
if (
options.format.metadata[kAbstract] &&
(isHtmlDocOutput(options.format.pandoc) ||
isEpubOutput(options.format.pandoc))
) {
options.format.metadata[kAbstractTitle] =
options.format.metadata[kAbstractTitle] ||
options.format.language[kSectionTitleAbstract];
}
// see if there are extras
const postprocessors: Array<
(
output: string,
) => Promise<{ supporting?: string[]; resources?: string[] } | void>
> = [];
const htmlPostprocessors: Array<HtmlPostProcessor> = [];
const htmlFinalizers: Array<(doc: Document) => Promise<void>> = [];
const htmlRenderAfterBody: string[] = [];
const dependenciesFile = options.services.temp.createFile();
if (
sysFilters.length > 0 || options.format.formatExtras ||
options.project?.formatExtras
) {
const projectExtras = options.project?.formatExtras
? (await options.project.formatExtras(
options.source,
options.flags || {},
options.format,
options.services,
))
: {};
const formatExtras = options.format.formatExtras
? (await options.format.formatExtras(
options.source,
options.markdown,
options.flags || {},
options.format,
options.libDir,
options.services,
options.offset,
options.project,
options.quiet,
))
: {};
// start with the merge
const inputExtras = mergeConfigs(
projectExtras,
formatExtras,
{
metadata: projectExtras.metadata?.[kDocumentClass]
? {
[kDocumentClass]: projectExtras.metadata?.[kDocumentClass],
}
: undefined,
},
);
const extras = await resolveExtras(
options.source,
inputExtras,
options.format,
cwd,
options.libDir,
dependenciesFile,
options.project,
);
// record postprocessors
postprocessors.push(...(extras.postprocessors || []));
// add a keep-source post processor if we need one
if (
options.format?.render[kKeepSource] || formatHasCodeTools(options.format)
) {
htmlPostprocessors.push(codeToolsPostprocessor(options.format));
}
// save post-processors
htmlPostprocessors.push(...(extras.html?.[kHtmlPostprocessors] || []));
// Save finalizers
htmlFinalizers.push(...(extras.html?.[kHtmlFinalizers] || []));
if (isHtmlFileOutput(options.format.pandoc)) {
// add a post-processor for fixing overflow-x in cell output display
htmlPostprocessors.push(overflowXPostprocessor);
// katex post-processor
if (
options.flags?.katex ||
options.format.pandoc[kHtmlMathMethod] === "katex"
) {
htmlPostprocessors.push(katexPostProcessor());
}
if (!projectIsWebsite(options.project)) {
// add a resource discovery postProcessor if we are not in a website project
htmlPostprocessors.push(discoverResourceRefs);
// in order for tabsets etc to show the right mouse cursor,
// we need hrefs in anchor elements to be "empty" instead of missing.
// Existing href attributes trigger the any-link pseudo-selector that
// browsers set to `cursor: pointer`.
//
// In project websites, quarto-nav.js does the same thing so this step
// isn't necessary.
htmlPostprocessors.push(fixEmptyHrefs);
}
// Include Math, if explicitly requested (this will result
// in math dependencies being injected into the page)
if (forceMath) {
const htmlMarkdownHandlers: MarkdownPipelineHandler[] = [];
htmlMarkdownHandlers.push({
getUnrendered: () => {
return {
inlines: {
"quarto-enable-math-inline": "$e = mC^2$",
},
};
},
processRendered: (
_rendered: unknown,
_doc: Document,
) => {
},
});
const htmlMarkdownPipeline = createMarkdownPipeline(
"quarto-book-math",
htmlMarkdownHandlers,
);
const htmlPipelinePostProcessor = (
doc: Document,
): Promise<HtmlPostProcessResult> => {
htmlMarkdownPipeline.processRenderedMarkdown(doc);
return Promise.resolve({
resources: [],
supporting: [],
});
};
htmlRenderAfterBody.push(htmlMarkdownPipeline.markdownAfterBody());
htmlPostprocessors.push(htmlPipelinePostProcessor);
}
}
// Capture markdown that should be appended post body
htmlRenderAfterBody.push(...(extras.html?.[kMarkdownAfterBody] || []));
// merge sysFilters if we have them
if (sysFilters.length > 0) {
extras.filters = extras.filters || {};
extras.filters.post = extras.filters.post || [];
extras.filters.post.unshift(
...(sysFilters.map((filter) => resourcePath(join("filters", filter)))),
);
}
// merge args
if (extras.args) {
args.push(...extras.args);
printArgs.push(...extras.args);
}
// merge pandoc
if (extras.pandoc) {
// Special case - we need to more intelligently merge pandoc from
// by breaking apart the from string
if (
typeof (allDefaults[kFrom]) === "string" &&
typeof (extras.pandoc[kFrom]) === "string"
) {
const userFrom = splitPandocFormatString(allDefaults[kFrom] as string);
const extrasFrom = splitPandocFormatString(
extras.pandoc[kFrom] as string,
);
allDefaults[kFrom] = pandocFormatWith(
userFrom.format,
"",
extrasFrom.options + userFrom.options,
);
printAllDefaults[kFrom] = allDefaults[kFrom];
}
allDefaults = mergeConfigs(extras.pandoc, allDefaults);
printAllDefaults = mergeConfigs(extras.pandoc, printAllDefaults);
// Special case - theme is resolved on extras and should override allDefaults
if (extras.pandoc[kHighlightStyle] === null) {
delete printAllDefaults[kHighlightStyle];
allDefaults[kHighlightStyle] = null;
} else if (extras.pandoc[kHighlightStyle]) {
delete printAllDefaults[kHighlightStyle];
allDefaults[kHighlightStyle] = extras.pandoc[kHighlightStyle];
} else {
delete printAllDefaults[kHighlightStyle];
delete allDefaults[kHighlightStyle];
}
}
// merge metadata
if (extras.metadata || extras.metadataOverride) {
// before we merge metadata, ensure that partials are proper paths
resolveTemplatePartialPaths(
options.format.metadata,
cwd,
options.project,
);
options.format.metadata = {
...mergeConfigs(
extras.metadata || {},
options.format.metadata,
),
...extras.metadataOverride || {},
};
printMetadata = mergeConfigs(extras.metadata || {}, printMetadata);
cleanMetadataForPrinting(printMetadata);
}
// merge notebooks that have been provided by the document / user
// or by the project as format extras
if (extras[kNotebooks]) {
const documentNotebooks = options.format.render[kNotebookView];
// False means that the user has explicitely disabled notebooks
if (documentNotebooks !== false) {
const userNotebooks = documentNotebooks === true
? []
: Array.isArray(documentNotebooks)
? documentNotebooks
: documentNotebooks !== undefined
? [documentNotebooks]
: [];
// Only add notebooks that aren't already present
const uniqExtraNotebooks = extras[kNotebooks].filter((nb) => {
return !userNotebooks.find((userNb) => {
return userNb.notebook === nb.notebook;
});
});
options.format.render[kNotebookView] = [
...userNotebooks,
...uniqExtraNotebooks,
];
}
}
// clean 'columns' from pandoc defaults to typst
if (isTypstOutput(options.format.pandoc)) {
delete allDefaults[kColumns];
delete printAllDefaults[kColumns];
}
// The user template (if any)
const userTemplate = getPandocArg(args, "--template") ||
allDefaults[kTemplate];
// The user partials (if any)
const userPartials = readPartials(options.format.metadata, cwd);
const inputDir = normalizePath(cwd);
const resolvePath = (path: string) => {
if (isAbsolute(path)) {
return path;
} else {
return join(inputDir, path);
}
};
const templateContext = extras.templateContext;
if (templateContext) {
// Clean the template partial output
cleanTemplatePartialMetadata(
printMetadata,
templateContext.partials || [],
);
// The format is providing a more robust local template
// to use, stage the template and pass it on to pandoc
const template = userTemplate
? resolvePath(userTemplate)
: templateContext.template;
// Validate any user partials
if (!userTemplate && userPartials.length > 0) {
const templateNames = templateContext.partials?.map((temp) =>
basename(temp)
);
if (templateNames) {
const userPartialNames = userPartials.map((userPartial) =>
basename(userPartial)
);
const hasAtLeastOnePartial = userPartialNames.find((userPartial) => {
return templateNames.includes(userPartial);
});
if (!hasAtLeastOnePartial) {
const errorMsg =
`The format '${allDefaults.to}' only supports the following partials:\n${
templateNames.join("\n")
}\n\nPlease provide one or more of these partials.`;
throw new Error(errorMsg);
}
} else {
throw new Error(
`The format ${allDefaults.to} does not support providing any template partials.`,
);
}
}
// Place any user partials at the end of the list of partials
const partials: string[] = templateContext.partials || [];
partials.push(...userPartials);
// Stage the template and partials
const stagedTemplate = await stageTemplate(
options,
extras,
{
template,
partials,
},
);
// Clean out partials from metadata, they are not needed downstream
delete options.format.metadata[kTemplatePartials];
allDefaults[kTemplate] = stagedTemplate;
} else {
// ipynb is allowed to have templates without warning
if (userPartials.length > 0 && !isIpynbOutput(options.format.pandoc)) {
// The user passed partials to a format that doesn't support
// staging and partials.
throw new Error(
`The format ${allDefaults.to} does not support providing any template partials.`,
);
} else if (userTemplate) {
// Use the template provided by the user
allDefaults[kTemplate] = userTemplate;
}
}
// more cleanup
options.format.metadata = cleanupPandocMetadata({
...options.format.metadata,
});
printMetadata = cleanupPandocMetadata(printMetadata);
if (extras[kIncludeInHeader]) {
if (
allDefaults[kIncludeInHeader] !== undefined &&
!ld.isArray(allDefaults[kIncludeInHeader])
) {
// FIXME we need to fix the type up in FormatExtras..
allDefaults[kIncludeInHeader] = [
allDefaults[kIncludeInHeader],
] as unknown as string[];
}
allDefaults = {
...allDefaults,
[kIncludeInHeader]: [
...extras[kIncludeInHeader] || [],
...allDefaults[kIncludeInHeader] || [],
],
};
}
if (
extras[kIncludeBeforeBody]
) {
if (
allDefaults[kIncludeBeforeBody] !== undefined &&
!ld.isArray(allDefaults[kIncludeBeforeBody])
) {
// FIXME we need to fix the type up in FormatExtras..
allDefaults[kIncludeBeforeBody] = [
allDefaults[kIncludeBeforeBody],
] as unknown as string[];
}
allDefaults = {
...allDefaults,
[kIncludeBeforeBody]: [
...extras[kIncludeBeforeBody] || [],
...allDefaults[kIncludeBeforeBody] || [],
],
};
}
if (extras[kIncludeAfterBody]) {
if (
allDefaults[kIncludeAfterBody] !== undefined &&
!ld.isArray(allDefaults[kIncludeAfterBody])
) {
// FIXME we need to fix the type up in FormatExtras..
allDefaults[kIncludeAfterBody] = [
allDefaults[kIncludeAfterBody],
] as unknown as string[];
}
allDefaults = {
...allDefaults,
[kIncludeAfterBody]: [
...allDefaults[kIncludeAfterBody] || [],
...extras[kIncludeAfterBody] || [],
],
};
}
// Resolve the body envelope here
// body envelope to includes (project body envelope always wins)
if (extras.html?.[kBodyEnvelope] && projectExtras.html?.[kBodyEnvelope]) {
extras.html[kBodyEnvelope] = projectExtras.html[kBodyEnvelope];
}
resolveBodyEnvelope(allDefaults, extras, options.services.temp);
// add any filters
allDefaults.filters = [
...extras.filters?.pre || [],
...allDefaults.filters || [],
...extras.filters?.post || [],
];
// make the filter paths windows safe
allDefaults.filters = allDefaults.filters.map((filter) => {
if (typeof filter === "string") {
return pandocMetadataPath(filter);
} else {
return {
type: filter.type,
path: pandocMetadataPath(filter.path),
};
}
});
// Capture any format filter params
const filterParams = extras[kFilterParams];
if (filterParams) {
Object.keys(filterParams).forEach((key) => {
formatFilterParams[key] = filterParams[key];
});
}
}
// add a shortcode escaping post-processor if we need one
if (
isMarkdownOutput(options.format) &&
requiresShortcodeUnescapePostprocessor(options.markdown)
) {
postprocessors.push(shortcodeUnescapePostprocessor);
}
// resolve some title variables
const title = allDefaults?.[kVariables]?.[kTitle] ||
options.format.metadata[kTitle];
const pageTitle = allDefaults?.[kVariables]?.[kPageTitle] ||
options.format.metadata[kPageTitle];
const titlePrefix = allDefaults?.[kTitlePrefix];
// provide default page title if necessary
if (!title && !pageTitle && isHtmlFileOutput(options.format.pandoc)) {
const [_dir, stem] = dirAndStem(options.source);
args.push(
"--metadata",
`pagetitle:${pandocAutoIdentifier(stem, false)}`,
);
}
// don't ever duplicate pagetite/title and title-prefix
if (
(pageTitle !== undefined && pageTitle === titlePrefix) ||
(pageTitle === undefined && title === titlePrefix)
) {
delete allDefaults[kTitlePrefix];
}
// if we are doing keepYaml then remove it from pandoc 'to'
if (options.keepYaml && allDefaults.to) {
allDefaults.to = allDefaults.to.replaceAll(`+${kYamlMetadataBlock}`, "");
}
// Attempt to cache the code page, if this windows.
// We cache the code page to prevent looking it up
// in the registry repeatedly (which triggers MS Defender)
if (isWindows) {
await cacheCodePage();
}
// filter results json file
const filterResultsFile = options.services.temp.createFile();
const writerKeys: ("to" | "writer")[] = ["to", "writer"];
for (const key of writerKeys) {
if (allDefaults[key]?.match(/[.]lua$/)) {
formatFilterParams["custom-writer"] = allDefaults[key];
allDefaults[key] = resourcePath("filters/customwriter/customwriter.lua");
}
}
// set up the custom .qmd reader
if (allDefaults.from) {
formatFilterParams["user-defined-from"] = allDefaults.from;
}
allDefaults.from = resourcePath("filters/qmd-reader.lua");