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

markdownListIndentation.ts

212 lines7.1 KB

1import { keepLeadingWhitespace, keepsLeadingWhitespace } from "./markdownLeadingWhitespace.ts";
2import { keepOrderedListNumbers, keepsOrderedListNumbers } from "./markdownOrderedListNumbers.ts";
3​
4interface MarkdownPosition {
5 readonly start?: {
6 readonly line?: number;
7 readonly offset?: number;
8 };
9}
10​
11interface MarkdownAstNode {
12 readonly type: string;
13 readonly identifier?: unknown;
14 readonly value?: unknown;
15 readonly position?: MarkdownPosition;
16 children?: MarkdownAstNode[];
18​
19interface MarkdownFile {
20 readonly value?: unknown;
22​
23interface MarkdownParser {
24 parse(markdown: string): unknown;
26​
27interface RecoveredMarkdown {
28 readonly blocks: MarkdownAstNode[];
29 readonly source: string;
31​
32const INLINE_PARSE_PREFIX = "t3-markdown-inline-prefix ";
33​
34function isSameLineOverIndentedCode(
35 node: MarkdownAstNode,
36 parent: MarkdownAstNode | undefined,
37 markdown: string,
38): boolean {
39 if (
40 node.type !== "code" ||
41 parent?.type !== "listItem" ||
42 typeof node.value !== "string" ||
43 !/^[\t ]/.test(node.value)
44 ) {
45 return false;
46 }
47​
48 const nodeStart = node.position?.start;
49 const parentStart = parent.position?.start;
50 if (
51 nodeStart?.line === undefined ||
52 nodeStart.offset === undefined ||
53 parentStart?.line === undefined ||
54 parentStart.offset === undefined ||
55 nodeStart.line !== parentStart.line
56 ) {
57 return false;
58 }
59​
60 const sourceCharacter = markdown[nodeStart.offset];
61 return sourceCharacter !== "`" && sourceCharacter !== "~";
63​
64function parseRecoveredMarkdown(value: string, parser: MarkdownParser, refs: string) {
65 // Prefix block-looking input to parse inline extensions; retain later block children after blank lines.
66 const source = `${refs}${INLINE_PARSE_PREFIX}${value}`;
67 const document = parser.parse(source) as MarkdownAstNode;
68 const blocks = document.children?.filter((n) => (n.position?.start?.offset ?? 0) >= refs.length);
69 const block = blocks?.[0];
70 const children = block?.children;
71 const first = children?.[0];
72 if (
73 !blocks ||
74 (block?.type !== "paragraph" && block?.type !== "heading") ||
75 !children ||
76 first?.type !== "text" ||
77 typeof first.value !== "string" ||
78 !first.value.startsWith(INLINE_PARSE_PREFIX)
79 ) {
80 return { blocks: [{ type: "text", value }], source };
81 }
82​
83 const firstValue = first.value.slice(INLINE_PARSE_PREFIX.length);
84 return {
85 blocks: [
86 {
87 ...block,
88 children: [...(firstValue ? [{ ...first, value: firstValue }] : []), ...children.slice(1)],
89 },
90 ...blocks.slice(1),
91 ],
92 source,
93 };
95​
96/**
97 * Indented code in an item starts five columns past the marker, so its tabs reach tab stops
98 * measured from there. Expands the leading tabs up to the first line's content as the source
99 * columns place them, since the recovered text is measured again from column zero.
100 */
101export function expandIndentedCodeTabs(value: string, source: string, start: number): string {
102 if (!value.includes("\t")) return value;
103 const columns = (text: string, from = 0) =>
104 [...text].reduce((col, c) => col + (c === "\t" ? 4 - (col % 4) : 1), from);
105 const marker = /^([-*+]|\d{1,9}[.)])/.exec(source.slice(start))?.[0];
106 if (marker === undefined) return value;
107 const before = source.slice(0, start);
108 const prefix = before.slice(Math.max(before.lastIndexOf("\n"), before.lastIndexOf("\r")) + 1);
109 const base = columns(prefix + marker) + 5;
110 const end = columns(/^[\t ]*/.exec(value)![0], base);
111 // Not the `m` flag: its `^` also matches after U+2028/U+2029, which Markdown treats as text.
112 return value.replace(/(?<=^|[\r\n])[\t ]+/g, (indent) => {
113 let col = base;
114 let at = 0;
115 while (at < indent.length && col < end) col = columns(indent[at++]!, col);
116 return " ".repeat(col - base) + indent.slice(at);
117 });
119​
120function blocksFromIndentedCode(
121 node: MarkdownAstNode,
122 parser: MarkdownParser,
123 refs: string,
124): RecoveredMarkdown {
125 const value = typeof node.value === "string" ? node.value.trim() : "";
126 const recovered = parseRecoveredMarkdown(value, parser, refs);
127 if (keepsOrderedListNumbers(parser)) {
128 for (const block of recovered.blocks) keepOrderedListNumbers(block, recovered.source);
129 }
130 if (keepsLeadingWhitespace(parser)) {
131 // The trimmed first line sets where the item's content starts.
132 const indent = /^[\t ]*/.exec(String(node.value))![0];
133 const columns = [...indent].reduce(
134 (column, character) => (character === "\t" ? (Math.floor(column / 4) + 1) * 4 : column + 1),
135 0,
136 );
137 keepLeadingWhitespace({ type: "root", children: recovered.blocks }, recovered.source, columns);
138 }
139 const first = recovered.blocks[0];
140 return {
141 ...recovered,
142 blocks:
143 first && node.position
144 ? [{ ...first, position: node.position }, ...recovered.blocks.slice(1)]
145 : recovered.blocks,
146 };
148​
149// CommonMark treats four or more spaces after a list marker as code.
150function attachListItemIndentationNormalizer(this: MarkdownParser) {
151 return (tree: MarkdownAstNode, file: MarkdownFile) => {
152 if (typeof file.value !== "string") {
153 return;
154 }
155 // Remark omits the leading BOM from its offsets.
156 const markdown = file.value.replace(/^\uFEFF/, "");
157 const identifiers: string[] = [];
158 const collect = (node: MarkdownAstNode) => {
159 if (node.type === "definition" && typeof node.identifier === "string") {
160 identifiers.push(node.identifier);
161 }
162 node.children?.forEach(collect);
163 };
164 collect(tree);
165 // micromark only parses `[text][label]` as a reference when the label is defined; the href
166 // still comes from the document's own definition when mdast becomes hast. Stubs are limited
167 // to labels the text can name, matched as mdast normalizes identifiers, to keep reparses small.
168 const definitionsFor = (value: string) => {
169 if (identifiers.length === 0) return "";
170 const text = value
171 .replace(/[\t\n\r ]+/g, " ")
172 .toLowerCase()
173 .toUpperCase()
174 .toLowerCase();
175 return identifiers
176 .filter((identifier) => text.includes(identifier))
177 .map((identifier) => `[${identifier}]: <>\n\n`)
178 .join("");
179 };
180​
181 const visit = (node: MarkdownAstNode, source: string) => {
182 if (!node.children) {
183 return;
184 }
185 if (!node.children.some((child) => isSameLineOverIndentedCode(child, node, source))) {
186 for (const child of node.children) visit(child, source);
187 return;
188 }
189 node.children = node.children.flatMap((child) => {
190 if (isSameLineOverIndentedCode(child, node, source)) {
191 const start = node.position!.start!.offset!;
192 const value = expandIndentedCodeTabs(String(child.value), source, start);
193 const recovered = blocksFromIndentedCode(
194 { ...child, value },
195 this,
196 definitionsFor(value),
197 );
198 for (const block of recovered.blocks) {
199 visit(block, recovered.source);
200 }
201 return recovered.blocks;
202 }
203 visit(child, source);
204 return [child];
205 });
206 };
207​
208 visit(tree, markdown);
209 };
211​
212export const remarkNormalizeListItemIndentation = attachListItemIndentationNormalizer;