autocomplete.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  1. import { spawn } from "child_process";
  2. import { readdirSync, statSync } from "fs";
  3. import { homedir } from "os";
  4. import { basename, dirname, join } from "path";
  5. import { fuzzyFilter } from "./fuzzy.ts";
  6. const PATH_DELIMITERS = new Set([" ", "\t", '"', "'", "="]);
  7. function toDisplayPath(value: string): string {
  8. return value.replace(/\\/g, "/");
  9. }
  10. function escapeRegex(value: string): string {
  11. return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  12. }
  13. function buildFdPathQuery(query: string): string {
  14. const normalized = toDisplayPath(query);
  15. if (!normalized.includes("/")) {
  16. return normalized;
  17. }
  18. const hasTrailingSeparator = normalized.endsWith("/");
  19. const trimmed = normalized.replace(/^\/+|\/+$/g, "");
  20. if (!trimmed) {
  21. return normalized;
  22. }
  23. const separatorPattern = "[\\\\/]";
  24. const segments = trimmed
  25. .split("/")
  26. .filter(Boolean)
  27. .map((segment) => escapeRegex(segment));
  28. if (segments.length === 0) {
  29. return normalized;
  30. }
  31. let pattern = segments.join(separatorPattern);
  32. if (hasTrailingSeparator) {
  33. pattern += separatorPattern;
  34. }
  35. return pattern;
  36. }
  37. function findLastDelimiter(text: string): number {
  38. for (let i = text.length - 1; i >= 0; i -= 1) {
  39. if (PATH_DELIMITERS.has(text[i] ?? "")) {
  40. return i;
  41. }
  42. }
  43. return -1;
  44. }
  45. function findUnclosedQuoteStart(text: string): number | null {
  46. let inQuotes = false;
  47. let quoteStart = -1;
  48. for (let i = 0; i < text.length; i += 1) {
  49. if (text[i] === '"') {
  50. inQuotes = !inQuotes;
  51. if (inQuotes) {
  52. quoteStart = i;
  53. }
  54. }
  55. }
  56. return inQuotes ? quoteStart : null;
  57. }
  58. function isTokenStart(text: string, index: number): boolean {
  59. return index === 0 || PATH_DELIMITERS.has(text[index - 1] ?? "");
  60. }
  61. function extractQuotedPrefix(text: string): string | null {
  62. const quoteStart = findUnclosedQuoteStart(text);
  63. if (quoteStart === null) {
  64. return null;
  65. }
  66. if (quoteStart > 0 && text[quoteStart - 1] === "@") {
  67. if (!isTokenStart(text, quoteStart - 1)) {
  68. return null;
  69. }
  70. return text.slice(quoteStart - 1);
  71. }
  72. if (!isTokenStart(text, quoteStart)) {
  73. return null;
  74. }
  75. return text.slice(quoteStart);
  76. }
  77. function parsePathPrefix(prefix: string): { rawPrefix: string; isAtPrefix: boolean; isQuotedPrefix: boolean } {
  78. if (prefix.startsWith('@"')) {
  79. return { rawPrefix: prefix.slice(2), isAtPrefix: true, isQuotedPrefix: true };
  80. }
  81. if (prefix.startsWith('"')) {
  82. return { rawPrefix: prefix.slice(1), isAtPrefix: false, isQuotedPrefix: true };
  83. }
  84. if (prefix.startsWith("@")) {
  85. return { rawPrefix: prefix.slice(1), isAtPrefix: true, isQuotedPrefix: false };
  86. }
  87. return { rawPrefix: prefix, isAtPrefix: false, isQuotedPrefix: false };
  88. }
  89. function buildCompletionValue(
  90. path: string,
  91. options: { isDirectory: boolean; isAtPrefix: boolean; isQuotedPrefix: boolean },
  92. ): string {
  93. const needsQuotes = options.isQuotedPrefix || path.includes(" ");
  94. const prefix = options.isAtPrefix ? "@" : "";
  95. if (!needsQuotes) {
  96. return `${prefix}${path}`;
  97. }
  98. const openQuote = `${prefix}"`;
  99. const closeQuote = '"';
  100. return `${openQuote}${path}${closeQuote}`;
  101. }
  102. // Use fd to walk directory tree (fast, respects .gitignore)
  103. async function walkDirectoryWithFd(
  104. baseDir: string,
  105. fdPath: string,
  106. query: string,
  107. maxResults: number,
  108. signal: AbortSignal,
  109. ): Promise<Array<{ path: string; isDirectory: boolean }>> {
  110. const args = [
  111. "--base-directory",
  112. baseDir,
  113. "--max-results",
  114. String(maxResults),
  115. "--type",
  116. "f",
  117. "--type",
  118. "d",
  119. "--follow",
  120. "--hidden",
  121. "--exclude",
  122. ".git",
  123. "--exclude",
  124. ".git/*",
  125. "--exclude",
  126. ".git/**",
  127. ];
  128. if (toDisplayPath(query).includes("/")) {
  129. args.push("--full-path");
  130. }
  131. if (query) {
  132. args.push(buildFdPathQuery(query));
  133. }
  134. return await new Promise((resolve) => {
  135. if (signal.aborted) {
  136. resolve([]);
  137. return;
  138. }
  139. const child = spawn(fdPath, args, {
  140. stdio: ["ignore", "pipe", "pipe"],
  141. });
  142. let stdout = "";
  143. let resolved = false;
  144. const finish = (results: Array<{ path: string; isDirectory: boolean }>) => {
  145. if (resolved) return;
  146. resolved = true;
  147. signal.removeEventListener("abort", onAbort);
  148. resolve(results);
  149. };
  150. const onAbort = () => {
  151. if (child.exitCode === null) {
  152. child.kill("SIGKILL");
  153. }
  154. };
  155. signal.addEventListener("abort", onAbort, { once: true });
  156. child.stdout.setEncoding("utf-8");
  157. child.stdout.on("data", (chunk: string) => {
  158. stdout += chunk;
  159. });
  160. child.on("error", () => {
  161. finish([]);
  162. });
  163. child.on("close", (code) => {
  164. if (signal.aborted || code !== 0 || !stdout) {
  165. finish([]);
  166. return;
  167. }
  168. const lines = stdout.trim().split("\n").filter(Boolean);
  169. const results: Array<{ path: string; isDirectory: boolean }> = [];
  170. for (const line of lines) {
  171. const displayLine = toDisplayPath(line);
  172. const hasTrailingSeparator = displayLine.endsWith("/");
  173. const normalizedPath = hasTrailingSeparator ? displayLine.slice(0, -1) : displayLine;
  174. if (normalizedPath === ".git" || normalizedPath.startsWith(".git/") || normalizedPath.includes("/.git/")) {
  175. continue;
  176. }
  177. results.push({
  178. path: displayLine,
  179. isDirectory: hasTrailingSeparator,
  180. });
  181. }
  182. finish(results);
  183. });
  184. });
  185. }
  186. export interface AutocompleteItem {
  187. value: string;
  188. label: string;
  189. description?: string;
  190. }
  191. type Awaitable<T> = T | Promise<T>;
  192. export interface SlashCommand {
  193. name: string;
  194. description?: string;
  195. argumentHint?: string;
  196. // Function to get argument completions for this command
  197. // Returns null if no argument completion is available
  198. getArgumentCompletions?(argumentPrefix: string): Awaitable<AutocompleteItem[] | null>;
  199. }
  200. export interface AutocompleteSuggestions {
  201. items: AutocompleteItem[];
  202. prefix: string; // What we're matching against (e.g., "/" or "src/")
  203. }
  204. export interface AutocompleteProvider {
  205. /** Characters that should naturally trigger this provider at token boundaries. */
  206. triggerCharacters?: string[];
  207. // Get autocomplete suggestions for current text/cursor position
  208. // Returns null if no suggestions available
  209. getSuggestions(
  210. lines: string[],
  211. cursorLine: number,
  212. cursorCol: number,
  213. options: { signal: AbortSignal; force?: boolean },
  214. ): Promise<AutocompleteSuggestions | null>;
  215. // Apply the selected item
  216. // Returns the new text and cursor position
  217. applyCompletion(
  218. lines: string[],
  219. cursorLine: number,
  220. cursorCol: number,
  221. item: AutocompleteItem,
  222. prefix: string,
  223. ): {
  224. lines: string[];
  225. cursorLine: number;
  226. cursorCol: number;
  227. };
  228. // Check if file completion should trigger for explicit Tab completion
  229. shouldTriggerFileCompletion?(lines: string[], cursorLine: number, cursorCol: number): boolean;
  230. }
  231. // Combined provider that handles both slash commands and file paths
  232. export class CombinedAutocompleteProvider implements AutocompleteProvider {
  233. private commands: (SlashCommand | AutocompleteItem)[];
  234. private basePath: string;
  235. private fdPath: string | null;
  236. constructor(commands: (SlashCommand | AutocompleteItem)[] = [], basePath: string, fdPath: string | null = null) {
  237. this.commands = commands;
  238. this.basePath = basePath;
  239. this.fdPath = fdPath;
  240. }
  241. async getSuggestions(
  242. lines: string[],
  243. cursorLine: number,
  244. cursorCol: number,
  245. options: { signal: AbortSignal; force?: boolean },
  246. ): Promise<AutocompleteSuggestions | null> {
  247. const currentLine = lines[cursorLine] || "";
  248. const textBeforeCursor = currentLine.slice(0, cursorCol);
  249. const atPrefix = this.extractAtPrefix(textBeforeCursor);
  250. if (atPrefix) {
  251. const { rawPrefix, isQuotedPrefix } = parsePathPrefix(atPrefix);
  252. const suggestions = await this.getFuzzyFileSuggestions(rawPrefix, {
  253. isQuotedPrefix,
  254. signal: options.signal,
  255. });
  256. if (suggestions.length === 0) return null;
  257. return {
  258. items: suggestions,
  259. prefix: atPrefix,
  260. };
  261. }
  262. if (!options.force && textBeforeCursor.startsWith("/")) {
  263. const spaceIndex = textBeforeCursor.indexOf(" ");
  264. if (spaceIndex === -1) {
  265. const prefix = textBeforeCursor.slice(1);
  266. const commandItems = this.commands.map((cmd) => {
  267. const name = "name" in cmd ? cmd.name : cmd.value;
  268. const hint = "argumentHint" in cmd && cmd.argumentHint ? cmd.argumentHint : undefined;
  269. const desc = cmd.description ?? "";
  270. const fullDesc = hint ? (desc ? `${hint} — ${desc}` : hint) : desc;
  271. return {
  272. name,
  273. label: name,
  274. description: fullDesc || undefined,
  275. };
  276. });
  277. const filtered = fuzzyFilter(commandItems, prefix, (item) => item.name).map((item) => ({
  278. value: item.name,
  279. label: item.label,
  280. ...(item.description && { description: item.description }),
  281. }));
  282. if (filtered.length === 0) return null;
  283. return {
  284. items: filtered,
  285. prefix: textBeforeCursor,
  286. };
  287. }
  288. const commandName = textBeforeCursor.slice(1, spaceIndex);
  289. const argumentText = textBeforeCursor.slice(spaceIndex + 1);
  290. const command = this.commands.find((cmd) => {
  291. const name = "name" in cmd ? cmd.name : cmd.value;
  292. return name === commandName;
  293. });
  294. if (!command || !("getArgumentCompletions" in command) || !command.getArgumentCompletions) {
  295. return null;
  296. }
  297. const argumentSuggestions = await command.getArgumentCompletions(argumentText);
  298. if (!Array.isArray(argumentSuggestions) || argumentSuggestions.length === 0) {
  299. return null;
  300. }
  301. return {
  302. items: argumentSuggestions,
  303. prefix: argumentText,
  304. };
  305. }
  306. const pathMatch = this.extractPathPrefix(textBeforeCursor, options.force ?? false);
  307. if (pathMatch === null) {
  308. return null;
  309. }
  310. const suggestions = this.getFileSuggestions(pathMatch);
  311. if (suggestions.length === 0) return null;
  312. return {
  313. items: suggestions,
  314. prefix: pathMatch,
  315. };
  316. }
  317. applyCompletion(
  318. lines: string[],
  319. cursorLine: number,
  320. cursorCol: number,
  321. item: AutocompleteItem,
  322. prefix: string,
  323. ): { lines: string[]; cursorLine: number; cursorCol: number } {
  324. const currentLine = lines[cursorLine] || "";
  325. const beforePrefix = currentLine.slice(0, cursorCol - prefix.length);
  326. const afterCursor = currentLine.slice(cursorCol);
  327. const isQuotedPrefix = prefix.startsWith('"') || prefix.startsWith('@"');
  328. const hasLeadingQuoteAfterCursor = afterCursor.startsWith('"');
  329. const hasTrailingQuoteInItem = item.value.endsWith('"');
  330. const adjustedAfterCursor =
  331. isQuotedPrefix && hasTrailingQuoteInItem && hasLeadingQuoteAfterCursor ? afterCursor.slice(1) : afterCursor;
  332. // Check if we're completing a slash command (prefix starts with "/" but NOT a file path)
  333. // Slash commands are at the start of the line and don't contain path separators after the first /
  334. const isSlashCommand = prefix.startsWith("/") && beforePrefix.trim() === "" && !prefix.slice(1).includes("/");
  335. if (isSlashCommand) {
  336. // This is a command name completion
  337. const newLine = `${beforePrefix}/${item.value} ${adjustedAfterCursor}`;
  338. const newLines = [...lines];
  339. newLines[cursorLine] = newLine;
  340. return {
  341. lines: newLines,
  342. cursorLine,
  343. cursorCol: beforePrefix.length + item.value.length + 2, // +2 for "/" and space
  344. };
  345. }
  346. // Check if we're completing a file attachment (prefix starts with "@")
  347. if (prefix.startsWith("@")) {
  348. // This is a file attachment completion
  349. // Don't add space after directories so user can continue autocompleting
  350. const isDirectory = item.label.endsWith("/");
  351. const suffix = isDirectory ? "" : " ";
  352. const newLine = `${beforePrefix + item.value}${suffix}${adjustedAfterCursor}`;
  353. const newLines = [...lines];
  354. newLines[cursorLine] = newLine;
  355. const hasTrailingQuote = item.value.endsWith('"');
  356. const cursorOffset = isDirectory && hasTrailingQuote ? item.value.length - 1 : item.value.length;
  357. return {
  358. lines: newLines,
  359. cursorLine,
  360. cursorCol: beforePrefix.length + cursorOffset + suffix.length,
  361. };
  362. }
  363. // Check if we're in a slash command context (beforePrefix contains "/command ")
  364. const textBeforeCursor = currentLine.slice(0, cursorCol);
  365. if (textBeforeCursor.includes("/") && textBeforeCursor.includes(" ")) {
  366. // This is likely a command argument completion
  367. const newLine = beforePrefix + item.value + adjustedAfterCursor;
  368. const newLines = [...lines];
  369. newLines[cursorLine] = newLine;
  370. const isDirectory = item.label.endsWith("/");
  371. const hasTrailingQuote = item.value.endsWith('"');
  372. const cursorOffset = isDirectory && hasTrailingQuote ? item.value.length - 1 : item.value.length;
  373. return {
  374. lines: newLines,
  375. cursorLine,
  376. cursorCol: beforePrefix.length + cursorOffset,
  377. };
  378. }
  379. // For file paths, complete the path
  380. const newLine = beforePrefix + item.value + adjustedAfterCursor;
  381. const newLines = [...lines];
  382. newLines[cursorLine] = newLine;
  383. const isDirectory = item.label.endsWith("/");
  384. const hasTrailingQuote = item.value.endsWith('"');
  385. const cursorOffset = isDirectory && hasTrailingQuote ? item.value.length - 1 : item.value.length;
  386. return {
  387. lines: newLines,
  388. cursorLine,
  389. cursorCol: beforePrefix.length + cursorOffset,
  390. };
  391. }
  392. // Extract @ prefix for fuzzy file suggestions
  393. private extractAtPrefix(text: string): string | null {
  394. const quotedPrefix = extractQuotedPrefix(text);
  395. if (quotedPrefix?.startsWith('@"')) {
  396. return quotedPrefix;
  397. }
  398. const lastDelimiterIndex = findLastDelimiter(text);
  399. const tokenStart = lastDelimiterIndex === -1 ? 0 : lastDelimiterIndex + 1;
  400. if (text[tokenStart] === "@") {
  401. return text.slice(tokenStart);
  402. }
  403. return null;
  404. }
  405. // Extract a path-like prefix from the text before cursor
  406. private extractPathPrefix(text: string, forceExtract: boolean = false): string | null {
  407. const quotedPrefix = extractQuotedPrefix(text);
  408. if (quotedPrefix) {
  409. return quotedPrefix;
  410. }
  411. const lastDelimiterIndex = findLastDelimiter(text);
  412. const pathPrefix = lastDelimiterIndex === -1 ? text : text.slice(lastDelimiterIndex + 1);
  413. // For forced extraction (Tab key), always return something
  414. if (forceExtract) {
  415. return pathPrefix;
  416. }
  417. // For natural triggers, return if it looks like a path, ends with /, starts with ~/, .
  418. // Only return empty string if the text looks like it's starting a path context
  419. if (pathPrefix.includes("/") || pathPrefix.startsWith(".") || pathPrefix.startsWith("~/")) {
  420. return pathPrefix;
  421. }
  422. // Return empty string only after a space (not for completely empty text)
  423. // Empty text should not trigger file suggestions - that's for forced Tab completion
  424. if (pathPrefix === "" && text.endsWith(" ")) {
  425. return pathPrefix;
  426. }
  427. return null;
  428. }
  429. // Expand home directory (~/) to actual home path
  430. private expandHomePath(path: string): string {
  431. if (path.startsWith("~/")) {
  432. const expandedPath = join(homedir(), path.slice(2));
  433. // Preserve trailing slash if original path had one
  434. return path.endsWith("/") && !expandedPath.endsWith("/") ? `${expandedPath}/` : expandedPath;
  435. } else if (path === "~") {
  436. return homedir();
  437. }
  438. return path;
  439. }
  440. private resolveScopedFuzzyQuery(rawQuery: string): { baseDir: string; query: string; displayBase: string } | null {
  441. const normalizedQuery = toDisplayPath(rawQuery);
  442. const slashIndex = normalizedQuery.lastIndexOf("/");
  443. if (slashIndex === -1) {
  444. return null;
  445. }
  446. const displayBase = normalizedQuery.slice(0, slashIndex + 1);
  447. const query = normalizedQuery.slice(slashIndex + 1);
  448. let baseDir: string;
  449. if (displayBase.startsWith("~/")) {
  450. baseDir = this.expandHomePath(displayBase);
  451. } else if (displayBase.startsWith("/")) {
  452. baseDir = displayBase;
  453. } else {
  454. baseDir = join(this.basePath, displayBase);
  455. }
  456. try {
  457. if (!statSync(baseDir).isDirectory()) {
  458. return null;
  459. }
  460. } catch {
  461. return null;
  462. }
  463. return { baseDir, query, displayBase };
  464. }
  465. private scopedPathForDisplay(displayBase: string, relativePath: string): string {
  466. const normalizedRelativePath = toDisplayPath(relativePath);
  467. if (displayBase === "/") {
  468. return `/${normalizedRelativePath}`;
  469. }
  470. return `${toDisplayPath(displayBase)}${normalizedRelativePath}`;
  471. }
  472. // Get file/directory suggestions for a given path prefix
  473. private getFileSuggestions(prefix: string): AutocompleteItem[] {
  474. try {
  475. let searchDir: string;
  476. let searchPrefix: string;
  477. const { rawPrefix, isAtPrefix, isQuotedPrefix } = parsePathPrefix(prefix);
  478. let expandedPrefix = rawPrefix;
  479. // Handle home directory expansion
  480. if (expandedPrefix.startsWith("~")) {
  481. expandedPrefix = this.expandHomePath(expandedPrefix);
  482. }
  483. const isRootPrefix =
  484. rawPrefix === "" ||
  485. rawPrefix === "./" ||
  486. rawPrefix === "../" ||
  487. rawPrefix === "~" ||
  488. rawPrefix === "~/" ||
  489. rawPrefix === "/" ||
  490. (isAtPrefix && rawPrefix === "");
  491. if (isRootPrefix) {
  492. // Complete from specified position
  493. if (rawPrefix.startsWith("~") || expandedPrefix.startsWith("/")) {
  494. searchDir = expandedPrefix;
  495. } else {
  496. searchDir = join(this.basePath, expandedPrefix);
  497. }
  498. searchPrefix = "";
  499. } else if (rawPrefix.endsWith("/")) {
  500. // If prefix ends with /, show contents of that directory
  501. if (rawPrefix.startsWith("~") || expandedPrefix.startsWith("/")) {
  502. searchDir = expandedPrefix;
  503. } else {
  504. searchDir = join(this.basePath, expandedPrefix);
  505. }
  506. searchPrefix = "";
  507. } else {
  508. // Split into directory and file prefix
  509. const dir = dirname(expandedPrefix);
  510. const file = basename(expandedPrefix);
  511. if (rawPrefix.startsWith("~") || expandedPrefix.startsWith("/")) {
  512. searchDir = dir;
  513. } else {
  514. searchDir = join(this.basePath, dir);
  515. }
  516. searchPrefix = file;
  517. }
  518. const entries = readdirSync(searchDir, { withFileTypes: true });
  519. const suggestions: AutocompleteItem[] = [];
  520. for (const entry of entries) {
  521. if (!entry.name.toLowerCase().startsWith(searchPrefix.toLowerCase())) {
  522. continue;
  523. }
  524. // Check if entry is a directory (or a symlink pointing to a directory)
  525. let isDirectory = entry.isDirectory();
  526. if (!isDirectory && entry.isSymbolicLink()) {
  527. try {
  528. const fullPath = join(searchDir, entry.name);
  529. isDirectory = statSync(fullPath).isDirectory();
  530. } catch {
  531. // Broken symlink or permission error - treat as file
  532. }
  533. }
  534. let relativePath: string;
  535. const name = entry.name;
  536. const displayPrefix = rawPrefix;
  537. if (displayPrefix.endsWith("/")) {
  538. // If prefix ends with /, append entry to the prefix
  539. relativePath = displayPrefix + name;
  540. } else if (displayPrefix.includes("/") || displayPrefix.includes("\\")) {
  541. // Preserve ~/ format for home directory paths
  542. if (displayPrefix.startsWith("~/")) {
  543. const homeRelativeDir = displayPrefix.slice(2); // Remove ~/
  544. const dir = dirname(homeRelativeDir);
  545. relativePath = `~/${dir === "." ? name : join(dir, name)}`;
  546. } else if (displayPrefix.startsWith("/")) {
  547. // Absolute path - construct properly
  548. const dir = dirname(displayPrefix);
  549. if (dir === "/") {
  550. relativePath = `/${name}`;
  551. } else {
  552. relativePath = `${dir}/${name}`;
  553. }
  554. } else {
  555. relativePath = join(dirname(displayPrefix), name);
  556. // path.join normalizes away ./ prefix, preserve it
  557. if (displayPrefix.startsWith("./") && !relativePath.startsWith("./")) {
  558. relativePath = `./${relativePath}`;
  559. }
  560. }
  561. } else {
  562. // For standalone entries, preserve ~/ if original prefix was ~/
  563. if (displayPrefix.startsWith("~")) {
  564. relativePath = `~/${name}`;
  565. } else {
  566. relativePath = name;
  567. }
  568. }
  569. relativePath = toDisplayPath(relativePath);
  570. const pathValue = isDirectory ? `${relativePath}/` : relativePath;
  571. const value = buildCompletionValue(pathValue, {
  572. isDirectory,
  573. isAtPrefix,
  574. isQuotedPrefix,
  575. });
  576. suggestions.push({
  577. value,
  578. label: name + (isDirectory ? "/" : ""),
  579. });
  580. }
  581. // Sort directories first, then alphabetically
  582. suggestions.sort((a, b) => {
  583. const aIsDir = a.value.endsWith("/");
  584. const bIsDir = b.value.endsWith("/");
  585. if (aIsDir && !bIsDir) return -1;
  586. if (!aIsDir && bIsDir) return 1;
  587. return a.label.localeCompare(b.label);
  588. });
  589. return suggestions;
  590. } catch (_e) {
  591. // Directory doesn't exist or not accessible
  592. return [];
  593. }
  594. }
  595. // Score an entry against the query (higher = better match)
  596. // isDirectory adds bonus to prioritize folders
  597. private scoreEntry(filePath: string, query: string, isDirectory: boolean): number {
  598. const fileName = basename(filePath);
  599. const lowerFileName = fileName.toLowerCase();
  600. const lowerQuery = query.toLowerCase();
  601. let score = 0;
  602. // Exact filename match (highest)
  603. if (lowerFileName === lowerQuery) score = 100;
  604. // Filename starts with query
  605. else if (lowerFileName.startsWith(lowerQuery)) score = 80;
  606. // Substring match in filename
  607. else if (lowerFileName.includes(lowerQuery)) score = 50;
  608. // Substring match in full path
  609. else if (filePath.toLowerCase().includes(lowerQuery)) score = 30;
  610. // Directories get a bonus to appear first
  611. if (isDirectory && score > 0) score += 10;
  612. return score;
  613. }
  614. // Fuzzy file search using fd (fast, respects .gitignore)
  615. private async getFuzzyFileSuggestions(
  616. query: string,
  617. options: { isQuotedPrefix: boolean; signal: AbortSignal },
  618. ): Promise<AutocompleteItem[]> {
  619. if (!this.fdPath || options.signal.aborted) {
  620. return [];
  621. }
  622. try {
  623. const scopedQuery = this.resolveScopedFuzzyQuery(query);
  624. const fdBaseDir = scopedQuery?.baseDir ?? this.basePath;
  625. const fdQuery = scopedQuery?.query ?? query;
  626. const entries = await walkDirectoryWithFd(fdBaseDir, this.fdPath, fdQuery, 100, options.signal);
  627. if (options.signal.aborted) {
  628. return [];
  629. }
  630. const scoredEntries = entries
  631. .map((entry) => ({
  632. ...entry,
  633. score: fdQuery ? this.scoreEntry(entry.path, fdQuery, entry.isDirectory) : 1,
  634. }))
  635. .filter((entry) => entry.score > 0);
  636. scoredEntries.sort((a, b) => b.score - a.score);
  637. const topEntries = scoredEntries.slice(0, 20);
  638. const suggestions: AutocompleteItem[] = [];
  639. for (const { path: entryPath, isDirectory } of topEntries) {
  640. const pathWithoutSlash = isDirectory ? entryPath.slice(0, -1) : entryPath;
  641. const displayPath = scopedQuery
  642. ? this.scopedPathForDisplay(scopedQuery.displayBase, pathWithoutSlash)
  643. : pathWithoutSlash;
  644. const entryName = basename(pathWithoutSlash);
  645. const completionPath = isDirectory ? `${displayPath}/` : displayPath;
  646. const value = buildCompletionValue(completionPath, {
  647. isDirectory,
  648. isAtPrefix: true,
  649. isQuotedPrefix: options.isQuotedPrefix,
  650. });
  651. suggestions.push({
  652. value,
  653. label: entryName + (isDirectory ? "/" : ""),
  654. description: displayPath,
  655. });
  656. }
  657. return suggestions;
  658. } catch {
  659. return [];
  660. }
  661. }
  662. // Check if we should trigger file completion (called on Tab key)
  663. shouldTriggerFileCompletion(lines: string[], cursorLine: number, cursorCol: number): boolean {
  664. const currentLine = lines[cursorLine] || "";
  665. const textBeforeCursor = currentLine.slice(0, cursorCol);
  666. // Don't trigger if we're typing a slash command at the start of the line
  667. if (textBeforeCursor.trim().startsWith("/") && !textBeforeCursor.trim().includes(" ")) {
  668. return false;
  669. }
  670. return true;
  671. }
  672. }