Compare commits

...
Author SHA1 Message Date
l0ng-ai 89bb74eb98 feat(markdown): run code blocks and command lines from the gutter
Markdown files get run icons like IDEA's Markdown command runner: a shell code
block (sh, bash, zsh, shell, console, PowerShell) runs in a new terminal tab from
its opening fence, and a code block line runs when a Run Anything provider
recognizes it (Maven and Gradle command lines, run configuration names).
Leading $ prompts and trailing comments are dropped.

Languages & Frameworks > Markdown > Commands turns detection off and picks where
blocks run (project or the file's folder); unset, the icon asks when the two
differ. Untrusted projects get no icons.

Closes #4499
2026-11-19 21:16:52 +08:00
l0ng-ai e44e389571 fix(vcs): improve Commit panel layout and message typography (#4518)
The Commit panel wraps change actions into groups when the pane is narrow, so Expand All and Collapse All stay visible, and Commit and Push… wraps its label instead of cutting it. The commit message uses the editor's font family, size, weight and line height.
2026-11-19 20:58:36 +08:00
20 changed files with 532 additions and 99 deletions

No files matched your search

+21 -1
View File
@@ -1194,11 +1194,31 @@ pub struct ArduinoSettings {
}
/// Languages & Frameworks › Markdown. Like IDEA's, it is application-level only.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct MarkdownSettings {
/// Preview (and notebook Markdown cell) font size in px; unset follows the editor font size.
pub preview_font_size: Option<u32>,
/// "Detect commands that can be run right from Markdown files": gutter run icons on
/// shell code blocks and on command lines in code blocks.
pub run_commands: bool,
/// Where those commands run; unset asks when the project and the file's folder differ.
pub command_directory: Option<MarkdownCommandDirectory>,
}
impl Default for MarkdownSettings {
fn default() -> Self {
Self { preview_font_size: None, run_commands: true, command_directory: None }
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "lowercase")]
pub enum MarkdownCommandDirectory {
/// The project's root folder.
Project,
/// The Markdown file's parent folder.
File,
}
impl LanguagesSettings {
+56
View File
@@ -98,3 +98,59 @@ test("commit message history opens above the message without an empty icon colum
expect(Math.abs(menuBox!.x - messageBox!.x)).toBeLessThan(2);
await expect(row.locator("span")).toHaveCount(1);
});
test("the Commit changes toolbar fits a narrow side pane", async ({ workbench: page }) => {
await stubRepository(page);
await page.keyboard.press("Meta+k");
await page.evaluate(async () => {
const path = "/src/workbench/toolwindows/store.ts";
const layout = await import(/* @vite-ignore */ path);
layout.moveToolWindow("commit", "left");
layout.setToolWindowSize("left", 164);
});
const panel = page.getByRole("region", { name: "Commit", exact: true });
const toolbar = panel.getByRole("toolbar", { name: "Changes" });
await expect(toolbar).toBeVisible();
const clipped = await toolbar.evaluate((bar) => {
const bounds = bar.getBoundingClientRect();
return [...bar.querySelectorAll("button")].flatMap((button) => {
const box = button.getBoundingClientRect();
return box.right > bounds.right + 1 || box.bottom > bounds.bottom + 1 ? [button.ariaLabel] : [];
});
});
expect(clipped).toEqual([]);
const push = panel.getByRole("button", { name: "Commit and Push…" });
const overflow = await push.locator("span").evaluate((label) => label.scrollWidth - label.clientWidth);
expect(overflow).toBeLessThanOrEqual(1);
await toolbar.getByRole("button", { name: "Collapse All" }).click();
await expect(panel.getByRole("checkbox", { name: "Include build.gradle.kts in commit" })).toBeHidden();
});
test("the commit message uses the configured editor typography", async ({ workbench: page }) => {
await stubRepository(page);
await page.keyboard.press("Meta+k");
const message = page.getByRole("textbox", { name: "Commit message" });
await expect(message).toBeFocused();
await page.evaluate(async () => {
const path = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ path);
const settings = useProject.getState().settings;
useProject.setState({
settings: {
...settings,
editor: {
...settings?.editor,
fontFamily: "Fira Code",
fallbackFont: "Maple Mono NF CN",
fontSize: 17,
lineHeight: 28,
fontWeight: 500,
},
},
});
});
await expect(message).toHaveCSS("font-size", "17px");
await expect(message).toHaveCSS("line-height", "28px");
await expect(message).toHaveCSS("font-weight", "500");
await expect(message).toHaveCSS("font-family", /"Fira Code".*"Maple Mono NF CN"/);
});
+13
View File
@@ -8237,10 +8237,23 @@ export type ManifestDependency = {
to: number,
};
export type MarkdownCommandDirectory =
/** The project's root folder. */
"project" |
/** The Markdown file's parent folder. */
"file";
/** Languages & Frameworks › Markdown. Like IDEA's, it is application-level only. */
export type MarkdownSettings = {
/** Preview (and notebook Markdown cell) font size in px; unset follows the editor font size. */
previewFontSize?: number | null,
/**
* "Detect commands that can be run right from Markdown files": gutter run icons on
* shell code blocks and on command lines in code blocks.
*/
runCommands?: boolean,
/** Where those commands run; unset asks when the project and the file's folder differ. */
commandDirectory?: MarkdownCommandDirectory | null,
};
/** A marketplace entry with what is installed. */
+4
View File
@@ -97,4 +97,8 @@ export const buildToolsRunAnything: RunAnythingProvider = {
const tool = lineTool(line);
return !!tool && executeBuildLine(tool, line);
},
accepts(line) {
const tool = lineTool(line);
return !!tool && (tool === "maven" ? parseGoalLine(line) : parseTaskLine(line)).length > 0;
},
};
+2
View File
@@ -71,6 +71,7 @@ import { hotReload, hotReloadSession, hotRestart } from "./flutterHotReload";
import { npmGutter } from "./npmGutter";
import { launchSettingsGutter } from "./launchSettingsGutter";
import { runGutter } from "./runGutter";
import { markdownCommandGutter } from "./markdownCommands";
import { gradleDelegation } from "./gradleRun";
import { activateStackTrace, useStackTraces } from "./stackTrace";
import { clearRuntimeCache } from "./runtimes";
@@ -485,6 +486,7 @@ export function activate(): () => void {
}),
registerEditorContribution({ id: "run.targets", order: 55, extensions: runGutter }),
registerEditorContribution({ id: "run.npmScripts", order: 58, extensions: npmGutter }),
registerEditorContribution({ id: "run.markdownCommands", order: 58, extensions: markdownCommandGutter }),
registerEditorContribution({ id: "run.launchSettings", order: 58, extensions: launchSettingsGutter }),
registerMenuGroup({
id: "run.context",
+70
View File
@@ -0,0 +1,70 @@
import { afterEach, describe, expect, it } from "vitest";
import { useProject } from "@/platform/project";
import { commandMenuItems, markdownCommands, trimPrompt, type CommandEntry } from "./markdownCommands";
const accepts = (line: string) => /^(mvn|\.\/gradlew) /.test(line);
describe("Markdown commands", () => {
it("runs shell blocks from their fence and recognized command lines from any block", () => {
const text = [
"## Setup",
"```shell",
"$ mise install # tools",
"",
"mvn test",
"```",
"```java",
"mvn not a command here? still a recognized line",
"```",
"~~~text",
"./gradlew build",
"~~~",
].join("\n");
expect(markdownCommands(text, accepts).map((e) => [e.kind, e.line, e.lines])).toEqual([
["block", 1, ["mise install", "mvn test"]],
["line", 4, ["mvn test"]],
["line", 7, ["mvn not a command here? still a recognized line"]],
["line", 10, ["./gradlew build"]],
]);
});
it("ignores blocks without commands, other languages and unclosed fences' closing rules", () => {
expect(markdownCommands("```bash\n# only a comment\n```", accepts)).toEqual([]);
expect(markdownCommands("```python\nprint(1)\n```", accepts)).toEqual([]);
// A shorter closing fence doesn't close a longer one.
expect(markdownCommands("````sh\nls\n```\npwd\n````", accepts)[0]?.lines).toEqual(["ls", "```", "pwd"]);
});
it("keeps quoted # and PowerShell lines as written", () => {
expect(trimPrompt(['echo "a # b" # note', "$ git log #x", "#!/bin/sh"])).toEqual(['echo "a # b"', "git log"]);
expect(markdownCommands("```powershell\n$env:X = 1 # keep\n```", accepts)[0]?.lines).toEqual(["$env:X = 1 # keep"]);
});
});
describe("Markdown command menu", () => {
const block: CommandEntry = { kind: "block", name: "block:1", line: 1, lines: ["make build"] };
afterEach(() => useProject.setState({ project: null, settings: null }));
const open = (commandDirectory?: string) =>
useProject.setState({
project: { root: "/p", name: "p", settings: {}, trusted: true, isGit: false },
settings: { languages: { markdown: { commandDirectory } } } as never,
});
it("asks for the folder when the project and the file's folder differ", async () => {
open();
expect((await commandMenuItems(block, "/p/docs/README.md")).map((i) => "label" in i && i.label)).toEqual([
"Run from Project Root Directory",
"Run from Parent Directory of Current File (docs)",
]);
expect((await commandMenuItems(block, "/p/README.md")).map((i) => "label" in i && i.label)).toEqual([
"Run in Terminal",
]);
});
it("uses the configured folder", async () => {
open("file");
expect((await commandMenuItems(block, "/p/docs/README.md")).map((i) => "label" in i && i.label)).toEqual([
"Run in Terminal",
]);
});
});
+135
View File
@@ -0,0 +1,135 @@
/**
* Run icons in Markdown files, like IDEA's Markdown command runner: ▶ on a shell
* code block's opening fence runs the block in a new terminal tab, and ▶ on a
* line of any code block runs it when a Run Anything provider recognizes the
* command (`mvn test`, `./gradlew build`, a run configuration's name).
*/
import type { Extension } from "@codemirror/state";
import type { EditorDocContext } from "@/editor/api";
import { executeAction } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { markdownCommandSettings } from "@/platform/languageSettings";
import { useProject } from "@/platform/project";
import type { MenuItem } from "@/ui";
import { runAnythingProviderList } from "@/workbench/contributions";
import { entryGutter, type ScriptEntry } from "./npmGutter";
const SHELL = new Set(["sh", "bash", "zsh", "shell", "shellscript", "shell-script", "console"]);
const POWERSHELL = new Set(["powershell", "pwsh", "ps1"]);
const FENCE = /^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)/;
export interface CommandEntry extends ScriptEntry {
kind: "block" | "line";
/** What runs: the block's commands, or the line's. */
lines: string[];
}
/** `line` without a trailing `# comment` outside quotes. */
function stripComment(line: string): string {
let single = false;
let double = false;
for (let i = 0; i < line.length; i++) {
const c = line[i];
if (c === "'" && !double) single = !single;
else if (c === '"' && !single) double = !double;
else if (c === "#" && !single && !double && (i === 0 || /\s/.test(line[i - 1]!))) return line.slice(0, i).trimEnd();
}
return line;
}
/** Shell lines without a leading `$` prompt or trailing comments; empty lines dropped. */
export function trimPrompt(lines: readonly string[]): string[] {
return lines.map((line) => stripComment(line.startsWith("$") ? line.slice(1) : line).trim()).filter(Boolean);
}
/**
* The runnable places of Markdown `text`: shell code blocks (on their opening fence)
* and code block lines `accepts` recognizes as commands.
*/
export function markdownCommands(text: string, accepts: (line: string) => boolean): CommandEntry[] {
const lines = text.split("\n");
const out: CommandEntry[] = [];
for (let i = 0; i < lines.length; i++) {
const open = FENCE.exec(lines[i]!);
if (!open) continue;
const marker = open[1]!;
const language = open[2]!.toLowerCase();
const close = new RegExp(`^ {0,3}${marker[0] === "`" ? "`" : "~"}{${marker.length},}\\s*$`);
let end = i + 1;
while (end < lines.length && !close.test(lines[end]!)) end++;
const body = lines.slice(i + 1, end).map((l) => l.replace(/\r$/, ""));
if (SHELL.has(language) || POWERSHELL.has(language)) {
const commands = POWERSHELL.has(language) ? body.filter((l) => l.trim()) : trimPrompt(body);
if (commands.length) out.push({ kind: "block", name: `block:${i}`, line: i, lines: commands });
}
body.forEach((raw, k) => {
const [command] = trimPrompt([raw]);
if (command && accepts(command))
out.push({ kind: "line", name: `line:${command}`, line: i + 1 + k, lines: [command] });
});
i = end;
}
return out;
}
/** Whether a Run Anything provider runs `line` as a command it recognizes. */
function accepted(line: string): boolean {
return runAnythingProviderList().some((p) => !!p.accepts?.(line));
}
async function runLine(line: string) {
for (const p of runAnythingProviderList()) if (p.accepts?.(line) && p.execute && (await p.execute(line))) return;
}
const parentDir = (path: string) => path.slice(0, Math.max(path.lastIndexOf("/"), 0)) || "/";
/** The folders a block may run in: the setting's, or both when it asks and they differ. */
function directories(path: string): { project: string; file: string } | string | null {
const { project, settings } = useProject.getState();
if (!project?.root) return null;
const file = parentDir(path);
const choice = markdownCommandSettings(settings).commandDirectory;
if (choice === "file") return file;
if (choice === "project" || file === project.root) return project.root;
return { project: project.root, file };
}
function runBlock(lines: string[], cwd: string) {
void executeAction("terminal.runLines", { lines, cwd });
}
export async function commandMenuItems(entry: ScriptEntry, path: string): Promise<MenuItem[]> {
const command = entry as CommandEntry;
if (command.kind === "line") {
const line = command.lines[0]!;
return [{ label: tx`Run '${line}'`, icon: "run", run: () => void runLine(line) }];
}
const dirs = directories(path);
if (!dirs) return [];
const shown = typeof dirs === "string" ? "" : dirs.file.slice(dirs.project.length + 1) || dirs.file;
if (typeof dirs === "string")
return [{ label: tx`Run in Terminal`, icon: "terminal", run: () => runBlock(command.lines, dirs) }];
return [
{ label: tx`Run from Project Root Directory`, icon: "terminal", run: () => runBlock(command.lines, dirs.project) },
{
label: tx`Run from Parent Directory of Current File (${shown})`,
icon: "terminal",
run: () => runBlock(command.lines, dirs.file),
},
];
}
export function markdownCommandGutter(ctx: EditorDocContext): Extension {
const { project, settings } = useProject.getState();
if (!project?.trusted || !markdownCommandSettings(settings).runCommands) return [];
return entryGutter(
ctx,
/\.(md|markdown)$/i,
(text) => markdownCommands(text, accepted),
commandMenuItems,
(entry) => {
const command = entry as CommandEntry;
return command.kind === "block" ? tx`Run in Terminal` : tx`Run '${command.lines[0]!}'`;
},
);
}
+4 -2
View File
@@ -312,6 +312,7 @@ class ScriptMarker extends GutterMarker {
readonly entry: ScriptEntry,
readonly path: string,
readonly menu: EntryMenu,
readonly title: (entry: ScriptEntry) => string,
) {
super();
}
@@ -322,7 +323,7 @@ class ScriptMarker extends GutterMarker {
const el = document.createElement("button");
el.type = "button";
el.className = styles.runMarker ?? "";
el.title = tx`Run '${this.entry.name}'`;
el.title = this.title(this.entry);
el.setAttribute("aria-label", el.title);
el.innerHTML = gutterIconMarkup("gutter-run") ?? "";
el.addEventListener("click", () => {
@@ -350,6 +351,7 @@ export function entryGutter(
file: RegExp,
entries: (text: string) => ScriptEntry[],
menu: EntryMenu,
title: (entry: ScriptEntry) => string = (entry) => tx`Run '${entry.name}'`,
): Extension {
const path = ctx.path;
if (ctx.virtual || !file.test(path) || !useProject.getState().project?.root) return [];
@@ -394,7 +396,7 @@ export function entryGutter(
markers: (view) =>
runIconsShown()
? RangeSet.of(
view.state.field(entriesField).map((e) => new ScriptMarker(e, path, menu).range(e.pos)),
view.state.field(entriesField).map((e) => new ScriptMarker(e, path, menu, title).range(e.pos)),
true,
)
: RangeSet.empty,
+1
View File
@@ -30,6 +30,7 @@ export const runConfigsRunAnything: RunAnythingProvider = {
group: "Run Configurations",
order: 10,
items: (query) => matchingConfigs(useRun.getState().configs, query).map(item),
accepts: (line) => useRun.getState().configs.some((c) => c.name === line.trim()),
execute(line) {
const config = useRun.getState().configs.find((c) => c.name === line.trim());
if (!config) return false;
@@ -1,5 +1,5 @@
import { useId } from "react";
import { NumberInput, Row, Section } from "../components/Form";
import { NumberInput, Row, Section, Select, SettingToggle } from "../components/Form";
import { useSetting } from "../components/context";
/** Languages & Frameworks › Markdown, after IDEA's: application-level, preview font size follows the editor font until set. */
@@ -7,24 +7,48 @@ export function MarkdownPage() {
const id = useId();
const [size, setSize] = useSetting<number | null>("languages.markdown.previewFontSize");
const [editorSize] = useSetting<number>("editor.fontSize");
const [runCommands] = useSetting<boolean>("languages.markdown.runCommands");
const [directory, setDirectory] = useSetting<"project" | "file" | null>("languages.markdown.commandDirectory");
return (
<Section title="Preview">
<Row
label="Preview font size"
htmlFor={id}
hint="Also used by Markdown cells in Jupyter notebooks. Defaults to the editor font size, independent of the UI font size."
>
<NumberInput
id={id}
value={size ?? editorSize}
onChange={setSize}
min={8}
max={72}
integer
unit="px"
aria-label="Preview font size"
<>
<Section title="Preview">
<Row
label="Preview font size"
htmlFor={id}
hint="Also used by Markdown cells in Jupyter notebooks. Defaults to the editor font size, independent of the UI font size."
>
<NumberInput
id={id}
value={size ?? editorSize}
onChange={setSize}
min={8}
max={72}
integer
unit="px"
aria-label="Preview font size"
/>
</Row>
</Section>
<Section title="Commands">
<SettingToggle
k="languages.markdown.runCommands"
label="Detect commands that can be run right from Markdown files"
/>
</Row>
</Section>
<Row label="Run commands from" disabled={!runCommands}>
<Select<"project" | "file">
value={directory ?? ("" as "project")}
options={DIRECTORY_OPTIONS}
onChange={setDirectory}
disabled={!runCommands}
aria-label="Run commands from"
/>
</Row>
</Section>
</>
);
}
const DIRECTORY_OPTIONS = [
{ value: "project", label: "Project directory" },
{ value: "file", label: "Markdown file parent directory" },
] as const;
+1 -1
View File
@@ -169,7 +169,7 @@ export const LANGUAGE_PAGES: PageSpec[] = [
title: "Markdown",
group: LANGUAGES_GROUP,
order: 400,
keywords: ["markdown", "preview", "font size", "jupyter", "notebook"],
keywords: ["markdown", "preview", "font size", "jupyter", "notebook", "run commands", "code block"],
component: MarkdownPage,
},
{
+19
View File
@@ -199,6 +199,25 @@ export function activate(): () => void {
focusActiveSoon();
},
},
{
id: "terminal.runLines",
title: "Run Lines in Terminal",
description: "Opens a shell tab and types `{ lines, name?, cwd? }` into it.",
category: "Terminal",
icon: "terminal",
when: "projectOpen",
hidden: true,
run: async ({ arg }) => {
const a = arg as { lines?: unknown; name?: unknown; cwd?: unknown } | undefined;
const lines = Array.isArray(a?.lines) ? a.lines.filter((x): x is string => typeof x === "string") : [];
const cwd = (typeof a?.cwd === "string" && a.cwd) || projectRoot();
if (!lines.length || !cwd) return;
const rt = await loadTerminalRuntime();
rt.newTabRunning(cwd, typeof a?.name === "string" && a.name ? a.name : undefined, lines);
toolWindowService().show(WINDOW, true);
focusActiveSoon();
},
},
{
id: "terminal.runCommand",
title: "Run Command in Terminal",
+1
View File
@@ -6,6 +6,7 @@ export {
closeAll,
detachTab,
newTab,
newTabRunning,
pluginSession,
syncTerminalProject,
tabTitle,
+8
View File
@@ -247,6 +247,14 @@ export function newTab(cwd: string, name?: string, command?: SessionOptions["com
return tab;
}
/** Opens a shell tab at `cwd` and types `lines` into it, each followed by Return. */
export function newTabRunning(cwd: string, name: string | undefined, lines: readonly string[]): TerminalTab {
const tab = newTab(cwd, name);
// Sent once the shell's PTY exists (the session buffers input until then).
getSession(tab.session)?.input(lines.map((line) => `${line}\r`).join(""));
return tab;
}
export function newTabAt(dir: string): TerminalTab {
return newTab(dir, basename(dir) || "Local");
}
+25 -10
View File
@@ -26,6 +26,20 @@
gap: var(--space-0-5);
padding: 0 6px;
}
.changesToolbar {
height: auto;
min-height: 32px;
flex-wrap: wrap;
column-gap: var(--space-2);
padding-block: var(--space-0-5);
}
.changesTools {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-0-5);
max-width: 100%;
}
.sep {
width: 1px;
height: 16px;
@@ -106,13 +120,12 @@
}
.commitBar {
flex: none;
height: 32px;
min-height: 32px;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-1);
padding: 0 6px 0 12px;
white-space: nowrap;
overflow: hidden;
gap: var(--space-0-5) var(--space-1);
padding: var(--space-0-5) 6px var(--space-0-5) 12px;
}
.grow {
flex: 1;
@@ -121,6 +134,7 @@
color: var(--fg-faint);
font-family: var(--font-mono);
font-size: var(--fs-tiny);
white-space: nowrap;
}
.lineLenWarn {
color: var(--warning);
@@ -136,8 +150,6 @@
border-top: 1px solid var(--border);
outline: none;
color: var(--fg-strong);
font-family: var(--font-mono);
font-size: var(--fs-code);
line-height: var(--lh-code);
-webkit-user-select: text;
user-select: text;
@@ -164,7 +176,6 @@
display: flex;
align-items: center;
gap: var(--space-2);
/* A narrow panel moves Commit and Push… to its own row rather than cutting its label. */
flex-wrap: wrap;
padding: 8px 6px 10px 10px;
white-space: nowrap;
@@ -175,10 +186,14 @@
.commitActions > .pushButton {
flex: 0 1 auto;
min-width: 0;
min-height: var(--h-button, 28px);
height: auto;
padding: var(--space-1) var(--space-3);
line-height: 1.3;
}
.pushButton > span {
overflow: hidden;
text-overflow: ellipsis;
white-space: normal;
overflow-wrap: anywhere;
}
.stashList {
flex: 1;
+82 -61
View File
@@ -18,7 +18,9 @@ import {
import { tx, txTemplate } from "@/platform/i18n";
import clsx from "clsx";
import { executeAction } from "@/platform/actions";
import { basename, dirname } from "@/platform/project";
import { fontWeightOf } from "@/platform/editorSettings";
import { resolveMonoFont } from "@/platform/fonts";
import { basename, dirname, useProject } from "@/platform/project";
import { isTestFile, useEffectiveRoots } from "@/platform/projectRoots";
import {
Button,
@@ -763,68 +765,79 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
return (
<div className={styles.changes}>
<div className={styles.toolbar} role="toolbar" aria-label={tx("Changes")}>
<IconButton icon="refresh" title="Refresh" size="small" onClick={() => void refreshNow()} />
{mode === "local" && <IconButton icon="commit" action="vcs.commit" size="small" />}
<IconButton icon="undo" action="vcs.rollback" size="small" />
{mode === "local" && <IconButton icon="changelist" action="vcs.changelist.new" size="small" />}
{mode !== "dialog" && <IconButton icon="git-pull" action="vcs.update" size="small" />}
<IconButton
ref={viewRef}
icon="eye"
title="View Options"
size="small"
aria-haspopup="menu"
onClick={() =>
viewRef.current &&
showContextMenu(bottomLeft(viewRef.current), [
{ kind: "header", label: "Group By" },
{ label: "Directory", checked: groupByDir, run: () => setGroupByDir(!groupByDir) },
// IDEA offers it once the project has several repositories.
...(repos.length > 1
? [{ label: "Repository", checked: groupByRepo, run: () => setGroupByRepo(!groupByRepo) }]
: []),
...(staging
? []
: [{ label: "Staging State", checked: groupByStaging, run: () => setGroupByStaging(!groupByStaging) }]),
{ kind: "separator" },
{
label: "Show Unversioned Files Separately",
checked: showUnversionedSeparately,
run: () => setShowUnversionedSeparately(!showUnversionedSeparately),
},
...(mode === "local"
? [
{ kind: "separator" } as const,
{ label: "Show Diff Preview", checked: diffPreview, run: () => setDiffPreview(!diffPreview) },
]
: []),
// Not in the Commit dialog, whose files always open as source.
...(mode === "dialog" ? [] : doubleClickMenu(doubleClickOpensDiff)),
])
}
/>
{/* WebStorm's Preview Diff: an embedded diff of the selection beside the changes (#1599). */}
{mode === "commit" && (
<div className={clsx(styles.toolbar, styles.changesToolbar)} role="toolbar" aria-label={tx("Changes")}>
<div className={styles.changesTools}>
<IconButton icon="refresh" title="Refresh" size="small" onClick={() => void refreshNow()} />
{mode === "local" && <IconButton icon="commit" action="vcs.commit" size="small" />}
<IconButton icon="undo" action="vcs.rollback" size="small" />
{mode === "local" && <IconButton icon="changelist" action="vcs.changelist.new" size="small" />}
{mode !== "dialog" && <IconButton icon="git-pull" action="vcs.update" size="small" />}
<IconButton
icon="editor-preview"
title="Preview Diff"
ref={viewRef}
icon="eye"
title="View Options"
size="small"
pressed={commitDiffPreview}
onClick={() => setCommitDiffPreview(!commitDiffPreview)}
aria-haspopup="menu"
onClick={() =>
viewRef.current &&
showContextMenu(bottomLeft(viewRef.current), [
{ kind: "header", label: "Group By" },
{ label: "Directory", checked: groupByDir, run: () => setGroupByDir(!groupByDir) },
// IDEA offers it once the project has several repositories.
...(repos.length > 1
? [{ label: "Repository", checked: groupByRepo, run: () => setGroupByRepo(!groupByRepo) }]
: []),
...(staging
? []
: [
{
label: "Staging State",
checked: groupByStaging,
run: () => setGroupByStaging(!groupByStaging),
},
]),
{ kind: "separator" },
{
label: "Show Unversioned Files Separately",
checked: showUnversionedSeparately,
run: () => setShowUnversionedSeparately(!showUnversionedSeparately),
},
...(mode === "local"
? [
{ kind: "separator" } as const,
{ label: "Show Diff Preview", checked: diffPreview, run: () => setDiffPreview(!diffPreview) },
]
: []),
// Not in the Commit dialog, whose files always open as source.
...(mode === "dialog" ? [] : doubleClickMenu(doubleClickOpensDiff)),
])
}
/>
)}
<span className={styles.sep} />
{mode !== "dialog" && (
<IconButton icon="locate" title="Select Opened File" size="small" onClick={selectOpened} />
)}
<IconButton icon="expand-all" title="Expand All" size="small" onClick={() => setCollapsed(new Set())} />
<IconButton
icon="collapse-all"
title="Collapse All"
size="small"
onClick={() => setCollapsed(new Set([...byKey.values()].filter((n) => n.type !== "file").map((n) => n.key)))}
/>
{/* WebStorm's Preview Diff: an embedded diff of the selection beside the changes (#1599). */}
{mode === "commit" && (
<IconButton
icon="editor-preview"
title="Preview Diff"
size="small"
pressed={commitDiffPreview}
onClick={() => setCommitDiffPreview(!commitDiffPreview)}
/>
)}
</div>
<div className={styles.changesTools}>
{mode !== "dialog" && (
<IconButton icon="locate" title="Select Opened File" size="small" onClick={selectOpened} />
)}
<IconButton icon="expand-all" title="Expand All" size="small" onClick={() => setCollapsed(new Set())} />
<IconButton
icon="collapse-all"
title="Collapse All"
size="small"
onClick={() =>
setCollapsed(new Set([...byKey.values()].filter((n) => n.type !== "file").map((n) => n.key)))
}
/>
</div>
</div>
{mode !== "dialog" && <OperationBanner />}
<div
@@ -1133,6 +1146,8 @@ export function CommitMessageField({
}
const cfg = useWorkflowSettings((s) => s.vcs.commit);
const editor = useProject((s) => s.settings?.editor);
const { family, size } = resolveMonoFont(undefined, editor);
const first = message.split("\n")[0] ?? "";
const tooLong = cfg.limitSubject && first.length > cfg.subjectLimit;
const problems = messageProblems(message, cfg).filter((p) => !p.startsWith("Subject line"));
@@ -1182,7 +1197,13 @@ export function CommitMessageField({
data-autofocus={autoFocus ? "" : undefined}
className={clsx(styles.message, !showMargin && styles.noMargin, emptyError && styles.messageError)}
aria-invalid={emptyError || undefined}
style={{ ["--guide" as string]: `${margin}ch` }}
style={{
["--guide" as string]: `${margin}ch`,
fontFamily: family,
fontSize: size,
fontWeight: fontWeightOf(editor?.fontWeight, 400),
lineHeight: editor?.lineHeight ? `${editor.lineHeight}px` : undefined,
}}
value={message}
placeholder={tx("Commit Message")}
aria-label={tx("Commit message")}
+25 -4
View File
@@ -238,8 +238,14 @@ export interface LanguagesValid {
updateSnapshots: boolean;
};
};
/** Preview font size in px; `null` follows the editor font size. */
markdown: { previewFontSize: number | null };
markdown: {
/** Preview font size in px; `null` follows the editor font size. */
previewFontSize: number | null;
/** Run icons on shell code blocks and command lines. */
runCommands: boolean;
/** Where commands run; `null` asks when the project and the file's folder differ. */
commandDirectory: "project" | "file" | null;
};
}
export interface ProjectStructureValid {
@@ -329,7 +335,7 @@ export const DEFAULT_LANGUAGES: LanguagesValid = {
updateSnapshots: false,
},
},
markdown: { previewFontSize: null },
markdown: { previewFontSize: null, runCommands: true, commandDirectory: null },
};
export const DEFAULT_PROJECT_STRUCTURE: ProjectStructureValid = {
@@ -510,7 +516,14 @@ export function validateLanguages(raw: unknown): LanguagesValid {
updateSnapshots: bool(maven.updateSnapshots, d.java.maven.updateSnapshots),
},
},
markdown: { previewFontSize: previewSize(markdown.previewFontSize) },
markdown: {
previewFontSize: previewSize(markdown.previewFontSize),
runCommands: bool(markdown.runCommands, d.markdown.runCommands),
commandDirectory:
markdown.commandDirectory === "project" || markdown.commandDirectory === "file"
? markdown.commandDirectory
: null,
},
};
}
@@ -528,6 +541,14 @@ export function markdownPreviewFontSize(settings: unknown): number {
);
}
/** Languages & Frameworks › Markdown › Commands of `settings`. */
export function markdownCommandSettings(
settings: unknown,
): Pick<LanguagesValid["markdown"], "runCommands" | "commandDirectory"> {
const markdown = validateLanguages(obj(settings).languages).markdown;
return { runCommands: markdown.runCommands, commandDirectory: markdown.commandDirectory };
}
/** Reactive `markdownPreviewFontSize` of the open project. */
export function useMarkdownPreviewFontSize(): number {
return useProject((s) => markdownPreviewFontSize(s.settings));
+9 -1
View File
@@ -2664,5 +2664,13 @@
"The agent's default": "The agent's default",
"Commit messages are short: a fast model with low effort is usually enough.": "Commit messages are short: a fast model with low effort is usually enough.",
"Change Project Color…": "Change Project Color…",
"Project Color": "Project Color"
"Project Color": "Project Color",
"Run Lines in Terminal": "Run Lines in Terminal",
"Opens a shell tab and types `{ lines, name?, cwd? }` into it.": "Opens a shell tab and types `{ lines, name?, cwd? }` into it.",
"Run in Terminal": "Run in Terminal",
"Run from Project Root Directory": "Run from Project Root Directory",
"Run from Parent Directory of Current File ({shown})": "Run from Parent Directory of Current File ({shown})",
"Detect commands that can be run right from Markdown files": "Detect commands that can be run right from Markdown files",
"Run commands from": "Run commands from",
"Markdown file parent directory": "Markdown file parent directory"
}
+9 -1
View File
@@ -9039,5 +9039,13 @@
"The agent's default": "智能体的默认值",
"Commit messages are short: a fast model with low effort is usually enough.": "提交信息很短,通常用快速模型配低推理强度就够了。",
"Change Project Color…": "更改项目颜色…",
"Project Color": "项目颜色"
"Project Color": "项目颜色",
"Run Lines in Terminal": "在终端中运行多行命令",
"Opens a shell tab and types `{ lines, name?, cwd? }` into it.": "打开一个 Shell 终端标签页并输入 `{ lines, name?, cwd? }`。",
"Run in Terminal": "在终端中运行",
"Run from Project Root Directory": "从项目根目录运行",
"Run from Parent Directory of Current File ({shown})": "从当前文件的父目录运行({shown})",
"Detect commands that can be run right from Markdown files": "检测可以直接从 Markdown 文件运行的命令",
"Run commands from": "运行命令的目录",
"Markdown file parent directory": "Markdown 文件的父目录"
}
+5
View File
@@ -1817,6 +1817,11 @@ export interface RunAnythingProvider {
items(query: string): RunAnythingItem[];
/** Runs `line` when it belongs to this provider (`mvn clean`); false leaves it to the next one. */
execute?(line: string): boolean | Promise<boolean>;
/**
* Whether `execute` runs `line` as a command this provider recognizes (cheap,
* synchronous): Markdown offers run icons for such lines in code blocks.
*/
accepts?(line: string): boolean;
}
const runAnythingProviders = new Map<string, RunAnythingProvider>();