feat(code-insight): Export to Text File in the Find Usages tool window (#6292)

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 <[email protected]>
Цей коміт міститься в:
Mansur Akhmadiтаmansur-akhmadi authored and GitHub committed 2026-11-27 15:06:50 +08:00
1 джерело aebc2fe02d
коміт 4a3eacff62
7 files changed
+368 -23

No files matched your search

+1 -1
Переглянути файл
@@ -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**.
+1 -1
Переглянути файл
@@ -75,7 +75,7 @@ description: "代码补全、导航、查找用法、文档、层次结构与文
| **高亮文件中的用法** | `⇧⌘F7` | `Ctrl+Shift+F7` |
| **下一个高亮的用法** / **上一个** | `⌃⌥↓` / `⌃⌥↑` | `Ctrl+Alt+Down` / `Ctrl+Alt+Up` |
**查找用法** 把结果按文件分组列在 **查找用法** 工具窗口中,并带预览。**显示用法** 在光标处用弹窗显示。**最近的查找用法**(通过查找操作执行)列出最近十次搜索,包括标签页已关闭的,选中一项即重新运行。移动光标时,编辑器会自动高亮光标下符号的所有出现位置。
**查找用法** 把结果按文件分组列在 **查找用法** 工具窗口中,并带预览。**显示用法** 在光标处用弹窗显示。**最近的查找用法**(通过查找操作执行)列出最近十次搜索,包括标签页已关闭的,选中一项即重新运行。工具窗口工具栏中的 **导出到文本文件** 把当前显示的结果(应用访问过滤,不含已排除的用法)保存为文本文件。移动光标时,编辑器会自动高亮光标下符号的所有出现位置。
声明上方会显示用法数量(如 `3 usages`)和这段代码最后的作者(来自 Git blame),并标注最近一次修改的日期。可以在 **设置 › 编辑器 › 嵌入提示** 的 **Code Vision** 一节中关闭。
+112 -18
Переглянути файл
@@ -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 (
<Tabs
variant="compact"
@@ -144,6 +155,84 @@ export function toggleExcludedUsages(excluded: ReadonlySet<string>, 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<string>,
): 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>,
): 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<void> {
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<Node[]>(
() =>
(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<Node[]>(() => (files.length ? [{ kind: "summary", key: SUMMARY_KEY }] : []), [files.length]);
@@ -288,6 +373,15 @@ export function UsagesView() {
<UsageAccessFilter items={allUsages} vertical />
<IconButton icon="expand-all" title="Expand All" size="small" iconSize={16} onClick={() => setAll(false)} />
<IconButton icon="collapse-all" title="Collapse All" size="small" iconSize={16} onClick={() => setAll(true)} />
<span className={styles.toolbarSep} />
<IconButton
icon="export"
title="Export to Text File…"
action="usages.exportToTextFile"
size="small"
iconSize={16}
disabled={search.loading || files.every(isExcluded)}
/>
</div>
<div className={styles.body} onKeyDown={onKeyDown}>
{!search.loading && !search.error && search.scope === "project" && (
+13 -1
Переглянути файл
@@ -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",
+231
Переглянути файл
@@ -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<string | null> => "/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> = {}): 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(<UsagesView />);
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(<UsagesView />);
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(<UsagesView />);
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(<UsagesView />);
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();
});
});
+5 -1
Переглянути файл
@@ -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"
}
+5 -1
Переглянути файл
@@ -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": "无法导出用法"
}