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"'`<>]+/giu;
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" && isTerminalUrl(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
105export function 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 isTerminalUrl(value: string): boolean {
176 return /^https?:\/\//iu.test(value);
177}
178
179export function collectWrappedTerminalLinkLine(
180 bufferLineNumber: number,
181 getLine: (bufferLineIndex: number) => TerminalBufferLineLike | null | undefined,
182): WrappedTerminalLinkLine | null {
183 const anchorLine = getLine(bufferLineNumber - 1);
184 if (!anchorLine) return null;
185
186 let startBufferLineNumber = bufferLineNumber;
187 let startLine = anchorLine;
188
189 while (startBufferLineNumber > 1 && startLine.isWrapped) {
190 const previousLine = getLine(startBufferLineNumber - 2);
191 if (!previousLine) return null;
192 startBufferLineNumber -= 1;
193 startLine = previousLine;
194 }
195
196 const segments: WrappedTerminalLinkLineSegment[] = [];
197 let nextStartIndex = 0;
198 let currentBufferLineNumber = startBufferLineNumber;
199
200 while (true) {
201 const currentLine = getLine(currentBufferLineNumber - 1);
202 if (!currentLine) break;
203
204 const nextLine = getLine(currentBufferLineNumber);
205 const hasWrappedContinuation = nextLine?.isWrapped === true;
206 const text = currentLine.translateToString(!hasWrappedContinuation);
207
208 segments.push({
209 bufferLineNumber: currentBufferLineNumber,
210 text,
211 startIndex: nextStartIndex,
212 endIndex: nextStartIndex + text.length,
213 });
214 nextStartIndex += text.length;
215
216 if (!hasWrappedContinuation) break;
217 currentBufferLineNumber += 1;
218 }
219
220 return {
221 text: segments.map((segment) => segment.text).join(""),
222 segments,
223 };
224}
225
226function resolveCharacterPosition(
227 segments: ReadonlyArray<WrappedTerminalLinkLineSegment>,
228 characterIndex: number,
229): TerminalLinkBufferPosition {
230 for (const segment of segments) {
231 if (characterIndex < segment.endIndex) {
232 return {
233 x: characterIndex - segment.startIndex + 1,
234 y: segment.bufferLineNumber,
235 };
236 }
237 }
238
239 const lastSegment = segments[segments.length - 1];
240 return {
241 x: Math.max(lastSegment?.text.length ?? 0, 1),
242 y: lastSegment?.bufferLineNumber ?? 1,
243 };
244}
245
246export function resolveWrappedTerminalLinkRange(
247 wrappedLine: WrappedTerminalLinkLine,
248 match: Pick<TerminalLinkMatch, "start" | "end">,
249): TerminalLinkBufferRange {
250 return {
251 start: resolveCharacterPosition(wrappedLine.segments, match.start),
252 end: resolveCharacterPosition(wrappedLine.segments, match.end - 1),
253 };
254}
255
256export function wrappedTerminalLinkRangeIntersectsBufferLine(
257 range: TerminalLinkBufferRange,
258 bufferLineNumber: number,
259): boolean {
260 return range.start.y <= bufferLineNumber && bufferLineNumber <= range.end.y;
261}
262
263export function isTerminalLinkActivation(
264 event: Pick<MouseEvent, "metaKey" | "ctrlKey">,
265 platform = typeof navigator === "undefined" ? "" : navigator.platform,
266): boolean {
267 if (platform.length === 0) return false;
268 return isMacPlatform(platform)
269 ? event.metaKey && !event.ctrlKey
270 : event.ctrlKey && !event.metaKey;
271}
272
273export function resolvePathLinkTarget(rawPath: string, cwd: string): string {
274 const { path, line, column } = splitPathAndPosition(rawPath);
275
276 let resolvedPath = path;
277 if (path.startsWith("~/")) {
278 const home = inferHomeFromCwd(cwd);
279 if (home) {
280 const separator: "/" | "\\" = isWindowsPathStyle(home) ? "\\" : "/";
281 resolvedPath = joinPath(home, path.slice(2), separator);
282 }
283 } else if (!isAbsolutePath(path)) {
284 const separator: "/" | "\\" = isWindowsPathStyle(cwd) ? "\\" : "/";
285 resolvedPath = joinPath(cwd, path, separator);
286 }
287
288 if (!line) return resolvedPath;
289 return `${resolvedPath}:${line}${column ? `:${column}` : ""}`;
290}