Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

fix(editor): prevent IME text insertion in Vim normal mode

zipg15bf5c5844d1
diff --git a/apps/desktop/src/components/editor/QueryEditor.vue b/apps/desktop/src/components/editor/QueryEditor.vue
index 5c4364d05a..2323079069 100644
--- a/apps/desktop/src/components/editor/QueryEditor.vue
+++ b/apps/desktop/src/components/editor/QueryEditor.vue
@@ -116,6 +116,7 @@ import { matchesShortcut } from "@/lib/editor/keyboardShortcuts";
import { trimmedSelectionLayer } from "@/lib/editor/codemirrorTrimmedSelectionLayer";
import { editorClipboardLineEndingsExtension } from "@/lib/editor/editorClipboardLineEndings";
import { applyVimConfig, isVimMappingCommand, loadVimConfig } from "@/lib/editor/vimConfig";
+import { createVimImeGuard } from "@/lib/editor/vimImeGuard";
import { configureVimSystemClipboard } from "@/lib/editor/vimSystemClipboard";
import { selectionMatchOccurrences } from "@/lib/editor/codemirrorSelectionMatches";
@@ -1536,6 +1537,7 @@ function vimModeExtension(enabled = settingsStore.editorSettings.vimModeEnabled)
},
]),
vimExtension,
+ createVimImeGuard(codeMirrorRuntime.editorViewModule, codeMirrorRuntime.codeMirrorGetVimCm),
]);
}
diff --git a/apps/desktop/src/components/editor/__tests__/QueryEditor.componentSplit.integration.spec.ts b/apps/desktop/src/components/editor/__tests__/QueryEditor.componentSplit.integration.spec.ts
index ba8ea89667..4fc5e1efdf 100644
--- a/apps/desktop/src/components/editor/__tests__/QueryEditor.componentSplit.integration.spec.ts
+++ b/apps/desktop/src/components/editor/__tests__/QueryEditor.componentSplit.integration.spec.ts
@@ -29,11 +29,12 @@ afterEach(() => {
vi.restoreAllMocks();
});
-async function mountEditor(overrides: Partial<QueryEditorProps> = {}) {
+async function mountEditor(overrides: Partial<QueryEditorProps> = {}, vimEnabled = false) {
const pinia = createPinia();
setActivePinia(pinia);
const settingsStore = useSettingsStore();
const connectionStore = useConnectionStore();
+ settingsStore.editorSettings.vimModeEnabled = vimEnabled;
settingsStore.editorSettings.showExecutionTargetPicker = false;
settingsStore.editorSettings.executeMode = "current";
settingsStore.editorSettings.executeAllOnBlankLine = false;
@@ -86,6 +87,23 @@ function foldedRangeCount(view: EditorView): number {
}
describe("QueryEditor component split integration", () => {
+ it("keeps composing Vim navigation and committed IME text out of the SQL model", async () => {
+ const { view, props } = await mountEditor({}, true);
+ const original = props.modelValue;
+ view.contentDOM.dispatchEvent(new CompositionEvent("compositionstart", { bubbles: true }));
+ const event = new KeyboardEvent("keydown", { key: "Process", code: "KeyL", keyCode: 229, isComposing: true, bubbles: true, cancelable: true });
+ view.contentDOM.dispatchEvent(event);
+ expect(event.defaultPrevented).toBe(true);
+ expect(view.state.selection.main.head).toBe(1);
+ const position = view.state.selection.main.head;
+ const handled = view.state.facet(EditorView.inputHandler).some((handler) => handler(view, position, position, "hjkl", () => view.state.update({ changes: { from: position, insert: "hjkl" } })));
+ expect(handled).toBe(true);
+ view.contentDOM.dispatchEvent(new CompositionEvent("compositionend", { bubbles: true, data: "hjkl" }));
+ await nextTick();
+ expect(view.state.doc.toString()).toBe(original);
+ expect(props.modelValue).toBe(original);
+ });
+
it("executes each IRIS query separately after the Contains operator", async () => {
const first = "select * from oec_order_adminstatus where STAT_Code [ '123'";
const second = "select top 10 * from Ens_HOSDocument";
diff --git a/apps/desktop/src/lib/editor/__tests__/vimImeGuard.spec.ts b/apps/desktop/src/lib/editor/__tests__/vimImeGuard.spec.ts
new file mode 100644
index 0000000000..79b1bc0499
--- /dev/null
+++ b/apps/desktop/src/lib/editor/__tests__/vimImeGuard.spec.ts
@@ -0,0 +1,163 @@
+// @vitest-environment happy-dom
+
+import { Compartment, EditorState, Prec } from "@codemirror/state";
+import { EditorView, ViewPlugin } from "@codemirror/view";
+import { history, undo } from "@codemirror/commands";
+import { getCM, vim } from "@replit/codemirror-vim";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { createVimImeGuard } from "../vimImeGuard";
+
+const views: EditorView[] = [];
+const sample = "SELECT 1;\nSELECT 2;\nSELECT 3;";
+
+function editor(enabled = true) {
+ const compartment = new Compartment();
+ const extension = () => [vim({ status: true }), createVimImeGuard({ EditorView, ViewPlugin }, getCM)];
+ const view = new EditorView({
+ parent: document.body,
+ state: EditorState.create({ doc: sample, extensions: [history(), compartment.of(enabled ? Prec.highest(extension()) : [])] }),
+ });
+ views.push(view);
+ return { view, disable: () => view.dispatch({ effects: compartment.reconfigure([]) }), enable: () => view.dispatch({ effects: compartment.reconfigure(Prec.highest(extension())) }) };
+}
+
+function key(view: EditorView, value: string, options: KeyboardEventInit = {}) {
+ const event = new KeyboardEvent("keydown", { key: value, bubbles: true, cancelable: true, ...options });
+ view.contentDOM.dispatchEvent(event);
+ return event;
+}
+
+function input(view: EditorView, text: string) {
+ const from = view.state.selection.main.from;
+ const to = view.state.selection.main.to;
+ for (const handler of view.state.facet(EditorView.inputHandler)) {
+ if (handler(view, from, to, text, () => view.state.update({ changes: { from, to, insert: text }, userEvent: "input.type.compose" }))) return true;
+ }
+ view.dispatch({ changes: { from, to, insert: text }, selection: { anchor: from + text.length }, userEvent: "input.type.compose" });
+ return false;
+}
+
+afterEach(() => {
+ for (const view of views.splice(0)) view.destroy();
+ document.body.replaceChildren();
+});
+
+describe("Vim IME command guard", () => {
+ it.each([
+ { key: "l", code: "KeyL", isComposing: true },
+ { key: "Process", code: "KeyL", keyCode: 229 },
+ { key: "Unidentified", code: "KeyL", keyCode: 229 },
+ { key: "Unidentified", code: "KeyL" },
+ { key: "l", code: "KeyL", keyCode: 229 },
+ ])("moves the cursor without inserting text for $key / $keyCode / $isComposing", (event) => {
+ const { view } = editor();
+ expect(key(view, event.key, event).defaultPrevented).toBe(true);
+ expect(view.state.selection.main.head).toBe(1);
+ expect(view.state.doc.toString()).toBe(sample);
+ });
+
+ it("handles keys ignored by CodeMirror while a composition is active", () => {
+ const { view } = editor();
+ view.contentDOM.dispatchEvent(new CompositionEvent("compositionstart", { bubbles: true }));
+ key(view, "l", { code: "KeyL", isComposing: true });
+ key(view, "l", { code: "KeyL", isComposing: true });
+ expect(view.state.selection.main.head).toBe(2);
+ expect(view.state.doc.toString()).toBe(sample);
+ });
+
+ it("preserves counted commands, operators and undo", () => {
+ const { view } = editor();
+ for (const code of ["Digit2", "KeyD", "KeyD"]) key(view, "Process", { code, keyCode: 229 });
+ expect(view.state.doc.toString()).toBe("SELECT 3;");
+ key(view, "u", { isComposing: true });
+ expect(view.state.doc.toString()).toBe(sample);
+ });
+
+ it.each(["hjkl", "你好", "中", "z"])("rejects stray normal-mode text %s", (text) => {
+ const { view } = editor();
+ expect(input(view, text)).toBe(true);
+ expect(view.state.doc.toString()).toBe(sample);
+ });
+
+ it("repairs native composition DOM changes without inserting them into a normal-mode document", async () => {
+ const { view } = editor();
+ view.focus();
+ view.contentDOM.dispatchEvent(new CompositionEvent("compositionstart", { bubbles: true }));
+ view.contentDOM.querySelector(".cm-line")!.textContent = "hjklSELECT 1;";
+ view.contentDOM.dispatchEvent(new CompositionEvent("compositionend", { bubbles: true, data: "hjkl" }));
+ await vi.waitFor(() => expect(view.contentDOM.querySelector(".cm-line")!.textContent).toBe("SELECT 1;"));
+ expect(view.state.doc.toString()).toBe(sample);
+ });
+
+ it("keeps native Chinese composition DOM changes in insert mode", async () => {
+ const { view } = editor();
+ view.focus();
+ key(view, "i");
+ view.contentDOM.dispatchEvent(new CompositionEvent("compositionstart", { bubbles: true }));
+ view.contentDOM.querySelector(".cm-line")!.textContent = "你好SELECT 1;";
+ view.contentDOM.dispatchEvent(new CompositionEvent("compositionend", { bubbles: true, data: "你好" }));
+ await vi.waitFor(() => expect(view.state.doc.toString()).toBe("你好" + sample));
+ expect(getCM(view)?.state.vim?.insertMode).toBe(true);
+ });
+
+ it("enters insert mode via an IME key and allows Chinese composition", () => {
+ const { view } = editor();
+ expect(key(view, "Process", { code: "KeyI", keyCode: 229 }).defaultPrevented).toBe(true);
+ expect(getCM(view)?.state.vim?.insertMode).toBe(true);
+ expect(input(view, "你好")).toBe(false);
+ expect(view.state.doc.toString()).toBe("你好" + sample);
+ key(view, "Escape");
+ expect(getCM(view)?.state.vim?.insertMode).toBe(false);
+ expect(input(view, "hjkl")).toBe(true);
+ });
+
+ it("preserves shifted physical commands and visual editing", () => {
+ const { view } = editor();
+ key(view, "Process", { code: "KeyV", keyCode: 229, shiftKey: true });
+ expect(getCM(view)?.state.vim?.visualLine).toBe(true);
+ key(view, "Process", { code: "KeyD", keyCode: 229 });
+ expect(view.state.doc.toString()).toBe("SELECT 2;\nSELECT 3;");
+ });
+
+ it("keeps literal-character commands working", () => {
+ const { view } = editor();
+ key(view, "r");
+ expect(getCM(view)?.state.vim?.expectLiteralNext).toBe(true);
+ key(view, "Process", { code: "KeyX", keyCode: 229 });
+ expect(input(view, "x")).toBe(true);
+ expect(view.state.doc.toString()).toBe("xELECT 1;\nSELECT 2;\nSELECT 3;");
+ });
+
+ it("does not consume system shortcuts, dead keys or insert-mode keydowns", () => {
+ const { view } = editor();
+ expect(key(view, "Process", { code: "KeyJ", keyCode: 229, metaKey: true }).defaultPrevented).toBe(false);
+ expect(key(view, "Process", { code: "KeyJ", keyCode: 229, altKey: true }).defaultPrevented).toBe(false);
+ expect(key(view, "Dead", { code: "Quote", isComposing: true }).defaultPrevented).toBe(false);
+ expect(key(view, "F2", { isComposing: true }).defaultPrevented).toBe(false);
+ key(view, "i");
+ expect(key(view, "Process", { code: "KeyJ", keyCode: 229 }).defaultPrevented).toBe(false);
+ });
+
+ it("does not block clipboard or programmatic changes in normal mode", () => {
+ const { view } = editor();
+ view.dispatch({ changes: { from: 0, insert: "-- pasted\n" }, userEvent: "input.paste" });
+ expect(view.state.doc.toString()).toBe("-- pasted\n" + sample);
+ expect(undo(view)).toBe(true);
+ expect(view.state.doc.toString()).toBe(sample);
+ });
+
+ it("removes the capture listener when Vim is disabled and can be enabled again", () => {
+ const { view, disable, enable } = editor();
+ disable();
+ expect(key(view, "Process", { code: "KeyJ", keyCode: 229 }).defaultPrevented).toBe(false);
+ enable();
+ key(view, "Process", { code: "KeyL", keyCode: 229 });
+ expect(view.state.selection.main.head).toBe(1);
+ });
+
+ it("leaves regular typing intact when Vim is disabled", () => {
+ const { view } = editor(false);
+ expect(input(view, "你好")).toBe(false);
+ expect(view.state.doc.toString()).toBe("你好" + sample);
+ });
+});
diff --git a/apps/desktop/src/lib/editor/vimImeGuard.ts b/apps/desktop/src/lib/editor/vimImeGuard.ts
new file mode 100644
index 0000000000..6a1e667825
--- /dev/null
+++ b/apps/desktop/src/lib/editor/vimImeGuard.ts
@@ -0,0 +1,80 @@
+import type { Extension } from "@codemirror/state";
+import type { EditorView } from "@codemirror/view";
+
+type ViewModule = typeof import("@codemirror/view");
+type GetVimEditor = typeof import("@replit/codemirror-vim").getCM;
+
+const imePhysicalKeys: Record<string, string> = {
+ Space: " ",
+ Backquote: "`~",
+ Minus: "-_",
+ Equal: "=+",
+ BracketLeft: "[{",
+ BracketRight: "]}",
+ Backslash: "\\|",
+ Semicolon: ";:",
+ Quote: "'\"",
+ Comma: ",<",
+ Period: ".>",
+ Slash: "/?",
+};
+
+function imeCommandKey(event: KeyboardEvent): string | undefined {
+ if (event.key !== "Process" && event.key !== "Unidentified") return event.key;
+ if (/^Key[A-Z]$/.test(event.code)) {
+ const letter = event.code.slice(3);
+ return event.shiftKey ? letter : letter.toLowerCase();
+ }
+ if (/^Digit\d$/.test(event.code)) {
+ const digit = event.code.slice(5);
+ return event.shiftKey ? ")!@#$%^&*("[Number(digit)] : digit;
+ }
+ const pair = imePhysicalKeys[event.code];
+ return pair?.[event.shiftKey && pair.length > 1 ? 1 : 0];
+}
+
+/** Keep IME input on Vim's command path while normal/visual mode owns the editor. */
+export function createVimImeGuard({ EditorView, ViewPlugin }: Pick<ViewModule, "EditorView" | "ViewPlugin">, getCM: GetVimEditor): Extension {
+ return [
+ ViewPlugin.fromClass(
+ class {
+ constructor(private view: EditorView) {
+ // CodeMirror skips its DOM key handlers during composition. Capture
+ // IME keys before that check, then use Vim's existing command handler
+ // so mappings, pending operators, status and multiple cursors agree.
+ view.contentDOM.addEventListener("keydown", this.keydown, true);
+ }
+
+ private keydown = (event: KeyboardEvent) => {
+ const cm = getCM(this.view);
+ const vim = cm?.state.vim;
+ if (!vim || vim.insertMode || vim.expectLiteralNext || cm.state.dialog || event.defaultPrevented) return;
+ if (event.ctrlKey || event.metaKey || event.altKey) return;
+ if (!event.isComposing && event.keyCode !== 229 && event.key !== "Process" && event.key !== "Unidentified" && !this.view.compositionStarted) return;
+ const key = imeCommandKey(event);
+ if (!key || key === "Dead") return;
+ const plugin = cm.state.vimPlugin;
+ if (!plugin) return;
+ const handled = plugin.handleKey(new KeyboardEvent("keydown", { key, code: event.code, shiftKey: event.shiftKey }), this.view);
+ if (!handled && key.length !== 1) return;
+ // Even an unmapped printable key must not become SQL in normal mode.
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ };
+
+ destroy() {
+ this.view.contentDOM.removeEventListener("keydown", this.keydown, true);
+ }
+ },
+ ),
+ // Put this after vim(): let its single-character/literal handling run
+ // first, then swallow text that an IME commits without a usable keydown.
+ // Vim edits and clipboard paste dispatch transactions directly, so this
+ // does not block commands that intentionally change the document.
+ EditorView.inputHandler.of((view) => {
+ const cm = getCM(view);
+ const vim = cm?.state.vim;
+ return !!vim && !vim.insertMode && !vim.expectLiteralNext && !cm.state.dialog;
+ }),
+ ];
+}
diff --git a/docs/testing/assets/vim-ime-8883/after.png b/docs/testing/assets/vim-ime-8883/after.png
new file mode 100644
index 0000000000..b7a8b1249c
Binary files /dev/null and b/docs/testing/assets/vim-ime-8883/after.png differ
diff --git a/docs/testing/assets/vim-ime-8883/before.png b/docs/testing/assets/vim-ime-8883/before.png
new file mode 100644
index 0000000000..fb6889cbfd
Binary files /dev/null and b/docs/testing/assets/vim-ime-8883/before.png differ
diff --git a/docs/testing/vim-ime-8883.md b/docs/testing/vim-ime-8883.md
new file mode 100644
index 0000000000..98cb3e60aa
--- /dev/null
+++ b/docs/testing/vim-ime-8883.md
@@ -0,0 +1,54 @@
+# Vim normal mode IME regression (#8883)
+
+Verified on macOS 26.3 on 2026-10-13.
+
+## Reproduction and desktop checks
+
+The installed DBX 0.6.41 reproduced the report: starting with an empty editor,
+pressing Escape, h/j/k/l, Enter and Escape left `hjkl` in SQL while the status
+still displayed NORMAL. The system input source was Pinyin – Simplified.
+
+![Installed version: text inserted in NORMAL](assets/vim-ime-8883/before.png)
+
+A local desktop build based on 0.6.42 used an isolated data directory and a
+SQLite in-memory connection. The embedded frontend ran at `tauri://localhost`.
+Normal-mode h/j/k/l left the three-line SQL document intact. INSERT-mode
+multiline clipboard paste, Escape, gg, yy, p and u worked as expected.
+
+![Local desktop build: SQL remains intact in NORMAL](assets/vim-ime-8883/after.png)
+
+On 2026-10-13, the user manually tested the final source in the **DBX Vim Source
+Check** desktop app and confirmed that h/j/k/l in NORMAL move the cursor rather
+than insert text. This manual check supplements the automated desktop input
+below. The user did not specify the input method used in that check.
+
+The control tool's printable keys in the new desktop process arrived as ordinary
+English keydown events, without composition events. Those automated desktop
+checks alone do not establish that real Pinyin candidate submission is fixed.
+Baidu and Doubao input methods were not enabled on this machine; their behavior,
+visual navigation and Chinese composition in INSERT have not been manually
+verified in this run.
+
+## Regression coverage
+
+A mounted QueryEditor regression fails on the unpatched upstream component and
+passes with the guard. Tests use the real CodeMirror Vim extension to cover
+Process/Unidentified keys, keyCode 229, composition-active navigation, operators,
+counts, visual editing, undo, normal-mode stray text, insert-mode Chinese text,
+literal commands, shortcuts, paste and disabling/re-enabling Vim. DOM mutation
+tests also check that rejected composition text is removed from the rendered
+editor, while insert-mode Chinese composition changes reach the document.
+
+```sh
+pnpm exec vitest run apps/desktop/src/lib/editor/__tests__/vimImeGuard.spec.ts \
+ apps/desktop/src/lib/editor/__tests__/vimConfig.spec.ts \
+ apps/desktop/src/lib/editor/__tests__/vimSystemClipboard.spec.ts \
+ apps/desktop/src/components/editor/__tests__/QueryEditor.componentSplit.integration.spec.ts \
+ apps/desktop/src/components/editor/__tests__/QueryEditor.snippetEscape.integration.spec.ts \
+ apps/desktop/src/components/editor/__tests__/useQueryEditorCompletionKeys.spec.ts
+```
+
+The six suites pass (88 tests). Frontend formatting, lint, typecheck (with the
+CI 8 GiB Node heap setting), the Vite production build and the native desktop
+build also pass. Lint and native builds report existing warnings outside the
+changed code. No i18n keys were added.