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。

feat(editor): add SQL statement navigation shortcuts (#12754)

PanyangY3bf7532df98b
diff --git a/apps/desktop/src/components/editor/QueryEditor.vue b/apps/desktop/src/components/editor/QueryEditor.vue
index 31f9dbcf9a..183d7eac62 100644
--- a/apps/desktop/src/components/editor/QueryEditor.vue
+++ b/apps/desktop/src/components/editor/QueryEditor.vue
@@ -67,6 +67,7 @@ import { clipboardLineEndings, copyToClipboard, readTextFromClipboard } from "@/
import { resolveExecutableSql, type SqlExecutionOverride } from "@/lib/sql/sqlExecutionTarget";
import { supportsExecutionTargetPicker, type SqlTextRange } from "@/lib/sql/sqlStatementRanges";
import { executableStatementRangeAtCursor, executableStatementRangeCacheForDoc, executableStatementRangeStartingAt as executableStatementRangeStartingAtLine, type ExecutableStatementRangeCache } from "@/lib/sql/executableStatementRangeCache";
+import { statementNavigationTarget, type StatementNavigationDirection } from "@/lib/sql/statementNavigation";
import { looksLikeDmlStatement } from "@/lib/sql/dmlChangePreview";
@@ -1223,6 +1224,24 @@ function selectCurrentStatementFromContextMenu(): void {
selectCurrentStatementFromView(currentView);
}
+/**
+ * Move the caret between executable statements without changing the document.
+ * Reuses the same statement ranges as 「执行当前语句」/「选中当前语句」 so the
+ * navigation boundaries always match what execution would run.
+ */
+function navigateStatementFromView(currentView: EditorViewType, direction: StatementNavigationDirection): boolean {
+ executableStatementRangeCache = executableStatementRangeCacheForDoc(executableStatementRangeCache, currentView.state.doc, props.databaseType, sqlStatementParameterOptions());
+ const target = statementNavigationTarget(executableStatementRangeCache.ranges, currentView.state.selection.main.head, direction);
+ if (target === null) return false;
+ currentView.dispatch({
+ selection: { anchor: target },
+ scrollIntoView: true,
+ userEvent: "select.keyboard",
+ });
+ currentView.focus();
+ return true;
+}
+
const contextMenuActions: QueryEditorContextMenuActions = {
executeFromContextMenu,
executeInNewResultTabFromContextMenu,
@@ -1435,6 +1454,9 @@ function runKeymapExtension(codeMirrorKeymap: (typeof import("@codemirror/view")
...binding(shortcuts.redo, (view) => codeMirrorRuntime.codeMirrorRedo?.(view) ?? false),
...binding(shortcuts.selectAll, (view) => codeMirrorRuntime.codeMirrorSelectAll?.(view) ?? false),
...binding(shortcuts.selectCurrentStatement, selectCurrentStatementFromView),
+ ...binding(shortcuts.previousStatement, (currentView) => navigateStatementFromView(currentView, "previous")),
+ ...binding(shortcuts.nextStatement, (currentView) => navigateStatementFromView(currentView, "next")),
+ ...binding(shortcuts.statementStart, (currentView) => navigateStatementFromView(currentView, "start")),
...binding(shortcuts.extendSelection, extendQueryEditorSelectionForView),
...binding(shortcuts.addNextSelectionOccurrence, addNextQueryEditorSelectionOccurrence),
...binding(shortcuts.selectAllSelectionOccurrences, selectAllQueryEditorSelectionOccurrences),
diff --git a/apps/desktop/src/components/editor/__tests__/QueryEditorStatementNavigation.integration.spec.ts b/apps/desktop/src/components/editor/__tests__/QueryEditorStatementNavigation.integration.spec.ts
new file mode 100644
index 0000000000..0feed2c4a2
--- /dev/null
+++ b/apps/desktop/src/components/editor/__tests__/QueryEditorStatementNavigation.integration.spec.ts
@@ -0,0 +1,130 @@
+// @vitest-environment happy-dom
+
+import { createApp, h, nextTick, reactive, shallowRef } from "vue";
+import { createPinia, setActivePinia } from "pinia";
+import { createI18n } from "vue-i18n";
+import { EditorView } from "@codemirror/view";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import QueryEditor from "../QueryEditor.vue";
+import { useSettingsStore } from "@/stores/settingsStore";
+import { useConnectionStore } from "@/stores/connectionStore";
+import type { QueryEditorProps } from "../queryEditorTypes";
+
+vi.mock("@/lib/common/clipboard", () => ({
+ copyToClipboard: vi.fn().mockResolvedValue(undefined),
+ readTextFromClipboard: vi.fn().mockResolvedValue(""),
+}));
+
+const cleanups: Array<() => void> = [];
+
+afterEach(() => {
+ for (const cleanup of cleanups.splice(0).reverse()) cleanup();
+ vi.restoreAllMocks();
+});
+
+async function mountEditor(modelValue: string, overrides: Partial<QueryEditorProps> = {}) {
+ const pinia = createPinia();
+ setActivePinia(pinia);
+ const settingsStore = useSettingsStore();
+ useConnectionStore();
+ settingsStore.editorSettings.showExecutionTargetPicker = false;
+ settingsStore.editorSettings.executeMode = "current";
+ settingsStore.editorSettings.executeAllOnBlankLine = false;
+ // Explicit modifiers (instead of Mod) keep the keymap deterministic on every
+ // platform, mirroring QueryEditorSelectCurrentStatement.integration.spec.ts.
+ settingsStore.editorSettings.shortcuts.previousStatement = "Ctrl+Alt+ArrowUp";
+ settingsStore.editorSettings.shortcuts.nextStatement = "Ctrl+Alt+ArrowDown";
+ settingsStore.editorSettings.shortcuts.statementStart = "Ctrl+Alt+Home";
+ const props = reactive<QueryEditorProps>({ modelValue, tabId: "statement-navigation", databaseType: "mysql", dialect: "mysql", autoFocus: false, ...overrides });
+ const editor = shallowRef<InstanceType<typeof QueryEditor>>();
+ const host = document.createElement("div");
+ document.body.append(host);
+ const app = createApp({
+ render: () =>
+ h(QueryEditor, {
+ ...props,
+ ref: editor,
+ "onUpdate:modelValue": (value: string) => {
+ props.modelValue = value;
+ },
+ }),
+ });
+ app.use(pinia);
+ app.use(createI18n({ legacy: false, locale: "en", messages: { en: {} }, missingWarn: false, fallbackWarn: false }));
+ app.mount(host);
+ cleanups.push(() => {
+ app.unmount();
+ host.remove();
+ });
+ await vi.waitFor(() => expect(host.querySelector(".cm-editor")).not.toBeNull(), { timeout: 5000 });
+ const view = EditorView.findFromDOM(host.querySelector(".cm-editor") as HTMLElement)!;
+ return { view, props, settingsStore };
+}
+
+function pressStatementShortcut(view: EditorView, key: string, keyCode: number): KeyboardEvent {
+ const event = new KeyboardEvent("keydown", { key, keyCode, code: key, ctrlKey: true, altKey: true, bubbles: true, cancelable: true });
+ Object.defineProperty(event, "keyCode", { get: () => keyCode });
+ view.contentDOM.dispatchEvent(event);
+ return event;
+}
+
+function cursor(view: EditorView): number {
+ return view.state.selection.main.head;
+}
+
+function placeCursor(view: EditorView, offset: number) {
+ view.dispatch({ selection: { anchor: offset } });
+}
+
+describe("QueryEditor statement navigation", () => {
+ const SQL = "SELECT 1;\n\nSELECT 2 FROM t;\n\nUPDATE t SET x = 1;";
+
+ it("jumps to the next statement start from inside a statement", async () => {
+ const { view } = await mountEditor(SQL);
+ placeCursor(view, SQL.indexOf("SELECT 1") + 3);
+
+ pressStatementShortcut(view, "ArrowDown", 40);
+ await nextTick();
+
+ expect(cursor(view)).toBe(SQL.indexOf("SELECT 2"));
+ });
+
+ it("walks back to the current statement start, then the previous statement", async () => {
+ const { view } = await mountEditor(SQL);
+ placeCursor(view, SQL.indexOf("SELECT 2") + 4);
+
+ pressStatementShortcut(view, "ArrowUp", 38);
+ await nextTick();
+ expect(cursor(view)).toBe(SQL.indexOf("SELECT 2"));
+
+ pressStatementShortcut(view, "ArrowUp", 38);
+ await nextTick();
+ expect(cursor(view)).toBe(SQL.indexOf("SELECT 1"));
+ });
+
+ it("jumps to the statement start from the middle of the statement", async () => {
+ const { view } = await mountEditor(SQL);
+ placeCursor(view, SQL.indexOf("UPDATE") + 5);
+
+ pressStatementShortcut(view, "Home", 36);
+ await nextTick();
+
+ expect(cursor(view)).toBe(SQL.indexOf("UPDATE"));
+ });
+
+ it("keeps the caret in place on the first and last statement boundaries", async () => {
+ const { view } = await mountEditor(SQL);
+ const first = SQL.indexOf("SELECT 1");
+ const last = SQL.indexOf("UPDATE t");
+ placeCursor(view, first);
+
+ pressStatementShortcut(view, "ArrowUp", 38);
+ await nextTick();
+ expect(cursor(view)).toBe(first);
+
+ placeCursor(view, last);
+ pressStatementShortcut(view, "ArrowDown", 40);
+ await nextTick();
+ expect(cursor(view)).toBe(last);
+ });
+});
diff --git a/apps/desktop/src/i18n/__tests__/featureMessages.spec.ts b/apps/desktop/src/i18n/__tests__/featureMessages.spec.ts
index 86ede94b4a..ad89416719 100644
--- a/apps/desktop/src/i18n/__tests__/featureMessages.spec.ts
+++ b/apps/desktop/src/i18n/__tests__/featureMessages.spec.ts
@@ -151,6 +151,11 @@ const FEATURE_MESSAGES: FeatureMessages[] = [
{ feature: "schema diff deploy ignores foreign key checks", keys: under("diff", ["ignoreForeignKeyChecks", "ignoreForeignKeyChecksHint"]), translated: true },
{ feature: "shortcut recorder", keys: under("settings", ["shortcutRecordKeys", "shortcutRecordKeysRecordingHint", "shortcutRecordKeysWindowInactive"]), locales: ALL_LOCALES.filter((locale) => locale !== "th") },
{ feature: "select current statement", keys: ["settings.shortcutSelectCurrentStatement", "editor.contextMenu.selectCurrentStatement"] },
+ {
+ feature: "statement navigation shortcuts",
+ keys: under("settings", ["shortcutPreviousStatement", "shortcutNextStatement", "shortcutStatementStart"]),
+ translated: true,
+ },
{ feature: "MCP history kind", keys: ["history.kinds.mcp"] },
{ feature: "editor selection to AI (#10058)", keys: under("ai", ["selectionChipLabel", "selectionChipDetail", "externalTargetUnavailable"]) },
{ feature: "SQL formatter layout style", keys: under("settings", ["sqlFormatterLayoutStyle", "sqlFormatterLayoutStyleDbx", "sqlFormatterLayoutStyleClassic"]) },
diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.ts
index 5939c7e85b..847bccf69d 100644
--- a/apps/desktop/src/i18n/locales/az.ts
+++ b/apps/desktop/src/i18n/locales/az.ts
@@ -8201,6 +8201,9 @@ export default withEnglishFallback({
shortcutRedo: "Təkrar et",
shortcutSelectAll: "Hamısını seç",
shortcutSelectCurrentStatement: "Cari ifadəni seç",
+ shortcutPreviousStatement: "Əvvəlki ifadəyə keç",
+ shortcutNextStatement: "Növbəti ifadəyə keç",
+ shortcutStatementStart: "İfadənin əvvəlinə keç",
shortcutAddNextSelectionOccurrence: "Növbəti uyğunluğu əlavə et",
shortcutSelectAllSelectionOccurrences: "Bütün uyğunluqları seç",
shortcutExtendSelection: "Seçimi genişləndir",
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index b704bd5e12..78b08230cd 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -9748,6 +9748,9 @@ export default {
shortcutRedo: "Redo",
shortcutSelectAll: "Select all",
shortcutSelectCurrentStatement: "Select current statement",
+ shortcutPreviousStatement: "Go to previous statement",
+ shortcutNextStatement: "Go to next statement",
+ shortcutStatementStart: "Go to statement start",
shortcutAddNextSelectionOccurrence: "Add next occurrence",
shortcutSelectAllSelectionOccurrences: "Select all occurrences",
shortcutSelectLineEnds: "Select line ends",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 8a4a3cd59b..c20c3b6d81 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -8791,6 +8791,9 @@ export default withEnglishFallback({
shortcutRedo: "Rehacer",
shortcutSelectAll: "Seleccionar todo",
shortcutSelectCurrentStatement: "Seleccionar la sentencia actual",
+ shortcutPreviousStatement: "Ir a la instrucción anterior",
+ shortcutNextStatement: "Ir a la instrucción siguiente",
+ shortcutStatementStart: "Ir al inicio de la instrucción",
shortcutAddNextSelectionOccurrence: "Añadir siguiente coincidencia",
shortcutSelectAllSelectionOccurrences: "Seleccionar todas las coincidencias",
shortcutExtendSelection: "Ampliar selección",
diff --git a/apps/desktop/src/i18n/locales/id.ts b/apps/desktop/src/i18n/locales/id.ts
index fc7e18dc46..eb433c7768 100644
--- a/apps/desktop/src/i18n/locales/id.ts
+++ b/apps/desktop/src/i18n/locales/id.ts
@@ -9010,6 +9010,9 @@ export default withEnglishFallback({
shortcutRedo: "Ulangi",
shortcutSelectAll: "Pilih semua",
shortcutSelectCurrentStatement: "Pilih pernyataan saat ini",
+ shortcutPreviousStatement: "Ke pernyataan sebelumnya",
+ shortcutNextStatement: "Ke pernyataan berikutnya",
+ shortcutStatementStart: "Ke awal pernyataan",
shortcutAddNextSelectionOccurrence: "Tambah kemunculan berikutnya",
shortcutSelectAllSelectionOccurrences: "Pilih semua kemunculan",
shortcutExtendSelection: "Perluas seleksi",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 66df418c00..50e21a2765 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -8554,6 +8554,9 @@ export default withEnglishFallback({
shortcutRedo: "Ripeti",
shortcutSelectAll: "Seleziona tutto",
shortcutSelectCurrentStatement: "Seleziona l'istruzione corrente",
+ shortcutPreviousStatement: "Vai all'istruzione precedente",
+ shortcutNextStatement: "Vai all'istruzione successiva",
+ shortcutStatementStart: "Vai all'inizio dell'istruzione",
shortcutAddNextSelectionOccurrence: "Aggiungi occorrenza successiva",
shortcutSelectAllSelectionOccurrences: "Seleziona tutte le occorrenze",
shortcutExtendSelection: "Estendi selezione",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 46479a5415..1879680ac6 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -8543,6 +8543,9 @@ export default withEnglishFallback({
shortcutRedo: "やり直す",
shortcutSelectAll: "すべて選択",
shortcutSelectCurrentStatement: "現在のステートメントを選択",
+ shortcutPreviousStatement: "前のステートメントへ移動",
+ shortcutNextStatement: "次のステートメントへ移動",
+ shortcutStatementStart: "ステートメントの先頭へ移動",
shortcutAddNextSelectionOccurrence: "次の出現箇所を選択に追加",
shortcutSelectAllSelectionOccurrences: "すべての出現箇所を選択",
shortcutExtendSelection: "選択範囲を拡張",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index a4c3afd021..81f4d1e258 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -8452,6 +8452,9 @@ export default withEnglishFallback({
shortcutRedo: "다시 실행",
shortcutSelectAll: "모두 선택",
shortcutSelectCurrentStatement: "현재 문 선택",
+ shortcutPreviousStatement: "이전 문으로 이동",
+ shortcutNextStatement: "다음 문으로 이동",
+ shortcutStatementStart: "문 시작으로 이동",
shortcutAddNextSelectionOccurrence: "다음 일치 항목 선택 추가",
shortcutSelectAllSelectionOccurrences: "모든 일치 항목 선택",
shortcutEditCell: "셀 편집",
diff --git a/apps/desktop/src/i18n/locales/pl.ts b/apps/desktop/src/i18n/locales/pl.ts
index 7d7a7c9247..49b0ea4c3e 100644
--- a/apps/desktop/src/i18n/locales/pl.ts
+++ b/apps/desktop/src/i18n/locales/pl.ts
@@ -9032,6 +9032,9 @@ export default withEnglishFallback({
shortcutRedo: "Ponów",
shortcutSelectAll: "Zaznacz wszystko",
shortcutSelectCurrentStatement: "Zaznacz bieżącą instrukcję",
+ shortcutPreviousStatement: "Przejdź do poprzedniej instrukcji",
+ shortcutNextStatement: "Przejdź do następnej instrukcji",
+ shortcutStatementStart: "Przejdź do początku instrukcji",
shortcutAddNextSelectionOccurrence: "Dodaj następne wystąpienie",
shortcutSelectAllSelectionOccurrences: "Zaznacz wszystkie wystąpienia",
shortcutSelectLineEnds: "Zaznacz końce linii",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index e04d8c22b0..9147503bfc 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -8552,6 +8552,9 @@ export default withEnglishFallback({
shortcutRedo: "Refazer",
shortcutSelectAll: "Selecionar tudo",
shortcutSelectCurrentStatement: "Selecionar a instrução atual",
+ shortcutPreviousStatement: "Ir para a instrução anterior",
+ shortcutNextStatement: "Ir para a próxima instrução",
+ shortcutStatementStart: "Ir para o início da instrução",
shortcutAddNextSelectionOccurrence: "Adicionar próxima ocorrência",
shortcutSelectAllSelectionOccurrences: "Selecionar todas as ocorrências",
shortcutExtendSelection: "Expandir seleção",
diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts
index 29ad6cbd14..0522d2b136 100644
--- a/apps/desktop/src/i18n/locales/ru.ts
+++ b/apps/desktop/src/i18n/locales/ru.ts
@@ -9936,6 +9936,9 @@ export default withEnglishFallback({
shortcutRedo: "Повторить",
shortcutSelectAll: "Выделить всё",
shortcutSelectCurrentStatement: "Выделить текущую инструкцию",
+ shortcutPreviousStatement: "Перейти к предыдущей инструкции",
+ shortcutNextStatement: "Перейти к следующей инструкции",
+ shortcutStatementStart: "Перейти к началу инструкции",
shortcutAddNextSelectionOccurrence: "Добавить следующее вхождение",
shortcutSelectAllSelectionOccurrences: "Выделить все вхождения",
shortcutExtendSelection: "Расширить выделение",
diff --git a/apps/desktop/src/i18n/locales/th.ts b/apps/desktop/src/i18n/locales/th.ts
index 516c79f0c4..35f3e6d933 100644
--- a/apps/desktop/src/i18n/locales/th.ts
+++ b/apps/desktop/src/i18n/locales/th.ts
@@ -10373,6 +10373,9 @@ export default withEnglishFallback({
shortcutRedo: "ทำซ้ำ",
shortcutSelectAll: "เลือกทั้งหมด",
shortcutSelectCurrentStatement: "เลือก Statement ปัจจุบัน",
+ shortcutPreviousStatement: "ไปยังคำสั่งก่อนหน้า",
+ shortcutNextStatement: "ไปยังคำสั่งถัดไป",
+ shortcutStatementStart: "ไปยังจุดเริ่มต้นของคำสั่ง",
shortcutAddNextSelectionOccurrence: "เพิ่มรายการที่พบถัดไป",
shortcutSelectAllSelectionOccurrences: "เลือกทุกตำแหน่งที่พบ",
shortcutSelectLineEnds: "เลือกท้ายบรรทัด",
diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.ts
index 8728696dee..3cb93d7ce8 100644
--- a/apps/desktop/src/i18n/locales/tr.ts
+++ b/apps/desktop/src/i18n/locales/tr.ts
@@ -8103,6 +8103,9 @@ export default withEnglishFallback({
shortcutRedo: "Yinele",
shortcutSelectAll: "Tümünü seç",
shortcutSelectCurrentStatement: "Geçerli ifadeyi seç",
+ shortcutPreviousStatement: "Önceki ifadeye git",
+ shortcutNextStatement: "Sonraki ifadeye git",
+ shortcutStatementStart: "İfadenin başına git",
shortcutAddNextSelectionOccurrence: "Sonraki eşleşmeyi ekle",
shortcutSelectAllSelectionOccurrences: "Tüm eşleşmeleri seç",
shortcutExtendSelection: "Seçimi genişlet",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index fe5fcf0c0b..f282d2cd34 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -9724,6 +9724,9 @@ export default withEnglishFallback({
shortcutRedo: "重做",
shortcutSelectAll: "全选",
shortcutSelectCurrentStatement: "选中当前语句",
+ shortcutPreviousStatement: "跳到上一条 SQL 语句",
+ shortcutNextStatement: "跳到下一条 SQL 语句",
+ shortcutStatementStart: "跳到当前语句开头",
shortcutAddNextSelectionOccurrence: "增加下一个选中词",
shortcutSelectAllSelectionOccurrences: "选中所有选中词",
shortcutSelectLineEnds: "选中行尾",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 1972f28c97..ce61837001 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -7856,6 +7856,9 @@ export default withEnglishFallback({
shortcutRedo: "重做",
shortcutSelectAll: "全選",
shortcutSelectCurrentStatement: "選取目前語句",
+ shortcutPreviousStatement: "跳到上一條 SQL 語句",
+ shortcutNextStatement: "跳到下一條 SQL 語句",
+ shortcutStatementStart: "跳到目前語句開頭",
shortcutAddNextSelectionOccurrence: "增加下一個選取詞",
shortcutSelectAllSelectionOccurrences: "選取所有選取詞",
shortcutExtendSelection: "擴展選取範圍",
diff --git a/apps/desktop/src/lib/__tests__/editor/shortcutRegistry.spec.ts b/apps/desktop/src/lib/__tests__/editor/shortcutRegistry.spec.ts
index a9045de6ae..f3a7f62402 100644
--- a/apps/desktop/src/lib/__tests__/editor/shortcutRegistry.spec.ts
+++ b/apps/desktop/src/lib/__tests__/editor/shortcutRegistry.spec.ts
@@ -206,6 +206,22 @@ describe("shortcutRegistry editor actions", () => {
expect(findCrossScopeShortcutConflicts(DEFAULT_SHORTCUT_SETTINGS).selectCurrentStatement).toContain("disconnectSidebarConnection");
});
+ it("registers conflict-free statement navigation shortcuts", () => {
+ const previous = SHORTCUT_DEFINITIONS.find((item) => item.id === "previousStatement");
+ const next = SHORTCUT_DEFINITIONS.find((item) => item.id === "nextStatement");
+ const start = SHORTCUT_DEFINITIONS.find((item) => item.id === "statementStart");
+
+ expect(previous).toMatchObject({ labelKey: "settings.shortcutPreviousStatement", scope: "editor", defaultShortcut: "Ctrl+Shift+ArrowUp" });
+ expect(next).toMatchObject({ labelKey: "settings.shortcutNextStatement", scope: "editor", defaultShortcut: "Ctrl+Shift+ArrowDown" });
+ expect(start).toMatchObject({ labelKey: "settings.shortcutStatementStart", scope: "editor", defaultShortcut: "Alt+Home" });
+
+ for (const id of ["previousStatement", "nextStatement", "statementStart"] as const) {
+ expect(DEFAULT_SHORTCUT_SETTINGS[id]).toBe(SHORTCUT_DEFINITIONS.find((item) => item.id === id)?.defaultShortcut);
+ expect(shortcutToCodeMirrorKey(DEFAULT_SHORTCUT_SETTINGS[id])).not.toBe("");
+ expect(findShortcutConflict(id, DEFAULT_SHORTCUT_SETTINGS[id], DEFAULT_SHORTCUT_SETTINGS)).toBeNull();
+ }
+ });
+
it("keeps current-view search and editor find contextual on Mod+F", () => {
const focusSearch = SHORTCUT_DEFINITIONS.find((item) => item.id === "focusSearch");
const find = SHORTCUT_DEFINITIONS.find((item) => item.id === "find");
diff --git a/apps/desktop/src/lib/__tests__/sql/statementNavigation.spec.ts b/apps/desktop/src/lib/__tests__/sql/statementNavigation.spec.ts
new file mode 100644
index 0000000000..8dad022baa
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/sql/statementNavigation.spec.ts
@@ -0,0 +1,72 @@
+import { describe, expect, it } from "vitest";
+import { executableStatementRanges, type SqlTextRange } from "@/lib/sql/sqlStatementRanges";
+import { statementNavigationTarget } from "@/lib/sql/statementNavigation";
+
+const SQL = ["SELECT 1;", "", "SELECT 2", "FROM t;", "", "UPDATE t SET x = 1;"].join("\n");
+
+function range(from: number, to: number, sql = ""): SqlTextRange {
+ return { from, to, sql };
+}
+
+describe("statementNavigationTarget", () => {
+ const ranges = executableStatementRanges(SQL, "postgres");
+ const first = SQL.indexOf("SELECT 1");
+ const second = SQL.indexOf("SELECT 2");
+ const third = SQL.indexOf("UPDATE t");
+
+ it("parses the fixture into three executable statements", () => {
+ expect(ranges).toHaveLength(3);
+ expect(ranges.map((item) => item.from)).toEqual([first, second, third]);
+ });
+
+ it("moves to the next statement from its start or from inside it", () => {
+ expect(statementNavigationTarget(ranges, first, "next")).toBe(second);
+ expect(statementNavigationTarget(ranges, first + 3, "next")).toBe(second);
+ expect(statementNavigationTarget(ranges, second, "next")).toBe(third);
+ });
+
+ it("has nowhere to go from the last statement", () => {
+ expect(statementNavigationTarget(ranges, third, "next")).toBeNull();
+ expect(statementNavigationTarget(ranges, SQL.length, "next")).toBeNull();
+ });
+
+ it("moves to the current statement start first when going back", () => {
+ expect(statementNavigationTarget(ranges, second + 5, "previous")).toBe(second);
+ expect(statementNavigationTarget(ranges, second, "previous")).toBe(first);
+ expect(statementNavigationTarget(ranges, third + 2, "previous")).toBe(third);
+ });
+
+ it("has nowhere to go before the first statement", () => {
+ expect(statementNavigationTarget(ranges, first, "previous")).toBeNull();
+ expect(statementNavigationTarget(ranges, 0, "previous")).toBeNull();
+ });
+
+ it("jumps to the start of the statement under the caret", () => {
+ expect(statementNavigationTarget(ranges, second + 7, "start")).toBe(second);
+ expect(statementNavigationTarget(ranges, third + 1, "start")).toBe(third);
+ expect(statementNavigationTarget(ranges, second, "start")).toBeNull();
+ });
+
+ it("resolves the blank line between two statements to the following one", () => {
+ const gap = ranges[0].to + 1;
+ expect(gap).toBeGreaterThan(first);
+ expect(gap).toBeLessThan(second);
+ expect(statementNavigationTarget(ranges, gap, "start")).toBe(second);
+ expect(statementNavigationTarget(ranges, gap, "next")).toBe(second);
+ // Going back from the gap lands on the statement that just ended.
+ expect(statementNavigationTarget(ranges, gap, "previous")).toBe(first);
+ });
+
+ it("falls back to the first statement when the caret precedes all ranges", () => {
+ const leading = [range(10, 20)];
+ expect(statementNavigationTarget(leading, 2, "next")).toBe(10);
+ expect(statementNavigationTarget(leading, 2, "start")).toBe(10);
+ expect(statementNavigationTarget(leading, 2, "previous")).toBeNull();
+ });
+
+ it("returns null without statements", () => {
+ expect(statementNavigationTarget([], 0, "next")).toBeNull();
+ expect(statementNavigationTarget([], 0, "previous")).toBeNull();
+ expect(statementNavigationTarget([], 0, "start")).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/lib/editor/shortcutRegistry.ts b/apps/desktop/src/lib/editor/shortcutRegistry.ts
index b7f08ac75d..f8017e2cba 100644
--- a/apps/desktop/src/lib/editor/shortcutRegistry.ts
+++ b/apps/desktop/src/lib/editor/shortcutRegistry.ts
@@ -28,6 +28,9 @@ export type ShortcutActionId =
| "redo"
| "selectAll"
| "selectCurrentStatement"
+ | "previousStatement"
+ | "nextStatement"
+ | "statementStart"
| "extendSelection"
| "addNextSelectionOccurrence"
| "selectAllSelectionOccurrences"
@@ -342,6 +345,24 @@ export const SHORTCUT_DEFINITIONS: ShortcutDefinition[] = [
scope: "editor",
defaultShortcut: "Mod+Shift+E",
},
+ {
+ id: "previousStatement",
+ labelKey: "settings.shortcutPreviousStatement",
+ scope: "editor",
+ defaultShortcut: "Ctrl+Shift+ArrowUp",
+ },
+ {
+ id: "nextStatement",
+ labelKey: "settings.shortcutNextStatement",
+ scope: "editor",
+ defaultShortcut: "Ctrl+Shift+ArrowDown",
+ },
+ {
+ id: "statementStart",
+ labelKey: "settings.shortcutStatementStart",
+ scope: "editor",
+ defaultShortcut: "Alt+Home",
+ },
{
id: "extendSelection",
labelKey: "settings.shortcutExtendSelection",
diff --git a/apps/desktop/src/lib/sql/statementNavigation.ts b/apps/desktop/src/lib/sql/statementNavigation.ts
new file mode 100644
index 0000000000..11fb6e6c90
--- /dev/null
+++ b/apps/desktop/src/lib/sql/statementNavigation.ts
@@ -0,0 +1,49 @@
+import type { SqlTextRange } from "@/lib/sql/sqlStatementRanges";
+
+export type StatementNavigationDirection = "previous" | "next" | "start";
+
+/**
+ * Resolve the caret position for the statement-navigation commands.
+ *
+ * - `previous`: inside a statement, jump to that statement's start first; when
+ * the caret already sits on a statement start, jump to the previous start.
+ * - `next`: jump to the start of the following statement.
+ * - `start`: jump to the start of the statement under the caret. From the gap
+ * between two statements, jump to the following statement.
+ *
+ * Returns `null` when the caret is already at the requested boundary or no
+ * such statement exists, so the keymap binding can report "not handled" and
+ * leave other editor bindings alone.
+ */
+export function statementNavigationTarget(ranges: readonly SqlTextRange[], cursor: number, direction: StatementNavigationDirection): number | null {
+ if (ranges.length === 0) return null;
+
+ // Last range starting at or before the caret. `-1` means the caret sits
+ // before the first statement (leading comments/whitespace).
+ let index = -1;
+ for (let i = 0; i < ranges.length; i += 1) {
+ if (ranges[i].from > cursor) break;
+ index = i;
+ }
+
+ if (index === -1) {
+ return direction === "previous" ? null : ranges[0].from;
+ }
+
+ const current = ranges[index];
+ const insideCurrent = cursor <= current.to;
+
+ if (direction === "next") {
+ return ranges[index + 1]?.from ?? null;
+ }
+
+ if (direction === "start") {
+ if (!insideCurrent) return ranges[index + 1]?.from ?? null;
+ return current.from === cursor ? null : current.from;
+ }
+
+ // previous
+ if (!insideCurrent) return current.from;
+ if (cursor > current.from) return current.from;
+ return ranges[index - 1]?.from ?? null;
+}