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
Цей коміт міститься в:
l0ng-ai authored and GitHub committed 2026-12-02 23:19:12 +08:00
1 джерело ac9f745dcf
коміт bbbcf23c77
16 files changed
+121 -26

No files matched your search

+1 -1
Переглянути файл
@@ -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
+1 -1
Переглянути файл
@@ -76,7 +76,7 @@ nnoremap gi <Action>(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 中一样在列表中上下移动,除非你自己设置了它们的处理方式。
## 限制
+69
Переглянути файл
@@ -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);
});
}
+2 -1
Переглянути файл
@@ -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);
+27 -3
Переглянути файл
@@ -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))
);
};
}
+15
Переглянути файл
@@ -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<string, 1 | -1> = { 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),
+3 -1
Переглянути файл
@@ -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"
}
-2
Переглянути файл
@@ -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",
-2
Переглянути файл
@@ -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",
-2
Переглянути файл
@@ -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": "캐럿 앞 단어 삭제",
-2
Переглянути файл
@@ -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",
-2
Переглянути файл
@@ -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",
-2
Переглянути файл
@@ -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": "Удалить слово перед кареткой",
-2
Переглянути файл
@@ -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",
-2
Переглянути файл
@@ -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": "刪除游標前的單字",
+3 -3
Переглянути файл
@@ -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": "上一行 / 上一个建议"
}