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

wordsHast.ts

1,296 lines49.5 KB

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