Open History to see the last commit
1import type { mediaKindFromPath } from "./mediaPreview.ts";
2import {
3 isNetworkPath,
4 isWindowsAbsolutePath,
5 stripSlashPrefixedWindowsDrive,
6 workspaceRelativeFilePath,
7} from "./path.ts";
8import {
9 type FilePathPosition,
10 formatFilePathPosition,
11 parseFileUrlHref,
12 resolvePathLinkTarget,
13 splitFilePathPosition,
14} from "./fileLinks.ts";
15
16const RELATIVE_PATH_PREFIX_PATTERN = /^(~\/|\.{1,2}\/)/;
17
18// Names may use any script (`線性代數/考試.pdf`) and routing punctuation (`posts.$id.tsx`,
19// `(group)/[id]/+page.svelte`, `@scope/pkg`). The final segment is optional so an explicit
20// folder link may end in `/` (`patches/`, `docs/My Folder/`). A bare name with no slash still fails.
21const RELATIVE_FILE_PATH_PATTERN =
22 /^(?:[\p{L}\p{M}\p{N}._$+@()[\]-]+(?: +[\p{L}\p{M}\p{N}._$+@()[\]-]+)*\/)+(?:[\p{L}\p{M}\p{N}._$+@()[\]-]+(?: +[\p{L}\p{M}\p{N}._$+@()[\]-]+)*(?::\d+(?::\d+|-\d+)?)?)?$/u;
23
24// No `@` here: `me@example.com` is an address, not a file.
25const RELATIVE_FILE_NAME_PATTERN =
26 /^[\p{L}\p{M}\p{N}._$+()[\]-]+(?: +[\p{L}\p{M}\p{N}._$+()[\]-]+)*\.[\p{L}\p{M}\p{N}_-]+(?::\d+(?::\d+|-\d+)?)?$/u;
27
28const EXTERNAL_SCHEME_PATTERN = /^([A-Za-z][A-Za-z0-9+.-]*):(.*)$/;
29
30const POSITION_SUFFIX_PATTERN = /:\d+(?::\d+|-\d+)?$/;
31
32const HASH_POSITION_PATTERN = /#L\d+(?:C\d+|-L?\d+)?$/i;
33
34const INLINE_CODE_POSITION_PATTERN = /(?::\d+(?::\d+|-\d+)?|#L\d+(?:C\d+|-L?\d+)?)$/i;
35
36const POSITION_ONLY_PATTERN = /^\d+(?::\d+|-\d+)?$/;
37
38const INLINE_CODE_WHITESPACE_PATTERN = /\s/;
39
40// Inline code with spaces is a file only when it is absolute and every word is a plain name:
41// `/Users/me/Mobile Documents/a - b.md` is, `/usr/bin/python3 -m venv .venv` (a flag) is not.
42// A space only in the last segment reads as a command (`/usr/local/bin/node server.js`), so it
43// must sit under a user root, and nothing after a bin folder counts.
44const SPACED_ABSOLUTE_PATH_ROOT_PATTERN = /^(?:\/|~\/|[A-Za-z]:[\\/]|\\\\)/;
45const SPACED_PATH_BODY_PATTERN =
46 /^(?:[\p{L}\p{M}\p{N}._$+@()[\]-]+(?: +(?!-+\p{L})[\p{L}\p{M}\p{N}._$+@()[\]-]+)*(?:[\\/]|$))+$/u;
47
48function isSpacedAbsoluteFilePath(text: string): boolean {
49 const root = SPACED_ABSOLUTE_PATH_ROOT_PATTERN.exec(text)?.[0];
50 if (root === undefined) return false;
51 const body = text.slice(root.length).replace(INLINE_CODE_POSITION_PATTERN, "");
52 if (!SPACED_PATH_BODY_PATTERN.test(body)) return false;
53 const firstSpace = body.indexOf(" ");
54 const foldersBeforeSpace = body.slice(0, firstSpace).split(PATH_SEPARATOR_PATTERN).slice(0, -1);
55 if (foldersBeforeSpace.some((folder) => folder === "bin" || folder === "sbin")) return false;
56 const spaceInFolder = PATH_SEPARATOR_PATTERN.test(body.slice(firstSpace));
57 if (root === "\\\\" && foldersBeforeSpace.length < (spaceInFolder ? 1 : 2)) return false;
58 if (!spaceInFolder && root === "/" && !/^(?:Users|home)[\\/]/.test(body)) return false;
59 if (PATH_SEPARATOR_PATTERN.test(body.at(-1) ?? "")) return true;
60 const basename = body.split(PATH_SEPARATOR_PATTERN).at(-1) ?? "";
61 return FILE_EXTENSION_PATTERN.test(basename) || EXTENSIONLESS_FILE_NAMES.has(basename);
62}
63
64const PATH_SEPARATOR_PATTERN = /[\\/]/;
65// Agents shorten long paths with a `...` or `…` segment, which no file chip can open.
66const ELIDED_PATH_SEGMENT_PATTERN = /(?:^|[\\/])(?:\.{3,}|…)(?:[\\/]|$)/;
67
68const FILE_EXTENSION_PATTERN = /\.[A-Za-z0-9_-]+$/;
69const ANY_FILE_EXTENSION_PATTERN = /\.[^./\\]+$/;
70const VERSION_SUFFIX_PATTERN = /\d\.\d[^.]*$/;
71const NUMERIC_DOTTED_PATTERN = /^\d+(?:\.\d+)+$/;
72
73const POSIX_FILE_ROOT_PREFIXES = [
74 "/Users/",
75 "/home/",
76 "/tmp/",
77 "/var/",
78 "/etc/",
79 "/opt/",
80 "/mnt/",
81 "/Volumes/",
82 "/private/",
83 "/root/",
84 "/usr/",
85 "/bin/",
86 "/sbin/",
87 "/lib/",
88 "/lib64/",
89 "/srv/",
90 "/dev/",
91 "/proc/",
92 "/sys/",
93 "/run/",
94 "/boot/",
95 "/media/",
96 "/workspace/",
97 "/workspaces/",
98] as const;
99
100export const EXTENSIONLESS_FILE_NAMES: ReadonlySet<string> = new Set([
101 "Makefile",
102 "makefile",
103 "GNUmakefile",
104 "Dockerfile",
105 "Containerfile",
106 "Justfile",
107 "justfile",
108 "Rakefile",
109 "Gemfile",
110 "Procfile",
111 "Brewfile",
112 "Caddyfile",
113 "Vagrantfile",
114 "Jenkinsfile",
115 "Podfile",
116 "Fastfile",
117 "BUILD",
118 "WORKSPACE",
119 "LICENSE",
120 "LICENCE",
121 "COPYING",
122 "NOTICE",
123 "AUTHORS",
124 "CONTRIBUTORS",
125 "CHANGELOG",
126 "README",
127 "CODEOWNERS",
128]);
129
130const SINGLE_LABEL_HOSTNAMES = new Set(["localhost"]);
131
132const GENERIC_HOSTNAME_TLDS = new Set([
133 "com",
134 "net",
135 "org",
136 "io",
137 "dev",
138 "app",
139 "ai",
140 "co",
141 "edu",
142 "gov",
143 "mil",
144 "info",
145 "biz",
146 "xyz",
147 "me",
148 "tv",
149 "gg",
150 "chat",
151 "cloud",
152 "site",
153 "online",
154 "tech",
155 "store",
156 "link",
157]);
158
159const COUNTRY_HOSTNAME_TLDS = new Set([
160 "uk",
161 "de",
162 "fr",
163 "nl",
164 "se",
165 "no",
166 "fi",
167 "dk",
168 "pl",
169 "ch",
170 "at",
171 "be",
172 "es",
173 "it",
174 "pt",
175 "eu",
176 "us",
177 "ca",
178 "au",
179 "nz",
180 "jp",
181 "kr",
182 "cn",
183 "br",
184 "ru",
185 "mx",
186 "ie",
187 "cz",
188 "tr",
189 "sg",
190 "hk",
191 // C++ sources end in `.cc`, so `allocator.cc:217` names a file, not a host and port.
192 "cc",
193]);
194
195function looksLikeHostname(segment: string, hasPosition: boolean): boolean {
196 if (segment.startsWith(".")) return false;
197 const lowered = segment.toLowerCase();
198 if (SINGLE_LABEL_HOSTNAMES.has(lowered)) return true;
199 if (NUMERIC_DOTTED_PATTERN.test(segment)) return true;
200 const labels = lowered.split(".");
201 const lastLabel = labels.at(-1);
202 if (labels.length < 2 || lastLabel === undefined) return false;
203 if (GENERIC_HOSTNAME_TLDS.has(lastLabel)) return true;
204 return !hasPosition && COUNTRY_HOSTNAME_TLDS.has(lastLabel);
205}
206
207export function inlineCodeFilePathCandidate(codeText: string): string | null {
208 const trimmed = codeText.trim();
209 if (trimmed.length === 0 || trimmed.includes("`") || /[<>]/.test(trimmed)) return null;
210 if (INLINE_CODE_WHITESPACE_PATTERN.test(trimmed) && !isSpacedAbsoluteFilePath(trimmed)) {
211 return null;
212 }
213
214 const candidate = isWindowsAbsolutePath(trimmed) ? trimmed : trimmed.replaceAll("\\", "/");
215 const position = INLINE_CODE_POSITION_PATTERN.exec(candidate)?.[0];
216 const hasPosition = position !== undefined;
217 const withoutPosition = candidate.replace(INLINE_CODE_POSITION_PATTERN, "");
218 // Resolvers split at the first `#`, so a `#L` anchor only works on a path without another `#`.
219 if (position?.startsWith("#") && withoutPosition.includes("#")) return null;
220 if (!hasPosition && !PATH_SEPARATOR_PATTERN.test(candidate)) return null;
221 if (ELIDED_PATH_SEGMENT_PATTERN.test(withoutPosition)) return null;
222
223 const hasExplicitPathShape =
224 RELATIVE_PATH_PREFIX_PATTERN.test(candidate) ||
225 candidate.startsWith("/") ||
226 isWindowsAbsolutePath(candidate);
227 if (!hasExplicitPathShape) {
228 // Markdown destinations accept `patches/`. Inline code still needs a
229 // file-shaped final segment, so a trailing slash stays plain code.
230 if (withoutPosition.endsWith("/")) return null;
231 const firstSegment = withoutPosition.split("/")[0] ?? withoutPosition;
232 if (looksLikeHostname(firstSegment, hasPosition)) return null;
233 const basename =
234 withoutPosition
235 .replace(/[/\\]+$/, "")
236 .split(/[\\/]/)
237 .at(-1) ?? "";
238 if (VERSION_SUFFIX_PATTERN.test(basename)) return null;
239 if (!FILE_EXTENSION_PATTERN.test(basename)) {
240 if (!hasPosition) return EXTENSIONLESS_FILE_NAMES.has(basename) ? candidate : null;
241 // A `:line` suffix alone does not make `I/W217:220` a file reference.
242 if (
243 withoutPosition.includes("/") &&
244 !ANY_FILE_EXTENSION_PATTERN.test(basename) &&
245 !EXTENSIONLESS_FILE_NAMES.has(basename)
246 ) {
247 return null;
248 }
249 }
250 }
251 return candidate;
252}
253
254export function safeDecodeURIComponent(value: string): string {
255 try {
256 return decodeURIComponent(value);
257 } catch {
258 return value;
259 }
260}
261
262// Markdown whitespace is ASCII, so a path may end in U+00A0. A `$` regex would be quadratic.
263function trimAscii(value: string): string {
264 let end = value.length;
265 while (/[ \t\r\n]/.test(value[end - 1] ?? "")) end--;
266 return value.slice(0, end).replace(/^[ \t\r\n]+/, "");
267}
268
269// An angle destination may start or end in whitespace, which later trimming would drop, so encode it
270// as the renderer does once decoded. Words encodes what `encodeURI` does except `%`; micromark also
271// escapes a `%` that two alphanumerics do not follow.
272export function encodeMarkdownLinkBoundaryWhitespace(url: string, strayPercent: boolean): string {
273 if (!/^[ \t]|[ \t]$/.test(url)) return url;
274 const escaped = strayPercent ? url.replace(/%(?![\dA-Za-z]{2})/g, "%25") : url;
275 const wellFormed = escaped.replace(/\p{Cs}/gu, "\uFFFD");
276 return wellFormed
277 .split("%")
278 .map((part) => encodeURI(part))
279 .join("%");
280}
281
282export function normalizeMarkdownLinkDestination(value: string): string {
283 const trimmed = trimAscii(value);
284 return trimmed.startsWith("<") && trimmed.endsWith(">") ? trimmed.slice(1, -1) : trimmed;
285}
286
287export function splitMarkdownLinkSearchAndHash(value: string): {
288 readonly path: string;
289 readonly hash: string;
290} {
291 const hashIndex = value.indexOf("#");
292 const pathWithSearch = hashIndex >= 0 ? value.slice(0, hashIndex) : value;
293 const hash = hashIndex >= 0 ? value.slice(hashIndex) : "";
294 const queryIndex = pathWithSearch.indexOf("?");
295 return {
296 path: queryIndex >= 0 ? pathWithSearch.slice(0, queryIndex) : pathWithSearch,
297 hash,
298 };
299}
300
301/**
302 * The decoded path a markdown destination names on the host, before any workspace resolution, or
303 * null for a `file:` URL that does not parse. Clients and the guest media route both read it here.
304 */
305export function markdownDestinationHostPath(source: string): string | null {
306 if (/^file:/i.test(source)) {
307 const target = parseFileUrlHref(source);
308 return target === null
309 ? null
310 : stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(target.path));
311 }
312 return stripSlashPrefixedWindowsDrive(
313 safeDecodeURIComponent(splitMarkdownLinkSearchAndHash(source).path),
314 );
315}
316
317const DIRECT_IMAGE_SOURCE_PATTERN = /^(?:https?:|data:|blob:|\/\/)/i;
318const URI_SCHEME_PATTERN = /^[A-Za-z][A-Za-z0-9+.-]*:/;
319
320export type MarkdownImageSource =
321 | { readonly _tag: "Direct"; readonly uri: string }
322 | { readonly _tag: "WorkspaceFile"; readonly path: string; readonly relative?: true }
323 | { readonly _tag: "Blocked" };
324
325// A POSIX filename may contain a backslash, so only Windows roots treat it as a separator.
326function joinWorkspacePath(workspaceRoot: string, relativePath: string): string {
327 if (!isWindowsAbsolutePath(workspaceRoot)) {
328 return `${workspaceRoot.replace(/\/+$/, "")}/${relativePath.replace(/^\/+/, "")}`;
329 }
330 const root = workspaceRoot.replace(/[\\/]+$/, "");
331 return `${root}\\${relativePath.replace(/[\\/]/g, "\\").replace(/^\\+/, "")}`;
332}
333
334/** Rendering is not a click, so a network path loads only from the project's own share. */
335function hostFileSource(
336 path: string,
337 workspaceRoot: string | null | undefined,
338): MarkdownImageSource {
339 return isNetworkPath(path) && workspaceRelativeFilePath(path, workspaceRoot) === null
340 ? { _tag: "Blocked" }
341 : { _tag: "WorkspaceFile", path };
342}
343
344/**
345 * Filesystem paths belong to the environment host and must never reach a
346 * browser or native image component without first becoming a signed asset URL.
347 */
348export function classifyMarkdownImageSource(
349 value: string | null | undefined,
350 workspaceRoot?: string | null,
351): MarkdownImageSource {
352 if (value === null || value === undefined) return { _tag: "Blocked" };
353
354 const source = normalizeMarkdownLinkDestination(value);
355 if (source.length === 0 || source.startsWith("#") || source.startsWith("?")) {
356 return { _tag: "Blocked" };
357 }
358 if (DIRECT_IMAGE_SOURCE_PATTERN.test(source)) {
359 return { _tag: "Direct", uri: source };
360 }
361
362 const path = markdownDestinationHostPath(source);
363 if (path === null) return { _tag: "Blocked" };
364 if (/^file:/i.test(source)) return hostFileSource(path, workspaceRoot);
365 if (path.length === 0) return { _tag: "Blocked" };
366 if (path.startsWith("/") || isWindowsAbsolutePath(path)) {
367 return hostFileSource(path, workspaceRoot);
368 }
369 if (URI_SCHEME_PATTERN.test(path) || path.startsWith("~/") || path.startsWith("~\\")) {
370 return { _tag: "Blocked" };
371 }
372 if (!workspaceRoot) return { _tag: "Blocked" };
373
374 return { _tag: "WorkspaceFile", path: joinWorkspacePath(workspaceRoot, path), relative: true };
375}
376
377export function shouldRenderMarkdownImageAsFileLink(
378 source: MarkdownImageSource,
379 mediaKind: ReturnType<typeof mediaKindFromPath>,
380): boolean {
381 return source._tag === "WorkspaceFile" && mediaKind === null;
382}
383
384export function isMarkdownFileLinkLabel(label: string, href: string): boolean {
385 const destination = parseMarkdownFileLink(href);
386 if (!destination) return false;
387 const normalize = (path: string) =>
388 path.replaceAll("\\", "/").replace(/^\.\//, "").replace(/\/+$/, "");
389 const trimmed = label.trim();
390 const isWindowsDestination = isWindowsAbsolutePath(destination.path);
391 const destinationPath = isWindowsDestination
392 ? normalize(destination.path).toLowerCase()
393 : normalize(destination.path);
394 const matchesLabelPosition = (labelPosition: FilePathPosition): boolean => {
395 if (
396 (labelPosition.line !== undefined && labelPosition.line !== destination.line) ||
397 (labelPosition.column !== undefined && labelPosition.column !== destination.column) ||
398 (labelPosition.endLine !== undefined && labelPosition.endLine !== destination.endLine)
399 ) {
400 return false;
401 }
402 let labelPath = normalize(labelPosition.path);
403 if (labelPath.length === 0) return true;
404 if (isWindowsDestination) {
405 labelPath = labelPath.toLowerCase();
406 }
407 return destinationPath === labelPath || destinationPath.endsWith(`/${labelPath}`);
408 };
409 const hashIndex = trimmed.lastIndexOf("#");
410 if (hashIndex >= 0) {
411 const path = trimmed.slice(0, hashIndex);
412 const anchored = splitFilePathPosition(path, trimmed.slice(hashIndex));
413 // A `:line` suffix before the hash wins in splitFilePathPosition; only a position from the anchor counts here.
414 if (anchored.line !== undefined && anchored.path === path && matchesLabelPosition(anchored)) {
415 return true;
416 }
417 }
418 return (
419 matchesLabelPosition(splitFilePathPosition(trimmed)) ||
420 (trimmed.length > 0 && matchesLabelPosition(splitFilePathPosition(label)))
421 );
422}
423
424export function isRelativeFilePath(path: string): boolean {
425 return (
426 RELATIVE_PATH_PREFIX_PATTERN.test(path) ||
427 (!path.startsWith("/") && !isWindowsAbsolutePath(path))
428 );
429}
430
431function looksLikePosixFilesystemPath(path: string): boolean {
432 if (!path.startsWith("/")) return false;
433 if (POSIX_FILE_ROOT_PREFIXES.some((prefix) => path.startsWith(prefix))) return true;
434 if (POSITION_SUFFIX_PATTERN.test(path)) return true;
435 const basename = path.slice(path.lastIndexOf("/") + 1);
436 return EXTENSIONLESS_FILE_NAMES.has(basename) || FILE_EXTENSION_PATTERN.test(basename.trimEnd());
437}
438
439function looksLikeFilePath(path: string, authoredPath: string): boolean {
440 if (isWindowsAbsolutePath(path) || RELATIVE_PATH_PREFIX_PATTERN.test(path)) return true;
441 if (path.startsWith("/")) return looksLikePosixFilesystemPath(authoredPath);
442 if (EXTENSIONLESS_FILE_NAMES.has(path)) return true;
443 return RELATIVE_FILE_PATH_PATTERN.test(authoredPath) || RELATIVE_FILE_NAME_PATTERN.test(path);
444}
445
446function hasExternalScheme(path: string): boolean {
447 if (isWindowsAbsolutePath(path)) return false;
448 const match = path.match(EXTERNAL_SCHEME_PATTERN);
449 if (!match) return false;
450 const rest = match[2] ?? "";
451 if (rest.startsWith("//")) return true;
452 return !POSITION_ONLY_PATTERN.test(rest);
453}
454
455export function parseMarkdownSandboxFileLink(href: string): FilePathPosition | null {
456 const prefix = /^sandbox:(?=\/)/i.exec(href);
457 if (!prefix) return null;
458
459 const source = splitMarkdownLinkSearchAndHash(href.slice(prefix[0].length));
460 const path = safeDecodeURIComponent(source.path);
461 // A sandbox URI names a local file on the thread host, never a network share.
462 if (path.length < 2 || isNetworkPath(path) || path.includes("\0") || /[\t\r\n]/.test(path)) {
463 return null;
464 }
465 const position = splitFilePathPosition(
466 stripSlashPrefixedWindowsDrive(path),
467 safeDecodeURIComponent(source.hash),
468 );
469 return ELIDED_PATH_SEGMENT_PATTERN.test(position.path) ? null : position;
470}
471
472export function parseMarkdownFileLink(href: string): FilePathPosition | null {
473 const normalized = normalizeMarkdownLinkDestination(href);
474 if (normalized.length === 0 || normalized.startsWith("#") || normalized.startsWith("//")) {
475 return null;
476 }
477
478 const sandboxFile = parseMarkdownSandboxFileLink(normalized);
479 if (sandboxFile) return sandboxFile;
480
481 const fileUrl = normalized.toLowerCase().startsWith("file:")
482 ? parseFileUrlHref(normalized)
483 : null;
484 const source = fileUrl ?? splitMarkdownLinkSearchAndHash(normalized);
485 const path = stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(trimAscii(source.path)));
486 const hash = safeDecodeURIComponent(trimAscii(source.hash));
487 if (path.length === 0 || hasExternalScheme(path)) return null;
488
489 const position = parseFilePathLink(path, hash, fileUrl !== null);
490 // `src\a.ts` is Windows-relative. A link that already parses keeps its spelling, since POSIX
491 // names may contain `\`; a rooted `\\host` or `\foo` would change root if rewritten.
492 if (position || /^[\\/]/.test(path) || isWindowsAbsolutePath(path)) return position;
493 return path.includes("\\") ? parseFilePathLink(path.replaceAll("\\", "/"), hash) : null;
494}
495
496function parseFilePathLink(path: string, hash: string, isFileUrl = false): FilePathPosition | null {
497 const position = splitFilePathPosition(path, hash);
498 return !ELIDED_PATH_SEGMENT_PATTERN.test(position.path) &&
499 (isFileUrl || looksLikeFilePath(position.path, path))
500 ? position
501 : null;
502}
503
504const BACKTICK_RUN_PATTERN = /`+/g;
505
506function collectLineCodeSpans(line: string, spans: string[]) {
507 const runs = line.includes("`") ? [...line.matchAll(BACKTICK_RUN_PATTERN)] : [];
508 if (runs.length < 2) return;
509 const runsByLength = new Map<number, number[]>();
510 for (const [i, run] of runs.entries()) {
511 const indexes = runsByLength.get(run[0].length);
512 if (indexes) indexes.push(i);
513 else runsByLength.set(run[0].length, [i]);
514 }
515 const cursorByLength = new Map<number, number>();
516 let textStart = 0;
517 for (let i = 0; i < runs.length; i += 1) {
518 const run = runs[i]!;
519 let backslashes = 0;
520 while (run.index - backslashes > textStart && line[run.index - backslashes - 1] === "\\") {
521 backslashes += 1;
522 }
523 // An escaped backtick is literal outside code spans; only closers keep backslashes literal.
524 const length = run[0].length - (backslashes % 2);
525 const candidates = runsByLength.get(length) ?? [];
526 let cursor = cursorByLength.get(length) ?? 0;
527 while (cursor < candidates.length && candidates[cursor]! <= i) cursor += 1;
528 cursorByLength.set(length, cursor);
529 const close = candidates[cursor];
530 if (length === 0 || close === undefined) continue;
531 const span = line.slice(run.index + run[0].length, runs[close]!.index).trim();
532 if (span) spans.push(span);
533 i = close;
534 textStart = runs[close]!.index + runs[close]![0].length;
535 }
536}
537
538// A backtick fence's info string cannot contain a backtick: "```a```" is a code span.
539const FENCE_OPENER_PATTERN = /^(`{3,}(?![^`]*`)|~{3,})/;
540const FENCE_CLOSER_PATTERN = /^(`{3,}|~{3,}) *$/;
541const LIST_MARKER_PATTERN = /^(?:[-+*]|(\d{1,9})[.)])( +|$)/;
542const THEMATIC_BREAK_PATTERN = /^([-*_]) *(?:\1 *){2,}$/;
543const ATX_HEADING_PATTERN = /^#{1,6}(?: |$)/;
544const SETEXT_UNDERLINE_PATTERN = /^(?:=+|-+) *$/;
545// What ends a paragraph, so a line starting with one is never its lazy continuation.
546const PARAGRAPH_INTERRUPTION_PATTERN =
547 /^(?:>|`{3,}(?![^`]*`)|~{3,}|(?:[-+*]|\d{1,9}[.)])(?: |$)|#{1,6}(?: |$)|([-*_]) *(?:\1 *){2,}$)/;
548
549const FOOTNOTE_DEFINITION_PATTERN = /^\[\^(?:\\[\\[\]]|\\(?![\\[\]])|[^ \t\r\n\\[\]]){1,999}\]: */;
550const TABLE_DELIMITER_PATTERN = /^\|? *:?-+:? *(?:\| *:?-+:? *)*\|? *$/;
551
552const BLOCKQUOTE = 0;
553// A recovered list block continues within the original code block's four-column prefix.
554const RECOVERED_LIST_CODE = -4;
555
556function tableColumnCount(row: string): number {
557 const trimmed = row.trimEnd();
558 let columns = 1;
559 for (const match of trimmed.matchAll(/\\[\\|]|\|/g)) {
560 if (match[0] === "|" && match.index > 0 && match.index < trimmed.length - 1) columns += 1;
561 }
562 return columns;
563}
564
565function isTableDelimiter(header: string, line: string): boolean {
566 return (
567 header.trimEnd() !== "|" &&
568 /[|:]/.test(line) &&
569 TABLE_DELIMITER_PATTERN.test(line) &&
570 tableColumnCount(line) === tableColumnCount(header)
571 );
572}
573
574function expandMarkdownLine(line: string): string {
575 const source = line.endsWith("\r") ? line.slice(0, -1) : line;
576 if (!source.includes("\t")) return source;
577 let column = 0;
578 return source.replace(/\t|[^\t]+/g, (part) => {
579 const expanded = part === "\t" ? " ".repeat(4 - (column % 4)) : part;
580 column += expanded.length;
581 return expanded;
582 });
583}
584
585function markdownIndent(source: string, position: number): number {
586 let indent = 0;
587 while (source[position + indent] === " ") indent += 1;
588 return indent;
589}
590
591function blockquoteContentStart(source: string, marker: number): number {
592 return marker + (source[marker + 1] === " " ? 2 : 1);
593}
594
595function matchMarkdownContainers(
596 source: string,
597 containers: readonly number[],
598 blankEndsItemAt = -1,
599) {
600 let position = 0;
601 let matched = 0;
602 for (const container of containers) {
603 const indent = markdownIndent(source, position);
604 const first = source[position + indent];
605 if (container === BLOCKQUOTE) {
606 if (indent > 3 || first !== ">") break;
607 position = blockquoteContentStart(source, position + indent);
608 } else if (first === undefined) {
609 if (matched === blankEndsItemAt) break;
610 } else if (indent >= Math.abs(container)) {
611 position += Math.abs(container);
612 } else {
613 break;
614 }
615 matched += 1;
616 }
617 return { position, matched };
618}
619
620// List recovery prefixes the first line as prose. A table delimiter or a setext underline
621// can still turn that first block into a table or heading, which the renderer leaves literal.
622function recoveredListStartsWithParagraph(
623 lines: readonly string[],
624 index: number,
625 header: string,
626 containers: readonly number[],
627): boolean {
628 for (let next = index + 1; next < lines.length; next += 1) {
629 const source = expandMarkdownLine(lines[next]!);
630 const { position, matched } = matchMarkdownContainers(source, containers);
631 if (matched < containers.length) break;
632 const indent = markdownIndent(source, position);
633 const content = source.slice(position + indent);
634 if (!content || indent < 4) break;
635 if (indent >= 8) continue;
636 if (SETEXT_UNDERLINE_PATTERN.test(content)) return false;
637 if (PARAGRAPH_INTERRUPTION_PATTERN.test(content) || FOOTNOTE_DEFINITION_PATTERN.test(content)) {
638 break;
639 }
640 if (next === index + 1 && isTableDelimiter(`x ${header}`, content)) return false;
641 }
642 return true;
643}
644
645// Normalize lone CR without changing offsets or splitting CRLF into two line endings.
646function normalizeLoneCarriageReturns(text: string): string {
647 return text.replace(/\r(?!\n)/g, "\n");
648}
649
650export function extractInlineCodeSpans(text: string): string[] {
651 if (!text.includes("`")) return [];
652 const markdown = normalizeLoneCarriageReturns(text);
653 let masked = "";
654 let copied = 0;
655 if (markdown.includes("](")) {
656 visitLinkTails(markdown, (_href, start, end) => {
657 masked += markdown.slice(copied, start) + markdown.slice(start, end).replaceAll("`", " ");
658 copied = end;
659 });
660 }
661 const spans: string[] = [];
662 const inlineMarkdown = copied > 0 ? masked + markdown.slice(copied) : undefined;
663 visitMarkdownLines(markdown, (line, start, code) => {
664 if (code) return;
665 collectLineCodeSpans(inlineMarkdown?.slice(start, start + line.length) ?? line, spans);
666 });
667 return spans;
668}
669
670/**
671 * Visits text and code lines. Blockquotes and list items are tracked line by line as
672 * CommonMark nests them, because a fence closes only at its own container's indentation and ends
673 * with that container. A full parse would be exact but costs about 100x this scan, which runs on
674 * every streamed chunk.
675 */
676function visitMarkdownLines(
677 text: string,
678 visit: (line: string, start: number, code: boolean) => void,
679) {
680 // Open containers, outermost first: blockquotes, indented content, and recovered list code.
681 const containers: number[] = [];
682 let fence: { marker: string; indented: boolean } | null = null;
683 // Whether the previous line left a paragraph open, and whether indented code is still open:
684 // micromark lets neither be interrupted by an empty list item or one not numbered 1.
685 let paragraph = false;
686 let indentedCode = false;
687 // A table has a header candidate until its delimiter row opens the body.
688 let table: { depth: number; header?: string } | undefined;
689 // Depth of an item that has only its marker so far; a blank line next ends it.
690 let emptyItemDepth = 0;
691 let lineStart = 0;
692 const lines = text.split("\n");
693 for (const [index, line] of lines.entries()) {
694 const previousTable = table;
695 table = undefined;
696 const start = lineStart;
697 lineStart += line.length + 1;
698 const source = expandMarkdownLine(line);
699 const containerCount = containers.length;
700 const prefix = matchMarkdownContainers(source, containers, emptyItemDepth - 1);
701 const { matched } = prefix;
702 let { position } = prefix;
703 emptyItemDepth = 0;
704 let indent = 0;
705 let content = "";
706 const readIndent = () => {
707 indent = markdownIndent(source, position);
708 content = source.slice(position + indent);
709 };
710 readIndent();
711
712 if (fence) {
713 if (matched === containers.length) {
714 if (content === "") continue;
715 // A fence written inside indented code ends with that code.
716 if (!fence.indented || indent >= 4) {
717 visit(line, start, true);
718 const closer = FENCE_CLOSER_PATTERN.exec(content)?.[1];
719 if (
720 closer?.startsWith(fence.marker[0]!) &&
721 closer.length >= fence.marker.length &&
722 (fence.indented || indent <= 3)
723 ) {
724 fence = null;
725 paragraph = false;
726 }
727 continue;
728 }
729 }
730 fence = null;
731 paragraph = false;
732 }
733
734 if (matched < containers.length) {
735 if (
736 paragraph &&
737 content !== "" &&
738 containers.lastIndexOf(RECOVERED_LIST_CODE) < matched &&
739 (indent >= 4 ||
740 (!PARAGRAPH_INTERRUPTION_PATTERN.test(content) &&
741 !FOOTNOTE_DEFINITION_PATTERN.test(content)))
742 ) {
743 visit(line, start, false);
744 continue;
745 }
746 containers.length = matched;
747 paragraph = false;
748 indentedCode = false;
749 }
750 // micromark decides this once per line, and not at all on a line that closed a container.
751 const interrupts = paragraph || indentedCode;
752 const closedContainer = matched < containerCount;
753
754 for (;;) {
755 if (content === "") {
756 paragraph = false;
757 break;
758 }
759 const opener = FENCE_OPENER_PATTERN.exec(content)?.[1];
760 if (indent >= 4) {
761 if (!paragraph && !closedContainer) indentedCode = true;
762 // Inside a paragraph an indented line is text, where only a backtick run opens code (a span).
763 if (opener && (!paragraph || opener[0] === "`")) {
764 fence = { marker: opener, indented: true };
765 visit(line, start, true);
766 } else {
767 visit(line, start, !paragraph);
768 }
769 break;
770 }
771 indentedCode = false;
772 if (opener) {
773 fence = { marker: opener, indented: false };
774 visit(line, start, true);
775 break;
776 }
777 if (content[0] === ">") {
778 containers.push(BLOCKQUOTE);
779 position = blockquoteContentStart(source, position + indent);
780 paragraph = false;
781 readIndent();
782 continue;
783 }
784 if (THEMATIC_BREAK_PATTERN.test(content)) {
785 paragraph = false;
786 break;
787 }
788 const footnote = FOOTNOTE_DEFINITION_PATTERN.exec(content);
789 if (footnote) {
790 containers.push(4);
791 position += indent + footnote[0].length;
792 paragraph = false;
793 readIndent();
794 continue;
795 }
796 const item = LIST_MARKER_PATTERN.exec(content);
797 const emptyItem = item?.[0].length === content.length;
798 // Only a non-empty item, numbered 1 if ordered, starts a list in the middle of a block.
799 if (
800 item &&
801 !(interrupts && (emptyItem || (item[1] !== undefined && Number(item[1]) !== 1)))
802 ) {
803 const padding = item[2]!.length;
804 const width = item[0].length - padding + (emptyItem || padding > 4 ? 1 : padding);
805 containers.push(indent + width);
806 if (emptyItem) emptyItemDepth = containers.length;
807 position += indent + width;
808 paragraph = false;
809 readIndent();
810 // The renderer recovers same-line indented list code with whitespace left in its value.
811 if (
812 !emptyItem &&
813 padding > 5 &&
814 recoveredListStartsWithParagraph(lines, index, content, containers)
815 ) {
816 containers.push(RECOVERED_LIST_CODE);
817 visit(line, start, false);
818 paragraph = true;
819 break;
820 }
821 continue;
822 }
823 visit(line, start, false);
824 if (
825 ATX_HEADING_PATTERN.test(content) ||
826 (paragraph && SETEXT_UNDERLINE_PATTERN.test(content))
827 ) {
828 paragraph = false;
829 } else if (
830 previousTable?.depth === containers.length &&
831 !closedContainer &&
832 (previousTable.header === undefined || isTableDelimiter(previousTable.header, content))
833 ) {
834 table = { depth: containers.length };
835 paragraph = false;
836 } else {
837 table = { depth: containers.length, header: content };
838 paragraph = true;
839 }
840 break;
841 }
842 }
843}
844
845function markdownRunEndFinder(markdown: string, delimiter: RegExp) {
846 let runStart = -1;
847 let runEnd = -1;
848 return (start: number) => {
849 if (start >= runStart && start <= runEnd) return runEnd;
850 delimiter.lastIndex = start;
851 runStart = start;
852 let match = delimiter.exec(markdown);
853 while (match?.[0].length === 2 && match[0][0] === "\\") match = delimiter.exec(markdown);
854 runEnd = match?.index ?? markdown.length;
855 return runEnd;
856 };
857}
858
859function markdownLinkTailScanner(markdown: string) {
860 // A blank line ends the paragraph, so no part of a link's tail runs past one.
861 const whitespaceEnd = markdownRunEndFinder(markdown, /[^ \t\r\n]|\n[ \t\r]*\n/g);
862 // Escape pairs (`\"`, `\\`) match so the finder can skip them.
863 const doubleQuoteEnd = markdownRunEndFinder(markdown, /\\[\\"]|"|\n[ \t\r]*\n/g);
864 const singleQuoteEnd = markdownRunEndFinder(markdown, /\\[\\']|'|\n[ \t\r]*\n/g);
865 const parenthesisEnd = markdownRunEndFinder(markdown, /\\[\\()]|[()]|\n[ \t\r]*\n/g);
866 const titleWhitespaceEnd = markdownRunEndFinder(markdown, /[^ \t\r\n]|\n[ \t\r]*\n/g);
867 return (start: number) => {
868 const end = whitespaceEnd(start);
869 const quote = markdown[end];
870 if (quote === ")") return end + 1;
871 if (end === start || (quote !== '"' && quote !== "'" && quote !== "(")) return null;
872 const titleEnd =
873 quote === '"' ? doubleQuoteEnd : quote === "'" ? singleQuoteEnd : parenthesisEnd;
874 const quoteEnd = titleEnd(end + 1);
875 if (markdown[quoteEnd] !== (quote === "(" ? ")" : quote)) return null;
876 const close = titleWhitespaceEnd(quoteEnd + 1);
877 return markdown[close] === ")" ? close + 1 : null;
878 };
879}
880
881// micromark's own nesting limit. It also keeps link scanning linear: a scan only runs past another
882// link's opening parenthesis while that parenthesis counts toward this depth.
883const MAX_BARE_DESTINATION_PAREN_DEPTH = 32;
884
885function bareMarkdownLinkDestinationEnd(markdown: string, start: number): number | null {
886 // Destinations end at ASCII spaces and controls but not NUL, which micromark reads as U+FFFD.
887 const delimiter = /[\x01-\x20\x7f()\\]/g;
888 delimiter.lastIndex = start;
889 let depth = 0;
890 while (true) {
891 const index = delimiter.exec(markdown)?.index ?? markdown.length;
892 const char = markdown[index];
893 if (char === "\\") {
894 if (/[()\\]/.test(markdown[index + 1] ?? "")) delimiter.lastIndex = index + 2;
895 } else if (char === "(") {
896 if (depth === MAX_BARE_DESTINATION_PAREN_DEPTH) return null;
897 depth += 1;
898 } else if (char === ")" && depth > 0) {
899 depth -= 1;
900 } else {
901 return depth === 0 ? index : null;
902 }
903 }
904}
905
906export function markdownLinkDestinationScanner(markdown: string) {
907 const whitespaceEnd = markdownRunEndFinder(markdown, /[^ \t\r\n]|\n[ \t\r]*\n/g);
908 const angleEnd = markdownRunEndFinder(markdown, /\\[\\<>]|[<>\r\n]/g);
909 // Separate caches keep scans moving forward when angle destinations fall back to bare ones.
910 const angleTail = markdownLinkTailScanner(markdown);
911 const bareTail = markdownLinkTailScanner(markdown);
912 return (start: number) => {
913 if (markdown[start] !== "(") return null;
914 const hrefStart = whitespaceEnd(start + 1);
915 if (markdown[hrefStart] === "<") {
916 const hrefEnd = angleEnd(hrefStart + 1);
917 if (hrefEnd > hrefStart + 1 && markdown[hrefEnd] === ">") {
918 const end = angleTail(hrefEnd + 1);
919 if (end !== null) return { hrefStart: hrefStart + 1, hrefEnd, end };
920 }
921 }
922 const hrefEnd = bareMarkdownLinkDestinationEnd(markdown, hrefStart);
923 if (hrefEnd === null) return null;
924 const end = bareTail(hrefEnd);
925 return end === null ? null : { hrefStart, hrefEnd, end };
926 };
927}
928
929// Code block lines become spaces, keeping every offset.
930function blankCodeBlocks(text: string): string {
931 if (!/ {4}|\t|```|~~~/.test(text)) return text;
932 let blanked = "";
933 let copied = 0;
934 visitMarkdownLines(text, (line, start, code) => {
935 if (!code) return;
936 blanked += text.slice(copied, start) + line.replace(/[^\r]/g, " ");
937 copied = start + line.length;
938 });
939 return blanked + text.slice(copied);
940}
941
942// Labels may nest balanced brackets (`[the [docs] guide](...)`), and the composer escapes them
943// (`[\[id\].tsx](...)`), so `\[` and `\]` never count. A blank line ends the paragraph and its labels.
944function visitLinkTails(text: string, visit: (href: string, from: number, to: number) => void) {
945 const markdown = blankCodeBlocks(text);
946 const scanDestination = markdownLinkDestinationScanner(markdown);
947 const paragraphEnd = markdownRunEndFinder(markdown, /\n[ \t\r]*\n/g);
948 // A code span closes at the next run of as many backticks in its paragraph.
949 const closersByLength = new Map<number, { ends: number[]; next: number }>();
950 for (const run of markdown.matchAll(/`+/g)) {
951 const closers = closersByLength.get(run[0].length) ?? { ends: [], next: 0 };
952 closers.ends.push(run.index + run[0].length);
953 closersByLength.set(run[0].length, closers);
954 }
955 // Only punctuation forms an escape pair. A newline still starts a paragraph break.
956 const bracket = /\\[!-/:-@[-`{-~]|!\[|[[\]]|`+|\n[ \t\r]*\n/g;
957 const openers: boolean[] = [];
958 for (let match = bracket.exec(markdown); match; match = bracket.exec(markdown)) {
959 if (match[0].startsWith("\\")) continue;
960 if (match[0].startsWith("`")) {
961 const length = match[0].length;
962 const closers = closersByLength.get(length) ?? { ends: [], next: 0 };
963 while ((closers.ends[closers.next] ?? Infinity) - length < bracket.lastIndex) closers.next++;
964 const end = closers.ends[closers.next];
965 if (end !== undefined && end - length <= paragraphEnd(bracket.lastIndex)) {
966 bracket.lastIndex = end;
967 }
968 } else if (match[0].startsWith("\n")) {
969 openers.length = 0;
970 } else if (match[0].endsWith("[")) {
971 openers.push(match[0] === "![");
972 } else if (openers.length > 0) {
973 const image = openers.pop();
974 const destination = scanDestination(match.index + 1);
975 if (!destination) continue;
976 // A link cannot contain a link, but it can contain an image.
977 if (!image) openers.length = 0;
978 bracket.lastIndex = destination.end;
979 const href = markdown.slice(destination.hrefStart, destination.hrefEnd);
980 visit(href, match.index + 1, destination.end);
981 }
982 }
983}
984
985export function extractMarkdownLinkHrefs(text: string): string[] {
986 const hrefs: string[] = [];
987 visitLinkTails(normalizeLoneCarriageReturns(text), (href) => {
988 if (href) hrefs.push(href);
989 });
990 return hrefs;
991}
992
993export function resolveMarkdownFileLinkTarget(
994 href: string | undefined,
995 cwd?: string,
996 baseDir: string | undefined = cwd,
997): string | null {
998 return resolveMarkdownFileLink(href, cwd, baseDir)?.targetPath ?? null;
999}
1000
1001/** Resolves the displayed position and the editor target, which opens at the start line. */
1002export function resolveMarkdownFileLink(
1003 href: string | undefined,
1004 cwd?: string,
1005 baseDir: string | undefined = cwd,
1006): { sourcePath: string; targetPath: string; position: FilePathPosition } | null {
1007 const source = href ? parseMarkdownFileLink(href) : null;
1008 if (!source) return null;
1009
1010 const targetPath = resolveParsedFileLinkTarget(source, cwd, baseDir);
1011 if (!targetPath) return null;
1012 return {
1013 sourcePath: source.path,
1014 targetPath,
1015 position: {
1016 ...splitFilePathPosition(targetPath),
1017 ...(source.endLine !== undefined ? { endLine: source.endLine } : {}),
1018 },
1019 };
1020}
1021
1022function resolveParsedFileLinkTarget(
1023 target: FilePathPosition,
1024 cwd: string | undefined,
1025 baseDir: string | undefined,
1026): string | null {
1027 const pathWithPosition = formatFilePathPosition(target);
1028 if (!isRelativeFilePath(pathWithPosition)) {
1029 // Opening a network path makes Windows sign in to its host with the user's
1030 // NTLM credentials, so only the project's own share becomes a file link.
1031 return isNetworkPath(target.path) && workspaceRelativeFilePath(target.path, cwd) === null
1032 ? null
1033 : pathWithPosition;
1034 }
1035 if (!baseDir) return null;
1036 return resolvePathLinkTarget(pathWithPosition, baseDir);
1037}
1038
1039export function isWindowsDrivePathHref(href: string): boolean {
1040 return /^[A-Za-z]:[\\/]/.test(safeDecodeURIComponent(href));
1041}
1042
1043// Punctuation and symbols from CJK Symbols and Punctuation and from Halfwidth and Fullwidth Forms,
1044// plus the Arabic-script comma, semicolon, question mark, and full stop.
1045export const SCRIPT_PUNCTUATION = /(?=[ -〿-،؛؟۔])[\p{P}\p{S}]/u;
1046
1047/** Where ASCII text runs into such a mark, or -1. Unicode before it may make the mark part of the text. */
1048export function scriptPunctuationAfterAscii(text: string): number {
1049 const index = text.search(/[^!-~]/u);
1050 return index > 0 && SCRIPT_PUNCTUATION.test(text.charAt(index)) ? index : -1;
1051}
1052
1053// Bare prose paths need a filesystem root or a position, so `/api/users.json` stays a route,
1054// and a file-shaped last segment.
1055export function absoluteFilePathMatches(text: string): Array<{ index: number; path: string }> {
1056 const paths: Array<{ index: number; path: string }> = [];
1057 for (const match of text.matchAll(/(^|[\s(["'])(\/[^\s<>"'`]+)/g)) {
1058 const cut = scriptPunctuationAfterAscii(match[2]!);
1059 const source = cut > 0 ? match[2]!.slice(0, cut) : match[2]!;
1060 let parentheses = 0;
1061 let brackets = 0;
1062 for (const character of source) {
1063 if (character === "(") parentheses += 1;
1064 if (character === ")") parentheses -= 1;
1065 if (character === "[") brackets += 1;
1066 if (character === "]") brackets -= 1;
1067 }
1068 let end = source.length;
1069 while (end > 0) {
1070 const character = source[end - 1]!;
1071 if (character === ")" && parentheses < 0) parentheses += 1;
1072 else if (character === "]" && brackets < 0) brackets += 1;
1073 else if (!".,;!?:".includes(character)) break;
1074 end -= 1;
1075 }
1076 const path = source.slice(0, end);
1077 // Trimming `/tmp/a/....` to `/tmp/a/` would hide its elided segment.
1078 if (path.endsWith("/") && source.startsWith("...", end)) continue;
1079 if (
1080 !POSIX_FILE_ROOT_PREFIXES.some((prefix) => path.startsWith(prefix)) &&
1081 !POSITION_SUFFIX_PATTERN.test(path)
1082 )
1083 continue;
1084 // Prose ends a path at whitespace, so `/Users/me/Library/Application Support/...` must not link.
1085 const hashPosition = HASH_POSITION_PATTERN.exec(path)?.[0];
1086 const filePath = hashPosition ? path.slice(0, -hashPosition.length) : path;
1087 const basename = filePath.slice(filePath.lastIndexOf("/") + 1);
1088 if (
1089 !POSITION_SUFFIX_PATTERN.test(path) &&
1090 !FILE_EXTENSION_PATTERN.test(basename) &&
1091 !EXTENSIONLESS_FILE_NAMES.has(basename)
1092 )
1093 continue;
1094 if (hashPosition && /[?#]/.test(filePath)) continue;
1095 const parsed = parseMarkdownFileLink(path);
1096 if (!parsed || (hashPosition && parsed.line === undefined)) continue;
1097 paths.push({ index: match.index + match[1]!.length, path });
1098 }
1099 return paths;
1100}
1101
1102// A drive path that has not reached whitespace yet: `C:`, `C:\Users\me`, `C:/work`.
1103export const UNFINISHED_DRIVE_PATH = /(?:^|\W)[A-Za-z]:(?:[\\/]\S*)?$/;