-
Notifications
You must be signed in to change notification settings - Fork 433
Expand file tree
/
Copy pathformat-typst.ts
More file actions
243 lines (224 loc) · 7.97 KB
/
format-typst.ts
File metadata and controls
243 lines (224 loc) · 7.97 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
/*
* format-typst.ts
*
* Copyright (C) 2020-2022 Posit Software, PBC
*/
import { join } from "../../deno_ral/path.ts";
import { RenderServices } from "../../command/render/types.ts";
import { ProjectContext } from "../../project/types.ts";
import { BookExtension } from "../../project/types/book/book-shared.ts";
import {
kBrand,
kCiteproc,
kColumns,
kDefaultImageExtension,
kFigFormat,
kFigHeight,
kFigWidth,
kLight,
kLogo,
kNumberSections,
kSectionNumbering,
kShiftHeadingLevelBy,
kVariant,
kWrap,
} from "../../config/constants.ts";
import {
Format,
FormatExtras,
FormatPandoc,
LightDarkBrand,
Metadata,
PandocFlags,
} from "../../config/types.ts";
import { formatResourcePath } from "../../core/resources.ts";
import { createFormat } from "../formats-shared.ts";
import { hasLevelOneHeadings as hasL1Headings } from "../../core/lib/markdown-analysis/level-one-headings.ts";
import {
BrandNamedLogo,
LogoLightDarkSpecifier,
} from "../../resources/types/schema-types.ts";
import {
brandWithAbsoluteLogoPaths,
fillLogoPaths,
resolveLogo,
} from "../../core/brand/brand.ts";
import { LogoLightDarkSpecifierPathOptional } from "../../resources/types/zod/schema-types.ts";
const typstBookExtension: BookExtension = {
selfContainedOutput: true,
// multiFile defaults to false (single-file book)
};
export function typstFormat(): Format {
return createFormat("Typst", "pdf", {
execute: {
[kFigWidth]: 5.5,
[kFigHeight]: 3.5,
[kFigFormat]: "svg",
},
pandoc: {
standalone: true,
[kDefaultImageExtension]: "svg",
[kWrap]: "none",
[kCiteproc]: false,
},
extensions: {
book: typstBookExtension,
},
resolveFormat: typstResolveFormat,
formatExtras: async (
_input: string,
markdown: string,
flags: PandocFlags,
format: Format,
_libDir: string,
_services: RenderServices,
_offset?: string,
_project?: ProjectContext,
): Promise<FormatExtras> => {
const pandoc: FormatPandoc = {};
const metadata: Metadata = {};
// provide default section numbering if required
if (
(flags?.[kNumberSections] === true ||
format.pandoc[kNumberSections] === true)
) {
// number-sections imples section-numbering
if (!format.metadata?.[kSectionNumbering]) {
metadata[kSectionNumbering] = "1.1.a";
}
}
// unless otherwise specified, pdfs with only level 2 or greater headings get their
// heading level shifted by -1.
const hasLevelOneHeadings = await hasL1Headings(markdown);
if (
!hasLevelOneHeadings &&
flags?.[kShiftHeadingLevelBy] === undefined &&
format.pandoc?.[kShiftHeadingLevelBy] === undefined
) {
pandoc[kShiftHeadingLevelBy] = -1;
}
const brand = format.render.brand;
// For Typst, convert brand logo paths to project-absolute (with /)
// before merging with document logo metadata. Typst resolves / paths
// via --root which points to the project directory.
const typstBrand = brandWithAbsoluteLogoPaths(brand);
const logoSpec = format
.metadata[kLogo] as LogoLightDarkSpecifierPathOptional;
const sizeOrder: BrandNamedLogo[] = [
"small",
"medium",
"large",
];
// temporary: if document logo has object or light/dark objects
// without path, do our own findLogo to add the path
// typst is the exception not needing path but we'll probably deprecate this
const logo = fillLogoPaths(typstBrand, logoSpec, sizeOrder);
format.metadata[kLogo] = resolveLogo(typstBrand, logo, sizeOrder);
// force columns to wrap and move any 'columns' setting to metadata
const columns = format.pandoc[kColumns];
if (columns) {
pandoc[kColumns] = undefined;
metadata[kColumns] = columns;
}
// Provide a template and partials
// For Typst books, a book extension overrides these partials
const templateDir = formatResourcePath("typst", join("pandoc", "quarto"));
const templateContext = {
template: join(templateDir, "template.typ"),
partials: [
"numbering.typ",
"definitions.typ",
"typst-template.typ",
"page.typ",
"typst-show.typ",
"notes.typ",
"biblio.typ",
].map((partial) => join(templateDir, partial)),
};
// Postprocessor to fix Skylighting code block styling (issue #14126).
// Pandoc's generated Skylighting function uses block(fill: bgcolor, blocks)
// which lacks width, inset, and radius. We surgically fix this in the .typ
// output. If brand monospace-block has a background-color, we also override
// the bgcolor value.
const brandData = (format.render[kBrand] as LightDarkBrand | undefined)
?.[kLight];
const monospaceBlock = brandData?.processedData?.typography?.[
"monospace-block"
];
let brandBgColor = (monospaceBlock && typeof monospaceBlock !== "string")
? monospaceBlock["background-color"] as string | undefined
: undefined;
// Resolve palette color names (e.g. "code-bg" → "#1e1e2e")
if (brandBgColor && brandData?.data?.color?.palette) {
const palette = brandData.data.color.palette as Record<string, string>;
let resolved = brandBgColor;
while (palette[resolved]) {
resolved = palette[resolved];
}
brandBgColor = resolved;
}
return {
pandoc,
metadata,
templateContext,
postprocessors: [
skylightingPostProcessor(brandBgColor),
],
};
},
});
}
// Fix Skylighting code block styling in .typ output (issue #14126).
// The Pandoc-generated Skylighting function uses block(fill: bgcolor, blocks)
// which lacks width, inset, and radius. This postprocessor matches the entire
// Skylighting function by its distinctive signature and patches only within it.
// When brand provides a monospace-block background-color, also overrides the
// bgcolor value. This is a temporary workaround until the fix is upstreamed
// to the Skylighting library.
function skylightingPostProcessor(brandBgColor?: string) {
// Match the entire #let Skylighting(...) = { ... } function.
// The signature is stable and generated by Skylighting's Typst backend.
const skylightingFnRe =
/(#let Skylighting\(fill: none, number: false, start: 1, sourcelines\) = \{[\s\S]*?\n\})/;
return async (output: string) => {
const content = Deno.readTextFileSync(output);
const match = skylightingFnRe.exec(content);
if (!match) {
// No Skylighting function found — document may not have code blocks,
// or upstream changed the function signature. Nothing to patch.
return;
}
let fn = match[1];
// Fix block() call: add width, inset, radius
fn = fn.replace(
"block(fill: bgcolor, blocks)",
"block(fill: bgcolor, width: 100%, inset: 8pt, radius: 2pt, blocks)",
);
// Override bgcolor with brand monospace-block background-color
if (brandBgColor) {
fn = fn.replace(
/let bgcolor = rgb\("[^"]*"\)/,
`let bgcolor = rgb("${brandBgColor}")`,
);
}
if (fn !== match[1]) {
Deno.writeTextFileSync(output, content.replace(match[1], fn));
}
};
}
function typstResolveFormat(format: Format) {
// Pandoc citeproc with typst output requires adjustment
// https://github.com/jgm/pandoc/commit/e89a3edf24a025d5bb0fe8c4c7a8e6e0208fa846
if (
format.pandoc?.[kCiteproc] === true &&
!format.pandoc.to?.includes("-citations") &&
!format.render[kVariant]?.includes("-citations")
) {
// citeproc: false is the default, so user setting it to true means they want to use
// Pandoc's citeproc which requires `citations` extensions to be disabled (e.g typst-citations)
// This adds the variants for them if not set already
format.render[kVariant] = [format.render?.[kVariant], "-citations"].join(
"",
);
}
}