From 1a21efa4aa0daed0b727b0dc9decd0281579f4c3 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Tue, 17 Nov 2026 07:15:11 +0800 Subject: [PATCH] feat(plugins): a plugin command can answer Escape in the editor (API 1.10) (#3844) `[[contributes.keymaps]]` accepts `key = "Escape"` with a required `when`. Plain keys stayed out of plugin shortcuts, and Escape could not be added as a shortcut anyway: the IDE's own keymap uses it, so the binding would be dropped. It becomes the editor's lowest-precedence Escape handler instead: the command runs once popups, completion, rename, selection, extra carets and Vim had no use for the key, and only while its `when` holds (the latest plugin's binding first). `when` is accepted only on such a binding; manifests that set it elsewhere, or bind Escape on one platform only, are refused. --- crates/ide-host/src/plugins/ui_points.rs | 58 +++++++++++++++++++-- docs/en/plugins/guides/commands.mdx | 18 +++++++ docs/en/plugins/manifest.mdx | 2 +- docs/zh/plugins/guides/commands.mdx | 15 ++++++ docs/zh/plugins/manifest.mdx | 2 +- plugins/README.md | 6 ++- src/features/plugins/escapeBindings.test.ts | 55 +++++++++++++++++++ src/features/plugins/escapeBindings.ts | 50 ++++++++++++++++++ src/features/plugins/uiPoints.tsx | 13 +++-- 9 files changed, 210 insertions(+), 9 deletions(-) create mode 100644 src/features/plugins/escapeBindings.test.ts create mode 100644 src/features/plugins/escapeBindings.ts diff --git a/crates/ide-host/src/plugins/ui_points.rs b/crates/ide-host/src/plugins/ui_points.rs index c3b4e24b7..bab56bded 100644 --- a/crates/ide-host/src/plugins/ui_points.rs +++ b/crates/ide-host/src/plugins/ui_points.rs @@ -13,6 +13,7 @@ //! [[contributes.keymaps]] //! command = "check" //! key = "Ctrl+Alt+C" # `mac` for a different binding on macOS (`Meta+Alt+C`) +//! # key = "Escape" + when = "…" # API 1.10: Escape in an editor that the IDE had no use for //! //! [[contributes.statusBar]] //! id = "branch" @@ -203,8 +204,16 @@ struct KeymapDecl { key: String, #[serde(default, skip_serializing_if = "Option::is_none")] mac: Option, + /// Only with an `Escape` binding (API 1.10): when the command clears something. + #[serde(default, skip_serializing_if = "Option::is_none")] + when: Option, } +/// The one plain key a plugin may bind (API 1.10): in a focused editor, after the IDE's own uses of +/// Escape (popups, completion, rename, selection, extra carets, Vim) found nothing to do, like a +/// handler at the end of IDEA's EditorEscape chain. +const ESCAPE: &str = "Escape"; + const MODIFIERS: [&str; 4] = ["Meta", "Ctrl", "Alt", "Shift"]; const NAMED_KEYS: [&str; 22] = [ "Enter", @@ -262,9 +271,21 @@ pub fn validate_binding(binding: &str) -> Result<(), String> { pub(super) fn keymap(pkg: &Package, decl: toml::Value) -> Result { let d: KeymapDecl = decode(KEYMAPS, decl)?; declared_command(pkg, KEYMAPS, &d.command)?; - validate_binding(&d.key).map_err(|e| format!("contributes.keymaps: {e}"))?; - if let Some(m) = &d.mac { - validate_binding(m).map_err(|e| format!("contributes.keymaps: {e}"))?; + let escape = d.key == ESCAPE || d.mac.as_deref() == Some(ESCAPE); + if escape { + if d.key != ESCAPE || d.mac.as_deref().is_some_and(|m| m != ESCAPE) { + return Err("contributes.keymaps: an Escape binding is Escape on every platform".into()); + } + pkg.manifest.needs_api("contributes.keymaps key = \"Escape\"", 10)?; + let when = d.when.as_deref().ok_or("contributes.keymaps: an Escape binding needs a `when` clause")?; + validate_when(when).map_err(|e| format!("contributes.keymaps: {e}"))?; + } else if d.when.is_some() { + return Err("contributes.keymaps: `when` is only for an Escape binding".into()); + } + for binding in std::iter::once(&d.key).chain(&d.mac) { + if binding != ESCAPE { + validate_binding(binding).map_err(|e| format!("contributes.keymaps: {e}"))?; + } } Ok(UiDecl::new(d.command.clone(), d.key.clone(), json(&d)?)) } @@ -1114,6 +1135,37 @@ mod tests { } } + #[test] + fn escape_bindings_need_api_1_10_and_a_when_clause() { + let pkg = |api: &str| { + let manifest = ide_extension::Manifest::parse(&format!( + "id='test'\nname='Test'\nversion='1.0.0'\nengines.openidea='{api}'\n[[contributes.commands]]\nid='clear'\ntitle='Clear'" + )) + .unwrap(); + Package::new(manifest, std::path::PathBuf::from("/unused")) + }; + let check = |api: &str, decl: &str| keymap(&pkg(api), toml::from_str(decl).unwrap()); + let escape = "command='clear'\nkey='Escape'\nwhen='plugin.test.active'"; + let ok = check("^1.10", escape).unwrap(); + assert_eq!(ok.json["when"], "plugin.test.active"); + assert!(check("^1.10", &format!("{escape}\nmac='Escape'")).is_ok()); + for (api, decl, error) in [ + ("^1.9", escape, "1.10"), + ("^1.10", "command='clear'\nkey='Escape'", "when"), + ("^1.10", "command='clear'\nkey='Escape'\nwhen='a &&'", "when"), + ("^1.10", &format!("{escape}\nmac='Meta+K'") as &str, "every platform"), + ("^1.10", "command='clear'\nkey='Ctrl+K'\nmac='Escape'\nwhen='x'", "every platform"), + ("^1.10", "command='clear'\nkey='Ctrl+K'\nwhen='x'", "only for an Escape"), + ("^1.10", "command='clear'\nkey='Enter'", "needs Ctrl"), + ("^1.10", "command='clear'\nkey='Shift+Escape'", "needs Ctrl"), + ] { + let err = check(api, decl).unwrap_err(); + assert!(err.contains(error), "{api} {decl}\n→ {err}"); + } + // Other bindings are unchanged. + assert!(check("^1.9", "command='clear'\nkey='Ctrl+Alt+C'").is_ok()); + } + #[test] fn bindings_need_a_modifier() { for ok in ["Ctrl+Alt+C", "Meta+Shift+K", "F5", "Shift+F6", "Meta+K Meta+C", "Alt+Enter"] { diff --git a/docs/en/plugins/guides/commands.mdx b/docs/en/plugins/guides/commands.mdx index 442f0571e..afeb516a9 100644 --- a/docs/en/plugins/guides/commands.mdx +++ b/docs/en/plugins/guides/commands.mdx @@ -132,6 +132,24 @@ mac = "Meta+Alt+C" # optional; macOS uses `key` as written when it is mis the user already uses that keystroke, or when the action already has a binding. The user can rebind it in **Settings › Keymap**. +### Escape in the editor + +API 1.10 lets a command answer a plain Escape in a focused editor, to clear +something the plugin shows there (a highlight, a mode): + +```toml +[[contributes.keymaps]] +command = "clear-highlight" +key = "Escape" +when = "plugin.my-plugin.highlighting" # required; set it with set-context while there is something to clear +``` + +- It runs only after everything the IDE does with Escape in the editor found nothing to do: + closing a popup, completion or rename, collapsing a selection or extra carets, Vim. +- `when` is required and `key` (and `mac`, if given) must be `Escape`. Escape is the only plain + key a plugin can bind, and `when` is accepted only on such a binding. +- When several plugins' `when` hold, the most recently loaded one runs. + ## Menus ```toml diff --git a/docs/en/plugins/manifest.mdx b/docs/en/plugins/manifest.mdx index f2be564df..228841f8b 100644 --- a/docs/en/plugins/manifest.mdx +++ b/docs/en/plugins/manifest.mdx @@ -104,7 +104,7 @@ Each contribution point is a table (`[contributes.settings]`) or an array of tab | ------------------- | -------------------------------------------------------------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | | `commands` | `id`, `title`, `category?`, `when?`, `icon?` | to run them | [Commands and actions](/en/plugins/guides/commands) | | `menus` | `menu`, `command`, `when?`, `view?`, `submenu?` | no | [Commands and actions](/en/plugins/guides/commands) | -| `keymaps` | `command`, `key`, `mac?` | no | [Commands and actions](/en/plugins/guides/commands) | +| `keymaps` | `command`, `key`, `mac?`, `when?` (Escape only) | no | [Commands and actions](/en/plugins/guides/commands) | | `statusBar` | `id`, `text`, `tooltip?`, `command?`, `align?`, `priority?` | no | [Views and decorations](/en/plugins/guides/views) | | `settings` | `schema` (a JSON file), or `pages` (API 1.3), `title?` | no | [Lifecycle and events](/en/plugins/lifecycle#settings) | | `secrets` | `name`, `label`, `description?` | to use them | [Permissions and capabilities](/en/plugins/capabilities#secrets) | diff --git a/docs/zh/plugins/guides/commands.mdx b/docs/zh/plugins/guides/commands.mdx index 1efd39645..c137aa180 100644 --- a/docs/zh/plugins/guides/commands.mdx +++ b/docs/zh/plugins/guides/commands.mdx @@ -119,6 +119,21 @@ mac = "Meta+Alt+C" # 可选;缺省时 macOS 原样使用 `key` - 插件快捷键只是默认值,优先级低于 IDE:按键映射预设或用户已经占用该按键、或该动作已有绑定时, 插件的快捷键会被丢弃。用户可以在 **设置 › 按键映射** 中重新绑定。 +### 编辑器中的 Escape + +API 1.10 起,命令可以响应焦点编辑器中单独按下的 Escape,用来清除插件在编辑器里显示的内容(高亮、某种模式): + +```toml +[[contributes.keymaps]] +command = "clear-highlight" +key = "Escape" +when = "plugin.my-plugin.highlighting" # 必填;有内容可清除时用 set-context 设置 +``` + +- 只有 IDE 在编辑器里对 Escape 的处理都没有生效时才会执行:关闭弹窗、补全或重命名,收起选区或多余的光标,Vim。 +- 必须写 `when`,且 `key`(以及给出的 `mac`)必须是 `Escape`。Escape 是插件唯一能绑定的单独按键,`when` 也只用于这种绑定。 +- 多个插件的 `when` 同时成立时,执行最后加载的那个插件的命令。 + ## 菜单 ```toml diff --git a/docs/zh/plugins/manifest.mdx b/docs/zh/plugins/manifest.mdx index 6fa442c96..ad8c63493 100644 --- a/docs/zh/plugins/manifest.mdx +++ b/docs/zh/plugins/manifest.mdx @@ -104,7 +104,7 @@ optional = ["net:api.openai.com", "secrets"] | ------------------- | ---------------------------------------------------------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | | `commands` | `id`、`title`、`category?`、`when?`、`icon?` | 执行时需要 | [命令与动作](/zh/plugins/guides/commands) | | `menus` | `menu`、`command`、`when?`、`view?`、`submenu?` | 否 | [命令与动作](/zh/plugins/guides/commands) | -| `keymaps` | `command`、`key`、`mac?` | 否 | [命令与动作](/zh/plugins/guides/commands) | +| `keymaps` | `command`、`key`、`mac?`、`when?`(仅 Escape) | 否 | [命令与动作](/zh/plugins/guides/commands) | | `statusBar` | `id`、`text`、`tooltip?`、`command?`、`align?`、`priority?` | 否 | [视图与装饰](/zh/plugins/guides/views) | | `settings` | `schema`(JSON 文件)或 `pages`(API 1.3)、`title?` | 否 | [生命周期与事件](/zh/plugins/lifecycle) | | `secrets` | `name`、`label`、`description?` | 使用时需要 | [权限与能力](/zh/plugins/capabilities) | diff --git a/plugins/README.md b/plugins/README.md index 9452767f0..0311bde2f 100644 --- a/plugins/README.md +++ b/plugins/README.md @@ -150,7 +150,7 @@ work), but 0.1 code no longer runs: rebuild it against the 1.0 SDK. | `providers` | `kinds`, `languages` (editor providers, see _Providers_) | yes | | `secrets` | `name`, `label`, `description?` (see _Network_) | to use them | | `menus` | `menu` (`editor.context`, `projectView.context`, `editorTab.context`, `viewItem.context`, `tools`, `commit.message`; API 1.4: `editor.title`, `mainToolbar`, `problems.context`, `searchResults.context`), `view?`, `command`, `when?` | no | -| `keymaps` | `command`, `key`, `mac?` (`Ctrl+Alt+C`; a chord: `Meta+K Meta+C`) | no | +| `keymaps` | `command`, `key`, `mac?` (`Ctrl+Alt+C`; a chord: `Meta+K Meta+C`); `key = "Escape"` with a required `when` (API 1.10) runs after the editor's own Escape handling | no | | `statusBar` | `id`, `text`, `tooltip?`, `command?`, `align?`, `priority?` | no | | `settings` | `schema` (JSON file) or `pages` (API 1.3), `title?` — see _Settings_ | no | | `views` | `id`, `title`, `icon?` (an icon name or a package SVG), `location` (`left`, `right`, `bottom`, `services`), `web?` (_Web views_), `group?`, `when?` (API 1.3) | without `web` | @@ -443,6 +443,10 @@ matching SDK. Released 1.9 plugins keep working. New in 1.10: `build.dependencies`) returns the Maven / Gradle graph the Dependency Analyzer has, as a flat list with conflict and omission status, behind the low-risk `build.read` capability. No build tool runs. See _Build dependency graph_. +- **Escape in the editor.** `[[contributes.keymaps]]` takes `key = "Escape"` with a + required `when`: the command runs on a plain Escape in a focused editor once the + IDE's own Escape handling (popups, completion, rename, selection, extra carets, + Vim) found nothing to do. ### API 1.9 diff --git a/src/features/plugins/escapeBindings.test.ts b/src/features/plugins/escapeBindings.test.ts new file mode 100644 index 000000000..77abdd2dd --- /dev/null +++ b/src/features/plugins/escapeBindings.test.ts @@ -0,0 +1,55 @@ +import { EditorSelection, EditorState } from "@codemirror/state"; +import { EditorView, keymap, runScopeHandlers } from "@codemirror/view"; +import { defaultKeymap } from "@codemirror/commands"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { registerAction } from "@/platform/actions"; +import { setContext } from "@/platform/context"; +import { addEscapeBinding, escapeAction, escapeBindings } from "./escapeBindings"; + +const off: (() => void)[] = []; +afterEach(() => { + off.splice(0).forEach((dispose) => dispose()); + setContext("plugin.scope.active", false); +}); + +const escape = (view: EditorView) => + runScopeHandlers(view, new KeyboardEvent("keydown", { key: "Escape", keyCode: 27 }), "editor"); + +describe("plugin Escape bindings", () => { + it("run only after the editor's own Escape handling found nothing to do", () => { + const run = vi.fn(); + off.push(registerAction({ id: "plugin.scope.clear", title: "Clear", run })); + off.push(addEscapeBinding("plugin.scope.clear", "plugin.scope.active")); + const view = new EditorView({ + state: EditorState.create({ + doc: "one two", + selection: EditorSelection.create([EditorSelection.cursor(0), EditorSelection.cursor(4)]), + extensions: [EditorState.allowMultipleSelections.of(true), escapeBindings, keymap.of(defaultKeymap)], + }), + }); + setContext("plugin.scope.active", true); + // Extra carets first: Escape keeps the main one, the plugin is not asked. + expect(escape(view)).toBe(true); + expect(view.state.selection.ranges).toHaveLength(1); + expect(run).not.toHaveBeenCalled(); + expect(escape(view)).toBe(true); + expect(run).toHaveBeenCalledTimes(1); + // Its `when` is false: Escape is left to whatever else handles it. + setContext("plugin.scope.active", false); + expect(escape(view)).toBe(false); + expect(run).toHaveBeenCalledTimes(1); + view.destroy(); + }); + + it("prefers the latest binding whose when holds and skips missing actions", () => { + off.push(registerAction({ id: "plugin.a.clear", title: "A", run: () => {} })); + off.push(registerAction({ id: "plugin.b.clear", title: "B", run: () => {} })); + off.push(addEscapeBinding("plugin.a.clear", "plugin.scope.active")); + const b = addEscapeBinding("plugin.b.clear", "plugin.scope.active"); + off.push(addEscapeBinding("plugin.gone.clear", "plugin.scope.active")); + setContext("plugin.scope.active", true); + expect(escapeAction()).toBe("plugin.b.clear"); + b(); + expect(escapeAction()).toBe("plugin.a.clear"); + }); +}); diff --git a/src/features/plugins/escapeBindings.ts b/src/features/plugins/escapeBindings.ts new file mode 100644 index 000000000..36e6f54f7 --- /dev/null +++ b/src/features/plugins/escapeBindings.ts @@ -0,0 +1,50 @@ +/** + * Plugin Escape bindings (`[[contributes.keymaps]] key = "Escape"` with `when`, API 1.10): run in + * a focused editor only after everything the IDE does with Escape there (popups, completion, + * rename, selection, extra carets, Vim) found nothing to do — the lowest-precedence Escape key, + * like a handler at the end of IDEA's EditorEscape chain. The first binding whose `when` holds + * runs; a later plugin's binding is tried first. + */ +import { Prec } from "@codemirror/state"; +import { keymap } from "@codemirror/view"; +import { executeAction, getAction } from "@/platform/actions"; +import { evaluateWhen } from "@/platform/context"; + +interface EscapeBinding { + action: string; + when: string; +} + +const bindings: EscapeBinding[] = []; + +export function addEscapeBinding(action: string, when: string): () => void { + const binding = { action, when }; + bindings.push(binding); + return () => { + const i = bindings.indexOf(binding); + if (i >= 0) bindings.splice(i, 1); + }; +} + +/** The action a plain Escape in an editor runs now, if any. */ +export function escapeAction(): string | null { + for (let i = bindings.length - 1; i >= 0; i--) { + const { action, when } = bindings[i]!; + if (getAction(action) && evaluateWhen(when)) return action; + } + return null; +} + +export const escapeBindings = Prec.lowest( + keymap.of([ + { + key: "Escape", + run: () => { + const action = escapeAction(); + if (!action) return false; + void executeAction(action); + return true; + }, + }, + ]), +); diff --git a/src/features/plugins/uiPoints.tsx b/src/features/plugins/uiPoints.tsx index 3638b73f1..36722519f 100644 --- a/src/features/plugins/uiPoints.tsx +++ b/src/features/plugins/uiPoints.tsx @@ -43,6 +43,7 @@ import { usePlugins } from "./store"; import { pluginActionId } from "./points"; import { defineUiPoint } from "./projection"; import { declareStatusItem } from "./runtimeUi"; +import { addEscapeBinding, escapeBindings } from "./escapeBindings"; import { registerWindowView } from "./views/viewWindows"; import { CUSTOM_EDITOR_KIND, @@ -261,6 +262,8 @@ interface KeymapDecl { command: string; key: string; mac?: string | null; + /** With an Escape binding (API 1.10). */ + when?: string | null; } // --- status bar ------------------------------------------------------------------- @@ -443,9 +446,12 @@ export function defineViewUiPoints(): () => void { defineUiPoint("keymaps", { title: "Shortcuts", project: ({ pluginId, decl }) => - registerExtensionBindings(pluginActionId(pluginId, decl.command), [ - isMacHost() ? (decl.mac ?? decl.key) : decl.key, - ]), + // Escape (only ever with `when`) is the editor's last Escape handler, not a shortcut. + decl.key === "Escape" && decl.when + ? addEscapeBinding(pluginActionId(pluginId, decl.command), decl.when) + : registerExtensionBindings(pluginActionId(pluginId, decl.command), [ + isMacHost() ? (decl.mac ?? decl.key) : decl.key, + ]), }), defineUiPoint("statusBar", { title: "Status Bar Items", @@ -494,6 +500,7 @@ export function defineViewUiPoints(): () => void { }, }), registerEditorContribution({ id: "plugins.editorPanels", extensions: () => editorPanelUpdates }), + registerEditorContribution({ id: "plugins.escapeBindings", extensions: () => escapeBindings }), defineUiPoint("editorPanels", { title: "Editor Panels", project: ({ pluginId, decl }) => projectEditorPanel(pluginId, decl),