From c725b1629da656f3548321f29f39fe8045292873 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Tue, 1 Dec 2026 20:47:41 +0800 Subject: [PATCH] fix(vim): replace a Visual selection when Ctrl+V is given to the IDE (#7242) With Ctrl+V's handler set to the IDE, pasting over a Visual selection inserted after it because the browser paste ran after Vim collapsed the selection. In Visual mode an IDE-handled paste stroke runs Paste, replacing the selection in one transaction; with the default handler Ctrl+V still starts a Visual block, as in IdeaVim. Fixes #7192 --- src/features/app/appActions.ts | 15 +++- src/features/vim/__tests__/vim.test.ts | 102 +++++++++++++++++++++---- src/features/vim/conflicts.ts | 10 ++- src/features/vim/engine.ts | 31 ++++++-- 4 files changed, 133 insertions(+), 25 deletions(-) diff --git a/src/features/app/appActions.ts b/src/features/app/appActions.ts index 4873d1d724..b41931f3d5 100644 --- a/src/features/app/appActions.ts +++ b/src/features/app/appActions.ts @@ -52,8 +52,19 @@ export function editCommand(command: "undo" | "redo" | "cut" | "copy" | "paste" } if (command === "selectAll" && selectReadingPane(document.activeElement)) return; if (command === "paste") { - void readClipboardPlainText().then((text) => document.execCommand("insertText", false, text)); - return; + const focused = document.activeElement; + const view = focused instanceof HTMLElement ? EditorView.findFromDOM(focused) : null; + const selection = view && view.contentDOM === focused ? view.state.selection : undefined; + return readClipboardPlainText().then((text) => { + if (view && selection?.ranges.some((range) => !range.empty)) { + // CodeMirror owns the selection, including Vim's Visual range. Replace it in + // one transaction so any cursor update sees the finished paste. + if (text && focused === document.activeElement && view.state.selection.eq(selection) && !view.state.readOnly) + view.dispatch(view.state.replaceSelection(text), { userEvent: "input.paste", scrollIntoView: true }); + } else { + document.execCommand("insertText", false, text); + } + }); } document.execCommand(command); }; diff --git a/src/features/vim/__tests__/vim.test.ts b/src/features/vim/__tests__/vim.test.ts index 64a83ae5b9..e01f745954 100644 --- a/src/features/vim/__tests__/vim.test.ts +++ b/src/features/vim/__tests__/vim.test.ts @@ -13,6 +13,7 @@ import { } from "@/editor/api"; import { executeAction, registerAction } from "@/platform/actions"; import { getContext } from "@/platform/context"; +import { editCommand } from "../../app/appActions"; import { _handleEx, applyRcCommands, vimExtension } from "../engine"; import { activate } from "../index"; import { useVimMode } from "../mode"; @@ -34,6 +35,18 @@ function makeView(extra = vimExtension()) { return new EditorView({ parent, state: EditorState.create({ doc: "one two\nthree", extensions: extra }) }); } +function pressCtrl(view: EditorView, key: string) { + const event = new KeyboardEvent("keydown", { + key, + code: `Key${key.toUpperCase()}`, + ctrlKey: true, + bubbles: true, + cancelable: true, + }); + view.contentDOM.dispatchEvent(event); + return event; +} + describe("Vim mode toggle", () => { let dispose = () => {}; beforeEach(() => { @@ -90,31 +103,21 @@ describe("Vim engine", () => { Vim.mapclear(); }); - it("leaves keys the user gave to the IDE to the editor: Select All, and the browser's cut and paste", () => { + it("leaves IDE overrides to the editor for Select All and paste without a selection", () => { const view = makeView([vimExtension(), keymap.of([{ key: "Ctrl-a", run: selectAll }])]); view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: "n 5" } }); - const press = (key: string) => { - const e = new KeyboardEvent("keydown", { - key, - code: `Key${key.toUpperCase()}`, - ctrlKey: true, - bubbles: true, - cancelable: true, - }); - view.contentDOM.dispatchEvent(e); - return e; - }; try { useVimSettings.setState({ enabled: true, handlers: {} }, true); - press("a"); + pressCtrl(view, "a"); expect(view.state.doc.toString()).toBe("n 6"); useVimSettings.setState({ enabled: true, handlers: { "Ctrl+A": "ide", "Ctrl+V": "ide" } }, true); - expect(press("a").defaultPrevented).toBe(true); + expect(pressCtrl(view, "a").defaultPrevented).toBe(true); expect(view.state.doc.toString()).toBe("n 6"); expect(view.state.selection.main).toMatchObject({ from: 0, to: 3 }); - const paste = press("v"); + view.dispatch({ selection: { anchor: 0 } }); + const paste = pressCtrl(view, "v"); expect(paste.defaultPrevented).toBe(false); expect(getCM(view)!.state.vim!.visualBlock).toBeFalsy(); } finally { @@ -580,6 +583,75 @@ describe("Vim engine", () => { }); }); +describe("Vim Ctrl+V", () => { + const pasted = "PASTED"; + const readText = vi.fn<() => Promise>(); + let view: EditorView; + let unregisterPaste: () => void; + + beforeEach(() => { + view = makeView(); + view.focus(); + unregisterPaste = registerAction({ id: "edit.paste", title: "Paste", run: editCommand("paste") }); + readText.mockReset().mockResolvedValue(pasted); + vi.stubGlobal("navigator", { clipboard: { readText }, userAgent: navigator.userAgent }); + // jsdom does not implement the native insertText command. + document.execCommand = (command, _showUI, value) => { + if (command !== "insertText" || value === undefined) return false; + view.dispatch(view.state.replaceSelection(value)); + return true; + }; + useVimSettings.setState({ enabled: true, handlers: {} }, true); + }); + + afterEach(() => { + unregisterPaste(); + Reflect.deleteProperty(document, "execCommand"); + vi.unstubAllGlobals(); + useVimSettings.setState({ enabled: false, handlers: {} }, true); + view.destroy(); + }); + + it("replaces a Visual selection with the IDE handler", async () => { + useVimSettings.setState({ enabled: true, handlers: { "Ctrl+V": "ide" } }, true); + const cm = getCM(view)!; + Vim.handleKey(cm, "v", "user"); + Vim.handleKey(cm, "e", "user"); + let finishRead = (_text: string) => {}; + readText.mockReturnValueOnce(new Promise((resolve) => (finishRead = resolve))); + + expect(pressCtrl(view, "v").defaultPrevented).toBe(true); + await tick(); + expect(view.state.selection.main).toMatchObject({ from: 0, to: 3 }); + expect(view.dom.getAttribute("data-vim-mode")).toBe("visual"); + finishRead(pasted); + await tick(); + + expect(view.state.doc.toString()).toBe("PASTED two\nthree"); + expect(view.dom.getAttribute("data-vim-mode")).toBe("normal"); + }); + + it("keeps Vim's Visual block on a mouse selection with the default handler, as IdeaVim does", async () => { + view.dispatch({ selection: { anchor: 0, head: 3 }, userEvent: "select.pointer" }); + expect(view.dom.getAttribute("data-vim-mode")).toBe("visual"); + + pressCtrl(view, "v"); + await tick(); + + expect(view.state.doc.toString()).toBe("one two\nthree"); + }); + + it("pastes in Insert mode and stays there", async () => { + Vim.handleKey(getCM(view)!, "i", "user"); + + expect(pressCtrl(view, "v").defaultPrevented).toBe(true); + await tick(); + + expect(view.state.doc.toString()).toBe("PASTEDone two\nthree"); + expect(view.dom.getAttribute("data-vim-mode")).toBe("insert"); + }); +}); + describe("line motions across editors", () => { const key = (view: EditorView, k: string) => view.contentDOM.dispatchEvent(new KeyboardEvent("keydown", { key: k, bubbles: true })); diff --git a/src/features/vim/conflicts.ts b/src/features/vim/conflicts.ts index 9969cd0726..b8777e186d 100644 --- a/src/features/vim/conflicts.ts +++ b/src/features/vim/conflicts.ts @@ -47,7 +47,7 @@ const byStroke = new Map(VIM_KEYS.map((k) => [normalizeBinding(k.stroke), k])); /** * IdeaVim hands these strokes to the IDE in one Vim mode only: an editing mode pastes, * Visual mode copies. Every other mode keeps the stroke's Vim meaning, so Ctrl+V still - * starts a Visual block in Normal mode. + * starts a Visual block in Normal and Visual mode. */ const MODE_ACTIONS: Readonly>>> = { "Ctrl+V": { insert: "edit.paste" }, @@ -55,6 +55,14 @@ const MODE_ACTIONS: Readonly>>> = "Ctrl+C": { visual: "edit.copy" }, }; +/** Paste strokes: given to the IDE in Visual mode, they replace the selection (IdeaVim's `ideaput`). */ +const PASTE_STROKES = new Set(["Ctrl+V", "Shift+Insert"]); + +/** The IDE action for a stroke the user gave to the IDE, in a mode where it acts on the selection. */ +export function ideActionFor(stroke: string, mode: string | null | undefined): string | null { + return mode === "visual" && PASTE_STROKES.has(normalizeBinding(stroke)) ? "edit.paste" : modeAction(stroke, mode); +} + /** The IDE action that replaces Vim's meaning of `stroke` in `mode`, if the mode changes it. */ export function modeAction(stroke: string, mode: string | null | undefined): string | null { if (!mode) return null; diff --git a/src/features/vim/engine.ts b/src/features/vim/engine.ts index 650c2b0439..dad594149c 100644 --- a/src/features/vim/engine.ts +++ b/src/features/vim/engine.ts @@ -12,7 +12,15 @@ import { strokeOf } from "@/platform/keymap"; import { executeAction, getAction } from "@/platform/actions"; import { showStatusInfo } from "@/workbench/contributions"; import { installClipboardHooks } from "./clipboard"; -import { modeAction, modeMovedToIde, movedToIde, VIM_EDITOR_ATTR, VIM_MODE_ATTR, vimModeOf } from "./conflicts"; +import { + ideActionFor, + modeAction, + modeMovedToIde, + movedToIde, + VIM_EDITOR_ATTR, + VIM_MODE_ATTR, + vimModeOf, +} from "./conflicts"; import { useVimMode, type VimModeState } from "./mode"; import { resolveActionId, type RcCommand, type SetOp } from "./rc"; import { useVimSettings } from "./settings"; @@ -288,17 +296,26 @@ const ideHandledKeys = EditorView.domEventHandlers({ if (!stroke) return false; const settings = useVimSettings.getState(); const mode = vimModeOf(e.target); - const action = modeMovedToIde(stroke, settings.handlers, mode) ? modeAction(stroke, mode) : null; - if (!movedToIde(stroke, settings.handlers) && !action) return false; - if (action) { - // The mode gives this stroke an IDE meaning: paste while inserting, copy a Visual selection. + const ideOverride = movedToIde(stroke, settings.handlers); + const action = modeMovedToIde(stroke, settings.handlers, mode) + ? modeAction(stroke, mode) + : ideOverride && mode === "visual" + ? ideActionFor(stroke, mode) + : null; + const visualPaste = action === "edit.paste" && mode === "visual"; + if (action && (!visualPaste || view.state.selection.ranges.some((range) => !range.empty))) { // Before the editor keymap: its default Ctrl-v scrolls the page, not pastes. e.preventDefault(); void executeAction(action); - const cm = getCM(view); - if (cm?.state.vim?.visualMode) Vim.exitVisualMode(cm as never); + // Paste reads the clipboard asynchronously. Vim leaves Visual mode when the paste + // replaces the selection and sets the caret, so only copy needs an explicit exit. + if (action === "edit.copy") { + const cm = getCM(view); + if (cm?.state.vim?.visualMode) Vim.exitVisualMode(cm as never); + } return true; } + if (!ideOverride) return false; if (runScopeHandlers(view, e, "editor")) return true; // Returning true would cancel the browser's cut or paste: skip Vim's handler for this event only. const plugin = getCM(view)?.state.vimPlugin as { handleKey?: unknown } | undefined;