Open History to see the last commit
1import type { Heading, Link, Paragraph, Root, RootContent, TableCell, Text } from "mdast";
2import type { Processor, Transformer } from "unified";
3import { SCRIPT_PUNCTUATION, scriptPunctuationAfterAscii } from "./markdownLinks.ts";
4
5/**
6 * GFM runs a bare URL on until whitespace, so Chinese, Japanese, and Arabic punctuation joins it,
7 * along with the rest of the sentence and any `**` that should have closed around it. A URL that is
8 * ASCII up to such a mark ends there. Unicode earlier in the URL means the mark may belong to it, so it stays.
9 */
10function scriptPunctuationIndex(link: Link): number {
11 const label = link.children.length === 1 ? link.children[0] : undefined;
12 if (label?.type !== "text" || !/^https?:\/\//i.test(link.url)) return -1;
13 if (link.url !== label.value && link.url !== `http://${label.value}`) return -1;
14 return scriptPunctuationAfterAscii(label.value);
15}
16
17/** GFM's text pass links bare URLs without positions; its tokenizer's links span their URL. */
18export function isBareLink(link: Link, source: string): boolean {
19 const start = link.position?.start.offset;
20 const end = link.position?.end.offset;
21 const label = link.children[0];
22 return (
23 !link.position ||
24 (start !== undefined &&
25 end !== undefined &&
26 label?.type === "text" &&
27 source.slice(start, end) === label.value)
28 );
29}
30
31/** Source offsets of the marks that tokenized bare URLs run past. */
32function scriptPunctuationOffsets(node: RootContent, source: string): number[] {
33 if (node.type === "link") {
34 const index = scriptPunctuationIndex(node);
35 const start = node.position?.start.offset;
36 return index > 0 && start !== undefined && isBareLink(node, source) ? [start + index] : [];
37 }
38 return "children" in node && node.type !== "linkReference"
39 ? (node.children as RootContent[]).flatMap((child) => scriptPunctuationOffsets(child, source))
40 : [];
41}
42
43const hasReference = (node: RootContent): boolean =>
44 node.type === "linkReference" ||
45 node.type === "imageReference" ||
46 node.type === "footnoteReference" ||
47 ("children" in node && (node.children as RootContent[]).some(hasReference));
48
49/** How many of the ascending numbers are below `value`. */
50function countBelow(sorted: readonly number[], value: number): number {
51 let low = 0;
52 let high = sorted.length;
53 while (low < high) {
54 const middle = (low + high) >> 1;
55 if (sorted[middle]! < value) low = middle + 1;
56 else high = middle;
57 }
58 return low;
59}
60
61/**
62 * Parses the block's text again with a tab before each mark. The tab ends the URL as a space would,
63 * so emphasis around the URL closes and later URLs and code get their own nodes. The tabs are then
64 * dropped and positions mapped back to the source. Returns false and leaves the block alone when its
65 * text would parse differently on its own, as a quote's continuation lines do.
66 */
67function reparseAtScriptPunctuation(
68 processor: Processor,
69 block: Paragraph | Heading | TableCell,
70 source: string,
71 offsets: number[],
72): boolean {
73 // A task item's paragraph starts at its checkbox; its first child starts after it.
74 const from = block.children[0]?.position?.start;
75 const to = block.children.at(-1)?.position?.end;
76 if (from?.offset === undefined || to?.offset === undefined || hasReference(block)) return false;
77 const base = from.offset;
78 const text = source.slice(base, to.offset);
79 // A tab is the marker, a quote's `>` on a later line would read as a new quote, a list's
80 // indentation would join a code span, and only a table unescapes `\|` in code.
81 if (
82 text.includes("\t") ||
83 /[\r\n][ ]*>/.test(text) ||
84 (/[\r\n] /.test(text) && text.includes("`")) ||
85 (block.type === "tableCell" && text.includes("\\|"))
86 ) {
87 return false;
88 }
89 const marks = offsets.map((offset) => offset - base);
90 // Each pass finds the next URL in a run with no spaces, like `http://a,http://b,http://c`.
91 for (let attempt = 0; attempt < 16; attempt++) {
92 marks.sort((a, b) => a - b);
93 const tabs = marks.map((mark, index) => mark + index);
94 const unmarked = (offset: number) => offset - countBelow(tabs, offset);
95 const marked = [0, ...marks]
96 .map((start, index) => text.slice(start, marks[index] ?? text.length))
97 .join("\t");
98 const [paragraph, ...rest] = (processor.parse(marked) as Root).children;
99 if (paragraph?.type !== "paragraph" || rest.length > 0) return false;
100 const more = scriptPunctuationOffsets(paragraph, marked);
101 if (more.length > 0) {
102 marks.push(...more.map(unmarked));
103 continue;
104 }
105
106 let tabCount = 0;
107 const moved = new Set<object>();
108 const restore = (node: RootContent): boolean => {
109 for (const point of node.position ? [node.position.start, node.position.end] : []) {
110 const offset = point.offset;
111 if (offset === undefined || moved.has(point)) continue;
112 moved.add(point);
113 const tabsOnLine = countBelow(tabs, offset) - countBelow(tabs, offset - point.column + 1);
114 point.column = (point.line === 1 ? from.column - 1 : 0) + point.column - tabsOnLine;
115 point.line += from.line - 1;
116 point.offset = base + unmarked(offset);
117 }
118 if (node.type === "text") {
119 tabCount += node.value.split("\t").length - 1;
120 node.value = node.value.replaceAll("\t", "");
121 } else if (
122 ("value" in node && node.value.includes("\t")) ||
123 ("url" in node && node.url.includes("\t"))
124 ) {
125 return false;
126 }
127 if (!("children" in node)) return true;
128 const children = node.children as RootContent[];
129 if (!children.every(restore)) return false;
130 node.children = children.filter(
131 (child) => child.type !== "text" || child.value !== "",
132 ) as typeof node.children;
133 return true;
134 };
135 if (!restore(paragraph) || tabCount !== tabs.length) return false;
136 block.children = paragraph.children;
137 return true;
138 }
139 return false;
140}
141
142/** Ends the bare URLs a reparse could not, and those GFM's text pass linked after emphasis. */
143function splitAtScriptPunctuation(node: RootContent, source: string) {
144 if (!("children" in node) || node.type === "link" || node.type === "linkReference") return;
145 const children = node.children as RootContent[];
146 for (let index = 0; index < children.length; index++) {
147 const child = children[index]!;
148 if (child.type !== "link") {
149 splitAtScriptPunctuation(child, source);
150 continue;
151 }
152 const at = isBareLink(child, source) ? scriptPunctuationIndex(child) : -1;
153 const label = child.children[0];
154 if (at < 0 || label?.type !== "text") continue;
155 // GFM drops this punctuation from the end of a URL; remarkKeepAutolinkSuffixes restores `_` and `~`.
156 const length = label.value.slice(0, at).replace(/[!"'*,.:;?_~]+$/, "").length;
157 const tail: Text = { type: "text", value: label.value.slice(length) };
158 const start = child.position?.start;
159 if (child.position && start?.offset !== undefined) {
160 const end = {
161 line: start.line,
162 column: start.column + length,
163 offset: start.offset + length,
164 };
165 tail.position = { start: end, end: child.position.end };
166 child.position = { start, end };
167 label.position = { start, end };
168 }
169 child.url = child.url.slice(0, child.url.length - label.value.length + length);
170 label.value = label.value.slice(0, length);
171 children.splice(index + 1, 0, tail);
172 index++;
173 }
174}
175
176export function remarkEndAutolinksAtScriptPunctuation(this: Processor): Transformer<Root> {
177 return (tree, file) => {
178 const source = String(file);
179 if (!SCRIPT_PUNCTUATION.test(source)) return;
180 const visit = (node: RootContent) => {
181 if (node.type === "paragraph" || node.type === "heading" || node.type === "tableCell") {
182 const offsets = scriptPunctuationOffsets(node, source);
183 if (offsets.length > 0) reparseAtScriptPunctuation(this, node, source, offsets);
184 splitAtScriptPunctuation(node, source);
185 } else if ("children" in node) {
186 (node.children as RootContent[]).forEach(visit);
187 }
188 };
189 tree.children.forEach(visit);
190 };
191}