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