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

wordsHast.ts

1,305 lines49.9 KB

1import type { Element, ElementContent, Root, Text } from "hast";
2import {
3 init as initWords,
4 renderToHtml as wordsRenderToHtml,
5 type RenderOptions as WordsRenderOptions,
6} from "@pierre/words/core";
7import wordsWasm from "@pierre/words/wasm";
8import { decodeHTML, decodeHTMLAttribute } from "entities";
9import { find, html as htmlSchema, svg as svgSchema } from "property-information";
10import { resolveCodexArtifactTemplate } from "@t3tools/shared/codexArtifactTemplates";
11import { resolveCodexFileCitationLink } from "@t3tools/shared/codexFileCitations";
12import type { ReferenceAutolink } from "@t3tools/client-runtime/source-control-clients";
13import { expandGithubEmojiAliases } from "@t3tools/client-runtime/pull-request-markdown";
14import { resolveChangeRequestMediaUrl } from "@t3tools/client-runtime/pull-request-references";
15import { GITHUB_ALERT_MARKER } from "@t3tools/shared/markdownGithubAlerts";
16import { absoluteFilePathMatches } from "@t3tools/shared/markdownLinks";
17import {
18 rehypeNormalizeLocalEditorLinks,
19 rehypePreserveImageSourceMeta,
20 sanitizeChatHast,
21} from "@t3tools/shared/markdownHast";
22​
23import { rehypeChipPunctuation } from "../components/chat/markdownChipPunctuation";
24import { rehypeHeadingIds } from "../components/chat/markdownFragments";
25import { rehypeTextDirection } from "../components/chat/markdownTextDirection";
26​
27/** What a kind of message adds to chat Markdown. Pass a stable object: renderers cache by it. */
28export interface MarkdownExtensions {
29 /**
30 * A sent user message: a single `~` stays text, and a written list number that breaks the
31 * sequence stays, so the bubble shows what the composer showed.
32 */
33 readonly userMessage?: boolean;
34 /** Spaces typed at the start of a line show, as the composer showed them (keepLeadingWhitespace). */
35 readonly leadingWhitespace?: boolean;
36 /** A saved file's Markdown, which must not load URLs or act: links, images and HTML are text. */
37 readonly inert?: boolean;
38 /** The whole message flattened to one line of text and math, or `fallback` when empty. */
39 readonly preview?: { readonly fallback: string; readonly maxLength: number };
40 /** A change request's body: root-relative media resolve on its host, and references link. */
41 readonly changeRequest?: {
42 readonly repositoryUrl: string;
43 readonly autolinks: ((text: string) => ReadonlyArray<ReferenceAutolink>) | null;
44 };
45 /** Expand GitHub `:alias:` emoji shortcodes in prose outside code. */
46 readonly githubEmoji?: boolean;
48​
49export interface WordsHastOptions {
50 /** `$…$`, `$$…$$` and `math` code blocks render as SVG. */
51 readonly math: boolean;
52 /** Soft line breaks render as `<br>`, as remark-breaks does. */
53 readonly breaks: boolean;
54 /** Raw HTML shows as the text it was written as. */
55 readonly escapeHtml: boolean;
56 /** `★ Insight ───` blocks render as insight callouts. */
57 readonly insights: boolean;
58 readonly extensions: MarkdownExtensions;
60​
61const CODEX_DIRECTIVES = ["codex-file-citation", "codex-followup", "artifact-template"];
62​
63const VOID = new Set("area base br col embed hr img input link meta source track wbr".split(" "));
64​
65const TAG =
66 /<(\/?)([a-zA-Z][\w:-]*)((?:\s+[^\s"'>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)*)\s*(\/?)>|<!--(?:-?>|[\s\S]*?-->)|<![^>]*>|<\?[\s\S]*?\?>/g;
67const ATTRIBUTE = /([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
68​
69// Start tags an HTML parser closes an open `<p>` for, and the elements that scope that search.
70const CLOSES_PARAGRAPH = new Set(
71 "address article aside blockquote center details dialog dir div dl fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 header hgroup hr li listing main menu nav ol p plaintext pre search section summary table ul xmp dd dt".split(
72 " ",
73 ),
74);
75const PARAGRAPH_SCOPE = new Set([
76 "applet",
77 "caption",
78 "table",
79 "td",
80 "th",
81 "marquee",
82 "object",
83 "template",
84 "button",
85]);
86​
87type RenderOptions = Omit<WordsRenderOptions, "frontmatter">;
88​
89const decoder = new TextDecoder();
90const encoder = new TextEncoder();
91​
92// Browsers can disable WebAssembly (JIT off by policy, CSP); renderToHtml then falls back below.
93try {
94 initWords(new WebAssembly.Module(wordsWasm));
95} catch {}
96​
97function renderToHtml(markdown: string, options: RenderOptions): Uint8Array {
98 try {
99 return wordsRenderToHtml(markdown, options);
100 } catch {
101 return encoder.encode(
102 `<p>${markdown.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll("\n", "<br>")}</p>`,
103 );
104 }
106​
107const decode = (value: string) => (value.includes("&") ? decodeHTML(value) : value);
108​
109function properties(source: string | undefined, inSvg: boolean): Element["properties"] {
110 const result: Element["properties"] = {};
111 if (!source) return result;
112 for (const match of source.matchAll(ATTRIBUTE)) {
113 const name = match[1]!;
114 const info = find(inSvg ? svgSchema : htmlSchema, inSvg ? name : name.toLowerCase());
115 const raw = match[2] ?? match[3] ?? match[4];
116 if (raw === undefined) {
117 result[info.property] = info.boolean || info.overloadedBoolean ? true : "";
118 continue;
119 }
120 // Attribute values decode as attributes: `&copy=` in a query stays as written.
121 const value = raw.includes("&") ? decodeHTMLAttribute(raw) : raw;
122 result[info.property] =
123 info.spaceSeparated || info.commaSeparated
124 ? value.split(info.commaSeparated ? "," : /\s+/).filter(Boolean)
125 : info.boolean
126 ? true
127 : value;
128 }
129 return result;
131​
132interface Tokenized {
133 readonly root: Root;
134 /** Elements with a `data-sourcepos`, which raw HTML can write too. */
135 readonly positioned: Element[];
137​
138/**
139 * Hast for Words' HTML. Its own markup is well formed; raw HTML closes where its end tags say,
140 * and is sanitized afterwards, so a misnested tag can only change structure, never safety.
141 */
142function tokenize(html: string, offsetOf: (byte: number) => number): Tokenized {
143 const root: Root = { type: "root", children: [] };
144 const positioned: Element[] = [];
145 const stack: Array<Root | Element> = [root];
146 let svgDepth = 0;
147 let last = 0;
148 // rehypePreserveBareAnchorPlaceholders: an `<a>` with no attributes that never closes is text.
149 const anchors: Array<{ element: Element; parent: Root | Element; tag: string } | null> = [];
150 const text = (end: number) => {
151 if (end <= last) return;
152 const parent = stack.at(-1)!;
153 const value = decode(html.slice(last, end));
154 const previous = parent.children.at(-1);
155 if (previous?.type === "text") previous.value += value;
156 else parent.children.push({ type: "text", value } as Text);
157 };
158 for (const match of html.matchAll(TAG)) {
159 text(match.index);
160 last = match.index + match[0].length;
161 const tagName = match[2]?.toLowerCase();
162 if (!tagName) continue;
163 if (match[1]) {
164 if (tagName === "a") anchors.pop();
165 if (tagName === "p" && openParagraph(stack) < 0) {
166 // A stray `</p>` is an empty paragraph to an HTML parser.
167 (stack.at(-1)!.children as ElementContent[]).push({
168 type: "element",
169 tagName: "p",
170 properties: {},
171 children: [],
172 });
173 continue;
174 }
175 const at = stack.findLastIndex((node) => node.type === "element" && node.tagName === tagName);
176 if (at > 0) {
177 for (let index = at; index < stack.length; index++) {
178 if ((stack[index] as Element).tagName === "svg") svgDepth--;
179 }
180 stack.length = at;
181 }
182 continue;
183 }
184 const inSvg = svgDepth > 0 || tagName === "svg";
185 if (!inSvg && CLOSES_PARAGRAPH.has(tagName)) {
186 const paragraph = openParagraph(stack);
187 if (paragraph > 0) stack.length = paragraph;
188 }
189 const element: Element = {
190 type: "element",
191 tagName: inSvg ? match[2]! : tagName,
192 properties: properties(match[3], inSvg),
193 children: [],
194 };
195 const sourcepos = element.properties.dataSourcepos;
196 if (typeof sourcepos === "string") {
197 delete element.properties.dataSourcepos;
198 const [start, end] = sourcepos.split("-").map((byte) => offsetOf(Number(byte)));
199 element.position = {
200 start: { line: 1, column: start! + 1, offset: start! },
201 end: { line: 1, column: end! + 1, offset: end! },
202 };
203 positioned.push(element);
204 }
205 const parent = stack.at(-1)!;
206 (parent.children as ElementContent[]).push(element);
207 if (tagName === "a") {
208 anchors.push(match[3]?.trim() ? null : { element, parent, tag: match[0] });
209 }
210 // The HTML parser ignores `/>` on elements that are not void, such as `<a/>`.
211 if (!VOID.has(tagName) && (!match[4] || !inSvg)) {
212 stack.push(element);
213 if (tagName === "svg") svgDepth++;
214 }
215 }
216 text(html.length);
217 for (const anchor of anchors) {
218 if (!anchor) continue;
219 const siblings = anchor.parent.children as ElementContent[];
220 const at = siblings.indexOf(anchor.element);
221 if (at >= 0)
222 siblings.splice(at, 1, { type: "text", value: anchor.tag }, ...anchor.element.children);
223 }
224 normalizeRawTables(root);
225 // Words ends each block with a newline; hast from remark has none after the last.
226 const end = root.children.at(-1);
227 if (end?.type === "text") {
228 end.value = end.value.replace(/\n$/, "");
229 if (end.value.trim() === "") root.children.pop();
230 }
231 return { root, positioned };
233​
234const positionKey = (node: Element) =>
235 `${node.tagName.toLowerCase()}:${node.position!.start.offset}-${node.position!.end.offset}`;
236​
237/**
238 * Words' HTML for `markdown` as hast. A position marks what Words generated, so raw HTML that
239 * writes its own `data-sourcepos` keeps none: Words' elements are those it also writes with raw
240 * HTML escaped, and a range claimed more often than that is trusted for none of its claimants.
241 */
242function parse(markdown: string, options: RenderOptions): Root {
243 const offsetOf = utf16Offsets(markdown);
244 const render = (escapeHtml?: true) =>
245 tokenize(
246 decoder.decode(
247 renderToHtml(markdown, {
248 ...options,
249 ...(escapeHtml ? { escapeHtml } : {}),
250 sourcePositions: true,
251 }),
252 ),
253 offsetOf,
254 );
255 const { root, positioned } = render();
256 if (options.escapeHtml || options.skipHtml || !/data-sourcepos/i.test(markdown)) return root;
257 const generated = new Map<string, number>();
258 for (const node of render(true).positioned) {
259 const key = positionKey(node);
260 generated.set(key, (generated.get(key) ?? 0) + 1);
261 }
262 const claimed = new Map<string, number>();
263 for (const node of positioned) {
264 const key = positionKey(node);
265 claimed.set(key, (claimed.get(key) ?? 0) + 1);
266 }
267 for (const node of positioned) {
268 const key = positionKey(node);
269 if (claimed.get(key)! > (generated.get(key) ?? 0)) delete node.position;
270 }
271 return root;
273​
274/** The stack index of the `<p>` an HTML parser would close, or -1 when none is in scope. */
275function openParagraph(stack: ReadonlyArray<Root | Element>): number {
276 for (let index = stack.length - 1; index > 0; index--) {
277 const tagName = (stack[index] as Element).tagName;
278 if (tagName === "p") return index;
279 if (PARAGRAPH_SCOPE.has(tagName)) return -1;
280 }
281 return -1;
283​
284/** parse5 puts a raw HTML table's rows in a `<tbody>`; Words' own tables start with `<thead>`. */
285function normalizeRawTables(node: Root | Element) {
286 for (const child of node.children) {
287 if (child.type === "element") normalizeRawTables(child);
288 }
289 if (node.type !== "element" || node.tagName !== "table") return;
290 const first = node.children.findIndex((child) => isElement(child, "tr"));
291 if (first < 0) return;
292 node.children = [
293 ...node.children.slice(0, first),
294 { type: "element", tagName: "tbody", properties: {}, children: node.children.slice(first) },
295 ];
297​
298// Words leaves these raw in Markdown destinations, where micromark percent-encodes them.
299const UNSAFE_URL_CHARACTERS = /[\\[\]`{}|^"<> ]/g;
300const normalizeUri = (value: string) =>
301 value.replace(UNSAFE_URL_CHARACTERS, (character) => encodeURIComponent(character));
302​
303const windowsPath = (url: string) => {
304 const path = url.replace(/%5C/gi, "\\");
305 return /^[A-Za-z]:[\\/]/.test(path) ? path : undefined;
306};
307​
308const isElement = (node: unknown, tagName?: string): node is Element =>
309 (node as Element | undefined)?.type === "element" &&
310 (tagName === undefined || (node as Element).tagName === tagName);
311​
312const isElementNode = (node: ElementContent): node is Element => node.type === "element";
313​
314const isMarkdownImage = (node: unknown): boolean =>
315 (isElement(node, "img") && node.position !== undefined) ||
316 (isElement(node, "a") &&
317 node.position !== undefined &&
318 node.children.length === 1 &&
319 isMarkdownImage(node.children[0]));
320​
321const BREAK: ElementContent = { type: "element", tagName: "br", properties: {}, children: [] };
322​
323// Words' math: these elements and presentation attributes, and no links or handlers.
324const MATH_ELEMENTS = new Set(["svg", "g", "text", "tspan", "rect", "path"]);
325const MATH_PROPERTIES = new Set([
326 "xmlns",
327 "width",
328 "height",
329 "viewBox",
330 "fill",
331 "fontFamily",
332 "fontSize",
333 "fontStyle",
334 "fontWeight",
335 "role",
336 "ariaLabel",
337 "x",
338 "y",
339 "dx",
340 "dy",
341 "d",
342 "transform",
343 "stroke",
344 "strokeWidth",
345 "textAnchor",
346]);
347const MATH_STYLE = /^(?:display|vertical-align|overflow|margin|white-space)$/;
348​
349function sanitizeMath(node: Element): Element | null {
350 if (!MATH_ELEMENTS.has(node.tagName)) return null;
351 const properties: Element["properties"] = {};
352 for (const [key, value] of Object.entries(node.properties)) {
353 if (MATH_PROPERTIES.has(key)) properties[key] = value;
354 }
355 if (typeof node.properties.style === "string") {
356 const style = node.properties.style
357 .split(";")
358 .filter((rule) => MATH_STYLE.test(rule.split(":")[0]!.trim()))
359 .join(";");
360 if (style) properties.style = style;
361 }
362 const children: ElementContent[] = [];
363 for (const child of node.children) {
364 if (child.type === "text") children.push(child);
365 else if (child.type === "element") {
366 const clean = sanitizeMath(child);
367 if (clean) children.push(clean);
368 }
369 }
370 return { ...node, properties, children };
372​
373interface Walk {
374 /** Words' hast for more Markdown, rendered with the same options; `indent` as leadingWhitespace's. */
375 readonly render: (markdown: string, indent: number) => Root;
376 readonly source: string;
377 readonly options: WordsHastOptions;
378 readonly math: Map<string, Element>;
379 /** A per-render id prefix for math placeholders, which authored ids cannot share. */
380 readonly mathKey: string;
381 /** What insightSource opened each insight block with, when it opened any. */
382 readonly insightMarker: RegExp | null;
384​
385/** UTF-16 offsets for the UTF-8 byte offsets in Words' `data-sourcepos`. */
386function utf16Offsets(source: string): (byte: number) => number {
387 if (!/[^\x00-\x7f]/.test(source)) return (byte) => byte;
388 const offsets: number[] = [];
389 for (let index = 0; index < source.length; index++) {
390 const code = source.codePointAt(index)!;
391 const bytes = code < 0x80 ? 1 : code < 0x800 ? 2 : code < 0x10000 ? 3 : 4;
392 for (let byte = 0; byte < bytes; byte++) offsets.push(index);
393 if (code >= 0x10000) index++;
394 }
395 offsets.push(source.length);
396 return (byte) => offsets[byte] ?? source.length;
398​
399const sourceOf = (node: Element, source: string) =>
400 node.position ? source.slice(node.position.start.offset, node.position.end.offset) : "";
401​
402const textOf = (node: ElementContent): string =>
403 node.type === "text"
404 ? node.value
405 : node.type === "element"
406 ? node.children.map(textOf).join("")
407 : "";
408​
409/** A directive's attributes, as strings; anything else Words would never write reads as none. */
410function directiveAttributes(node: Element): Record<string, string> {
411 let parsed: unknown;
412 try {
413 parsed = JSON.parse(String(node.properties.dataAttributes ?? "{}"));
414 } catch {
415 return {};
416 }
417 if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {};
418 return Object.fromEntries(
419 Object.entries(parsed).filter(
420 (entry): entry is [string, string] => typeof entry[1] === "string",
421 ),
422 );
424​
425/** remarkCodexDirectives: what a directive Words parsed becomes, as the remark plugin builds it. */
426function codexDirective(node: Element, walk: Walk, inLink: boolean): ElementContent {
427 const name = node.properties.dataDirective;
428 const attributes = directiveAttributes(node);
429 const asText = (): ElementContent => {
430 const value: ElementContent = { type: "text", value: sourceOf(node, walk.source) };
431 return node.tagName === "div"
432 ? { type: "element", tagName: "p", properties: {}, children: [value] }
433 : value;
434 };
435 if (name === "codex-file-citation") {
436 const citation = resolveCodexFileCitationLink(attributes);
437 if (!citation || inLink) return asText();
438 return {
439 type: "element",
440 tagName: "a",
441 properties: { href: citation.href },
442 children: [{ type: "text", value: citation.label }],
443 ...(node.position ? { position: node.position } : {}),
444 };
445 }
446 if (name === "codex-followup") {
447 if (!attributes.prompt?.trim() || !node.children.map(textOf).join("").trim()) return asText();
448 return { type: "element", tagName: "span", properties: {}, children: node.children };
449 }
450 const template = resolveCodexArtifactTemplate(attributes);
451 if (!template) return asText();
452 return {
453 type: "element",
454 tagName: "div",
455 properties: {
456 dataCodexArtifactTemplate: "true",
457 dataArtifactKind: template.artifactKind,
458 dataDisplayName: template.displayName,
459 ...(template.galleryKind === undefined ? {} : { dataGalleryKind: template.galleryKind }),
460 dataSkillDirectory: template.skillDirectory,
461 dataSkillName: template.skillName,
462 },
463 children: [],
464 };
466​
467const INLINE_PREFIX = "t3-markdown-inline-prefix:";
468​
469function stripPositions(node: ElementContent) {
470 delete node.position;
471 if (node.type === "element") node.children.forEach(stripPositions);
473​
474/**
475 * remarkNormalizeListItemIndentation: four spaces after a list marker make indented code, but
476 * agents mean wide indentation, so code starting on the marker's line is Markdown again. True
477 * when it recovered the item, whose children it then has transformed.
478 */
479function recoverIndentedCode(
480 item: Element,
481 list: Root | Element,
482 walk: Walk,
483 inLink: boolean,
484 inCode: boolean,
485): boolean {
486 const code = item.children.find((child) => child.type === "element");
487 const start = code?.position?.start.offset;
488 const itemStart = item.position?.start.offset;
489 if (!isElement(code, "pre") || start === undefined || itemStart === undefined) return false;
490 const value = textOf(code);
491 if (!/^[\t ]/.test(value)) return false;
492 if (walk.source.slice(itemStart, start).includes("\n") || /[`~]/.test(walk.source[start]!)) {
493 return false;
494 }
495 // The trimmed first line sets where the item's content starts.
496 const indent = [.../^[\t ]*/.exec(value)![0]].reduce(
497 (column, character) => (character === "\t" ? (Math.floor(column / 4) + 1) * 4 : column + 1),
498 0,
499 );
500 // The prefix keeps block syntax at the start, such as `#`, from opening a block.
501 const source = `${INLINE_PREFIX}${value.trim()}`;
502 const recovered = walk.render(source, indent);
503 const paragraph = recovered.children.find((child) => child.type === "element");
504 const first = isElement(paragraph, "p") ? paragraph.children[0] : undefined;
505 if (first?.type !== "text" || !first.value.startsWith(INLINE_PREFIX)) return false;
506 first.value = first.value.slice(INLINE_PREFIX.length);
507 if (first.value === "") paragraph!.children.shift();
508 transform(recovered, { ...walk, source }, inLink, inCode);
509 transform(item, walk, inLink, inCode);
510 let blocks = recovered.children.filter(
511 (child) => !(child.type === "text" && child.value.trim() === ""),
512 ) as ElementContent[];
513 // Their positions point into `source`, not the message.
514 blocks.forEach(stripPositions);
515 let at = item.children.indexOf(code);
516 let remove = 1;
517 if (!isLooseList(list, walk.source)) {
518 // A tight item shows its text bare, as remark-rehype unwraps its paragraphs.
519 blocks = blocks.flatMap((block, index) => [
520 ...(index > 0 ? [{ type: "text", value: "\n" } as Text] : []),
521 ...(isElement(block, "p") ? block.children : [block]),
522 ]);
523 const isBlank = (node: ElementContent | undefined) =>
524 node?.type === "text" && node.value.trim() === "";
525 if (at === 1 && isBlank(item.children[0])) [at, remove] = [0, 2];
526 if (at + remove === item.children.length - 1 && isBlank(item.children.at(-1))) remove++;
527 }
528 item.children.splice(at, remove, ...blocks);
529 return true;
531​
532/** remark-rehype's listLoose: a blank line between items, or an item Words wrote as paragraphs. */
533function isLooseList(list: Root | Element, source: string): boolean {
534 const items = (list.children as ElementContent[]).filter((child): child is Element =>
535 isElement(child, "li"),
536 );
537 return items.some(
538 (item, index) =>
539 item.children.some((child) => isElement(child, "p")) ||
540 (index > 0 &&
541 /\n[ \t>]*\n/.test(
542 source.slice(
543 items[index - 1]!.position?.end.offset ?? 0,
544 item.position?.start.offset ?? 0,
545 ),
546 )),
547 );
549​
550const WRITTEN_NUMBER = /[ \t]*(\d{1,9})[.)]/y;
551​
552function keepListNumbers(list: Element, source: string) {
553 let expected = Number(list.properties.start ?? 1);
554 for (const item of list.children) {
555 if (!isElement(item, "li")) continue;
556 const offset = item.position?.start.offset;
557 WRITTEN_NUMBER.lastIndex = offset ?? 0;
558 const digits = offset === undefined ? undefined : WRITTEN_NUMBER.exec(source)?.[1];
559 const value = digits === undefined ? expected : Number(digits);
560 if (value !== expected) item.properties.value = String(value);
561 expected = value + 1;
562 }
564​
565/** What the chat's remark plugins add that Words does not. */
566const link = (href: string, label: string, properties: Element["properties"] = {}): Element => ({
567 type: "element",
568 tagName: "a",
569 properties: { href, ...properties },
570 children: [{ type: "text", value: label }],
571});
572​
573/** Links in text: absolute file paths (remarkLinkAbsoluteFilePaths), then a change request's references. */
574function linkText(value: string, walk: Walk): ElementContent[] | null {
575 let parts: ElementContent[] = [];
576 let offset = 0;
577 for (const { index, path } of absoluteFilePathMatches(value)) {
578 if (index > offset) parts.push({ type: "text", value: value.slice(offset, index) });
579 parts.push(link(path, path));
580 offset = index + path.length;
581 }
582 if (offset < value.length) parts.push({ type: "text", value: value.slice(offset) });
583 const autolinks = walk.options.extensions.changeRequest?.autolinks;
584 if (autolinks) {
585 parts = parts.flatMap((part) => {
586 if (part.type !== "text") return [part];
587 const found = autolinks(part.value);
588 if (found.length === 0) return [part];
589 const linked: ElementContent[] = [];
590 let start = 0;
591 for (const reference of found) {
592 if (start < reference.index) {
593 linked.push({ type: "text", value: part.value.slice(start, reference.index) });
594 }
595 linked.push(
596 link(reference.url, reference.label, { dataPullRequestAutolink: reference.kind }),
597 );
598 start = reference.index + reference.text.length;
599 }
600 if (start < part.value.length) linked.push({ type: "text", value: part.value.slice(start) });
601 return linked;
602 });
603 }
604 return parts.length === 1 && parts[0]!.type === "text" ? null : parts;
606​
607function transform(node: Root | Element, walk: Walk, inLink: boolean, inCode: boolean) {
608 const children = node.children as ElementContent[];
609 for (let index = 0; index < children.length; index++) {
610 const child = children[index]!;
611 if (child.type === "text") {
612 if (inCode) continue;
613 if (walk.options.extensions.githubEmoji && child.value.includes(":")) {
614 child.value = expandGithubEmojiAliases(child.value);
615 }
616 if (inLink) continue;
617 const parts = linkText(child.value, walk);
618 if (!parts) continue;
619 children.splice(index, 1, ...parts);
620 index += parts.length - 1;
621 continue;
622 }
623 if (child.type !== "element") continue;
624 // Words gives what it generates a source position; raw HTML that copies its attributes has none.
625 if (child.properties.dataDirective !== undefined && child.position) {
626 children[index] = codexDirective(child, walk, inLink);
627 index--;
628 continue;
629 }
630 const { tagName, properties: props } = child;
631 if (tagName === "svg") {
632 // Sanitizing drops SVG, so math waits under a placeholder until after it.
633 const clean = walk.options.math && child.position ? sanitizeMath(child) : null;
634 if (clean) {
635 const key = `${walk.mathKey}-${walk.math.size}`;
636 walk.math.set(key, clean);
637 children[index] = {
638 type: "element",
639 tagName: "span",
640 properties: { id: key },
641 children: [],
642 };
643 }
644 continue;
645 }
646 if (tagName === "a" && props.dataFootnoteRef !== undefined) {
647 // remark-rehype's footnote markup, before rehype-sanitize prefixes ids again.
648 props.href = `#user-content-${String(props.href).slice(1)}`;
649 props.id = `user-content-${String(props.id)}`;
650 props.ariaDescribedBy = ["footnote-label"];
651 } else if (tagName === "a" && props.dataFootnoteBackref !== undefined) {
652 const { href, ariaLabel } = props;
653 child.properties = {
654 href: `#user-content-${String(href).slice(1)}`,
655 dataFootnoteBackref: "",
656 ariaLabel,
657 className: ["data-footnote-backref"],
658 };
659 } else if (tagName === "li" && typeof props.id === "string" && props.id.startsWith("fn-")) {
660 props.id = `user-content-${props.id}`;
661 } else if (tagName === "section" && props.dataFootnotes !== undefined) {
662 child.properties = { dataFootnotes: "", className: ["footnotes"] };
663 child.children.unshift({
664 type: "element",
665 tagName: "h2",
666 properties: { className: ["sr-only"], id: "footnote-label" },
667 children: [{ type: "text", value: "Footnotes" }],
668 });
669 } else if (tagName === "a" && typeof props.href === "string") {
670 // remarkNormalizeLinksAndTagInlineCode: a Windows drive path links as a file URL.
671 const path = windowsPath(props.href);
672 props.href = path ? `file:///${path.replaceAll("\\", "/")}` : normalizeUri(props.href);
673 } else if (tagName === "img" && typeof props.src === "string") {
674 const changeRequest = walk.options.extensions.changeRequest;
675 const src = changeRequest
676 ? resolveChangeRequestMediaUrl(props.src, changeRequest.repositoryUrl)
677 : props.src;
678 props.src = windowsPath(src) ?? normalizeUri(src);
679 } else if (tagName === "code" && isElement(node, "pre")) {
680 if (props.dataMeta !== undefined) {
681 props.dataCodeMeta = props.dataMeta;
682 delete props.dataMeta;
683 }
684 } else if (tagName === "code" && !inLink) {
685 props.dataInlineCode = "";
686 } else if (tagName === "ol" && walk.options.extensions.userMessage) {
687 keepListNumbers(child, walk.source);
688 } else if (tagName === "li") {
689 const firstBlock = child.children.find(isElementNode);
690 if (isElement(firstBlock, "pre") && recoverIndentedCode(child, node, walk, inLink, inCode)) {
691 continue;
692 }
693 // Tight items put the checkbox directly in `<li>`, loose ones inside its first `<p>`.
694 const checkbox = isElement(child.children[0], "input")
695 ? child.children[0]
696 : isElement(firstBlock, "p") && isElement(firstBlock.children[0], "input")
697 ? firstBlock.children[0]
698 : undefined;
699 if (checkbox) {
700 props.className = ["task-list-item"];
701 const { checked } = checkbox.properties;
702 checkbox.properties = { type: "checkbox", checked, disabled: true };
703 if (node.type === "element") node.properties.className = ["contains-task-list"];
704 }
705 if (child.position) breakLines(child, walk.options.breaks);
706 } else if (tagName === "p" && Object.keys(child.properties).length === 0) {
707 // Words writes a Markdown paragraph bare; one with attributes is raw HTML, which keeps its
708 // lines as written, as remark-breaks never touched raw HTML.
709 breakLines(child, walk.options.breaks);
710 } else if (tagName === "blockquote") {
711 // remarkGithubAlerts
712 const paragraph = child.children.find((item) => item.type === "element");
713 const first = isElement(paragraph, "p") ? paragraph.children[0] : undefined;
714 const text = first?.type === "text" ? first.value : "";
715 const insight = walk.insightMarker?.exec(text);
716 const alert = GITHUB_ALERT_MARKER.exec(text);
717 // An alert marker followed by more inline content on its line is text, as remarkGithubAlerts reads it.
718 const match = insight
719 ? ([insight[0], "insight"] as const)
720 : alert && (alert[0].endsWith("\n") || (paragraph as Element).children.length === 1)
721 ? alert
722 : null;
723 if (match && first?.type === "text" && isElement(paragraph, "p")) {
724 first.value = first.value.slice(match[0].length);
725 if (first.value === "") paragraph.children.shift();
726 if (paragraph.children.length === 0) {
727 const at = child.children.indexOf(paragraph);
728 const next = child.children[at + 1];
729 // The line ending after it goes too, as remark leaves none for a removed paragraph.
730 const blank = next?.type === "text" && next.value.trim() === "" ? 2 : 1;
731 child.children.splice(at, blank);
732 }
733 props.dataAlert = match[1]!.toLowerCase();
734 }
735 }
736 transform(
737 child,
738 walk,
739 inLink || tagName === "a",
740 inCode || tagName === "code" || tagName === "pre",
741 );
742 }
744​
745/**
746 * remark-breaks puts a `<br>` before every soft line ending, and remarkBreakAroundImageLines
747 * before those next to a Markdown image. Both keep the line ending after it.
748 */
749/** A Markdown image alone on its line: nothing but a line ending (or the paragraph's edge) around it. */
750function imageOwnsLine(items: ElementContent[], at: number): boolean {
751 if (!isMarkdownImage(items[at])) return false;
752 const before = items[at - 1];
753 const after = items[at + 1];
754 const startsLine =
755 before === undefined ||
756 (before.type === "text" && /\n[ \t]*$/.test(before.value)) ||
757 isElement(before, "br");
758 const endsLine = after === undefined || (after.type === "text" && /^[ \t]*\n/.test(after.value));
759 return startsLine && endsLine;
761​
762const isBlockElement = (node: ElementContent | undefined) =>
763 node?.type === "element" && CLOSES_PARAGRAPH.has(node.tagName);
764​
765function breakLines(paragraph: Element, breaks: boolean) {
766 const items = paragraph.children;
767 for (let at = 0; at < items.length; at++) {
768 const item = items[at]!;
769 if (
770 item.type === "element" &&
771 breaks &&
772 item.tagName !== "code" &&
773 !CLOSES_PARAGRAPH.has(item.tagName)
774 ) {
775 breakLines(item, breaks);
776 }
777 if (item.type !== "text" || !item.value.includes("\n")) continue;
778 const afterImage = imageOwnsLine(items, at - 1);
779 const beforeImage = imageOwnsLine(items, at + 1);
780 const afterBlock = isBlockElement(items[at - 1]) || (at === 0 && paragraph.tagName === "li");
781 const beforeBlock =
782 isBlockElement(items[at + 1]) || (at === items.length - 1 && paragraph.tagName === "li");
783 const lines = item.value.split("\n");
784 const parts: ElementContent[] = [];
785 lines.forEach((line, index) => {
786 // A hard break's own line ending follows its <br>, and adds no second one;
787 // structural line endings around a list item's block children stay breaks between blocks.
788 const afterHardBreak = index === 1 && isElement(items[at - 1], "br");
789 const blockBoundary =
790 (index === 1 && lines[0] === "" && afterBlock) ||
791 (index === lines.length - 1 && line === "" && beforeBlock);
792 const breaksHere =
793 index > 0 &&
794 !afterHardBreak &&
795 !blockBoundary &&
796 (breaks || (index === 1 && afterImage) || (index === lines.length - 1 && beforeImage));
797 if (index > 0) {
798 if (breaksHere) {
799 const previous = parts.at(-1);
800 if (previous?.type === "text") previous.value = previous.value.replace(/[ \t]+$/, "");
801 parts.push(BREAK);
802 }
803 parts.push({ type: "text", value: `\n${line}` });
804 } else if (line) {
805 parts.push({ type: "text", value: line });
806 }
807 });
808 // Rejoin text that did not break, so the tree matches remark's text nodes.
809 const merged: ElementContent[] = [];
810 for (const part of parts) {
811 const previous = merged.at(-1);
812 if (part.type === "text" && previous?.type === "text") previous.value += part.value;
813 else merged.push(part);
814 }
815 items.splice(at, 1, ...merged);
816 at += merged.length - 1;
817 }
819​
820/**
821 * The wrapper copying reads (markdown-clipboard's MATH_SELECTOR): the formula's TeX, as the source
822 * Words drew it from, so copying any part of a formula copies the whole of it.
823 */
824// A formula wider than its block scrolls, with room for the glyphs that reach past its box; in a
825// table it keeps its width and the table scrolls.
826const MATH_SCROLL = [
827 "max-w-full",
828 "overflow-x-auto",
829 "overflow-y-hidden",
830 "px-0.5",
831 "py-0.75",
832 "in-[.chat-markdown-table-container]:max-w-none",
833 "in-[.chat-markdown-table-container]:overflow-visible",
834];
835​
836function mathWrapper(svg: Element): Element {
837 const tex = String(svg.properties.ariaLabel ?? "").trim();
838 const display = /display:\s*block/.test(String(svg.properties.style ?? ""));
839 return {
840 type: "element",
841 tagName: "span",
842 properties: display
843 ? {
844 className: ["chat-markdown-math-display", "block", ...MATH_SCROLL],
845 dataMarkdownMath: "display",
846 dataMarkdownCopy: `\\[\n${tex}\n\\]\n\n`,
847 }
848 : {
849 className: ["inline-block", "align-middle", ...MATH_SCROLL],
850 dataMarkdownMath: "inline",
851 dataMarkdownCopy: `\\(${tex}\\)`,
852 },
853 children: [svg],
854 };
856​
857function restoreMath(node: Root | Element, math: Map<string, Element>) {
858 const children = node.children as ElementContent[];
859 for (let index = 0; index < children.length; index++) {
860 const child = children[index]!;
861 if (child.type !== "element") continue;
862 const id = child.properties.id;
863 const svg = typeof id === "string" ? math.get(id.replace(/^user-content-/, "")) : undefined;
864 if (svg) children[index] = mathWrapper(svg);
865 else restoreMath(child, math);
866 }
868​
869const addHeadingIds = rehypeHeadingIds();
870const addTextDirection = rehypeTextDirection();
871const preserveImageSourceMeta = rehypePreserveImageSourceMeta();
872const normalizeLocalEditorLinks = rehypeNormalizeLocalEditorLinks();
873const groupChipPunctuation = rehypeChipPunctuation();
874​
875const INSIGHT_OPENING = /^( {0,3})(`?)★ Insight[ \t]+─{3,}\2[ \t]*$/u;
876const INSIGHT_CLOSING = /^( {0,3})(`?)─{3,}\2[ \t]*$/u;
877​
878interface InsightSource {
879 readonly source: string;
880 readonly tree: Root;
881 readonly marker: RegExp;
882 /** The offset in the message for an offset in `source`. */
883 readonly toOriginal: (offset: number) => number;
885​
886/**
887 * remarkAssistantInsights: a `★ Insight ───` line opens a quoted insight block, which a `───` line
888 * at the same indentation closes; the end of the text closes one that never does. Lines in code
889 * neither open nor close one, and an opening Words does not read as a quote's first line, as in
890 * an HTML block or a quote's lazy line, stays text.
891 */
892function insightSource(text: string, options: RenderOptions): InsightSource | null {
893 if (!text.includes("★ Insight")) return null;
894 const code: Array<readonly [number, number]> = [];
895 const findCode = (node: Root | Element) => {
896 for (const child of node.children) {
897 if (child.type !== "element") continue;
898 if (child.tagName === "pre" && child.position) {
899 code.push([child.position.start.offset!, child.position.end.offset!]);
900 } else findCode(child);
901 }
902 };
903 findCode(parse(text, options));
904 const nonce = Math.random().toString(36).slice(2);
905 const marker = new RegExp(String.raw`^\[!T3-INSIGHT-${nonce}-(\d+)\](?:\r?\n)?`);
906 const anywhere = new RegExp(String.raw`\[!T3-INSIGHT-${nonce}-(\d+)\]`, "g");
907 const lines = text.split(/(?<=\n)/u);
908 const skipped = new Set<number>();
909 for (;;) {
910 // Each line's offset in the message and in the source, and how much longer it got.
911 const offsets: Array<{ original: number; source: number; length: number; delta: number }> = [];
912 let original = 0;
913 let rewritten = 0;
914 let opened = 0;
915 let indent: string | undefined;
916 const source = lines
917 .map((line, lineIndex) => {
918 const value = line.replace(/[\r\n]+$/u, "");
919 const ending = line.slice(value.length);
920 const inCode = code.some(([start, end]) => original >= start && original < end);
921 let output = line;
922 if (indent === undefined) {
923 const opening = inCode ? null : INSIGHT_OPENING.exec(value);
924 if (opening && !skipped.has(lineIndex)) {
925 indent = opening[1] ?? "";
926 opened++;
927 output = `> [!T3-INSIGHT-${nonce}-${lineIndex}]${ending}`;
928 }
929 } else {
930 const closing = inCode ? null : INSIGHT_CLOSING.exec(value);
931 if (closing && closing[1] === indent) {
932 indent = undefined;
933 output = ending;
934 } else output = `> ${line}`;
935 }
936 offsets.push({
937 original,
938 source: rewritten,
939 length: line.length,
940 delta: output.length - line.length,
941 });
942 original += line.length;
943 rewritten += output.length;
944 return output;
945 })
946 .join("");
947 if (opened === 0) return null;
948 const tree = parse(source, options);
949 let stranded = false;
950 const visit = (node: Root | Element, quoteStart: Text | undefined) => {
951 for (const child of node.children) {
952 if (child.type === "text") {
953 for (const found of child.value.matchAll(anywhere)) {
954 if (child === quoteStart && found.index === 0) continue;
955 skipped.add(Number(found[1]));
956 stranded = true;
957 }
958 } else if (child.type === "element") {
959 const paragraph =
960 child.tagName === "blockquote" ? child.children.find(isElementNode) : undefined;
961 const first = isElement(paragraph, "p") ? paragraph.children[0] : undefined;
962 visit(child, first?.type === "text" ? first : quoteStart);
963 }
964 }
965 };
966 visit(tree, undefined);
967 if (stranded) continue;
968 return {
969 source,
970 tree,
971 marker,
972 toOriginal: (offset) => {
973 const line = offsets.findLast((entry) => entry.source <= offset) ?? offsets[0]!;
974 return (
975 line.original + Math.min(Math.max(offset - line.source - line.delta, 0), line.length)
976 );
977 },
978 };
979 }
981​
982/** Positions that point into an insight's rewritten source, moved back into the message. */
983function restorePositions(node: Root | Element, toOriginal: (offset: number) => number) {
984 for (const child of node.children) {
985 if (child.type !== "element") continue;
986 if (child.position) {
987 const start = toOriginal(child.position.start.offset!);
988 const end = toOriginal(child.position.end.offset!);
989 child.position = {
990 start: { line: 1, column: start + 1, offset: start },
991 end: { line: 1, column: end + 1, offset: end },
992 };
993 }
994 restorePositions(child, toOriginal);
995 }
997​
998const PREVIEW_SEPARATED = new Set([
999 "blockquote",
1000 "ul",
1001 "ol",
1002 "li",
1003 "table",
1004 "thead",
1005 "tbody",
1006 "tr",
1007]);
1008​
1009/** remarkThoughtPreview: the message as one line of text, keeping math, cut at `maxLength`. */
1010function flattenPreview(tree: Root, preview: NonNullable<MarkdownExtensions["preview"]>): Root {
1011 const children: ElementContent[] = [];
1012 let remaining = preview.maxLength;
1013 let fragments: string[] = [];
1014 const flush = () => {
1015 if (fragments.length === 0) return;
1016 children.push({ type: "text", value: fragments.join("").replace(/\s+/g, " ") });
1017 fragments = [];
1018 };
1019 const take = (value: string) => {
1020 const text = value.slice(0, remaining);
1021 remaining = text.length < value.length ? 0 : remaining - text.length;
1022 // A cut must not leave half a surrogate pair.
1023 return text.replace(/[\uD800-\uDBFF]$/, "");
1024 };
1025 const visit = (node: Root | ElementContent) => {
1026 if (remaining === 0) return;
1027 if (node.type === "text") {
1028 fragments.push(take(node.value));
1029 return;
1031 if (node.type === "element" && node.properties.dataMarkdownMath !== undefined) {
1032 flush();
1033 // One line has no room for display math, which a preview shows inline.
1034 const svg = node.children[0];
1035 children.push(
1036 node.properties.dataMarkdownMath === "display" && svg?.type === "element"
1037 ? mathWrapper({
1038 ...svg,
1039 properties: {
1040 ...svg.properties,
1041 style: "display:inline;vertical-align:middle;overflow:visible",
1042 },
1043 })
1044 : node,
1045 );
1046 return;
1048 if (node.type === "element" && node.tagName === "img") {
1049 fragments.push(take(String(node.properties.alt ?? "")));
1050 return;
1052 if (node.type === "element" && node.tagName === "br") {
1053 fragments.push(take(" "));
1054 return;
1056 if (node.type !== "root" && node.type !== "element") return;
1057 const separates = node.type === "root" || PREVIEW_SEPARATED.has(node.tagName);
1058 let first = true;
1059 for (const child of node.children as ElementContent[]) {
1060 if (remaining === 0) break;
1061 if (child.type === "text" && child.value.trim() === "" && separates) continue;
1062 if (!first && separates) fragments.push(take(" "));
1063 first = false;
1064 visit(child);
1066 };
1067 visit(tree);
1068 flush();
1069 const head = children[0];
1070 const tail = children.at(-1);
1071 if (head?.type === "text") head.value = head.value.trimStart();
1072 if (tail?.type === "text") tail.value = tail.value.trimEnd();
1073 const visible = children.some((child) => child.type !== "text" || child.value);
1074 return {
1075 type: "root",
1076 children: visible ? children : [{ type: "text", value: preview.fallback }],
1077 };
1079​
1080/** Links become their text, images their alt text, inline code plain text, Mermaid plain code. */
1081function makeInert(node: Root | Element) {
1082 const children = node.children as ElementContent[];
1083 for (let index = 0; index < children.length; index++) {
1084 const child = children[index]!;
1085 if (child.type !== "element") continue;
1086 if (child.tagName === "a") {
1087 children.splice(index, 1, ...child.children);
1088 index--;
1089 continue;
1091 if (child.tagName === "img") {
1092 children[index] = { type: "text", value: String(child.properties.alt ?? "") };
1093 continue;
1095 if (child.tagName === "code" && child.properties.dataInlineCode !== undefined) {
1096 children[index] = { type: "text", value: textOf(child) };
1097 continue;
1099 if (
1100 child.tagName === "code" &&
1101 String(child.properties.className ?? "").includes("language-mermaid")
1102 ) {
1103 child.properties.className = ["language-text"];
1105 makeInert(child);
1108​
1109/** ChatMarkdown's sanitized hast for `text`, rendered by Words. */
1110export function wordsHast(text: string, options: WordsHastOptions): Root {
1111 const { extensions } = options;
1112 const renderOptions: RenderOptions = {
1113 math: options.math,
1114 // llm-math's `\(…\)` and `\[…\]`, which agents write as often as `$`.
1115 texDelimiters: options.math,
1116 autolinkBoundaries: true,
1117 singleTilde: !extensions.userMessage,
1118 leadingWhitespace: extensions.leadingWhitespace === true,
1119 windowsPaths: true,
1120 codeMeta: true,
1121 directives: CODEX_DIRECTIVES,
1122 // Previews and inert Markdown drop raw HTML, as their remark plugins dropped html nodes.
1123 ...(extensions.preview || extensions.inert
1124 ? { skipHtml: true }
1125 : { escapeHtml: options.escapeHtml }),
1126 };
1127 const insights = options.insights ? insightSource(text, renderOptions) : null;
1128 const source = insights?.source ?? text;
1129 const tree = insights?.tree ?? parse(source, renderOptions);
1130 const walk: Walk = {
1131 render: (markdown, indent) =>
1132 parse(markdown, {
1133 ...renderOptions,
1134 leadingWhitespace: extensions.leadingWhitespace === true && { indent },
1135 }),
1136 source,
1137 options,
1138 math: new Map(),
1139 mathKey: `t3-math-${Math.random().toString(36).slice(2)}`,
1140 insightMarker: insights?.marker ?? null,
1141 };
1142 transform(tree, walk, false, false);
1143 preserveImageSourceMeta(tree as never);
1144 normalizeLocalEditorLinks(tree as never);
1145 const hast = sanitizeChatHast(tree);
1146 if (walk.math.size > 0) restoreMath(hast, walk.math);
1147 if (insights) restorePositions(hast, insights.toOriginal);
1148 if (extensions.inert) makeInert(hast);
1149 if (extensions.preview) return flattenPreview(hast, extensions.preview);
1150 addHeadingIds(hast);
1151 addTextDirection(hast as never);
1152 groupChipPunctuation(hast as never);
1153 return hast;
1155​
1156export interface CodexDirectiveSource {
1157 readonly name: string;
1158 readonly attributes: Record<string, string>;
1159 /** UTF-16 offsets of the whole directive in the source. */
1160 readonly start: number;
1161 readonly end: number;
1162 /** The label's text as written. */
1163 readonly label: string;
1164 /** Inside a link, where a file citation stays text. */
1165 readonly inLink: boolean;
1167​
1168/** The Codex directives in `markdown`, as Words reads them. */
1169export function codexDirectiveSources(markdown: string): CodexDirectiveSource[] {
1170 const found: CodexDirectiveSource[] = [];
1171 const visit = (node: Root | Element, inLink: boolean) => {
1172 for (const child of node.children) {
1173 if (child.type !== "element") continue;
1174 const name = child.properties.dataDirective;
1175 if (typeof name === "string" && child.position) {
1176 const { start, end } = child.position;
1177 found.push({
1178 name,
1179 attributes: directiveAttributes(child),
1180 start: start.offset!,
1181 end: end.offset!,
1182 label: directiveLabel(markdown.slice(start.offset, end.offset)),
1183 inLink,
1184 });
1186 visit(child, inLink || child.tagName === "a");
1188 };
1189 visit(
1190 parse(markdown, {
1191 windowsPaths: true,
1192 autolinkBoundaries: true,
1193 directives: CODEX_DIRECTIVES,
1194 }),
1195 false,
1196 );
1197 return found;
1199​
1200/** The label of a directive as written, `:name[label]{…}`: brackets nest in it, and `\` escapes. */
1201function directiveLabel(written: string): string {
1202 const open = written.indexOf("[");
1203 if (open < 0) return "";
1204 let depth = 0;
1205 for (let index = open; index < written.length; index++) {
1206 const character = written[index];
1207 if (character === "\\") index++;
1208 else if (character === "[") depth++;
1209 else if (character === "]" && --depth === 0) return written.slice(open + 1, index);
1211 return "";
1213​
1214/**
1215 * Words' HTML for `markdown` as hast, unsanitized and without the chat's additions. Code blocks,
1216 * links, list items and math carry source positions.
1217 */
1218export function markdownTree(
1219 markdown: string,
1220 options: { skipHtml?: boolean; singleTilde?: boolean; math?: boolean } = {},
1221): Root {
1222 return parse(markdown, {
1223 windowsPaths: true,
1224 autolinkBoundaries: true,
1225 skipHtml: options.skipHtml === true,
1226 singleTilde: options.singleTilde !== false,
1227 math: options.math === true,
1228 texDelimiters: options.math === true,
1229 });
1231​
1232/** The formulas Words reads in `text`, as source offsets, for editors that keep math as source. */
1233export function markdownMathRanges(text: string): Array<{ start: number; end: number }> {
1234 if (!/[$\\]|(?:`{3,}|~{3,})[ \t]*math\b/.test(text)) return [];
1235 const ranges: Array<{ start: number; end: number }> = [];
1236 const visit = (node: Root | Element) => {
1237 for (const child of node.children) {
1238 if (child.type !== "element") continue;
1239 if (child.tagName === "svg") {
1240 if (child.position) {
1241 ranges.push({ start: child.position.start.offset!, end: child.position.end.offset! });
1243 continue;
1245 visit(child);
1247 };
1248 visit(parse(text, { math: true, texDelimiters: true }));
1249 return ranges;
1251​
1252/** The HTML comments Words reads as raw HTML in `markdown`, not as code or text, as source offsets. */
1253export function markdownHtmlComments(markdown: string): Array<{ start: number; end: number }> {
1254 const openers = [...markdown.matchAll(/<!--(?!-?>)/g)].map((match) => match.index);
1255 if (openers.length === 0) return [];
1256 // A mark after each opener keeps a comment a comment; Words writes only real ones unescaped.
1257 let marked = "";
1258 let from = 0;
1259 for (const [index, at] of openers.entries()) {
1260 marked += `${markdown.slice(from, at + 4)}\uE000${index}\uE001`;
1261 from = at + 4;
1263 const html = decoder.decode(renderToHtml(marked + markdown.slice(from), { windowsPaths: true }));
1264 return [...html.matchAll(/<!--\uE000(\d+)\uE001/g)].map((match) => {
1265 const start = openers[Number(match[1])]!;
1266 const close = markdown.indexOf("-->", start + 4);
1267 return { start, end: close < 0 ? markdown.length : close + 3 };
1268 });
1270​
1271/**
1272 * The first definition of each label in `markdown`, as one line of Markdown. Words decides which
1273 * `[label]:` text defines one: each label is looked up again after the text.
1274 */
1275export function markdownReferenceDefinitions(markdown: string): string[] {
1276 const labels = new Map<string, string>();
1277 for (const match of markdown.matchAll(/\[((?:[^\\[\]]|\\.){1,999})\]:/g)) {
1278 const key = match[1]!.replace(/\s+/g, " ").trim().toLowerCase();
1279 // `[^1]:` is a footnote.
1280 if (key !== "" && !key.startsWith("^") && !labels.has(key)) labels.set(key, match[1]!);
1282 if (labels.size === 0) return [];
1283 let probe = `${markdown}\n\n`;
1284 const lookups = new Map<number, string>();
1285 for (const label of labels.values()) {
1286 lookups.set(probe.length, label);
1287 probe += `[${label}]\n\n`;
1289 const definitions: string[] = [];
1290 const visit = (node: Root | Element) => {
1291 for (const child of node.children) {
1292 if (child.type !== "element") continue;
1293 const label = lookups.get(child.position?.start.offset ?? -1);
1294 if (child.tagName === "a" && label !== undefined) {
1295 const href = String(child.properties.href ?? "").replace(/[<>\\\n]/g, encodeURIComponent);
1296 const title = child.properties.title;
1297 definitions.push(
1298 `[${label}]: <${href}>${typeof title === "string" ? ` "${title.replace(/\s+/g, " ").replace(/["\\]/g, "\\$&")}"` : ""}`,
1299 );
1300 } else visit(child);
1302 };
1303 visit(parse(probe, { windowsPaths: true }));
1304 return definitions;