Open History to see the last commit
1import { isMacPlatform } from "./lib/utils";
2
3export type TerminalLinkKind = "url" | "path";
4
5export interface TerminalLinkMatch {
6 kind: TerminalLinkKind;
7 text: string;
8 start: number;
9 end: number;
10}
11
12export interface TerminalLinkBufferPosition {
13 x: number;
14 y: number;
15}
16
17export interface TerminalLinkBufferRange {
18 start: TerminalLinkBufferPosition;
19 end: TerminalLinkBufferPosition;
20}
21
22export interface TerminalBufferLineLike {
23 readonly isWrapped?: boolean;
24 translateToString(trimRight?: boolean): string;
25}
26
27export interface WrappedTerminalLinkLineSegment {
28 bufferLineNumber: number;
29 text: string;
30 startIndex: number;
31 endIndex: number;
32}
33
34export interface WrappedTerminalLinkLine {
35 text: string;
36 segments: ReadonlyArray<WrappedTerminalLinkLineSegment>;
37}
38
39const URL_PATTERN = /https?:\/\/[^\s"'`<>]+/g;
40const FILE_PATH_PATTERN =
41 /(?:~\/|\.{1,2}\/|\/|[A-Za-z]:[\\/]|\\\\)[^\s"'`<>]+|[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+(?::\d+){0,2}/g;
42const TRAILING_PUNCTUATION_PATTERN = /[.,;!?]+$/;
43
44function trimClosingDelimiters(value: string): string {
45 let output = value.replace(TRAILING_PUNCTUATION_PATTERN, "");
46 if (output.length === 0) return output;
47
48 const trimUnbalanced = (open: string, close: string) => {
49 while (output.endsWith(close)) {
50 const opens = output.split(open).length - 1;
51 const closes = output.split(close).length - 1;
52 if (opens >= closes) return;
53 output = output.slice(0, -1);
54 }
55 };
56
57 trimUnbalanced("(", ")");
58 trimUnbalanced("[", "]");
59 trimUnbalanced("{", "}");
60 return output;
61}
62
63function overlaps(a: { start: number; end: number }, b: { start: number; end: number }): boolean {
64 return a.start < b.end && b.start < a.end;
65}
66
67function collectMatches(
68 line: string,
69 kind: TerminalLinkKind,
70 pattern: RegExp,
71 existing: TerminalLinkMatch[],
72): TerminalLinkMatch[] {
73 const matches: TerminalLinkMatch[] = [];
74 pattern.lastIndex = 0;
75
76 for (const rawMatch of line.matchAll(pattern)) {
77 const raw = rawMatch[0];
78 const start = rawMatch.index ?? -1;
79 if (start < 0 || raw.length === 0) continue;
80
81 const trimmed = trimClosingDelimiters(raw);
82 if (trimmed.length === 0) continue;
83 if (kind === "path" && /^https?:\/\//i.test(trimmed)) continue;
84
85 const candidate: TerminalLinkMatch = {
86 kind,
87 text: trimmed,
88 start,
89 end: start + trimmed.length,
90 };
91
92 const collides = [...existing, ...matches].some((other) => overlaps(candidate, other));
93 if (collides) continue;
94
95 matches.push(candidate);
96 }
97
98 return matches;
99}
100
101function isWindowsAbsolutePath(value: string): boolean {
102 return /^[A-Za-z]:[\\/]/.test(value) || value.startsWith("\\\\");
103}
104
105function isAbsolutePath(value: string): boolean {
106 return value.startsWith("/") || isWindowsAbsolutePath(value);
107}
108
109function isWindowsPathStyle(value: string): boolean {
110 return isWindowsAbsolutePath(value) || /[A-Za-z]:\\/.test(value);
111}
112
113function joinPath(base: string, next: string, separator: "/" | "\\"): string {
114 const cleanBase = base.replace(/[\\/]+$/, "");
115 if (separator === "\\") {
116 return `${cleanBase}\\${next.replaceAll("/", "\\")}`;
117 }
118 return `${cleanBase}/${next.replace(/^\/+/, "")}`;
119}
120
121function inferHomeFromCwd(cwd: string): string | undefined {
122 const posixUser = cwd.match(/^\/Users\/([^/]+)/);
123 if (posixUser?.[1]) {
124 return `/Users/${posixUser[1]}`;
125 }
126
127 const posixHome = cwd.match(/^\/home\/([^/]+)/);
128 if (posixHome?.[1]) {
129 return `/home/${posixHome[1]}`;
130 }
131
132 const windowsUser = cwd.match(/^([A-Za-z]:\\Users\\[^\\]+)/);
133 if (windowsUser?.[1]) {
134 return windowsUser[1];
135 }
136
137 return undefined;
138}
139
140export function splitPathAndPosition(value: string): {
141 path: string;
142 line: string | undefined;
143 column: string | undefined;
144} {
145 let path = value;
146 let column: string | undefined;
147 let line: string | undefined;
148
149 const columnMatch = path.match(/:(\d+)$/);
150 if (!columnMatch?.[1]) {
151 return { path, line: undefined, column: undefined };
152 }
153
154 column = columnMatch[1];
155 path = path.slice(0, -columnMatch[0].length);
156
157 const lineMatch = path.match(/:(\d+)$/);
158 if (lineMatch?.[1]) {
159 line = lineMatch[1];
160 path = path.slice(0, -lineMatch[0].length);
161 } else {
162 line = column;
163 column = undefined;
164 }
165
166 return { path, line, column };
167}
168
169export function extractTerminalLinks(line: string): TerminalLinkMatch[] {
170 const urlMatches = collectMatches(line, "url", URL_PATTERN, []);
171 const pathMatches = collectMatches(line, "path", FILE_PATH_PATTERN, urlMatches);
172 return [...urlMatches, ...pathMatches].toSorted((a, b) => a.start - b.start);
173}
174
175export function collectWrappedTerminalLinkLine(
176 bufferLineNumber: number,
177 getLine: (bufferLineIndex: number) => TerminalBufferLineLike | null | undefined,
178): WrappedTerminalLinkLine | null {
179 const anchorLine = getLine(bufferLineNumber - 1);
180 if (!anchorLine) return null;
181
182 let startBufferLineNumber = bufferLineNumber;
183 let startLine = anchorLine;
184
185 while (startBufferLineNumber > 1 && startLine.isWrapped) {
186 const previousLine = getLine(startBufferLineNumber - 2);
187 if (!previousLine) return null;
188 startBufferLineNumber -= 1;
189 startLine = previousLine;
190 }
191
192 const segments: WrappedTerminalLinkLineSegment[] = [];
193 let nextStartIndex = 0;
194 let currentBufferLineNumber = startBufferLineNumber;
195
196 while (true) {
197 const currentLine = getLine(currentBufferLineNumber - 1);
198 if (!currentLine) break;
199
200 const nextLine = getLine(currentBufferLineNumber);
201 const hasWrappedContinuation = nextLine?.isWrapped === true;
202 const text = currentLine.translateToString(!hasWrappedContinuation);
203
204 segments.push({
205 bufferLineNumber: currentBufferLineNumber,
206 text,
207 startIndex: nextStartIndex,
208 endIndex: nextStartIndex + text.length,
209 });
210 nextStartIndex += text.length;
211
212 if (!hasWrappedContinuation) break;
213 currentBufferLineNumber += 1;
214 }
215
216 return {
217 text: segments.map((segment) => segment.text).join(""),
218 segments,
219 };
220}
221
222function resolveCharacterPosition(
223 segments: ReadonlyArray<WrappedTerminalLinkLineSegment>,
224 characterIndex: number,
225): TerminalLinkBufferPosition {
226 for (const segment of segments) {
227 if (characterIndex < segment.endIndex) {
228 return {
229 x: characterIndex - segment.startIndex + 1,
230 y: segment.bufferLineNumber,
231 };
232 }
233 }
234
235 const lastSegment = segments[segments.length - 1];
236 return {
237 x: Math.max(lastSegment?.text.length ?? 0, 1),
238 y: lastSegment?.bufferLineNumber ?? 1,
239 };
240}
241
242export function resolveWrappedTerminalLinkRange(
243 wrappedLine: WrappedTerminalLinkLine,
244 match: Pick<TerminalLinkMatch, "start" | "end">,
245): TerminalLinkBufferRange {
246 return {
247 start: resolveCharacterPosition(wrappedLine.segments, match.start),
248 end: resolveCharacterPosition(wrappedLine.segments, match.end - 1),
249 };
250}
251
252export function wrappedTerminalLinkRangeIntersectsBufferLine(
253 range: TerminalLinkBufferRange,
254 bufferLineNumber: number,
255): boolean {
256 return range.start.y <= bufferLineNumber && bufferLineNumber <= range.end.y;
257}
258
259export function isTerminalLinkActivation(
260 event: Pick<MouseEvent, "metaKey" | "ctrlKey">,
261 platform = typeof navigator === "undefined" ? "" : navigator.platform,
262): boolean {
263 if (platform.length === 0) return false;
264 return isMacPlatform(platform)
265 ? event.metaKey && !event.ctrlKey
266 : event.ctrlKey && !event.metaKey;
267}
268
269export function resolvePathLinkTarget(rawPath: string, cwd: string): string {
270 const { path, line, column } = splitPathAndPosition(rawPath);
271
272 let resolvedPath = path;
273 if (path.startsWith("~/")) {
274 const home = inferHomeFromCwd(cwd);
275 if (home) {
276 const separator: "/" | "\\" = isWindowsPathStyle(home) ? "\\" : "/";
277 resolvedPath = joinPath(home, path.slice(2), separator);
278 }
279 } else if (!isAbsolutePath(path)) {
280 const separator: "/" | "\\" = isWindowsPathStyle(cwd) ? "\\" : "/";
281 resolvedPath = joinPath(cwd, path, separator);
282 }
283
284 if (!line) return resolvedPath;
285 return `${resolvedPath}:${line}${column ? `:${column}` : ""}`;
286}