From bbbcf23c7732eaa81b7abdf571ad547175ac78a2 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Wed, 2 Dec 2026 23:19:12 +0800 Subject: [PATCH] feat(vim): move through the completion list with Ctrl+N / Ctrl+P in Insert mode (#7525) With Vim on Windows and Linux, Ctrl+N and Ctrl+P in Insert mode went to the IDE keymap (Go to Class, Parameter Info) even while a completion list was open. While a list is open in Insert mode they now move its selection, unless the user set a handler for the stroke; Normal and Visual modes are unchanged. Fixes #7418 --- docs/en/guide/vim.mdx | 2 +- docs/zh/guide/vim.mdx | 2 +- e2e/vimLookupKeys.spec.ts | 69 ++++++++++++++++++++++++++++ src/editor/lsp/completion.ts | 3 +- src/features/vim/conflicts.ts | 30 ++++++++++-- src/features/vim/engine.ts | 15 ++++++ src/platform/locales/text/en.json | 4 +- src/platform/locales/text/es.json | 2 - src/platform/locales/text/fr.json | 2 - src/platform/locales/text/ko.json | 2 - src/platform/locales/text/pl.json | 2 - src/platform/locales/text/pt.json | 2 - src/platform/locales/text/ru.json | 2 - src/platform/locales/text/tr.json | 2 - src/platform/locales/text/zh-TW.json | 2 - src/platform/locales/text/zh.json | 6 +-- 16 files changed, 121 insertions(+), 26 deletions(-) create mode 100644 e2e/vimLookupKeys.spec.ts diff --git a/docs/en/guide/vim.mdx b/docs/en/guide/vim.mdx index f38a82f147..9b076a5153 100644 --- a/docs/en/guide/vim.mdx +++ b/docs/en/guide/vim.mdx @@ -76,7 +76,7 @@ Some keys are both Vim commands and IDE shortcuts, for example `Ctrl+R` (redo in - **Vim**: the key goes to the editor while Vim mode is on and an editor has focus. - **IDE**: the IDE action runs first; Vim still gets the key when no IDE action is enabled. -The defaults follow IdeaVim: `Esc`, `Ctrl+C`, `Ctrl+N`, `Ctrl+P`, `Ctrl+Q` and `Ctrl+T` go to the IDE, the others to Vim. +The defaults follow IdeaVim: `Esc`, `Ctrl+C`, `Ctrl+N`, `Ctrl+P`, `Ctrl+Q` and `Ctrl+T` go to the IDE, the others to Vim. While a completion list is open in Insert mode, `Ctrl+N` and `Ctrl+P` move through it, as in Vim, unless you set their handler yourself. ## Limits diff --git a/docs/zh/guide/vim.mdx b/docs/zh/guide/vim.mdx index 46c72f1268..5a1d918c85 100644 --- a/docs/zh/guide/vim.mdx +++ b/docs/zh/guide/vim.mdx @@ -76,7 +76,7 @@ nnoremap gi (GotoImplementation) - **Vim**:Vim 模式开启且焦点在编辑器中时,按键交给编辑器。 - **IDE**:先执行 IDE 操作;没有可用的 IDE 操作时,按键仍交给 Vim。 -默认值与 IdeaVim 一致:`Esc`、`Ctrl+C`、`Ctrl+N`、`Ctrl+P`、`Ctrl+Q` 和 `Ctrl+T` 交给 IDE,其余交给 Vim。 +默认值与 IdeaVim 一致:`Esc`、`Ctrl+C`、`Ctrl+N`、`Ctrl+P`、`Ctrl+Q` 和 `Ctrl+T` 交给 IDE,其余交给 Vim。在插入模式下补全列表打开时,`Ctrl+N` 和 `Ctrl+P` 会像在 Vim 中一样在列表中上下移动,除非你自己设置了它们的处理方式。 ## 限制 diff --git a/e2e/vimLookupKeys.spec.ts b/e2e/vimLookupKeys.spec.ts new file mode 100644 index 0000000000..0b26a5032c --- /dev/null +++ b/e2e/vimLookupKeys.spec.ts @@ -0,0 +1,69 @@ +/** Vim's Insert-mode Ctrl+N / Ctrl+P move through an open completion lookup. */ +import { expect, openFromTree, stubDesktop, test } from "./fixtures"; + +test.beforeEach(async ({ page }) => { + await page.addInitScript(() => + localStorage.setItem("openidea.vim.v1", JSON.stringify({ enabled: true, handlers: {} })), + ); + await page.goto("/"); + await expect(page.getByRole("tree", { name: "Project" })).toBeVisible(); +}); + +for (const preset of ["intellij-macos", "intellij-windows"]) { + test(`Ctrl+N / Ctrl+P move the lookup selection in Insert mode (${preset})`, async ({ page }) => { + const editor = await openFromTree(page, "build.gradle.kts"); + await stubDesktop(page); + await page.evaluate(async (preset) => { + const keymapModule = "/src/platform/keymap.ts"; + const { applyKeymapSettings } = await import(keymapModule); + applyKeymapSettings(preset, {}); + }, preset); + await expect(editor).toHaveAttribute("data-openidea-vim", "true"); + await page.evaluate(() => { + const item = (label: string) => ({ + label, + kind: "property", + detail: null, + labelDetail: null, + labelDescription: null, + documentation: null, + sortText: null, + filterText: null, + preselect: false, + deprecated: false, + insertText: label, + isSnippet: false, + replaceRange: null, + replaceRangeTab: null, + additionalEdits: [], + commitCharacters: [], + command: null, + data: null, + server: "kotlin", + }); + window.__ipc.handlers.lsp_completion = () => ({ + isIncomplete: false, + items: [item("alpha"), item("bravo"), item("charlie")], + }); + }); + await editor.locator(".cm-content").click(); + await page.keyboard.press("Escape"); + await page.keyboard.press("G"); + await page.keyboard.press("o"); + await expect(editor).toHaveAttribute("data-vim-mode", "insert"); + await page.keyboard.press("Control+Space"); + const popup = page.locator(".cm-tooltip-autocomplete"); + const selected = popup.locator("li[aria-selected=true] .cm-completionLabel"); + await expect(selected).toHaveText("alpha"); + // CodeMirror ignores lookup moves in the first moments after it opens (interactionDelay). + await page.waitForTimeout(200); + await page.keyboard.press("Control+n"); + await expect(selected).toHaveText("bravo"); + await page.keyboard.press("Control+n"); + await expect(selected).toHaveText("charlie"); + await page.keyboard.press("Control+p"); + await expect(selected).toHaveText("bravo"); + await expect(editor).toHaveAttribute("data-vim-mode", "insert"); + await expect(page.getByRole("dialog")).toHaveCount(0); + }); +} diff --git a/src/editor/lsp/completion.ts b/src/editor/lsp/completion.ts index 3a8790dc60..1c21a539f5 100644 --- a/src/editor/lsp/completion.ts +++ b/src/editor/lsp/completion.ts @@ -1145,7 +1145,8 @@ const lookupKeys = Prec.highest( }), ); -function moveLookup(view: EditorView, forward: boolean): boolean { +/** Moves the open lookup's selection down or up; false when no lookup is open. */ +export function moveLookup(view: EditorView, forward: boolean): boolean { if (completionStatus(view.state) !== "active") return false; focusedLookups.add(view); return moveCompletionSelection(forward)(view); diff --git a/src/features/vim/conflicts.ts b/src/features/vim/conflicts.ts index b8777e186d..c0e1cfbe1f 100644 --- a/src/features/vim/conflicts.ts +++ b/src/features/vim/conflicts.ts @@ -6,6 +6,8 @@ * A key the user moves from `vim` to `ide` is never Vim's, as with IdeaVim: * without an IDE action it does what the editor does with it (`movedToIde`). */ +import { completionStatus } from "@codemirror/autocomplete"; +import { EditorView } from "@codemirror/view"; import { normalizeBinding, type KeyClaim } from "@/platform/keymap"; import type { Handler, VimSettings } from "./settings"; @@ -29,9 +31,9 @@ export const VIM_KEYS: readonly VimKey[] = [ { stroke: "Ctrl+F", vim: "Page down", handler: "vim" }, { stroke: "Ctrl+I", vim: "Jump forward", handler: "vim" }, { stroke: "Ctrl+K", vim: "Enter a digraph in Insert mode", handler: "vim" }, - { stroke: "Ctrl+N", vim: "Next line", handler: "ide" }, + { stroke: "Ctrl+N", vim: "Next line / next suggestion", handler: "ide" }, { stroke: "Ctrl+O", vim: "Jump back / one Normal command", handler: "vim" }, - { stroke: "Ctrl+P", vim: "Previous line", handler: "ide" }, + { stroke: "Ctrl+P", vim: "Previous line / previous suggestion", handler: "ide" }, { stroke: "Ctrl+Q", vim: "Visual block", handler: "ide" }, { stroke: "Ctrl+R", vim: "Redo / insert register", handler: "vim" }, { stroke: "Ctrl+T", vim: "Indent", handler: "ide" }, @@ -145,6 +147,26 @@ export function vimModeOf(target: EventTarget | null): string | null { return el?.closest?.(`[${VIM_EDITOR_ATTR}]`)?.getAttribute(VIM_MODE_ATTR) ?? null; } +/** Vim's Insert-mode next / previous match: they move through an open completion lookup. */ +const LOOKUP_STROKES = new Set(["Ctrl+N", "Ctrl+P"]); + +/** + * Whether Insert mode's Ctrl+N / Ctrl+P go to the editor's open lookup rather than the IDE + * keymap (Go to Class, Parameter Info), unless the user gave the stroke a handler of their own. + */ +function lookupStroke( + e: KeyboardEvent, + stroke: string, + handlers: VimSettings["handlers"], + mode: string | null, +): boolean { + const name = normalizeBinding(stroke); + if (mode !== "insert" || !LOOKUP_STROKES.has(name) || name in handlers) return false; + const dom = (e.target as Element | null)?.closest?.(".cm-editor"); + const view = dom instanceof HTMLElement ? EditorView.findFromDOM(dom) : null; + return !!view && completionStatus(view.state) === "active"; +} + /** * Dispatcher claim: keystrokes whose handler is Vim go to a focused Vim editor. A stroke the * mode gives to the IDE is claimed too: the editor runs that IDE action itself, so an unrelated @@ -157,7 +179,9 @@ export function vimKeyClaim(settings: () => VimSettings): KeyClaim { return ( s.enabled && inVimEditor(e.target) && - (handlerFor(stroke, s.handlers, mode) === "vim" || modeMovedToIde(stroke, s.handlers, mode)) + (handlerFor(stroke, s.handlers, mode) === "vim" || + modeMovedToIde(stroke, s.handlers, mode) || + lookupStroke(e, stroke, s.handlers, mode)) ); }; } diff --git a/src/features/vim/engine.ts b/src/features/vim/engine.ts index 61958640b8..9b34b4bd37 100644 --- a/src/features/vim/engine.ts +++ b/src/features/vim/engine.ts @@ -8,6 +8,7 @@ import { EditorState, Prec, StateEffect, StateField, Transaction, type Extension import { EditorView, ViewPlugin, runScopeHandlers } from "@codemirror/view"; import { CodeMirror, Vim, getCM, vim } from "@replit/codemirror-vim"; import { adjacentEditor, externalHistory, transientChange, reportInputMode, type EditorDocContext } from "@/editor/api"; +import { moveLookup } from "@/editor/lsp/completion"; import { setContext } from "@/platform/context"; import { strokeOf } from "@/platform/keymap"; import { executeAction, getAction } from "@/platform/actions"; @@ -333,6 +334,19 @@ const ideHandledKeys = EditorView.domEventHandlers({ const LINE_MOTIONS: Record = { j: 1, ArrowDown: 1, k: -1, ArrowUp: -1 }; /** Normal-mode `j`/`k` on the last/first line continue into the host's neighbouring editor (notebook cells). */ +/** + * Insert mode's Ctrl+N / Ctrl+P (Vim's next / previous match) move through an open completion + * lookup, as ↓ / ↑ do. With no lookup open they keep their Vim meaning. + */ +const lookupKeysInInsert = EditorView.domEventHandlers({ + keydown(e, view) { + if (!e.ctrlKey || e.metaKey || e.altKey || e.shiftKey || (e.code !== "KeyN" && e.code !== "KeyP")) return false; + if (!getCM(view)?.state.vim?.insertMode || !moveLookup(view, e.code === "KeyN")) return false; + e.preventDefault(); + return true; + }, +}); + const lineMotionLeavesEditor = EditorView.domEventHandlers({ keydown(e, view) { const direction = LINE_MOTIONS[e.key]; @@ -437,6 +451,7 @@ export function vimExtension(ctx?: EditorDocContext): Extension { imeTransactions, escapeClosesPopupsFirst, lineMotionLeavesEditor, + lookupKeysInInsert, ideHandledKeys, vim(), modeTracker(ctx), diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 32a25808b8..5223e8a399 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -5254,5 +5254,7 @@ "Undeploying {name} ({contextPath})…": "Undeploying {name} ({contextPath})…", "Redeploying {name} ({contextPath})…": "Redeploying {name} ({contextPath})…", "Select Service Item": "Select Service Item", - "Tomcat did not confirm the deployment change for {name}.": "Tomcat did not confirm the deployment change for {name}." + "Tomcat did not confirm the deployment change for {name}.": "Tomcat did not confirm the deployment change for {name}.", + "Next line / next suggestion": "Next line / next suggestion", + "Previous line / previous suggestion": "Previous line / previous suggestion" } diff --git a/src/platform/locales/text/es.json b/src/platform/locales/text/es.json index ac2cfbb9bf..9276bf83b2 100644 --- a/src/platform/locales/text/es.json +++ b/src/platform/locales/text/es.json @@ -3559,8 +3559,6 @@ "Scroll line up": "Desplazar una línea hacia arriba", "Jump forward": "Saltar hacia adelante", "Jump back / one Normal command": "Saltar hacia atrás / un comando Normal", - "Next line": "Siguiente línea", - "Previous line": "Línea anterior", "Visual block": "Bloque visual", "Redo / insert register": "Rehacer / insertar registro", "Delete word before caret": "Eliminar palabra antes del cursor", diff --git a/src/platform/locales/text/fr.json b/src/platform/locales/text/fr.json index b5632e6c31..05ef6e01cd 100644 --- a/src/platform/locales/text/fr.json +++ b/src/platform/locales/text/fr.json @@ -3463,8 +3463,6 @@ "Scroll line up": "Défiler d'une ligne vers le haut", "Jump forward": "Saut en avant", "Jump back / one Normal command": "Saut en arrière / une commande Normal", - "Next line": "Ligne suivante", - "Previous line": "Ligne précédente", "Visual block": "Bloc visuel", "Redo / insert register": "Rétablir / insérer un registre", "Delete word before caret": "Supprimer le mot avant le curseur", diff --git a/src/platform/locales/text/ko.json b/src/platform/locales/text/ko.json index eafb384d30..1d85851f14 100644 --- a/src/platform/locales/text/ko.json +++ b/src/platform/locales/text/ko.json @@ -3609,8 +3609,6 @@ "Scroll line up": "한 줄 위로 스크롤", "Jump forward": "앞으로 점프", "Jump back / one Normal command": "뒤로 점프 / Normal 명령 한 번 실행", - "Next line": "다음 줄", - "Previous line": "이전 줄", "Visual block": "Visual 블록", "Redo / insert register": "다시 실행 / 레지스터 삽입", "Delete word before caret": "캐럿 앞 단어 삭제", diff --git a/src/platform/locales/text/pl.json b/src/platform/locales/text/pl.json index 15516b0c67..2d90044995 100644 --- a/src/platform/locales/text/pl.json +++ b/src/platform/locales/text/pl.json @@ -3530,8 +3530,6 @@ "Scroll line up": "Przewiń linię w górę", "Jump forward": "Przejdź do przodu", "Jump back / one Normal command": "Przejdź w tył / jedno polecenie trybu normalnego", - "Next line": "Następna linia", - "Previous line": "Poprzednia linia", "Visual block": "Blok wizualny", "Redo / insert register": "Ponów / wstaw rejestr", "Delete word before caret": "Usuń słowo przed kursorem", diff --git a/src/platform/locales/text/pt.json b/src/platform/locales/text/pt.json index 4b547497ec..acc9ad705e 100644 --- a/src/platform/locales/text/pt.json +++ b/src/platform/locales/text/pt.json @@ -3532,8 +3532,6 @@ "Scroll line up": "Rolar linha para cima", "Jump forward": "Avançar salto", "Jump back / one Normal command": "Voltar salto / um comando Normal", - "Next line": "Próxima linha", - "Previous line": "Linha anterior", "Visual block": "Bloco visual", "Redo / insert register": "Refazer / inserir registrador", "Delete word before caret": "Excluir palavra antes do cursor", diff --git a/src/platform/locales/text/ru.json b/src/platform/locales/text/ru.json index 35064e95f8..b39a7ab620 100644 --- a/src/platform/locales/text/ru.json +++ b/src/platform/locales/text/ru.json @@ -4978,8 +4978,6 @@ "Scroll line up": "Прокрутить на строку вверх", "Jump forward": "Перейти вперёд", "Jump back / one Normal command": "Перейти назад / одна обычная команда", - "Next line": "Следующая строка", - "Previous line": "Предыдущая строка", "Visual block": "Визуальный блок", "Redo / insert register": "Повторить / вставить регистр", "Delete word before caret": "Удалить слово перед кареткой", diff --git a/src/platform/locales/text/tr.json b/src/platform/locales/text/tr.json index fd71ec4a2a..180d6178e1 100644 --- a/src/platform/locales/text/tr.json +++ b/src/platform/locales/text/tr.json @@ -6238,8 +6238,6 @@ "Scroll line up": "Bir satır yukarı kaydır", "Jump forward": "İleri atla", "Jump back / one Normal command": "Geri atla / bir Normal komutu", - "Next line": "Sonraki satır", - "Previous line": "Önceki satır", "Visual block": "Görsel blok", "Redo / insert register": "Yinele / kayıt ekle", "Delete word before caret": "İmleçten önceki sözcüğü sil", diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index fd9c2f8ff7..a48623902f 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -4621,8 +4621,6 @@ "Scroll line up": "向上捲動一行", "Jump forward": "前進跳轉", "Jump back / one Normal command": "後退跳轉 / 執行一條 Normal 命令", - "Next line": "下一行", - "Previous line": "上一行", "Visual block": "可視塊", "Redo / insert register": "重做 / 插入暫存器", "Delete word before caret": "刪除游標前的單字", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 1bae955cae..04f61e9b05 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -5342,8 +5342,6 @@ "Scroll line up": "向上滚动一行", "Jump forward": "前进跳转", "Jump back / one Normal command": "后退跳转 / 执行一条 Normal 命令", - "Next line": "下一行", - "Previous line": "上一行", "Visual block": "可视块", "Redo / insert register": "重做 / 插入寄存器", "Delete word before caret": "删除光标前的单词", @@ -12155,5 +12153,7 @@ "Undeploying {name} ({contextPath})…": "正在取消部署 {name} ({contextPath})…", "Redeploying {name} ({contextPath})…": "正在重新部署 {name} ({contextPath})…", "Select Service Item": "选择服务项", - "Tomcat did not confirm the deployment change for {name}.": "Tomcat 未确认 {name} 的部署变更。" + "Tomcat did not confirm the deployment change for {name}.": "Tomcat 未确认 {name} 的部署变更。", + "Next line / next suggestion": "下一行 / 下一个建议", + "Previous line / previous suggestion": "上一行 / 上一个建议" }