fix(terminal): linkify bare filenames from ls and stop underlining trailing whitespace (#983)

Port VSCode's two-detector pattern (MIT): the existing path pass handles
tokens with a `/`, and a new bare-word pass emits tentative candidates
for whitespace-separated filenames so `ls` output becomes clickable.
The provider's existing `pathExists` check filters candidates that
don't resolve against the terminal's cwd.

Also fix an off-by-one in the xterm link range — `parsed.endIndex` is
the exclusive string-slice end, but xterm's `IBufferRange.end.x` is
1-based inclusive, so `+1` was including the trailing whitespace cell
of column-padded output ("package.json ").
This commit is contained in:
Neil
2026-04-23 00:29:59 -07:00
committed by GitHub
parent 96c5ca2636
commit 0101ef3bba
4 changed files with 273 additions and 40 deletions
@@ -1,5 +1,8 @@
import type { IDisposable, ILink } from '@xterm/xterm'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { PaneManager } from '@/lib/pane-manager/pane-manager'
import {
createFilePathLinkProvider,
getTerminalHtmlFileOpenHint,
handleOscLink,
isTerminalLinkActivation,
@@ -51,7 +54,8 @@ beforeEach(() => {
api: {
shell: {
openUrl: openUrlMock,
openFileUri: openFileUriMock
openFileUri: openFileUriMock,
pathExists: vi.fn().mockResolvedValue(true)
},
fs: {
authorizeExternalPath: authorizeExternalPathMock,
@@ -203,3 +207,69 @@ describe('handleOscLink', () => {
)
})
})
describe('createFilePathLinkProvider range bounds', () => {
function makePane(lineText: string): { id: number; terminal: unknown } {
return {
id: 1,
terminal: {
buffer: {
active: {
getLine: (_y: number) => ({
translateToString: (_trim: boolean) => lineText
})
}
}
}
}
}
function collectLinks(lineText: string): Promise<ILink[]> {
const pane = makePane(lineText)
const managerRef = {
current: { getPanes: () => [pane] } as unknown as PaneManager
}
const provider = createFilePathLinkProvider(
1,
{
worktreeId: 'wt-1',
worktreePath: '/repo',
startupCwd: '/repo',
managerRef,
linkProviderDisposablesRef: { current: new Map<number, IDisposable>() },
pathExistsCache: new Map<string, boolean>([
['/repo/CLAUDE.md', true],
['/repo/package.json', true]
])
},
{ textContent: '', style: { display: '' } } as unknown as HTMLElement,
'hint'
)
return new Promise<ILink[]>((resolve) => {
provider.provideLinks(1, (links) => resolve(links ?? []))
})
}
it('underlines only the filename itself, not the column padding from `ls`', async () => {
// ls pads each column with trailing spaces. Regression: the provider used
// to report `end.x = endIndex + 1`, which in xterm's 1-based *inclusive*
// convention overshoots the last filename cell by one, underlining the
// trailing space as well ("package.json ").
const line = 'CLAUDE.md package.json README.md'
const links = await collectLinks(line)
const byText = new Map(links.map((link) => [link.text, link]))
const claude = byText.get('CLAUDE.md')
expect(claude, 'CLAUDE.md should be linkified').toBeDefined()
// 'CLAUDE.md' occupies cols 1..9 (inclusive, 1-based). end.x must be 9.
expect(claude!.range.start.x).toBe(1)
expect(claude!.range.end.x).toBe('CLAUDE.md'.length)
const pkg = byText.get('package.json')
expect(pkg, 'package.json should be linkified').toBeDefined()
// 'package.json' starts at index 15 → col 16; inclusive end at col 15+12 = 27.
const pkgStartIndex = line.indexOf('package.json')
expect(pkg!.range.start.x).toBe(pkgStartIndex + 1)
expect(pkg!.range.end.x).toBe(pkgStartIndex + 'package.json'.length)
})
})
@@ -179,8 +179,14 @@ export function createFilePathLinkProvider(
return {
range: {
// Why: xterm's IBufferRange uses 1-based *inclusive* coords on
// both ends (the hit-test is `x >= start.x && x <= end.x`),
// but `parsed.endIndex` is the exclusive string-slice end.
// Converting start = +1 but end = +0 maps correctly so the
// underline stops on the last filename cell instead of bleeding
// into the trailing whitespace of column-padded `ls` output.
start: { x: parsed.startIndex + 1, y: bufferLineNumber },
end: { x: parsed.endIndex + 1, y: bufferLineNumber }
end: { x: parsed.endIndex, y: bufferLineNumber }
},
text: parsed.displayText,
activate: (event) => {
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest'
import {
extractTerminalFileLinks,
isPathInsideWorktree,
resolveTerminalFileLink,
toWorktreeRelativePath
@@ -11,6 +12,47 @@ describe('terminal path helpers', () => {
expect(toWorktreeRelativePath('C:\\repo\\src\\file.ts', 'C:\\repo')).toBe('src/file.ts')
})
describe('extractTerminalFileLinks bare-filename tokens', () => {
it('emits tentative link candidates for each token in ls-style output', () => {
const line = 'CLAUDE.md package.json pnpm-lock.yaml README.md'
const links = extractTerminalFileLinks(line)
const texts = links.map((link) => link.displayText)
expect(texts).toEqual(['CLAUDE.md', 'package.json', 'pnpm-lock.yaml', 'README.md'])
const claudeMd = links[0]
expect(line.slice(claudeMd.startIndex, claudeMd.endIndex)).toBe('CLAUDE.md')
})
it('recognises common extensionless project files (Makefile, LICENSE, …)', () => {
const links = extractTerminalFileLinks('Makefile LICENSE README Dockerfile src tests')
expect(links.map((link) => link.displayText).sort()).toEqual([
'Dockerfile',
'LICENSE',
'Makefile',
'README'
])
})
it('ignores pure numbers, flag-looking tokens, and dotfile-only strings', () => {
expect(extractTerminalFileLinks('42 100 .. . -v --verbose src dist')).toEqual([])
})
it('still strips trailing punctuation from bare filenames', () => {
const links = extractTerminalFileLinks('See package.json, pnpm-lock.yaml.')
expect(links.map((link) => link.displayText)).toEqual(['package.json', 'pnpm-lock.yaml'])
})
it('does not double-link bare tokens that are part of an already-matched path', () => {
const links = extractTerminalFileLinks('./src/file.ts is the entry point')
expect(links.map((link) => link.displayText)).toEqual(['./src/file.ts'])
})
it('carries line:column suffix on bare filenames (e.g. stack-trace output)', () => {
const links = extractTerminalFileLinks('foo.ts:12:3 failed')
expect(links).toHaveLength(1)
expect(links[0]).toMatchObject({ pathText: 'foo.ts', line: 12, column: 3 })
})
})
it('supports Windows cwd resolution for terminal file links', () => {
expect(
resolveTerminalFileLink(
+153 -38
View File
@@ -13,8 +13,28 @@ export type ResolvedTerminalFileLink = {
column: number | null
}
const FILE_LINK_CANDIDATE_REGEX =
/(?:\/|\.{1,2}\/|[A-Za-z0-9._-]+\/)[A-Za-z0-9._~\-/]*(?::\d+)?(?::\d+)?/g
// Ported from VSCode's terminal link detectors (MIT).
// Local paths: src/vs/workbench/contrib/terminalContrib/links/browser/terminalLocalLinkDetector.ts
// Bare words: src/vs/workbench/contrib/terminalContrib/links/browser/terminalWordLinkDetector.ts
//
// Two passes, matching VSCode's split between `TerminalLocalLinkDetector`
// (paths with a separator, including line:col suffix) and
// `TerminalWordLinkDetector` (bare whitespace-delimited tokens that only
// become links if they resolve against the cwd). The provider runs fs.stat
// on every candidate, so the word-pass stays conservative to keep fan-out
// small.
// Matches a path with at least one `/` separator, optionally followed by
// `:line` and `:col` suffixes (e.g. `src/foo.ts:12:3`, `./bin`, `/abs/path`).
const LOCAL_PATH_REGEX = /(?:\/|\.{1,2}\/|[A-Za-z0-9._-]+\/)[A-Za-z0-9._~\-/]*(?::\d+)?(?::\d+)?/g
// Word separators used by the bare-filename pass. Mirrors the default set in
// VSCode's `terminal.integrated.wordSeparators` with the exception that we
// include `:` indirectly via the line:col suffix parser rather than as a
// raw separator. A word is any maximal run of non-separator characters.
// \s matches NBSP in modern JS; xterm powerline glyphs are in the PUA and
// never appear in filenames, so we don't list them explicitly.
const WORD_TOKEN_REGEX = /[^\s()[\]{}'",;<>|`]+/g
const LEADING_TRIM_CHARS = new Set(['(', '[', '{', '"', "'"])
const TRAILING_TRIM_CHARS = new Set([')', ']', '}', '"', "'", ',', ';', '.'])
@@ -158,46 +178,141 @@ function normalizeJoinedPath(basePath: NormalizedAbsolutePath, relativePath: str
return `/${joinedSegments.join('/')}`.replace(/\/+$/, '') || '/'
}
export function extractTerminalFileLinks(lineText: string): ParsedTerminalFileLink[] {
const results: ParsedTerminalFileLink[] = []
const matches = lineText.matchAll(FILE_LINK_CANDIDATE_REGEX)
for (const match of matches) {
const rawText = match[0]
const rawStart = match.index ?? 0
// Project files that look like filenames despite having no extension. The
// word detector otherwise requires a `.` in the token to keep noise down —
// without this list, `ls` output containing `Makefile` or `LICENSE` would
// not be clickable.
const EXTENSIONLESS_FILENAMES = new Set([
'Makefile',
'Dockerfile',
'Rakefile',
'Gemfile',
'Procfile',
'LICENSE',
'README',
'CHANGELOG',
'AUTHORS',
'NOTICE',
'CONTRIBUTING'
])
const trimmed = trimBoundaryPunctuation(rawText, rawStart)
if (!trimmed) {
continue
}
const BARE_FILENAME_PATTERN = /^[A-Za-z0-9_][A-Za-z0-9._+-]*$/
const candidateText = trimmed.text
if (candidateText.includes('://')) {
continue
}
const prefix = lineText.slice(0, trimmed.startIndex)
if (/[A-Za-z][A-Za-z0-9+.-]*:\/\/$/.test(prefix)) {
continue
}
if (!candidateText.includes('/')) {
continue
}
const parsed = parsePathWithOptionalLineColumn(candidateText)
if (!parsed) {
continue
}
results.push({
pathText: parsed.pathText,
line: parsed.line,
column: parsed.column,
startIndex: trimmed.startIndex,
endIndex: trimmed.endIndex,
displayText: candidateText
})
// Bare words are validated against the filesystem by the provider, so this
// filter's job is to reject tokens that are obviously not filenames before
// we pay for a stat. Plain words like `src` or `my-cli` are usually
// directories or binaries and produce more noise than value — users who
// really want to open them can prefix with `./`.
function looksLikeFilename(token: string): boolean {
if (token.length < 2 || token.length > 100) {
return false
}
if (!BARE_FILENAME_PATTERN.test(token)) {
return false
}
if (/^\d+$/.test(token)) {
return false
}
if (token.includes('.')) {
return !/^\.+$/.test(token)
}
return EXTENSIONLESS_FILENAMES.has(token)
}
return results
type DetectedRange = { startIndex: number; endIndex: number; text: string }
// Shared tokenization: run a regex over the line, trim boundary punctuation,
// hand each surviving range to the caller. Collapses the three near-copies
// of this loop the module had grown.
function* detectRanges(lineText: string, regex: RegExp): Generator<DetectedRange> {
for (const match of lineText.matchAll(regex)) {
const rawStart = match.index ?? 0
const trimmed = trimBoundaryPunctuation(match[0], rawStart)
if (trimmed) {
yield trimmed
}
}
}
function isInsideUriScheme(lineText: string, range: DetectedRange): boolean {
if (range.text.includes('://')) {
return true
}
const prefix = lineText.slice(0, range.startIndex)
return /[A-Za-z][A-Za-z0-9+.-]*:\/\/$/.test(prefix)
}
function toParsedLink(range: DetectedRange): ParsedTerminalFileLink | null {
const parsed = parsePathWithOptionalLineColumn(range.text)
if (!parsed) {
return null
}
return {
pathText: parsed.pathText,
line: parsed.line,
column: parsed.column,
startIndex: range.startIndex,
endIndex: range.endIndex,
displayText: range.text
}
}
// Ported from VSCode's TerminalLocalLinkDetector. Extracts anything that
// contains a path separator, optionally with a `:line:col` suffix — covers
// `./src/foo.ts`, `/abs/bar`, `src/foo.ts:12:3`, etc.
function detectLocalPathLinks(lineText: string): ParsedTerminalFileLink[] {
const links: ParsedTerminalFileLink[] = []
for (const range of detectRanges(lineText, LOCAL_PATH_REGEX)) {
if (isInsideUriScheme(lineText, range)) {
continue
}
if (!range.text.includes('/')) {
continue
}
const link = toParsedLink(range)
if (link) {
links.push(link)
}
}
return links
}
// Ported from VSCode's TerminalWordLinkDetector. Tokenizes the line on
// separators and emits filename-ish words so `ls` output becomes clickable.
// Skips ranges already claimed by the local-path pass to avoid double links
// when a bare filename happens to be a substring of a longer path.
function detectBareFilenameLinks(
lineText: string,
claimedRanges: readonly [number, number][]
): ParsedTerminalFileLink[] {
const links: ParsedTerminalFileLink[] = []
for (const range of detectRanges(lineText, WORD_TOKEN_REGEX)) {
const overlaps = claimedRanges.some(
([start, end]) => range.startIndex < end && range.endIndex > start
)
if (overlaps) {
continue
}
const link = toParsedLink(range)
if (!link) {
continue
}
if (!looksLikeFilename(link.pathText)) {
continue
}
links.push(link)
}
return links
}
export function extractTerminalFileLinks(lineText: string): ParsedTerminalFileLink[] {
const pathLinks = detectLocalPathLinks(lineText)
const claimed = pathLinks.map(({ startIndex, endIndex }): [number, number] => [
startIndex,
endIndex
])
const wordLinks = detectBareFilenameLinks(lineText, claimed)
return [...pathLinks, ...wordLinks]
}
export function resolveTerminalFileLink(