diff --git a/docs/en/guide/code-intelligence.mdx b/docs/en/guide/code-intelligence.mdx index 1da0da40f7..a5b2e85d7c 100644 --- a/docs/en/guide/code-intelligence.mdx +++ b/docs/en/guide/code-intelligence.mdx @@ -75,7 +75,7 @@ Going to files, classes and symbols by name is covered in [Search and navigation | **Highlight Usages in File** | `⇧⌘F7` | `Ctrl+Shift+F7` | | **Next Highlighted Usage** / **Previous** | `⌃⌥↓` / `⌃⌥↑` | `Ctrl+Alt+Down` / `Ctrl+Alt+Up` | -**Find Usages** lists the results in the **Find Usages** tool window, grouped by file, with a preview. **Show Usages** shows them in a popup at the caret. The occurrences of the symbol under the caret are highlighted in the editor as you move. +**Find Usages** lists the results in the **Find Usages** tool window, grouped by file, with a preview. **Show Usages** shows them in a popup at the caret. **Recent Find Usages** (from Find Action) lists the last ten searches, including those whose tab was closed, and runs the chosen one again. The occurrences of the symbol under the caret are highlighted in the editor as you move. Above declarations, a **N usages** hint and the last author of the code (from Git blame) are shown, with the date of that last change. Turn them off under **Code Vision** in **Settings › Editor › Inlay Hints**. diff --git a/docs/zh/guide/code-intelligence.mdx b/docs/zh/guide/code-intelligence.mdx index 0da1605abe..899ade520d 100644 --- a/docs/zh/guide/code-intelligence.mdx +++ b/docs/zh/guide/code-intelligence.mdx @@ -75,7 +75,7 @@ description: "代码补全、导航、查找用法、文档、层次结构与文 | **高亮文件中的用法** | `⇧⌘F7` | `Ctrl+Shift+F7` | | **下一个高亮的用法** / **上一个** | `⌃⌥↓` / `⌃⌥↑` | `Ctrl+Alt+Down` / `Ctrl+Alt+Up` | -**查找用法** 把结果按文件分组列在 **查找用法** 工具窗口中,并带预览。**显示用法** 在光标处用弹窗显示。移动光标时,编辑器会自动高亮光标下符号的所有出现位置。 +**查找用法** 把结果按文件分组列在 **查找用法** 工具窗口中,并带预览。**显示用法** 在光标处用弹窗显示。**最近的查找用法**(通过查找操作执行)列出最近十次搜索,包括标签页已关闭的,选中一项即重新运行。移动光标时,编辑器会自动高亮光标下符号的所有出现位置。 声明上方会显示用法数量(如 `3 usages`)和这段代码最后的作者(来自 Git blame),并标注最近一次修改的日期。可以在 **设置 › 编辑器 › 嵌入提示** 的 **Code Vision** 一节中关闭。 diff --git a/src/features/code-insight/index.ts b/src/features/code-insight/index.ts index 0fd147d2aa..33833e7f16 100644 --- a/src/features/code-insight/index.ts +++ b/src/features/code-insight/index.ts @@ -13,12 +13,23 @@ import { registerToolWindow, } from "@/workbench/contributions"; import { getContext } from "@/platform/context"; +import { formatMessage, tx } from "@/platform/i18n"; +import { basename } from "@/platform/project"; +import { showContextMenu } from "@/ui/Menu"; import { clearProblems, installProblemsEvents, problemsReport, useProblems } from "./problemsStore"; import { installProblemDecorations } from "./decorations"; import { ProblemsTabs, ProblemsView, useProblemsHeaderMenu } from "./ProblemsView"; import { UsagesTabs, UsagesView, useUsagesHeaderMenu } from "./UsagesView"; import { UsagesPopup } from "./UsagesPopup"; -import { findUsages, rerunActiveUsages, resetUsages, showUsageResults, showUsagesPopup } from "./usages"; +import { + findUsages, + recentUsageSearches, + rerunActiveUsages, + rerunRecentUsages, + resetUsages, + showUsageResults, + showUsagesPopup, +} from "./usages"; import { HierarchyTabs, HierarchyView } from "./HierarchyView"; import { resetHierarchy, showHierarchy } from "./hierarchy"; import { installServerEvents, linterCovers } from "./servers"; @@ -28,6 +39,17 @@ import { installWorkspaceEditUndo } from "./workspaceUndo"; const EDITOR_WHEN = "textEditorActive && (editorFocus || !toolWindowFocus)"; +/** Recent Find Usages: IDEA's list of the last searches; the chosen one runs again in the tool window. */ +function showRecentUsages() { + const items = recentUsageSearches().map((search) => ({ + label: search.symbol ? formatMessage(tx("Usages of '{symbol}'"), { symbol: search.symbol }) : tx("Usages"), + verbatim: true, + shortcut: `${basename(search.path)}:${search.line + 1}`, + run: () => void rerunRecentUsages(search), + })); + showContextMenu("center", items, { title: "Recent Find Usages" }); +} + function useErrorBadge(): number | null { return useProblems((s) => s.counts.error || null); } @@ -127,6 +149,14 @@ export function activate(): () => void { when: EDITOR_WHEN, run: () => showUsagesPopup(), }, + { + id: "find.recentUsages", + title: "Recent Find Usages", + category: "Find", + when: "projectOpen", + enabled: () => recentUsageSearches().length > 0, + run: showRecentUsages, + }, { // ⌘R in the Find Usages tool window, as in IDEA. id: "usages.rerun", diff --git a/src/features/code-insight/recentUsages.test.ts b/src/features/code-insight/recentUsages.test.ts new file mode 100644 index 0000000000..75b8a30fec --- /dev/null +++ b/src/features/code-insight/recentUsages.test.ts @@ -0,0 +1,200 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const show = vi.fn(); +const hide = vi.fn(); +vi.mock("@/workbench/contributions", async (orig) => ({ + ...(await orig()), + toolWindowService: () => ({ show, hide }), +})); +const lspReferences = vi.fn(async (..._args: unknown[]) => ({ status: "ok", data: null })); +vi.mock("@/platform/ipc", async (orig) => { + const actual = await orig(); + return { ...actual, commands: { ...actual.commands, lspReferences } }; +}); +/** The caret Find Usages starts from (`null`: no editor). */ +let caret: { doc: number; path: string; line: number; col: number; word: string | null } | null = null; +/** Documents `withDocument` opened and closed, by path; a missing path fails to open. */ +const opened: string[] = []; +const closed: number[] = []; +const reportError = vi.fn(); +vi.mock("./ipc", async (orig) => ({ + ...(await orig()), + caretContext: () => (caret ? { ...caret, view: null } : null), + lspRequest: async (request: () => unknown) => { + request(); + return { locations: [], incomplete: null }; + }, + readManyFileLines: async () => new Map(), + withDocument: async (path: string, fn: (doc: number) => Promise) => { + if (path.includes("missing")) throw new Error(`Cannot open ${path}`); + opened.push(path); + const doc = 100 + opened.length; + try { + return await fn(doc); + } finally { + closed.push(doc); + } + }, + reportError, +})); + +vi.mock("@tauri-apps/api/core", async (orig) => ({ + ...(await orig()), + Channel: class { + onmessage = () => {}; + }, +})); + +const { executeAction, getAction } = await import("@/platform/actions"); +const { setContext } = await import("@/platform/context"); +const { useContextMenuStore } = await import("@/ui/Menu"); +const { activate } = await import("./index"); +const { activeUsageSearch, closeUsageTab, findUsages, recentUsageSearches, resetUsages, useUsages } = + await import("./usages"); + +const at = (path: string, line: number, col: number, word: string | null, doc = 1) => { + caret = { doc, path, line, col, word }; +}; +/** The (doc, line, col) of the last references request. */ +const lastRequest = () => { + const [, doc, pos, , , libraries] = lspReferences.mock.lastCall!; + return { doc, pos, libraries }; +}; + +describe("Recent Find Usages", () => { + beforeEach(() => { + resetUsages(); + lspReferences.mockClear(); + opened.length = 0; + closed.length = 0; + reportError.mockClear(); + useContextMenuStore.setState({ menu: null }); + }); + + it("remembers searches newest first, once per position, up to ten", async () => { + at("/p/a.rs", 1, 4, "foo"); + await findUsages(); + at("/p/b.rs", 2, 0, "bar"); + await findUsages(); + at("/p/a.rs", 1, 4, "foo"); + await findUsages(); + expect(recentUsageSearches().map((r) => r.symbol)).toEqual(["foo", "bar"]); + + // Same name elsewhere is another search. + at("/p/c.rs", 7, 2, "foo"); + await findUsages(); + expect(recentUsageSearches().map((r) => r.path)).toEqual(["/p/c.rs", "/p/a.rs", "/p/b.rs"]); + + for (let line = 10; line < 20; line++) { + at("/p/d.rs", line, 0, `s${line}`); + // oxlint-disable-next-line no-await-in-loop -- searches run one after another, like the user's + await findUsages(); + } + expect(recentUsageSearches()).toHaveLength(10); + expect(recentUsageSearches()[0]!.symbol).toBe("s19"); + expect(recentUsageSearches().at(-1)!.symbol).toBe("s10"); + }); + + it("keeps a search after its tab is closed and forgets it on a project switch", async () => { + at("/p/a.rs", 1, 4, "foo"); + await findUsages(); + closeUsageTab(activeUsageSearch(useUsages.getState())!.id); + expect(useUsages.getState().tabs).toHaveLength(0); + expect(recentUsageSearches().map((r) => r.symbol)).toEqual(["foo"]); + resetUsages(); + expect(recentUsageSearches()).toEqual([]); + }); + + it("does not remember a search that never started", async () => { + caret = null; + await findUsages(); + expect(recentUsageSearches()).toEqual([]); + }); + + describe("action", () => { + let dispose: () => void; + beforeEach(() => { + setContext("projectOpen", true); + dispose = activate(); + return () => dispose(); + }); + + it("is disabled until something was searched", async () => { + const action = getAction("find.recentUsages")!; + expect(action.title).toBe("Recent Find Usages"); + expect(action.enabled?.({ arg: undefined } as never)).toBe(false); + expect(await executeAction("find.recentUsages")).toBe(false); + expect(useContextMenuStore.getState().menu).toBeNull(); + }); + + it("lists the searches and runs the chosen one again, in the file's current document", async () => { + at("/p/a.rs", 1, 4, "foo", 7); + await findUsages(); + at("/p/b.rs", 2, 0, "bar", 8); + await findUsages(); + closeUsageTab(activeUsageSearch(useUsages.getState())!.id); + + expect(await executeAction("find.recentUsages")).toBe(true); + const menu = useContextMenuStore.getState().menu!; + expect(menu.title).toBe("Recent Find Usages"); + const items = menu.items.filter((i) => i.kind !== "header") as { + label: string; + shortcut?: string; + run(): void; + }[]; + expect(items.map((i) => [i.label, i.shortcut])).toEqual([ + ["Usages of 'bar'", "b.rs:3"], + ["Usages of 'foo'", "a.rs:2"], + ]); + + // The editor that searched `foo` may be gone: it asks in a document opened for it. + lspReferences.mockClear(); + items[1]!.run(); + await vi.waitFor(() => expect(activeUsageSearch(useUsages.getState())?.loading).toBe(false)); + expect(opened).toEqual(["/p/a.rs"]); + expect(lastRequest()).toEqual({ doc: 101, pos: { line: 1, col: 4 }, libraries: false }); + expect(activeUsageSearch(useUsages.getState())!.symbol).toBe("foo"); + expect(show).toHaveBeenCalledWith("usages"); + // Run again, it is the newest. + expect(recentUsageSearches().map((r) => r.symbol)).toEqual(["foo", "bar"]); + // That document closed with the search: the tab's Rerun opens it again. + expect(closed).toEqual([101]); + activeUsageSearch(useUsages.getState())!.rerun!(); + await vi.waitFor(() => expect(closed).toEqual([101, 102])); + expect(lastRequest()).toEqual({ doc: 102, pos: { line: 1, col: 4 }, libraries: false }); + }); + + it("keeps the scope a search was widened to", async () => { + at("/p/a.rs", 1, 4, "foo"); + await findUsages(); + activeUsageSearch(useUsages.getState())!.searchLibraries!(); + await vi.waitFor(() => expect(lastRequest().libraries).toBe(true)); + await vi.waitFor(() => expect(activeUsageSearch(useUsages.getState())!.loading).toBe(false)); + expect(recentUsageSearches()).toHaveLength(1); + + await executeAction("find.recentUsages"); + const item = useContextMenuStore.getState().menu!.items.find((i) => i.kind !== "header") as { run(): void }; + lspReferences.mockClear(); + item.run(); + await vi.waitFor(() => expect(lspReferences).toHaveBeenCalled()); + expect(lastRequest().libraries).toBe(true); + }); + + it("reports a file that can no longer be opened", async () => { + at("/p/missing.rs", 0, 0, "gone"); + await findUsages(); + await executeAction("find.recentUsages"); + const item = useContextMenuStore.getState().menu!.items.find((i) => i.kind !== "header") as { run(): void }; + lspReferences.mockClear(); + item.run(); + await vi.waitFor(() => expect(reportError).toHaveBeenCalledOnce()); + expect(String(reportError.mock.lastCall![0])).toContain("Cannot open /p/missing.rs"); + expect(lspReferences).not.toHaveBeenCalled(); + expect(activeUsageSearch(useUsages.getState())).toMatchObject({ + symbol: "gone", + loading: false, + error: "Cannot open /p/missing.rs", + }); + }); + }); +}); diff --git a/src/features/code-insight/usages.ts b/src/features/code-insight/usages.ts index 316315c620..62e47afdab 100644 --- a/src/features/code-insight/usages.ts +++ b/src/features/code-insight/usages.ts @@ -2,6 +2,7 @@ import { create } from "zustand"; import { Channel } from "@tauri-apps/api/core"; import type { ClassifiedReference, ReferenceAccess, ReferenceKind, Location, References, RequestId } from "@/bindings"; +import { editorsFor } from "@/editor/api"; import { clearLineTokens } from "@/editor/lineTokens"; import { showPendingHint } from "@/editor/lsp/hint"; import { incompleteNote } from "@/editor/lsp/lsp"; @@ -18,6 +19,7 @@ import { openLocation, readManyFileLines, reportError, + withDocument, type CaretContext, } from "./ipc"; import { syntaxUsages } from "./syntaxUsages"; @@ -299,6 +301,7 @@ export function resetUsages() { if (popupRequest !== null) void commands.cancelRequest(popupRequest).catch(() => {}); popupRequest = null; useUsages.setState({ tabs: [], active: null }); + recentSearches = []; useUsagesPopup.setState({ open: false, symbol: null, groups: [], note: null, loading: false, scope: null }); popupTarget = null; } @@ -309,8 +312,56 @@ export async function findUsages() { hint("Open a file to find usages"); return; } + await searchUsages(c, (fetch) => fetch(c), false, false); +} + +/** A past Find Usages search, run again by Recent Find Usages. */ +export interface RecentUsageSearch { + path: string; + line: number; + col: number; + symbol: string | null; + libraries: boolean; + widenable: boolean; +} + +const MAX_RECENT = 10; +let recentSearches: RecentUsageSearch[] = []; + +/** Recent Find Usages: the last searches, newest first, one per caret position. */ +export const recentUsageSearches = (): readonly RecentUsageSearch[] => recentSearches; + +/** Runs `search` again in a new tab, in its file's document whether or not an editor still has it open. */ +export async function rerunRecentUsages(search: RecentUsageSearch) { + const { path, line, col, symbol, libraries, widenable } = search; + await searchUsages( + { path, line, col, word: symbol }, + (fetch) => + withDocument(path, (doc) => + fetch({ doc, path, line, col, word: symbol, view: editorsFor(path)[0]?.view ?? null }), + ), + libraries, + widenable, + ); +} + +/** Runs `fetch` with the caret of a search: the editor's, or one in a document opened for each run. */ +type InDocument = (fetch: (c: CaretContext) => Promise) => Promise; + +/** Searches the usages at `c` into the tool window. */ +async function searchUsages( + c: Pick, + inDocument: InDocument, + libraries: boolean, + widenable: boolean, +) { + const here = (r: RecentUsageSearch) => r.path === c.path && r.line === c.line && r.col === c.col; // `widenable`: an earlier run of this search skipped the libraries. const run = async (prev: number | null, libraries: boolean, widenable: boolean) => { + recentSearches = [ + { path: c.path, line: c.line, col: c.col, symbol: c.word, libraries, widenable }, + ...recentSearches.filter((r) => !here(r)), + ].slice(0, MAX_RECENT); const id = ++searchSeq; const base = { id, @@ -325,13 +376,16 @@ export async function findUsages() { const request = nextRequestId(); inflight.set(id, request); try { - const { groups, note, librariesSkipped } = await fetchUsages( - c, - request, - (found) => { - if (inflight.get(id) === request) replaceUsageTab(id, { ...loading, groups: found.groups, note: found.note }); - }, - libraries, + const { groups, note, librariesSkipped } = await inDocument((caret) => + fetchUsages( + caret, + request, + (found) => { + if (inflight.get(id) === request) + replaceUsageTab(id, { ...loading, groups: found.groups, note: found.note }); + }, + libraries, + ), ); const scope = searchedScope(libraries, librariesSkipped, widenable); replaceUsageTab(id, { ...base, loading: false, groups, error: null, note, scope }); @@ -345,7 +399,7 @@ export async function findUsages() { if (inflight.get(id) === request) inflight.delete(id); } }; - await run(null, false, false); + await run(null, libraries, widenable); } /** diff --git a/src/platform/ideaActions.ts b/src/platform/ideaActions.ts index f98404367e..3e69926fad 100644 --- a/src/platform/ideaActions.ts +++ b/src/platform/ideaActions.ts @@ -37,6 +37,7 @@ export const IDEA_ACTIONS: Readonly> = { FindPrevWordAtCaret: "find.previousWordAtCaret", FindUsages: "find.usages", ShowUsages: "find.showUsages", + ShowRecentFindUsagesGroup: "find.recentUsages", HighlightUsagesInFile: "find.highlightUsages", ReformatCode: "code.reformat", OptimizeImports: "code.optimizeImports", diff --git a/src/platform/ideaKeymap.test.ts b/src/platform/ideaKeymap.test.ts index 4ac745fda8..5dcee130af 100644 --- a/src/platform/ideaKeymap.test.ts +++ b/src/platform/ideaKeymap.test.ts @@ -120,6 +120,14 @@ describe("IntelliJ IDEA keymap import", () => { expect(k.unknownActions).toEqual([]); }); + it("maps Recent Find Usages", () => { + const k = parseIdeaKeymap( + ``, + ); + expect(k.overrides["find.recentUsages"]).toEqual([normalizeBinding("Ctrl+Alt+Shift+F7")]); + expect(k.unknownActions).toEqual([]); + }); + it("maps Hungry Backspace", () => { const k = parseIdeaKeymap( ``, diff --git a/src/platform/keymaps/ideaParity.test.ts b/src/platform/keymaps/ideaParity.test.ts index eddfdc9561..15a574a877 100644 --- a/src/platform/keymaps/ideaParity.test.ts +++ b/src/platform/keymaps/ideaParity.test.ts @@ -91,6 +91,8 @@ describe("IDEA keymap parity", () => { // Rerun in the Find / Find Usages tool windows uses the Rerun shortcut. ["find.rerun", ["Meta+R"], ["Ctrl+F5"]], ["usages.rerun", ["Meta+R"], ["Ctrl+F5"]], + // ShowRecentFindUsagesGroup has no shortcut. + ["find.recentUsages", [], []], // Vcs.Log.GoToRef: Find in the Git Log table. ["vcs.log.goToRef", ["Meta+F"], ["Ctrl+F"]], // Back / Forward also carry the mouse side buttons (``). diff --git a/src/platform/keymaps/intellij-macos.ts b/src/platform/keymaps/intellij-macos.ts index 6d531a365f..0bb18c4e8d 100644 --- a/src/platform/keymaps/intellij-macos.ts +++ b/src/platform/keymaps/intellij-macos.ts @@ -75,6 +75,7 @@ export const intellijMacos: Record = { "find.replaceInPath": ["Meta+Shift+R"], "find.usages": ["Alt+F7"], "find.showUsages": ["Meta+Alt+F7"], + "find.recentUsages": [], "find.highlightUsages": ["Meta+Shift+F7"], // Code diff --git a/src/platform/keymaps/intellij-windows.ts b/src/platform/keymaps/intellij-windows.ts index ea9e08a5ff..7120fe71c7 100644 --- a/src/platform/keymaps/intellij-windows.ts +++ b/src/platform/keymaps/intellij-windows.ts @@ -76,6 +76,7 @@ export const intellijWindows: Record = { "find.replaceInPath": ["Ctrl+Shift+R"], "find.usages": ["Alt+F7"], "find.showUsages": ["Ctrl+Alt+F7"], + "find.recentUsages": [], "find.highlightUsages": ["Ctrl+Shift+F7"], // Code diff --git a/src/platform/keymaps/vscode-macos.ts b/src/platform/keymaps/vscode-macos.ts index d5ffa0e9a9..64a9b66357 100644 --- a/src/platform/keymaps/vscode-macos.ts +++ b/src/platform/keymaps/vscode-macos.ts @@ -127,6 +127,7 @@ export const vscodeMacos: Record = { "find.replaceInPath": ["Meta+Shift+H"], "find.usages": ["Alt+Shift+F12"], "find.showUsages": ["Shift+F12"], + "find.recentUsages": [], "find.highlightUsages": [], // Code diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index 225376d734..5055db396a 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -9341,5 +9341,6 @@ "Granted with grant option": "已授予(可轉授)", "No privileges are granted on this table.": "此資料表未授予任何權限。", "* With grant option: the grantee may grant the privilege to others.": "* WITH GRANT OPTION:被授權者可以將該權限再授予他人。", - "Separate several prefixes with commas: they are tried in order, then the official source.": "多個前綴以逗號分隔:依序嘗試,最後回退到官方來源。" + "Separate several prefixes with commas: they are tried in order, then the official source.": "多個前綴以逗號分隔:依序嘗試,最後回退到官方來源。", + "Recent Find Usages": "最近的查詢用法" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 11bcc3fe01..3eaeaafa5a 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -10398,5 +10398,6 @@ "Granted with grant option": "已授予(可转授)", "No privileges are granted on this table.": "此表未授予任何权限。", "* With grant option: the grantee may grant the privilege to others.": "* WITH GRANT OPTION:被授权者可以将该权限再授予他人。", - "Separate several prefixes with commas: they are tried in order, then the official source.": "多个前缀用逗号分隔:按顺序尝试,最后回退到官方源。" + "Separate several prefixes with commas: they are tried in order, then the official source.": "多个前缀用逗号分隔:按顺序尝试,最后回退到官方源。", + "Recent Find Usages": "最近的查找用法" }