From 4a3eacff6288744c1e8cf6eb7845b4e0d2cf0358 Mon Sep 17 00:00:00 2001 From: Mansur Akhmadi Date: Fri, 27 Nov 2026 14:06:50 +0700 Subject: [PATCH] feat(code-insight): Export to Text File in the Find Usages tool window (#6292) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds Export to Text File… to the Find Usages toolbar and Find Action. It writes the active search as shown (access filter applied, excluded usages left out) as an indented text report to a file picked in the save dialog, and reports write errors as a notification. Co-authored-by: mansur-akhmadi <10739460+mansur-akhmadi@users.noreply.github.com> --- docs/en/guide/code-intelligence.mdx | 2 +- docs/zh/guide/code-intelligence.mdx | 2 +- src/features/code-insight/UsagesView.tsx | 130 ++++++++-- src/features/code-insight/index.ts | 14 +- .../code-insight/usagesExport.test.tsx | 231 ++++++++++++++++++ src/platform/locales/text/en.json | 6 +- src/platform/locales/text/zh.json | 6 +- 7 files changed, 368 insertions(+), 23 deletions(-) create mode 100644 src/features/code-insight/usagesExport.test.tsx diff --git a/docs/en/guide/code-intelligence.mdx b/docs/en/guide/code-intelligence.mdx index a5b2e85d7..862d9c2a6 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. **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. +**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. **Export to Text File** in the tool window's toolbar saves the results as shown (with the access filter applied, without excluded usages) to a text file. 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 899ade520..9832113f9 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/UsagesView.tsx b/src/features/code-insight/UsagesView.tsx index fdd7a34e4..d21ad93a1 100644 --- a/src/features/code-insight/UsagesView.tsx +++ b/src/features/code-insight/UsagesView.tsx @@ -7,12 +7,14 @@ import { useCallback, useLayoutEffect, useMemo, useRef, useState, type KeyboardE import clsx from "clsx"; import { create } from "zustand"; import { previewColors, tokenSpans, useLineTokens } from "@/editor/lineTokens"; -import { formatMessage, useTx } from "@/platform/i18n"; +import { save } from "@/platform/dialog"; +import { writeDesktopText } from "@/platform/desktopFiles"; +import { formatMessage, tx, useTx } from "@/platform/i18n"; import { useEditorPrefs } from "@/platform/editorSettings"; import { BUNDLED_MONO_FAMILY, monoFontFamily } from "@/platform/fonts"; import { shortcutLabel } from "@/platform/keymap"; import { basename, relativeDir, useProject } from "@/platform/project"; -import { useOccurrenceNavigator } from "@/workbench/contributions"; +import { notifications, useOccurrenceNavigator } from "@/workbench/contributions"; import { EmptyState, Icon, @@ -41,10 +43,17 @@ import { useUsages, type Usage, type UsageGroup, + type UsageSearch, } from "./usages"; import styles from "./UsagesView.module.css"; -import { UsageAccessFilter, filterUsageAccess, supportsUsageAccess, useUsageAccessOptions } from "./UsageAccessFilter"; +import { + UsageAccessFilter, + filterUsageAccess, + supportsUsageAccess, + useUsageAccessOptions, + type UsageAccessOptions, +} from "./UsageAccessFilter"; type Node = | { kind: "summary"; key: string } @@ -63,22 +72,24 @@ export function UsagePreview({ usage }: { usage: Usage }) { ); } +function usageTabLabel(t: UsageSearch, tx: (text: string) => string): string { + if (!t.symbol) return tx("Usages"); + const text = + t.scope === "project" + ? tx("Usages of '{symbol}' in Project Files") + : t.scope === "libraries" + ? tx("Usages of '{symbol}' in Project and Libraries") + : tx("Usages of '{symbol}'"); + return formatMessage(text, { symbol: t.symbol }); +} + /** Tool window header: one content tab per search (`Usages of 'foo'`). */ export function UsagesTabs() { const tx = useTx(); const tabs = useUsages((s) => s.tabs); const search = useUsages(activeUsageSearch); if (!search) return null; - const label = (t: (typeof tabs)[number]) => { - if (!t.symbol) return tx("Usages"); - const text = - t.scope === "project" - ? tx("Usages of '{symbol}' in Project Files") - : t.scope === "libraries" - ? tx("Usages of '{symbol}' in Project and Libraries") - : tx("Usages of '{symbol}'"); - return formatMessage(text, { symbol: t.symbol }); - }; + const label = (t: (typeof tabs)[number]) => usageTabLabel(t, tx); return ( , usages: read return next; } +/** The search's file groups as the tree shows them (access filter applied, files left empty dropped). */ +function shownGroups(groups: readonly UsageGroup[], options: UsageAccessOptions): UsageGroup[] { + return groups.map((g) => ({ ...g, usages: filterUsageAccess(g.usages, options) })).filter((g) => g.usages.length > 0); +} + +function exportedGroups( + groups: readonly UsageGroup[], + options: UsageAccessOptions, + excluded: ReadonlySet, +): UsageGroup[] { + return shownGroups(groups, options) + .map((g) => ({ ...g, usages: g.usages.filter((u) => !excluded.has(usageKey(u))) })) + .filter((g) => g.usages.length > 0); +} + +/** Export to Text File: the tree as shown (access filter applied), indented four spaces a level, without excluded usages. */ +export function usagesReportText( + search: UsageSearch, + root: string, + options: UsageAccessOptions, + excluded: ReadonlySet, +): string { + const files = exportedGroups(search.groups, options, excluded); + const total = usageCount(files); + const note = search.note ? ` ${search.note}` : ""; + const lines = [ + usageTabLabel(search, tx), + `${tx("Found usages")} (${total} ${tx(total === 1 ? "result" : "results")})${note}`, + ]; + for (const g of files) { + const dir = relativeDir(root, g.path); + const n = g.usages.length; + lines.push(` ${basename(g.path)}${dir ? ` ${dir}` : ""} (${n} ${tx(n === 1 ? "usage" : "usages")})`); + for (const u of g.usages) lines.push(` ${u.line + 1} ${u.text.trim()}`); + } + return `${lines.join("\n")}\n`; +} + +const excludedIn = (search: UsageSearch) => useExcluded.getState().byTab[search.id] ?? NONE; + +/** Whether the active search has usages to export (shown and not excluded). */ +export function canExportUsages(): boolean { + const search = activeUsageSearch(useUsages.getState()); + return ( + !!search && + !search.loading && + exportedGroups(search.groups, useUsageAccessOptions.getState(), excludedIn(search)).length > 0 + ); +} + +/** Saves the active search's results as text, to a file picked in the save dialog. */ +export async function exportUsagesToTextFile(): Promise { + const search = activeUsageSearch(useUsages.getState()); + if (!search || !canExportUsages()) return; + const text = usagesReportText( + search, + useProject.getState().project?.root ?? "", + useUsageAccessOptions.getState(), + excludedIn(search), + ); + const path = await save({ + title: tx("Export to Text File"), + defaultPath: `${usageTabLabel(search, tx).replace(/[/\\:*?"<>|]/g, "_")}.txt`, + filters: [{ name: tx("Text file"), extensions: ["txt"] }], + }); + if (!path) return; + try { + await writeDesktopText(path, text); + } catch (e) { + notifications().notify({ + level: "error", + title: tx("Cannot export the usages"), + body: e instanceof Error ? e.message : String(e), + key: "usages.export", + }); + } +} + function openUsage(u: Usage, focus: boolean) { void openCodeLocation(u.path, { line: u.line, col: u.col }, { focus }); } @@ -159,11 +248,7 @@ export function UsagesView() { const accessOptions = useUsageAccessOptions(); const allUsages = useMemo(() => search?.groups.flatMap((g) => g.usages) ?? [], [search?.groups]); const files = useMemo( - () => - (search?.groups ?? []) - .map((g) => ({ ...g, usages: filterUsageAccess(g.usages, accessOptions) })) - .filter((g) => g.usages.length > 0) - .map((g) => ({ kind: "file", key: g.path, group: g })), + () => shownGroups(search?.groups ?? [], accessOptions).map((g) => ({ kind: "file", key: g.path, group: g })), [search?.groups, accessOptions], ); const roots = useMemo(() => (files.length ? [{ kind: "summary", key: SUMMARY_KEY }] : []), [files.length]); @@ -288,6 +373,15 @@ export function UsagesView() { setAll(false)} /> setAll(true)} /> + +
{!search.loading && !search.error && search.scope === "project" && ( diff --git a/src/features/code-insight/index.ts b/src/features/code-insight/index.ts index 33833e7f1..fab53bc08 100644 --- a/src/features/code-insight/index.ts +++ b/src/features/code-insight/index.ts @@ -19,7 +19,7 @@ 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 { UsagesTabs, UsagesView, canExportUsages, exportUsagesToTextFile, useUsagesHeaderMenu } from "./UsagesView"; import { UsagesPopup } from "./UsagesPopup"; import { findUsages, @@ -166,6 +166,18 @@ export function activate(): () => void { when: "projectOpen && activeToolWindow == 'usages'", run: rerunActiveUsages, }, + { + // IDEA's ExportToTextFile in the Find tool window. + id: "usages.exportToTextFile", + title: "Export to Text File…", + description: "Save the Find Usages results as a text file", + category: "Find", + icon: "export", + when: "projectOpen && activeToolWindow == 'usages'", + keywords: ["usages", "results", "save", "report", "txt"], + enabled: canExportUsages, + run: exportUsagesToTextFile, + }, { id: "find.showUsageResults", title: "Show Usage Results", diff --git a/src/features/code-insight/usagesExport.test.tsx b/src/features/code-insight/usagesExport.test.tsx new file mode 100644 index 000000000..57e7d2033 --- /dev/null +++ b/src/features/code-insight/usagesExport.test.tsx @@ -0,0 +1,231 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { act, fireEvent, render, screen } from "@testing-library/react"; +import type { Usage, UsageSearch } from "./usages"; + +const save = vi.fn(async (_options?: unknown): Promise => "/tmp/usages.txt"); +const writeDesktopText = vi.fn(async (_path: string, _text: string) => {}); +const notify = vi.fn(); +vi.mock(import("@/platform/dialog"), async (importOriginal) => ({ ...(await importOriginal()), save })); +vi.mock(import("@/platform/desktopFiles"), async (importOriginal) => ({ + ...(await importOriginal()), + writeDesktopText, +})); +vi.mock(import("@/workbench/contributions"), async (importOriginal) => ({ + ...(await importOriginal()), + notifications: () => ({ notify }) as never, +})); +vi.mock(import("@/platform/ipc"), async (importOriginal) => ({ + ...(await importOriginal()), + commands: { fsReadText: (path: string) => path } as never, + call: (async () => "") as never, +})); +vi.mock(import("@/editor/api"), async (importOriginal) => ({ ...(await importOriginal()), editorsFor: () => [] })); + +const { UsagesView, canExportUsages, exportUsagesToTextFile, usagesReportText } = await import("./UsagesView"); +const { useUsages } = await import("./usages"); +const { useUsageAccessOptions } = await import("./UsageAccessFilter"); +const { useProject } = await import("@/platform/project"); + +const ALL = { read: true, write: true }; +const usage = (path: string, line: number, text: string, access?: Usage["access"]): Usage => ({ + path, + line, + col: text.indexOf("total"), + endCol: text.indexOf("total") + 5, + text, + access, +}); + +function search(over: Partial = {}): UsageSearch { + return { + id: 7, + symbol: "total", + loading: false, + error: null, + note: null, + rerun: null, + scope: "project", + groups: [ + { + path: "/p/src/cart/cart.ts", + usages: [ + usage("/p/src/cart/cart.ts", 11, " return total;", "read"), + usage("/p/src/cart/cart.ts", 3, "total = 0;", "write"), + ], + }, + { path: "/p/main.ts", usages: [usage("/p/main.ts", 0, "print(total)", "read")] }, + ], + ...over, + }; +} + +function show(s: UsageSearch | null) { + useUsages.setState({ tabs: s ? [s] : [], active: s?.id ?? null }); +} + +afterEach(() => { + show(null); + useProject.setState({ project: null }); + useUsageAccessOptions.setState(ALL); + save.mockClear(); + writeDesktopText.mockReset(); + notify.mockClear(); +}); + +describe("usagesReportText", () => { + it("writes the tree as shown: title, summary, files with their folder and 1-based lines", () => { + expect(usagesReportText(search(), "/p", ALL, new Set())).toBe( + [ + "Usages of 'total' in Project Files", + "Found usages (3 results)", + " cart.ts src/cart (2 usages)", + " 12 return total;", + " 4 total = 0;", + " main.ts (1 usage)", + " 1 print(total)", + "", + ].join("\n"), + ); + }); + + it("follows the tab's title for each scope", () => { + const first = (s: UsageSearch) => usagesReportText(s, "/p", ALL, new Set()).split("\n")[0]; + expect(first(search({ scope: "libraries" }))).toBe("Usages of 'total' in Project and Libraries"); + expect(first(search({ scope: null }))).toBe("Usages of 'total'"); + expect(first(search({ symbol: null }))).toBe("Usages"); + }); + + it("applies the access filter and drops files it empties", () => { + const text = usagesReportText(search(), "/p", { read: false, write: true }, new Set()); + expect(text).toBe( + [ + "Usages of 'total' in Project Files", + "Found usages (1 result)", + " cart.ts src/cart (1 usage)", + " 4 total = 0;", + "", + ].join("\n"), + ); + }); + + it("keeps the summary's note", () => { + expect(usagesReportText(search({ note: "Partial results" }), "/p", ALL, new Set()).split("\n")[1]).toBe( + "Found usages (3 results) Partial results", + ); + }); + + it("writes only the summary when nothing is left", () => { + expect(usagesReportText(search({ groups: [] }), "/p", ALL, new Set())).toBe( + "Usages of 'total' in Project Files\nFound usages (0 results)\n", + ); + }); +}); + +describe("exportUsagesToTextFile", () => { + it("saves the active search to the picked file, named after the tab", async () => { + useProject.setState({ project: { root: "/p" } as never }); + show(search()); + expect(canExportUsages()).toBe(true); + await exportUsagesToTextFile(); + expect(save).toHaveBeenCalledWith( + expect.objectContaining({ + defaultPath: "Usages of 'total' in Project Files.txt", + filters: [{ name: "Text file", extensions: ["txt"] }], + }), + ); + expect(writeDesktopText).toHaveBeenCalledWith("/tmp/usages.txt", usagesReportText(search(), "/p", ALL, new Set())); + expect(notify).not.toHaveBeenCalled(); + }); + + it("leaves out excluded usages and files whose usages are all excluded", async () => { + useProject.setState({ project: { root: "/p" } as never }); + // Exclusions are kept per tab id: a fresh id keeps them out of the other tests. + show(search({ id: 8 })); + const view = render(); + const tree = screen.getByRole("tree", { name: "Usages" }); + fireEvent.mouseDown(screen.getByRole("treeitem", { name: "1print(total)" })); + fireEvent.keyDown(tree, { key: "Backspace" }); + fireEvent.mouseDown(screen.getByRole("treeitem", { name: "4total = 0;" })); + fireEvent.keyDown(tree, { key: "Delete" }); + await act(() => exportUsagesToTextFile()); + expect(writeDesktopText.mock.calls[0]?.[1]).toBe( + [ + "Usages of 'total' in Project Files", + "Found usages (1 result)", + " cart.ts src/cart (1 usage)", + " 12 return total;", + "", + ].join("\n"), + ); + view.unmount(); + }); + + it("writes nothing when the dialog is cancelled", async () => { + show(search()); + save.mockResolvedValueOnce(null); + await exportUsagesToTextFile(); + expect(writeDesktopText).not.toHaveBeenCalled(); + }); + + it("reports a failed write", async () => { + show(search()); + writeDesktopText.mockRejectedValueOnce(new Error("disk full")); + await exportUsagesToTextFile(); + expect(notify).toHaveBeenCalledWith( + expect.objectContaining({ level: "error", title: "Cannot export the usages", body: "disk full" }), + ); + }); + + it("is unavailable while searching, without a search, or when the filter hides every usage", async () => { + expect(canExportUsages()).toBe(false); + show(search({ loading: true })); + expect(canExportUsages()).toBe(false); + show(search({ groups: [{ path: "/p/a.ts", usages: [usage("/p/a.ts", 0, "total = 1", "write")] }] })); + useUsageAccessOptions.setState({ read: true, write: false }); + expect(canExportUsages()).toBe(false); + await exportUsagesToTextFile(); + expect(save).not.toHaveBeenCalled(); + }); +}); + +describe("toolbar", () => { + it("runs the export action", async () => { + const { activate } = await import("./index"); + const { setContext } = await import("@/platform/context"); + const dispose = activate(); + setContext("projectOpen", true); + setContext("activeToolWindow", "usages"); + show(search()); + const view = render(); + fireEvent.click(screen.getByRole("button", { name: "Export to Text File…" })); + await vi.waitFor(() => expect(writeDesktopText).toHaveBeenCalledTimes(1)); + view.unmount(); + dispose(); + setContext("projectOpen", false); + setContext("activeToolWindow", null); + }); + + it("is disabled when every shown usage is excluded or filtered out", () => { + show(search({ id: 9 })); + const view = render(); + const button = screen.getByRole("button", { name: "Export to Text File…" }); + expect(button).toBeEnabled(); + fireEvent.mouseDown(screen.getByRole("treeitem", { name: /^Found usages/ })); + fireEvent.keyDown(screen.getByRole("tree", { name: "Usages" }), { key: "Backspace" }); + expect(button).toBeDisabled(); + expect(canExportUsages()).toBe(false); + act(() => show(search({ groups: [{ path: "/p/a.ts", usages: [usage("/p/a.ts", 0, "total = 1", "write")] }] }))); + act(() => useUsageAccessOptions.setState({ read: true, write: false })); + expect(screen.getByRole("button", { name: "Export to Text File…" })).toBeDisabled(); + view.unmount(); + }); + + it("has Export to Text File, disabled while the search runs", () => { + show(search({ loading: true })); + const view = render(); + expect(screen.getByRole("button", { name: "Export to Text File…" })).toBeDisabled(); + act(() => show(search())); + expect(screen.getByRole("button", { name: "Export to Text File…" })).toBeEnabled(); + view.unmount(); + }); +}); diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 96bbcd521..e0d079956 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -4222,5 +4222,9 @@ "Use {suggested} for this project": "Use {suggested} for this project", "GitHub account: @{activeLogin}": "GitHub account: @{activeLogin}", "Uses GitHub CLI's active account without setting GH_TOKEN in the project environment.": "Uses GitHub CLI's active account without setting GH_TOKEN in the project environment.", - "Passes this account's GH_TOKEN to processes started in this project (terminals, agents, Git, and run configurations).": "Passes this account's GH_TOKEN to processes started in this project (terminals, agents, Git, and run configurations)." + "Passes this account's GH_TOKEN to processes started in this project (terminals, agents, Git, and run configurations).": "Passes this account's GH_TOKEN to processes started in this project (terminals, agents, Git, and run configurations).", + "Export to Text File…": "Export to Text File…", + "Export to Text File": "Export to Text File", + "Save the Find Usages results as a text file": "Save the Find Usages results as a text file", + "Cannot export the usages": "Cannot export the usages" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 46d68564c..a3d4c046a 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -10682,5 +10682,9 @@ "Uses GitHub CLI's active account without setting GH_TOKEN in the project environment.": "使用 GitHub CLI 当前活动账户,不在项目环境中设置 GH_TOKEN。", "Passes this account's GH_TOKEN to processes started in this project (terminals, agents, Git, and run configurations).": "将此账户的 GH_TOKEN 传递给此项目中启动的进程(终端、智能体、Git 和运行配置)。", "Get from Version Control": "从版本控制获取", - "Cannot connect to the remote host": "无法连接到远程主机" + "Cannot connect to the remote host": "无法连接到远程主机", + "Export to Text File…": "导出到文本文件…", + "Export to Text File": "导出到文本文件", + "Save the Find Usages results as a text file": "将查找用法的结果保存为文本文件", + "Cannot export the usages": "无法导出用法" }