diff --git a/src/features/search/__tests__/controller.test.ts b/src/features/search/__tests__/controller.test.ts index af327675e2..d4a4c7614b 100644 --- a/src/features/search/__tests__/controller.test.ts +++ b/src/features/search/__tests__/controller.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vitest"; import type { FileMatches, SearchQuery } from "@/platform/ipc"; import { SeController, type SeDeps, type SeSnapshot } from "../everywhere/controller"; import { buildRows } from "../everywhere/model"; +import type { ResolvedFilter } from "../everywhere/filters"; function deferred() { let resolve!: (v: T) => void; @@ -180,6 +181,68 @@ describe("SeController", () => { ).not.toContain("f:/data/scratches/scratch_3.md"); }); + it("reads * in a Files query as a wildcard when the query as typed finds nothing", async () => { + const index: Record = { + "User*Service": ["src/User*Service.kt"], + UserService: ["src/User*Service.kt", "src/UserService.java"], + "foo*.txt": [], + "foo.txt": ["foo.txt"], + "*Account*": [], + Account: ["src/UserAccountService.java"], + }; + const findFiles = vi.fn(async (q: string) => (index[q] ?? []).map(fm)); + const { c, last } = setup({ + findFiles, + outsideFiles: async () => [{ path: "/data/scratches/foo*.txt", relPath: "Scratches/foo*.txt" }], + }); + const files = () => + last() + .sections.get("files")! + .items.map((i) => i.key); + const run = async (query: string, filter?: ResolvedFilter) => { + c.run({ query, tab: "files", includeNonProject: false, filter, extra: {} }); + await flush(); + await flush(); + }; + + await run("*Account*"); + expect(files()).toEqual(["f:/p/src/UserAccountService.java"]); + await run("User*Service"); + expect(files()).toEqual(["f:/p/src/User*Service.kt"]); + // The match as typed is filtered out: what is shown decides, not what the index found. + await run("User*Service", { + excludedLanguages: ["kotlin"], + languageOf: (p) => (p.endsWith(".kt") ? "kotlin" : "java"), + }); + expect(files()).toEqual(["f:/p/src/UserService.java"]); + // A scratch file named with a `*` keeps the project's `foo.txt` out. + await run("foo*.txt"); + expect(files()).toEqual(["f:/data/scratches/foo*.txt"]); + // Nothing but wildcards stays a query that finds nothing. + findFiles.mockClear(); + await run("./*"); + expect(findFiles.mock.calls.map(([q]) => q)).toEqual(["./*"]); + }); + + it("still searches without the * when another section shows more meanwhile", async () => { + const typed = deferred[]>(); + const findFiles = vi.fn(async (q: string) => + q === "Account" ? [fm("src/UserAccountService.java")] : typed.promise, + ); + const { c, last } = setup({ findFiles }); + c.run({ query: "*Account*", tab: "all", includeNonProject: false, extra: {} }); + await flush(); + c.run({ query: "*Account*", tab: "all", includeNonProject: false, extra: { text: 50 } }); + typed.resolve([]); + await flush(); + await flush(); + expect( + last() + .sections.get("files")! + .items.map((i) => i.key), + ).toEqual(["f:/p/src/UserAccountService.java"]); + }); + // #4079 follow-up: a plain Windows absolute path names an indexed file. it("searches a pasted Windows absolute path as its project-relative path", async () => { const findFiles = vi.fn(async () => [fm("pkg/service/Config.go")]); diff --git a/src/features/search/__tests__/everywhereModel.test.ts b/src/features/search/__tests__/everywhereModel.test.ts index 179c372e37..e72acb9658 100644 --- a/src/features/search/__tests__/everywhereModel.test.ts +++ b/src/features/search/__tests__/everywhereModel.test.ts @@ -5,6 +5,9 @@ import type { SymbolMatch, WorkspaceSymbol } from "@/platform/ipc"; import { buildRows, fileItem, + itemWeight, + TEXT_WEIGHT, + withoutWildcards, matchActions, matchOutsideFiles, mergeSymbols, @@ -238,6 +241,26 @@ describe("items and rows", () => { expect(matchOutsideFiles(files, "bit.matcher")).toEqual([]); }); + it("itemWeight weighs a file as if a * in the query were not there", () => { + const f = fileItem({ path: "/p/src/UserService.java", relPath: "src/UserService.java", indices: [] }, null, null); + expect(itemWeight(f, "User*Service")).toBe(itemWeight(f, "UserService")); + }); + + it("itemWeight prefers the query as typed, on the path too, to the one without *", () => { + const f = fileItem({ path: "/p/src/foo-bar*/foo.ts", relPath: "src/foo-bar*/foo.ts", indices: [] }, null, null); + // `foo*` matches the path as typed; the name `foo` without the `*` would outrank text hits. + expect(itemWeight(f, "foo*")).toBeLessThan(TEXT_WEIGHT); + }); + + it("withoutWildcards skips a query the index would read as empty", () => { + expect(withoutWildcards("User*Service")).toBe("UserService"); + expect(withoutWildcards("UserService")).toBeNull(); + for (const q of ["*", "./*", "/*", "*:0", "* :12:3"]) expect(withoutWildcards(q), q).toBeNull(); + expect(withoutWildcards("c:/proj*ect", "C:/project")).toBeNull(); + expect(withoutWildcards("c:/proj*ect/", "C:\\project\\")).toBeNull(); + expect(withoutWildcards("C:/project/src/*.kt", "C:/project")).toBe("C:/project/src/.kt"); + }); + it("fileItem splits name and directory highlights", () => { const f = fileItem( { path: "/p/src/orders/OrderController.kt", relPath: "src/orders/OrderController.kt", indices: [4, 11, 12, 16] }, diff --git a/src/features/search/everywhere/controller.ts b/src/features/search/everywhere/controller.ts index e2d12b7308..3e93753a18 100644 --- a/src/features/search/everywhere/controller.ts +++ b/src/features/search/everywhere/controller.ts @@ -36,6 +36,7 @@ import { sectionsFor, splitSymbolQuery, textItems, + withoutWildcards, type OutsideFile, type SeItem, type SeTab, @@ -336,19 +337,24 @@ export class SeController { // Directories rank with the files (equal scores: the file first); a file type filter // and a `File.kt:42` query ask for files only. const withDirs = !!this.deps.findDirs && !!text && !filter && q.line === null; - const [indexed, dirs, outside] = await Promise.all([ - this.deps.findFiles(text, want), - withDirs ? this.deps.findDirs!(text, want).catch(() => []) : [], - text && this.deps.outsideFiles ? this.deps.outsideFiles().catch(() => []) : [], - ]); - const fetched = outside.length ? [...indexed, ...matchOutsideFiles(outside, text)] : indexed; - const merged = - dirs.length || outside.length - ? [...fetched.map((m) => ({ m, folder: false })), ...dirs.map((m) => ({ m, folder: true }))].sort( - (a, b) => b.m.score - a.m.score || Number(a.folder) - Number(b.folder), - ) - : fetched.map((m) => ({ m, folder: false })); - const matches = keep ? merged.filter(({ m }) => keep(m.path)) : merged; + const search = async (query: string) => { + const [indexed, dirs, outside] = await Promise.all([ + this.deps.findFiles(query, want), + withDirs ? this.deps.findDirs!(query, want).catch(() => []) : [], + query && this.deps.outsideFiles ? this.deps.outsideFiles().catch(() => []) : [], + ]); + const fetched = outside.length ? [...indexed, ...matchOutsideFiles(outside, query)] : indexed; + const merged = + dirs.length || outside.length + ? [...fetched.map((m) => ({ m, folder: false })), ...dirs.map((m) => ({ m, folder: true }))].sort( + (a, b) => b.m.score - a.m.score || Number(a.folder) - Number(b.folder), + ) + : fetched.map((m) => ({ m, folder: false })); + return keep ? merged.filter(({ m }) => keep(m.path)) : merged; + }; + let matches = await search(text); + const bare = matches.length ? null : withoutWildcards(text, this.deps.root()); + if (bare !== null && this.isLive(id, gen)) matches = await search(bare); this.set( id, gen, diff --git a/src/features/search/everywhere/model.ts b/src/features/search/everywhere/model.ts index 80abac5bb6..e3a27c11df 100644 --- a/src/features/search/everywhere/model.ts +++ b/src/features/search/everywhere/model.ts @@ -505,12 +505,37 @@ const MIXED: readonly SectionId[] = ["classes", "files", "symbols", "endpoints", */ export const TEXT_WEIGHT = 350; +/** + * A Files query without IDEA's `*` wildcard, when it has one and a name is left to search for. + * File search matches a subsequence already, so `*` needs no character of its own; the query as + * typed is searched first, so a name that really contains `*` is still found. + */ +export function withoutWildcards(query: string, root?: string | null): string | null { + if (!query.includes("*")) return null; + const q = query.replaceAll("*", ""); + // What the index would search for (`normalize_file_query`): an empty query lists recent files instead. + let rest = q.replace(/\s+/g, "").replace(/(:\d+)+$/, ""); + // A drive-letter root compares like Windows, where case does not matter. + const base = root?.replace(/\\/g, "/").replace(/\/+$/, ""); + if (base && rest.toLowerCase().startsWith(base.toLowerCase())) rest = rest.slice(base.length); + return rest.replace(/^(\.?\/)+/, "") ? q : null; +} + /** Comparable match degree of an item's name against the query (IDEA's `MatchingDegree`). */ export function itemWeight(item: SeItem, query: string): number { const name = (text: string) => matchText(text, query)?.score; switch (item.kind) { - case "file": - return name(item.name) ?? (name(item.rel) ?? 0) - 200; + case "file": { + // As file search does: the query as typed, else without its `*` wildcards. + const weigh = (q: string) => { + const byName = matchText(item.name, q)?.score; + if (byName !== undefined) return byName; + const byPath = matchText(item.rel, q)?.score; + return byPath === undefined ? undefined : byPath - 200; + }; + const bare = withoutWildcards(query); + return weigh(query) ?? (bare === null ? undefined : weigh(bare)) ?? -200; + } case "symbol": if (item.score !== undefined) return item.score; return name(item.name) ?? (item.container ? name(`${item.container}.${item.name}`) : undefined) ?? 0;