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。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
feat(editor): run DBX actions from Vim via :dbx commands (#13044)
Youmin9b8c4e145b38
diff --git a/apps/desktop/src/App.vue b/apps/desktop/src/App.vueindex 900945a2f6..afb52e6945 100644--- a/apps/desktop/src/App.vue+++ b/apps/desktop/src/App.vue@@ -172,6 +172,7 @@ import {switchToTabIndexFromShortcut,tabSwitcherDirectionFromShortcut,} from "@/lib/editor/keyboardShortcuts";+import { DBX_VIM_ACTION_EVENT, type DbxVimActionEvent } from "@/lib/editor/vimDbxActions";import { canSaveSqlTab } from "@/lib/tabs/sqlTabSaveTarget";import { initialTabSwitcherSelection, moveTabSwitcherSelection, tabSwitcherOrder } from "@/lib/tabs/tabSwitcher";import { createModifierDoubleTapShortcutController, isModifierDoubleTapShortcut, matchesModifierDoubleTapShortcut } from "@/lib/editor/modifierDoubleTapShortcut";@@ -4579,6 +4580,35 @@ async function closeActiveSurface() {queryStore.closeTab(queryStore.activeTabId);}}+// App-scoped `:dbx` actions. Editor-scoped ones are handled (and stopped) in+// QueryEditor before the event bubbles up to window.+function handleVimDbxAppAction(event: Event) {+ const { action } = (event as DbxVimActionEvent).detail;+ switch (action) {+ case "newQuery":+ void newQuery();+ break;+ case "closeTab":+ void closeActiveSurface();+ break;+ case "closeOtherTabs":+ appTabBarRef.value?.closeOtherActiveTabs();+ break;+ case "closeAllTabs":+ appTabBarRef.value?.closeAllTabs();+ break;+ case "reopenClosedTab":+ queryStore.reopenClosedTab();+ break;+ case "openSettings":+ openSettings();+ break;+ default:+ return;+ }+ event.preventDefault();+}+async function handleKeydown(e: KeyboardEvent) {if (e.defaultPrevented) return;@@ -5149,6 +5179,7 @@ onMounted(async () => {window.addEventListener("keydown", handleTabSwitcherKeydownCapture, true);window.addEventListener("keydown", handleAuxiliarySearchKeydownCapture, true);window.addEventListener("keydown", handleKeydown);+ window.addEventListener(DBX_VIM_ACTION_EVENT, handleVimDbxAppAction);window.addEventListener("keyup", handleKeyup, true);window.addEventListener("blur", handleTabSwitcherWindowBlur);document.addEventListener("visibilitychange", handleTabSwitcherVisibilityChange);@@ -5245,6 +5276,7 @@ onUnmounted(() => {window.removeEventListener("keydown", handleTabSwitcherKeydownCapture, true);window.removeEventListener("keydown", handleAuxiliarySearchKeydownCapture, true);window.removeEventListener("keydown", handleKeydown);+ window.removeEventListener(DBX_VIM_ACTION_EVENT, handleVimDbxAppAction);window.removeEventListener("keyup", handleKeyup, true);window.removeEventListener("blur", handleTabSwitcherWindowBlur);document.removeEventListener("visibilitychange", handleTabSwitcherVisibilityChange);diff --git a/apps/desktop/src/components/editor/QueryEditor.vue b/apps/desktop/src/components/editor/QueryEditor.vueindex f74c2c275e..1ba7e40157 100644--- a/apps/desktop/src/components/editor/QueryEditor.vue+++ b/apps/desktop/src/components/editor/QueryEditor.vue@@ -119,6 +119,8 @@ import { editorClipboardLineEndingsExtension } from "@/lib/editor/editorClipboarimport { applyVimConfig, isVimMappingCommand, loadVimConfig } from "@/lib/editor/vimConfig";import { createVimImeGuard } from "@/lib/editor/vimImeGuard";import { configureVimSystemClipboard } from "@/lib/editor/vimSystemClipboard";+import { configureVimDbxActions, DBX_VIM_ACTION_EVENT, type DbxVimActionEvent } from "@/lib/editor/vimDbxActions";+import type { ShortcutActionId } from "@/lib/editor/shortcutRegistry";import { selectionMatchOccurrences } from "@/lib/editor/codemirrorSelectionMatches";@@ -1603,6 +1605,67 @@ function configureDbxVimCommands(vimApi: typeof import("@replit/codemirror-vim")vimApi.defineEx("write", "w", (cm) => {cm.cm6?.contentDOM.dispatchEvent(new CustomEvent(DBX_VIM_SAVE_EVENT, { bubbles: true }));});+ configureVimDbxActions(vimApi, {+ onUnknownAction: (name) => toast(name ? `Unknown DBX action: ${name}` : "Usage: :dbx <action>", 3000),+ });+}++// Editor-scoped actions reachable from `:dbx <action>`. Each entry reuses the+// same function the keyboard shortcut runs, so Vim and shortcuts cannot drift.+// Return false when the action does not apply; the event then keeps bubbling+// so an outer listener (App.vue) can handle app-scoped actions.+const vimDbxActionHandlers: Partial<Record<ShortcutActionId, (currentView: EditorViewType) => boolean>> = {+ executeSql: (currentView) => {+ if (props.hideExecutionControls || shouldBlockExecutionShortcut(undefined, currentView)) return true;+ requestExecute({ bypassPicker: false });+ return true;+ },+ executeSqlInNewResultTab: (currentView) => {+ if (props.hideExecutionControls || shouldBlockExecutionShortcut(undefined, currentView)) return true;+ requestExecuteInNewResultTab();+ return true;+ },+ explainSql: (currentView) => {+ if (!props.enableExplainShortcut || !props.canExplain || shouldBlockExecutionShortcut(undefined, currentView)) return true;+ emit("explain");+ return true;+ },+ formatSql: () => {+ void formatCurrentSql();+ return true;+ },+ saveSql: () => {+ emit("save");+ return true;+ },+ expandSelectStar: (currentView) => {+ const target = selectStarExpansionTargetForView(currentView);+ if (target) void expandSelectStar(target);+ return true;+ },+ toggleLineComment: (currentView) => codeMirrorRuntime.codeMirrorToggleLineComment?.(currentView) ?? false,+ toggleBlockComment: (currentView) => (supportsQueryEditorBlockComments(props.databaseType) ? (codeMirrorRuntime.codeMirrorToggleBlockComment?.(currentView) ?? false) : true),+ selectCurrentStatement: selectCurrentStatementFromView,+ previousStatement: (currentView) => navigateStatementFromView(currentView, "previous"),+ nextStatement: (currentView) => navigateStatementFromView(currentView, "next"),+ statementStart: (currentView) => navigateStatementFromView(currentView, "start"),+ uppercaseSelection: () => convertSelectedSqlCase("upper"),+ lowercaseSelection: () => convertSelectedSqlCase("lower"),+ sendSelectionToAi: (currentView) => {+ const sql = selectedSqlFromView(currentView);+ if (sql.trim()) emit("sendSelectionToAi", sql);+ return true;+ },+ sqlIntentionActions: handleSqlIntentionActions,+};++function handleVimDbxAction(event: Event, currentView: EditorViewType): boolean {+ const { action } = (event as DbxVimActionEvent).detail;+ const handler = vimDbxActionHandlers[action];+ if (!handler || !handler(currentView)) return false;+ // Handled here: keep App.vue's fallback listener from running it again.+ event.stopPropagation();+ return true;}let vimConfigApplied = false;@@ -2328,6 +2391,9 @@ const codeMirrorLifecycle = useQueryEditorCodeMirror({emit("save");return true;},+ [DBX_VIM_ACTION_EVENT](event: Event, currentView: EditorViewType) {+ return handleVimDbxAction(event, currentView);+ },wheel(event) {if (!wheelZoomGestureGuard.accepts(event)) return false;event.preventDefault();diff --git a/apps/desktop/src/lib/editor/__tests__/vimDbxActions.spec.ts b/apps/desktop/src/lib/editor/__tests__/vimDbxActions.spec.tsnew file mode 100644index 0000000000..1d237b36b8--- /dev/null+++ b/apps/desktop/src/lib/editor/__tests__/vimDbxActions.spec.ts@@ -0,0 +1,92 @@+// @vitest-environment happy-dom++import { EditorState, Prec } from "@codemirror/state";+import { EditorView } from "@codemirror/view";+import { getCM, vim, Vim } from "@replit/codemirror-vim";+import { afterEach, beforeAll, describe, expect, it } from "vitest";+import { configureVimDbxActions, DBX_VIM_ACTION_EVENT, type DbxVimActionDetail } from "../vimDbxActions";++const views: EditorView[] = [];+const sample = "SELECT 1;\nSELECT 2;\nSELECT 3;";+const unknown: string[] = [];++beforeAll(() => {+ configureVimDbxActions(Vim, { onUnknownAction: (name) => unknown.push(name) });+});++function editor(cursor = 0) {+ const view = new EditorView({ parent: document.body, state: EditorState.create({ doc: sample, selection: { anchor: cursor }, extensions: [Prec.highest(vim())] }) });+ views.push(view);+ const events: { detail: DbxVimActionDetail; selection: string }[] = [];+ view.contentDOM.addEventListener(DBX_VIM_ACTION_EVENT, (event) => {+ const sel = view.state.selection.main;+ events.push({ detail: (event as CustomEvent<DbxVimActionDetail>).detail, selection: view.state.sliceDoc(sel.from, sel.to) });+ });+ const cm = getCM(view)!;+ const keys = (...ks: string[]) => ks.forEach((k) => Vim.handleKey(cm, k, "user"));+ return { view, events, cm, keys };+}++afterEach(() => {+ views.splice(0).forEach((view) => view.destroy());+ unknown.length = 0;+});++describe(":dbx", () => {+ it("dispatches the action from an Ex command, case-insensitively", () => {+ const { cm, events } = editor();+ Vim.handleEx(cm, "dbx FORMATSQL extra");+ expect(events.map((e) => e.detail)).toEqual([{ action: "formatSql", args: ["extra"] }]);+ });++ it("reports unknown actions without dispatching", () => {+ const { cm, events } = editor();+ Vim.handleEx(cm, "dbx nope");+ Vim.handleEx(cm, "dbx");+ expect(events).toEqual([]);+ expect(unknown).toEqual(["nope", ""]);+ });++ it("runs through a vimrc-style normal-mode mapping", () => {+ const { cm, events, keys } = editor();+ Vim.handleEx(cm, "nnoremap Qr :DbxExecuteSql<CR>");+ keys("Q", "r");+ expect(events.map((e) => e.detail.action)).toEqual(["executeSql"]);+ });++ it("documents why a spaced rhs does not work in :map", () => {+ const { cm, events, keys } = editor();+ Vim.handleEx(cm, "nnoremap Qx :dbx formatSql<CR>");+ keys("Q", "x");+ expect(events).toEqual([]);+ });++ it("supports a <Space> leader once the default <Space> motion is unmapped", () => {+ const { cm, events, keys } = editor();+ Vim.handleEx(cm, "unmap <Space>");+ Vim.handleEx(cm, "nnoremap <Space>e :DbxExplainSql<CR>");+ keys("<Space>", "e");+ expect(events.map((e) => e.detail.action)).toEqual(["explainSql"]);+ });++ it("keeps a charwise visual selection for the action", () => {+ const { cm, events, keys } = editor(0);+ Vim.handleEx(cm, "vnoremap Qr :DbxExecuteSql<CR>");+ keys("v", "e", "Q", "r"); // select "SELECT"+ expect(events.map((e) => e.selection)).toEqual(["SELECT"]);+ });++ it("keeps a linewise visual selection for the action", () => {+ const { cm, events, keys } = editor(sample.indexOf("SELECT 2"));+ keys("V", "G");+ Vim.handleEx(cm, "'<,'>dbx executeSql");+ expect(events.map((e) => e.selection)).toEqual(["SELECT 2;\nSELECT 3;"]);+ });++ it("does not reuse an old visual selection for a plain :dbx", () => {+ const { cm, events, keys } = editor(0);+ keys("v", "e", "<Esc>");+ Vim.handleEx(cm, "dbx executeSql");+ expect(events.map((e) => e.selection)).toEqual([""]);+ });+});diff --git a/apps/desktop/src/lib/editor/vimDbxActions.ts b/apps/desktop/src/lib/editor/vimDbxActions.tsnew file mode 100644index 0000000000..7b906eb687--- /dev/null+++ b/apps/desktop/src/lib/editor/vimDbxActions.ts@@ -0,0 +1,129 @@+import type { EditorView } from "@codemirror/view";+import type { ShortcutActionId } from "@/lib/editor/shortcutRegistry";++type VimApi = typeof import("@replit/codemirror-vim").Vim;+type GetVimEditor = typeof import("@replit/codemirror-vim").getCM;+type VimCm = NonNullable<ReturnType<GetVimEditor>>;++/** DOM event the `:dbx` Ex command dispatches; bubbles from the editor's contentDOM. */+export const DBX_VIM_ACTION_EVENT = "dbx-vim-action";++export interface DbxVimActionDetail {+ action: ShortcutActionId;+ /** Extra words after the action name, e.g. `:dbx formatSql foo` → ["foo"]. */+ args: string[];+}++export type DbxVimActionEvent = CustomEvent<DbxVimActionDetail>;++/**+ * Actions `:dbx` accepts. Names reuse ShortcutActionId so the vimrc and the+ * shortcut settings speak the same vocabulary. Matching is case-insensitive.+ */+export const DBX_VIM_ACTIONS = [+ // editor scope (handled by QueryEditor)+ "executeSql",+ "executeSqlInNewResultTab",+ "explainSql",+ "formatSql",+ "saveSql",+ "expandSelectStar",+ "toggleLineComment",+ "toggleBlockComment",+ "selectCurrentStatement",+ "previousStatement",+ "nextStatement",+ "statementStart",+ "uppercaseSelection",+ "lowercaseSelection",+ "sendSelectionToAi",+ "sqlIntentionActions",+ // app scope (fall through to App.vue's window listener)+ "newQuery",+ "closeTab",+ "closeOtherTabs",+ "closeAllTabs",+ "reopenClosedTab",+ "openSettings",+] as const satisfies readonly ShortcutActionId[];++const actionByLowerName = new Map<string, ShortcutActionId>(DBX_VIM_ACTIONS.map((id) => [id.toLowerCase(), id]));++export function resolveDbxVimAction(name: string | undefined): ShortcutActionId | undefined {+ return name ? actionByLowerName.get(name.toLowerCase()) : undefined;+}++/**+ * `:'<,'>dbx ...` runs after codemirror-vim has already left visual mode and+ * collapsed the selection. Rebuild it from `vim.lastSelection` so actions like+ * executeSql / formatSql keep their "selection first" behaviour.+ */+function restoreVisualSelection(cm: VimCm, view: EditorView): void {+ const last = cm.state.vim?.lastSelection;+ if (!last) return;+ const doc = view.state.doc;+ const offset = (pos: { line: number; ch: number }) => {+ const line = doc.line(Math.min(Math.max(pos.line + 1, 1), doc.lines));+ return Math.min(line.from + pos.ch, line.to);+ };+ const a = last.anchorMark?.find?.() ?? last.anchor;+ const h = last.headMark?.find?.() ?? last.head;+ let from = Math.min(offset(a), offset(h));+ let to = Math.max(offset(a), offset(h));+ if (last.visualLine || last.visualBlock) {+ // Block mode has no single-range equivalent; treat it like linewise.+ from = doc.lineAt(from).from;+ to = doc.lineAt(to).to;+ } else {+ // Vim's charwise head is inclusive; CodeMirror ranges are half-open.+ to = Math.min(to + 1, doc.length);+ }+ view.dispatch({ selection: { anchor: from, head: to } });+}++function isVisualRangeInput(input: string): boolean {+ return /^\s*'<\s*,\s*'>/.test(input);+}++/** `executeSql` → `DbxExecuteSql`, the space-free Ex name used in vimrc mappings. */+export function dbxVimExCommandName(action: ShortcutActionId): string {+ return `Dbx${action.charAt(0).toUpperCase()}${action.slice(1)}`;+}++function dispatchDbxAction(cm: VimCm, params: { input: string }, action: ShortcutActionId, args: string[]): void {+ const view = cm.cm6;+ if (!view) return;+ if (isVisualRangeInput(params.input)) restoreVisualSelection(cm, view);+ view.contentDOM.dispatchEvent(+ new CustomEvent<DbxVimActionDetail>(DBX_VIM_ACTION_EVENT, {+ bubbles: true,+ cancelable: true,+ detail: { action, args },+ }),+ );+}++/**+ * Register the Vim side of DBX actions. Safe to call once per app session.+ *+ * - `:dbx <action> [args...]` for typing interactively.+ * - `:DbxExecuteSql`, `:DbxFormatSql`, … one per action, for vimrc mappings.+ * codemirror-vim's `:map` splits its arguments on whitespace, so+ * `nnoremap Qr :dbx executeSql<CR>` would map only `:dbx`; the space-free+ * names avoid that.+ */+export function configureVimDbxActions(vimApi: VimApi, options: { onUnknownAction?: (name: string) => void } = {}): void {+ vimApi.defineEx("dbx", "dbx", (cm, params) => {+ const [name, ...args] = params.args ?? (params.argString ?? "").trim().split(/\s+/).filter(Boolean);+ const action = resolveDbxVimAction(name);+ if (!action) {+ options.onUnknownAction?.(name ?? "");+ return;+ }+ dispatchDbxAction(cm as VimCm, params, action, args);+ });+ for (const action of DBX_VIM_ACTIONS) {+ const name = dbxVimExCommandName(action);+ vimApi.defineEx(name, name, (cm, params) => dispatchDbxAction(cm as VimCm, params, action, params.args ?? []));+ }+}diff --git a/docs/content/docs/query-editor.cn.mdx b/docs/content/docs/query-editor.cn.mdxindex 76212d0a8d..5046dc4086 100644--- a/docs/content/docs/query-editor.cn.mdx+++ b/docs/content/docs/query-editor.cn.mdx@@ -24,6 +24,37 @@ set clipboard=unnamedplus配置 `set clipboard=unnamedplus` 后,Vim 的复制和删除会写入系统剪贴板,普通模式下的 `p` 和 `P` 会从系统剪贴板读取。不支持的命令不会阻止编辑器启动。+### 在 Vim 中执行 DBX 操作++在 Vim 命令行中输入 `:dbx <action>` 即可执行 DBX 操作。操作名与快捷键的 action ID 一致,且不区分大小写,例如 `:dbx formatsql` 同样有效。输入未知的操作名时只会显示提示,不会执行任何操作。++| 范围 | 操作 |+| --- | --- |+| 编辑器 | `executeSql`、`executeSqlInNewResultTab`、`explainSql`、`formatSql`、`saveSql`、`expandSelectStar`、`toggleLineComment`、`toggleBlockComment`、`selectCurrentStatement`、`previousStatement`、`nextStatement`、`statementStart`、`uppercaseSelection`、`lowercaseSelection`、`sendSelectionToAi`、`sqlIntentionActions` |+| 应用 | `newQuery`、`closeTab`、`closeOtherTabs`、`closeAllTabs`、`reopenClosedTab`、`openSettings` |++编辑器操作的行为与对应的快捷键相同。例如 `executeSql` 有选区时执行选中内容,否则执行当前语句。在可视模式下执行(命令行会变成 `:'<,'>dbx executeSql`)时,会先恢复可视选区,只使用选中的 SQL;行可视和块可视选区会扩展为整行。++撤销、缩进、删除行、合并行等 Vim 本身已提供的编辑操作不会通过 `:dbx` 提供,请直接使用 Vim 原生命令。++每个操作还有一个不含空格的命令:`:Dbx` 加上首字母大写的操作名,例如 `:DbxExecuteSql`、`:DbxFormatSql`。在 `vimrc` 的映射中请使用这些命令,因为 CodeMirror Vim 的映射遇到第一个空格就会截断,无法直接映射 `:dbx executeSql`:++```vim+nnoremap Qr :DbxExecuteSql<CR>+vnoremap Qr :DbxExecuteSql<CR>+nnoremap Qf :DbxFormatSql<CR>+nnoremap Qj :DbxNextStatement<CR>+nnoremap Qk :DbxPreviousStatement<CR>+```++CodeMirror Vim 在已输入的按键完整匹配某个内置命令时会立即执行,不会像 Vim 那样按 `timeoutlen` 等待后续按键。因此映射前缀请选择本身不是单键命令的键,例如 `Q`。常用的 leader 键 `<Space>`(光标右移)和 `,`(反向重复上一次 `f`/`t` 查找)会被内置命令直接吃掉,`<Space>r`、`,x` 这类映射不会被触发。如果想用它们作为前缀,请先取消其内置命令(该键原本的功能也会随之失效):++```vim+unmap <Space>+nnoremap <Space>r :DbxExecuteSql<CR>+vnoremap <Space>r :DbxExecuteSql<CR>+```+## 基本工作流<Steps>diff --git a/docs/content/docs/query-editor.mdx b/docs/content/docs/query-editor.mdxindex 85918b489c..7efef839d6 100644--- a/docs/content/docs/query-editor.mdx+++ b/docs/content/docs/query-editor.mdx@@ -24,6 +24,37 @@ set clipboard=unnamedplusWith `set clipboard=unnamedplus`, Vim yanks and deletes write to the system clipboard, and normal-mode `p` and `P` read from it. Unsupported commands do not prevent the editor from starting.+### Run DBX actions from Vim++Type `:dbx <action>` in the Vim command line to run a DBX action. Action names match the shortcut action IDs and are case-insensitive, so `:dbx formatsql` also works. An unknown name shows a notice instead of running anything.++| Scope | Actions |+| --- | --- |+| Editor | `executeSql`, `executeSqlInNewResultTab`, `explainSql`, `formatSql`, `saveSql`, `expandSelectStar`, `toggleLineComment`, `toggleBlockComment`, `selectCurrentStatement`, `previousStatement`, `nextStatement`, `statementStart`, `uppercaseSelection`, `lowercaseSelection`, `sendSelectionToAi`, `sqlIntentionActions` |+| App | `newQuery`, `closeTab`, `closeOtherTabs`, `closeAllTabs`, `reopenClosedTab`, `openSettings` |++Editor actions behave like their keyboard shortcuts. For example, `executeSql` runs the selection when there is one, and the current statement otherwise. Running from Visual mode, which enters `:'<,'>dbx executeSql`, restores the visual selection first, so only the selected SQL is used. Linewise and blockwise selections are expanded to whole lines.++Editing actions that Vim already provides, such as undo, indent, delete line, and join lines, are not exposed through `:dbx`; use the native Vim commands instead.++Each action also has a space-free command, `:Dbx` followed by the action name with its first letter capitalized, for example `:DbxExecuteSql` or `:DbxFormatSql`. Use these in `vimrc` mappings, because CodeMirror Vim mappings stop at the first space and cannot map `:dbx executeSql` directly:++```vim+nnoremap Qr :DbxExecuteSql<CR>+vnoremap Qr :DbxExecuteSql<CR>+nnoremap Qf :DbxFormatSql<CR>+nnoremap Qj :DbxNextStatement<CR>+nnoremap Qk :DbxPreviousStatement<CR>+```++CodeMirror Vim runs a built-in command as soon as the typed keys match it, without waiting for more keys the way Vim's `timeoutlen` does. Use a prefix that is not already a single-key command, such as `Q`. Common leader keys like `<Space>` (move right) and `,` (repeat the last `f`/`t` search backward) are consumed by their built-in commands, so mappings like `<Space>r` or `,x` never fire. To use one of them as a prefix, unmap its built-in command first, which also removes that key's original behavior:++```vim+unmap <Space>+nnoremap <Space>r :DbxExecuteSql<CR>+vnoremap <Space>r :DbxExecuteSql<CR>+```+## Basic Workflow<Steps>