Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

markdownWindowsPaths.ts

67 lines2.5 KB

1import type { Processor } from "unified";
2import { isWindowsAbsolutePath } from "./path.ts";
3​
4interface DestinationCompileContext {
5 readonly stack: ReadonlyArray<{ readonly type: string; url?: string }>;
6 resume(): string;
7 sliceSerialize(token: unknown): string;
8}
9​
10function keepWindowsPathDestination(this: DestinationCompileContext, token: unknown) {
11 const decoded = this.resume();
12 const authored = this.sliceSerialize(token);
13 const node = this.stack.at(-1);
14 // Character references still need decoding, so those destinations keep the parsed URL.
15 if (node)
16 node.url = isWindowsAbsolutePath(authored) && !authored.includes("&") ? authored : decoded;
18​
19// A drive path that has not reached whitespace yet: `C:`, `C:\Users\me`, `C:/work`.
20const UNFINISHED_DRIVE_PATH = /(?:^|\W)[A-Za-z]:(?:[\\/]\S*)?$/;
21​
22interface EscapeCompileContext {
23 readonly stack: ReadonlyArray<{
24 readonly type: string;
25 children?: Array<{ type: string; value?: string }>;
26 }>;
28​
29function keepWindowsPathEscape(this: EscapeCompileContext) {
30 const text = this.stack.at(-1)?.children?.at(-1);
31 if (text?.type !== "text" || text.value === undefined) return;
32 const before = text.value.slice(0, -1);
33 if (UNFINISHED_DRIVE_PATH.test(before)) {
34 text.value = `${before}\\${text.value.slice(-1)}`;
35 }
37​
38function keepWindowsProsePathEscape(this: EscapeCompileContext) {
39 // Destinations, titles, and labels are buffered in a fragment.
40 if (this.stack.at(-1)?.type !== "fragment") keepWindowsPathEscape.call(this);
42​
43/**
44 * Keeps escapes inside drive paths in prose only, for parsers that already escape Windows
45 * destinations themselves. Prose paths end at whitespace: past that, nothing tells a path
46 * from a sentence, and `C:\x and \*this\*` must still read `*this*`.
47 */
48export function remarkKeepWindowsProsePaths(this: Processor) {
49 (this.data().fromMarkdownExtensions ??= []).push({
50 exit: { characterEscape: keepWindowsProsePathEscape },
51 });
53​
54/**
55 * CommonMark reads the `\.` in `C:\me\.t3\shot.png` as an escape. Every backslash in a
56 * Windows path is a separator, so link, image, and definition destinations that are
57 * Windows paths keep the text as written, and so do escapes inside drive paths.
58 */
59export function remarkKeepWindowsPaths(this: Processor) {
60 (this.data().fromMarkdownExtensions ??= []).push({
61 exit: {
62 resourceDestinationString: keepWindowsPathDestination,
63 definitionDestinationString: keepWindowsPathDestination,
64 characterEscape: keepWindowsPathEscape,
65 },
66 });