feat(editor): support Vim config file
This commit is contained in:
1 parent
4269a61e2c
commit
dcaa0932f1
9 files changed
+347
-7
No files matched your search
@@ -0,0 +1,119 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { applyVimConfig, isVimMappingCommand, parseVimConfig } from "../vimConfig";
|
||||
|
||||
const fs = { exists: vi.fn(), readTextFile: vi.fn() };
|
||||
|
||||
vi.mock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => true }));
|
||||
vi.mock("@tauri-apps/api/path", () => ({
|
||||
homeDir: () => Promise.resolve("/home/tester"),
|
||||
join: (...parts: string[]) => Promise.resolve(parts.join("/")),
|
||||
}));
|
||||
vi.mock("@tauri-apps/plugin-fs", () => ({
|
||||
exists: (path: string) => fs.exists(path),
|
||||
readTextFile: (path: string) => fs.readTextFile(path),
|
||||
}));
|
||||
|
||||
describe("Vim config", () => {
|
||||
beforeEach(() => {
|
||||
fs.exists.mockReset();
|
||||
fs.readTextFile.mockReset();
|
||||
});
|
||||
|
||||
it.each(["\n", "\r\n"])("parses commands, comments and blank lines with %j endings", (ending) => {
|
||||
expect(parseVimConfig(['" DBX Vim config', "", " imap jj <Esc> ", " nmap Y y$", ' " another comment'].join(ending))).toEqual(["imap jj <Esc>", "nmap Y y$"]);
|
||||
});
|
||||
|
||||
it("loads the file once and reuses its commands for later editors", async () => {
|
||||
fs.exists.mockResolvedValue(true);
|
||||
fs.readTextFile.mockResolvedValue("imap jj <Esc>\r\nnmap Y y$\r\n");
|
||||
vi.resetModules();
|
||||
const { loadVimConfig } = await import("../vimConfig");
|
||||
const [first, second] = await Promise.all([loadVimConfig(), loadVimConfig()]);
|
||||
expect(first).toEqual(["imap jj <Esc>", "nmap Y y$"]);
|
||||
expect(second).toEqual(first);
|
||||
expect(fs.exists).toHaveBeenCalledExactlyOnceWith("/home/tester/.dbx/vimrc");
|
||||
expect(fs.readTextFile).toHaveBeenCalledExactlyOnceWith("/home/tester/.dbx/vimrc");
|
||||
});
|
||||
|
||||
it("starts without a config file", async () => {
|
||||
fs.exists.mockResolvedValue(false);
|
||||
vi.resetModules();
|
||||
const { loadVimConfig } = await import("../vimConfig");
|
||||
expect(await loadVimConfig()).toEqual([]);
|
||||
expect(fs.readTextFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("continues when the file cannot be read", async () => {
|
||||
fs.exists.mockResolvedValue(true);
|
||||
fs.readTextFile.mockRejectedValue(new Error("denied"));
|
||||
const warning = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
try {
|
||||
vi.resetModules();
|
||||
const { loadVimConfig } = await import("../vimConfig");
|
||||
expect(await loadVimConfig()).toEqual([]);
|
||||
expect(warning).toHaveBeenCalledOnce();
|
||||
} finally {
|
||||
warning.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("continues after an invalid command", () => {
|
||||
const execute = vi.fn((command: string) => {
|
||||
if (command === "bogus") throw new Error("unknown command");
|
||||
});
|
||||
const warning = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
try {
|
||||
applyVimConfig(["imap jj <Esc>", "bogus", "nmap Y y$"], execute);
|
||||
expect(execute.mock.calls.map(([command]) => command)).toEqual(["imap jj <Esc>", "bogus", "nmap Y y$"]);
|
||||
expect(warning).toHaveBeenCalledOnce();
|
||||
} finally {
|
||||
warning.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("applies an insert mapping to a CodeMirror Vim editor", async () => {
|
||||
const [{ EditorState }, { EditorView }, { Vim, vim, getCM }] = await Promise.all([import("@codemirror/state"), import("@codemirror/view"), import("@replit/codemirror-vim")]);
|
||||
const parent = document.createElement("div");
|
||||
document.body.append(parent);
|
||||
const view = new EditorView({ parent, state: EditorState.create({ doc: "select 1", extensions: [vim()] }) });
|
||||
try {
|
||||
const cm = getCM(view);
|
||||
expect(cm).not.toBeNull();
|
||||
if (!cm) return;
|
||||
applyVimConfig(["imap jj <Esc>"], (command) => Vim.handleEx(cm, command));
|
||||
Vim.handleKey(cm, "i");
|
||||
expect(cm.state.vim?.insertMode).toBe(true);
|
||||
Vim.handleKey(cm, "j");
|
||||
Vim.handleKey(cm, "j");
|
||||
expect(cm.state.vim?.insertMode).toBe(false);
|
||||
|
||||
const secondParent = document.createElement("div");
|
||||
document.body.append(secondParent);
|
||||
const secondView = new EditorView({ parent: secondParent, state: EditorState.create({ doc: "select 2", extensions: [vim()] }) });
|
||||
try {
|
||||
const secondCm = getCM(secondView);
|
||||
expect(secondCm).not.toBeNull();
|
||||
if (!secondCm) return;
|
||||
Vim.handleKey(secondCm, "i");
|
||||
Vim.handleKey(secondCm, "j");
|
||||
Vim.handleKey(secondCm, "j");
|
||||
expect(secondCm.state.vim?.insertMode).toBe(false);
|
||||
} finally {
|
||||
secondView.destroy();
|
||||
secondParent.remove();
|
||||
}
|
||||
} finally {
|
||||
view.destroy();
|
||||
parent.remove();
|
||||
}
|
||||
});
|
||||
|
||||
it("identifies shared mappings so later editor tabs do not add duplicates", () => {
|
||||
expect(isVimMappingCommand("imap jj <Esc>")).toBe(true);
|
||||
expect(isVimMappingCommand("nmap Y y$")).toBe(true);
|
||||
expect(isVimMappingCommand("inoremap jk <Esc>")).toBe(true);
|
||||
expect(isVimMappingCommand("set ignorecase")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { configureVimSystemClipboard } from "../vimSystemClipboard";
|
||||
|
||||
describe("Vim system clipboard", () => {
|
||||
it("connects unnamed yanks and pastes to the clipboard when configured", async () => {
|
||||
const [{ EditorState }, { EditorView }, { Vim, vim, getCM }] = await Promise.all([import("@codemirror/state"), import("@codemirror/view"), import("@replit/codemirror-vim")]);
|
||||
const clipboard = {
|
||||
readText: vi.fn().mockResolvedValue("external"),
|
||||
writeText: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
configureVimSystemClipboard(Vim, clipboard);
|
||||
const parent = document.createElement("div");
|
||||
document.body.append(parent);
|
||||
const view = new EditorView({ parent, state: EditorState.create({ doc: "A", extensions: [vim()] }) });
|
||||
try {
|
||||
const cm = getCM(view);
|
||||
expect(cm).not.toBeNull();
|
||||
if (!cm) return;
|
||||
const registers = Vim.getRegisterController();
|
||||
registers.pushText(undefined, "yank", "internal");
|
||||
expect(clipboard.writeText).not.toHaveBeenCalled();
|
||||
|
||||
Vim.handleEx(cm, "set clipboard=unnamedplus");
|
||||
expect(Vim.getOption("clipboard", cm as Parameters<typeof Vim.getOption>[1])).toBe("unnamedplus");
|
||||
registers.pushText(undefined, "yank", "selected SQL");
|
||||
expect(clipboard.writeText).toHaveBeenCalledWith("selected SQL");
|
||||
Vim.handleKey(cm, "y");
|
||||
Vim.handleKey(cm, "y");
|
||||
expect(clipboard.writeText).toHaveBeenCalledWith("A\n");
|
||||
|
||||
Vim.handleKey(cm, "p");
|
||||
await vi.waitFor(() => expect(view.state.doc.toString()).toContain("external"));
|
||||
expect(clipboard.readText).toHaveBeenCalledOnce();
|
||||
|
||||
Vim.handleEx(cm, "set clipboard=");
|
||||
clipboard.writeText.mockClear();
|
||||
registers.pushText(undefined, "yank", "local only");
|
||||
expect(clipboard.writeText).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
view.destroy();
|
||||
parent.remove();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
|
||||
|
||||
/** Commands supported by CodeMirror Vim are read from the desktop user's file. */
|
||||
export function parseVimConfig(text: string): string[] {
|
||||
return text
|
||||
.split(/\r?\n/)
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0 && !line.startsWith('"'));
|
||||
}
|
||||
|
||||
// CodeMirror Vim stores mappings globally. Applying one on every tab would
|
||||
// keep prepending duplicate mappings to its shared keymap.
|
||||
export function isVimMappingCommand(command: string): boolean {
|
||||
return /^(?:[niv]?noremap|[niv]?map|[niv]?unmap|[niv]?mapclear)(?:\s|$|!)/.test(command);
|
||||
}
|
||||
|
||||
let loading: Promise<string[]> | null = null;
|
||||
|
||||
/** Read once per app session; a restart picks up edits to ~/.dbx/vimrc. */
|
||||
export function loadVimConfig(): Promise<string[]> {
|
||||
loading ??= (async () => {
|
||||
if (!isTauriRuntime()) return [];
|
||||
try {
|
||||
const { homeDir, join } = await import("@tauri-apps/api/path");
|
||||
const { exists, readTextFile } = await import("@tauri-apps/plugin-fs");
|
||||
const file = await join(await homeDir(), ".dbx", "vimrc");
|
||||
if (!(await exists(file))) return [];
|
||||
return parseVimConfig(await readTextFile(file));
|
||||
} catch (error) {
|
||||
console.warn("[vim-config] could not read ~/.dbx/vimrc", error);
|
||||
return [];
|
||||
}
|
||||
})();
|
||||
return loading;
|
||||
}
|
||||
|
||||
/** A bad command must not prevent the remaining commands or editor startup. */
|
||||
export function applyVimConfig(commands: readonly string[], execute: (command: string) => void): void {
|
||||
for (const command of commands) {
|
||||
try {
|
||||
execute(command);
|
||||
} catch (error) {
|
||||
console.warn(`[vim-config] ignored command: ${command}`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
type VimApi = typeof import("@replit/codemirror-vim").Vim;
|
||||
|
||||
export interface VimClipboardAccess {
|
||||
readText(): Promise<string>;
|
||||
writeText(text: string): Promise<void>;
|
||||
}
|
||||
|
||||
/** Add `set clipboard=unnamedplus` without replacing CodeMirror Vim's editing commands. */
|
||||
export function configureVimSystemClipboard(vimApi: VimApi, clipboard: VimClipboardAccess): void {
|
||||
let clipboardOption = "";
|
||||
let unnamedPlus = false;
|
||||
|
||||
vimApi.defineOption("clipboard", "", "string", ["cb"], (value) => {
|
||||
if (value !== undefined) {
|
||||
clipboardOption = value;
|
||||
unnamedPlus = value.split(",").includes("unnamedplus");
|
||||
}
|
||||
return clipboardOption;
|
||||
});
|
||||
|
||||
const registers = vimApi.getRegisterController();
|
||||
const pushText = registers.pushText.bind(registers);
|
||||
registers.pushText = (registerName, operator, text, linewise, blockwise) => {
|
||||
if (unnamedPlus && registerName === "+") {
|
||||
// The library writes explicit + yanks through navigator.clipboard. Use
|
||||
// DBX's native clipboard path in the desktop webview instead.
|
||||
const value = linewise && !text.endsWith("\n") ? `${text}\n` : text;
|
||||
registers.getRegister("+").setText(value, linewise, blockwise);
|
||||
registers.unnamedRegister.setText(value, linewise, blockwise);
|
||||
} else {
|
||||
pushText(registerName, operator, text, linewise, blockwise);
|
||||
}
|
||||
if (unnamedPlus && registerName !== "_") {
|
||||
void clipboard.writeText(registers.unnamedRegister.toString()).catch((error) => {
|
||||
console.warn("[vim-config] could not write to system clipboard", error);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const findKey = vimApi.findKey.bind(vimApi);
|
||||
const pendingPastes = new WeakSet<object>();
|
||||
vimApi.findKey = (cm, key, origin) => {
|
||||
if (pendingPastes.has(cm)) return () => true;
|
||||
const registerName = cm.state.vim?.inputState.registerName;
|
||||
const command = findKey(cm, key, origin);
|
||||
if (!unnamedPlus || (key !== "p" && key !== "P") || (registerName && registerName !== "+") || !command || cm.state.vim?.insertMode) return command;
|
||||
|
||||
return () => {
|
||||
const vimState = cm.state.vim;
|
||||
if (!vimState) return command();
|
||||
const previousText = registers.unnamedRegister.toString();
|
||||
const previousLinewise = registers.unnamedRegister.linewise;
|
||||
pendingPastes.add(cm);
|
||||
void clipboard
|
||||
.readText()
|
||||
.then((text) => {
|
||||
if (cm.state.vim !== vimState) return;
|
||||
const linewise = text === previousText ? previousLinewise : text.endsWith("\n");
|
||||
registers.unnamedRegister.setText(text, linewise, false);
|
||||
// Explicit + pastes must use the freshly read native clipboard, not
|
||||
// the library's navigator.clipboard branch.
|
||||
vimState.inputState.registerName = undefined;
|
||||
command();
|
||||
})
|
||||
.catch((error) => {
|
||||
console.warn("[vim-config] could not read system clipboard", error);
|
||||
if (cm.state.vim === vimState) {
|
||||
vimState.inputState.registerName = undefined;
|
||||
command();
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
pendingPastes.delete(cm);
|
||||
});
|
||||
return true;
|
||||
};
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user