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
17 changed files with 369 additions and 28 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 {
+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 -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>();