feat(run): Fold Lines Like This in the Run console's context menu (#4635)

The Run console's context menu gets Fold Lines Like This: it opens Settings › Build, Execution, Deployment › Console with the selected single-line text, or the right-clicked line, added to the fold patterns. Verified with full vitest, typecheck, and in the app (pattern added, Cancel leaves settings unchanged).

Co-authored-by: mansur-akhmadi <10739460+mansur-akhmadi@users.noreply.github.com>
This commit is contained in:
Mansur Akhmadi
2026-11-20 10:15:00 +08:00
committed by GitHub
co-authored by mansur-akhmadi
parent 006405ca11
commit 36ecb53159
8 changed files with 284 additions and 4 deletions
+1 -1
View File
@@ -160,7 +160,7 @@ A **Compound** configuration starts several configurations at once. Run it to st
Each launch opens a tab in the **Run** tool window (bottom). The toolbar has **Rerun**, **Debug**, **Rerun Failed Tests** (for test runs), **Update Application**, **Find…**, **Scroll to End**, **Soft-Wrap**, **Clear All** and **Edit Configurations…**.
- File paths and stack trace frames in the output are links.
- Repeated lines can be folded; configure the patterns in **Settings › Build, Execution, Deployment › Console**, along with the buffer size and the console encoding.
- Repeated lines can be folded; configure the patterns in **Settings › Build, Execution, Deployment › Console**, along with the buffer size and the console encoding. **Fold Lines Like This** in the console's context menu opens that page with the selected text (or the clicked line) added as a pattern.
- Log lines can take the colour of their level (`ERROR`, `WARN`, `INFO`, `DEBUG`, `TRACE`); colours the program prints itself are kept. Turn it on and pick the colours in **Settings › Build, Execution, Deployment › Console**.
- For test runs the tab shows a test tree next to the output. See [Testing](/en/guide/testing).
+1 -1
View File
@@ -156,7 +156,7 @@ Maven 模块在 **自动** 和 **构建(Make)** 时由 jdtls(ECJ)构建
每次启动都会在底部的 **运行** 工具窗口里开一个标签页。工具栏有 **重新运行**、**调试**、**重新运行失败的测试**(测试运行时)、**更新应用**、**查找…**、**滚动到末尾**、**软换行**、**全部清除** 和 **编辑配置…**。
- 输出里的文件路径和堆栈帧都可以点击跳转。
- 重复的行可以折叠。折叠规则、缓冲区大小和控制台编码在 **设置 › 构建、执行、部署 › 控制台** 中配置。
- 重复的行可以折叠。折叠规则、缓冲区大小和控制台编码在 **设置 › 构建、执行、部署 › 控制台** 中配置。控制台右键菜单中的 **折叠与此类似的行** 会打开该页面,并把选中的文本(或右键所在的行)添加为折叠规则。
- 日志行可按级别着色(`ERROR`、`WARN`、`INFO`、`DEBUG`、`TRACE`);程序自行输出的颜色保持不变。默认关闭,可在 **设置 › 构建、执行、部署 › 控制台** 开启并修改颜色。
- 测试运行时,标签页会在输出旁显示测试树,参见[测试](/zh/guide/testing)。
+25
View File
@@ -29,6 +29,7 @@ import { useConsoleSelection } from "./useConsoleSelection";
import { hostBinding, formatBinding, hasPrimaryModifier, registerKeyClaim } from "@/platform/keymap";
import { WidestColumns } from "@/platform/consoleColumns";
import { tx } from "@/platform/i18n";
import { executeAction } from "@/platform/actions";
import { ConsoleFindBar } from "@/ui/ConsoleFindBar";
import { DEFAULT_FIND_OPTIONS, findInLines, type FindOptions } from "@/ui/consoleFind";
@@ -115,6 +116,15 @@ export interface Fold {
*/
export type DisplayRow = { kind: "line"; index: number; fold?: Fold } | { kind: "fold"; fold: Fold };
/**
* IDEA's Fold Lines Like This: the selection when it stays on one line, else the clicked line;
* trimmed, and `null` when that leaves nothing to fold on.
*/
export function foldLineText(selection: string, line: string | null): string | null {
const text = (selection || (line ?? "")).trim();
return text && !/[\r\n]/.test(text) ? text : null;
}
/**
* Folds runs of consecutive output lines (one or more) that contain one of
* `patterns`; runs whose first line id is in `expanded` stay open.
@@ -421,9 +431,18 @@ export function ConsoleView({
/** The selected text; after Select All the whole buffer, including rows that are not mounted. */
const selectedOutput = () => (allSelected() ? model.text() : (window.getSelection()?.toString() ?? ""));
/** The output line a context menu opened on; folds and the input row have none. */
const lineAt = (target: EventTarget) => {
const index = (target as Element).closest?.("[data-index]")?.getAttribute("data-index");
const row = index == null ? undefined : rows[Number(index)];
const line = row?.kind === "line" ? lines[row.index] : undefined;
return line && line.kind !== "system" ? line.text : null;
};
const onContextMenu = (e: MouseEvent) => {
e.preventDefault();
const selection = selectedOutput();
const foldText = foldLineText(selection, lineAt(e.target));
showContextMenu(e, [
{
label: "Copy",
@@ -441,6 +460,12 @@ export function ConsoleView({
run: openFind,
},
{ kind: "separator" },
{
label: "Fold Lines Like This",
disabled: !foldText,
// Opens Settings › Console with the text added to the fold patterns, for OK / Cancel there.
run: () => void executeAction("file.settings", `build.console#${foldText}`),
},
{ label: "Clear All", icon: "trash", disabled: !onClear, run: () => onClear?.() },
...(input
? [{ kind: "separator" } as const, { label: "Send EOF", shortcut: "⌃D", run: () => input.onEof() }]
+129
View File
@@ -0,0 +1,129 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, within } from "@testing-library/react";
import { useProject } from "@/platform/project";
import { hideContextMenu, useContextMenuStore } from "@/ui";
import { ConsoleModel } from "./console";
import { ConsoleView, foldLineText } from "./ConsoleView";
const actions = vi.hoisted(() => ({ executeAction: vi.fn(async () => {}) }));
vi.mock("@/platform/actions", async (orig) => ({ ...(await orig<object>()), executeAction: actions.executeAction }));
vi.mock("@tanstack/react-virtual", () => ({
useVirtualizer: ({ count }: { count: number }) => ({
getTotalSize: () => count * 20,
getVirtualItems: () => Array.from({ length: count }, (_, index) => ({ index, start: index * 20, key: index })),
scrollToIndex: () => {},
measureElement: () => {},
measure: () => {},
}),
}));
beforeEach(() => {
actions.executeAction.mockClear();
useProject.setState({ settings: null });
window.getSelection()?.removeAllRanges();
});
afterEach(() => act(hideContextMenu));
function setup(chunks: { kind: "stdout" | "stderr" | "system"; text: string }[]) {
const model = new ConsoleModel();
for (const c of chunks) model.append(c);
model.flush();
const { container } = render(
<ConsoleView model={model} version={1} softWrap={false} follow={false} onFollowChange={() => {}} cwd="/" />,
);
return within(container).getByRole("log");
}
function foldItem(target: Element) {
fireEvent.contextMenu(target);
const items = useContextMenuStore.getState().menu?.items ?? [];
return items.find((i) => "label" in i && i.label === "Fold Lines Like This") as
| { disabled?: boolean; run?: () => void }
| undefined;
}
function select(node: Node, start: number, end: number) {
const range = document.createRange();
range.setStart(node, start);
range.setEnd(node, end);
window.getSelection()!.removeAllRanges();
window.getSelection()!.addRange(range);
}
describe("foldLineText", () => {
it("takes a one-line selection, else the clicked line, trimmed", () => {
expect(foldLineText(" at org.junit.Assert ", "ignored")).toBe("at org.junit.Assert");
expect(foldLineText("", "\tat java.base/Thread.run(Thread.java:1583) ")).toBe(
"at java.base/Thread.run(Thread.java:1583)",
);
// A whole row picked by a triple click ends in its line break.
expect(foldLineText("DEBUG pool\n", null)).toBe("DEBUG pool");
});
it("has nothing for a selection across lines, a blank selection or a blank line", () => {
expect(foldLineText("first\nsecond", "first")).toBeNull();
expect(foldLineText("first\r\nsecond", "first")).toBeNull();
expect(foldLineText(" ", "a line")).toBeNull();
expect(foldLineText("", " ")).toBeNull();
expect(foldLineText("", null)).toBeNull();
});
});
describe("Fold Lines Like This", () => {
it("opens Settings › Console with the clicked line to add as a fold pattern", () => {
const log = setup([
{
kind: "stdout",
text: "start\n at org.springframework.test.context.TestContextManager.prepare(TestContextManager.java:248)\n",
},
]);
const row = log.querySelectorAll("[data-index]")[1]!;
const item = foldItem(row.firstElementChild ?? row)!;
expect(item.disabled).toBeFalsy();
item.run!();
expect(actions.executeAction).toHaveBeenCalledWith(
"file.settings",
"build.console#at org.springframework.test.context.TestContextManager.prepare(TestContextManager.java:248)",
);
});
it("uses the selected part of a line rather than the whole line", () => {
const log = setup([{ kind: "stdout", text: "12:00 DEBUG pool: idle\n" }]);
const row = log.querySelector("[data-index]")!;
const text = document.createTreeWalker(row, NodeFilter.SHOW_TEXT).nextNode()!;
select(text, 6, 11);
foldItem(row)!.run!();
expect(actions.executeAction).toHaveBeenCalledWith("file.settings", "build.console#DEBUG");
});
it("is disabled for a selection over several lines", () => {
const log = setup([{ kind: "stdout", text: "one\ntwo\n" }]);
const rows = log.querySelectorAll("[data-index]");
const range = document.createRange();
range.setStart(rows[0]!, 0);
range.setEnd(rows[1]!, rows[1]!.childNodes.length);
window.getSelection()!.removeAllRanges();
window.getSelection()!.addRange(range);
expect(foldItem(rows[0]!)!.disabled).toBe(true);
});
it("is disabled on a blank line, the IDE's own messages and a folded run", () => {
useProject.setState({ settings: { console: { foldPatterns: ["at org."] } } as never });
const log = setup([
{ kind: "stdout", text: "\n" },
{ kind: "system", text: "Process finished with exit code 0\n" },
]);
const rows = log.querySelectorAll("[data-index]");
expect(foldItem(rows[0]!)!.disabled).toBe(true);
expect(foldItem(rows[1]!)!.disabled).toBe(true);
act(hideContextMenu);
const folded = setup([{ kind: "stdout", text: "at org.a\nat org.b\n" }]);
const fold = folded.querySelector("[data-index]")!;
expect(fold.textContent).toContain("internal lines");
expect(foldItem(fold)!.disabled).toBe(true);
expect(actions.executeAction).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,107 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, within } from "@testing-library/react";
import { type Settings } from "@/platform/ipc";
const settingsSet = vi.fn();
const settingsGet = vi.fn();
const settingsGetGlobal = vi.fn();
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
return {
...real,
isTauri: () => true,
commands: {
...real.commands,
settingsSet: (...a: unknown[]) => settingsSet(...a),
settingsGet: () => settingsGet(),
settingsGetGlobal: () => settingsGetGlobal(),
},
};
});
import { executeAction } from "@/platform/actions";
import { useProject } from "@/platform/project";
import { DEFAULT_SETTINGS, setAt } from "../model/schema";
import { useSettingsDialog } from "../model/staging";
import { SettingsDialog } from "../dialog/SettingsDialog";
import { activate } from "..";
let current: Settings;
let dispose: () => void = () => {};
beforeEach(() => {
current = setAt(structuredClone(DEFAULT_SETTINGS) as Settings, "console.foldPatterns", ["at org.junit."]);
settingsSet.mockReset().mockImplementation(async (_scope: string, key: string, json: string) => {
current = setAt(current, key, JSON.parse(json));
return { status: "ok", data: current };
});
settingsGet.mockReset().mockImplementation(async () => current);
settingsGetGlobal.mockReset().mockImplementation(async () => current);
useProject.setState({ settings: current, project: null });
dispose = activate();
});
afterEach(() => {
act(() => useSettingsDialog.setState({ open: false }));
dispose();
});
/** Settings › Console as the console's Fold Lines Like This opens it. */
async function openWith(text: string) {
render(<SettingsDialog />);
await act(async () => {
await executeAction("file.settings", `build.console#${text}`);
});
const dialog = screen.getByRole("dialog", { name: "Settings" });
const list = await within(dialog).findByRole("listbox", { name: "Fold console lines that contain" });
return {
dialog,
patterns: () =>
within(list)
.getAllByRole("option")
.map((o) => o.textContent),
};
}
it("adds the console's line to the fold patterns, written on OK", async () => {
const { dialog, patterns } = await openWith("at com.example.Retry#call");
expect(patterns()).toEqual(["at org.junit.", "at com.example.Retry#call"]);
expect(settingsSet).not.toHaveBeenCalled();
await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "OK" })));
expect(settingsSet).toHaveBeenCalledWith(
"global",
"console.foldPatterns",
JSON.stringify(["at org.junit.", "at com.example.Retry#call"]),
);
});
it("writes nothing when the dialog is cancelled", async () => {
const { dialog } = await openWith("DEBUG");
await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" })));
expect(settingsSet).not.toHaveBeenCalled();
});
it("does not add a pattern the list already has", async () => {
const { dialog, patterns } = await openWith("at org.junit.");
expect(patterns()).toEqual(["at org.junit."]);
await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "OK" })));
expect(settingsSet).not.toHaveBeenCalled();
});
it("adds to the global list, not the project's own, while the global settings load", async () => {
const global = current;
settingsGetGlobal.mockImplementation(async () => global);
useProject.setState({
settings: setAt(global, "console.foldPatterns", ["at com.acme.internal."]),
project: { root: "/p", name: "p" } as never,
});
const { dialog, patterns } = await openWith("DEBUG");
expect(patterns()).toEqual(["at org.junit.", "DEBUG"]);
await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "OK" })));
expect(settingsSet).toHaveBeenCalledWith(
"global",
"console.foldPatterns",
JSON.stringify(["at org.junit.", "DEBUG"]),
);
});
+18 -1
View File
@@ -3,10 +3,15 @@
* Stepping), Python Debugger and Run/Debug. Consumed by the run and debugger
* features (and `ide-run` for encoding / termination timeout).
*/
import { useEffect } from "react";
import { WORKFLOW_LIMITS } from "@/platform/workflowSettings";
import { useSettingsPageFocus } from "@/workbench/contributions";
import { isTauri } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import type { SelectOption } from "@/ui";
import { ColorSwatches, FormGroup, GlobListEditor, NumberInput, Row, Toggle } from "../components/Form";
import { useSetting } from "../components/context";
import { usePageContext, useSetting } from "../components/context";
import { useSettingsDialog } from "../model/staging";
import { lazyPage } from "./lazyPage";
import type { PageSpec } from "./spec";
import { Indented, ToggleNumber } from "./workflowControls";
@@ -53,6 +58,18 @@ function BufferRow() {
function FoldPatterns() {
const [patterns, set] = useSetting<string[]>("console.foldPatterns");
// Opened as `build.console#<text>` by the console's Fold Lines Like This: add it as a pattern.
const { focus, consume } = useSettingsPageFocus();
// With a project open, the Global list arrives after the dialog opens (until then it is the project's).
const { scope } = usePageContext();
const globalPending = useSettingsDialog((s) => s.globalBase === s.base);
const hasProject = useProject((s) => !!s.project);
const waiting = scope === "global" && globalPending && hasProject && isTauri();
useEffect(() => {
if (!focus || waiting) return;
consume();
if (!patterns.includes(focus)) set([...patterns, focus]);
}, [focus, consume, waiting, patterns, set]);
return (
<Row
label="Fold console lines that contain"
+2 -1
View File
@@ -2705,5 +2705,6 @@
"Loading…": "Loading…",
"<schema>": "<schema>",
"Shelve Silently": "Shelve Silently",
"Unshelve Silently": "Unshelve Silently"
"Unshelve Silently": "Unshelve Silently",
"Fold Lines Like This": "Fold Lines Like This"
}
+1
View File
@@ -3349,6 +3349,7 @@
"Hold Shift to Debug, F4 to edit, Delete to remove": "按住 Shift 调试,F4 编辑,Delete 删除",
"Hold Shift to Run, F4 to edit, Delete to remove": "按住 Shift 运行,F4 编辑,Delete 删除",
"Send EOF": "发送 EOF",
"Fold Lines Like This": "折叠与此类似的行",
"Collapse folded lines": "折叠行",
"Close Tool Window Tab": "关闭工具窗口标签页",
"No open files": "没有打开的文件",