Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

improve: vimrc support (#4487)

Andy Khramtsov318da826faf9
diff --git a/frontend/src/core/codemirror/keymaps/__tests__/vim.test.ts b/frontend/src/core/codemirror/keymaps/__tests__/vim.test.ts
deleted file mode 100644
index 323b7d277f..0000000000
--- a/frontend/src/core/codemirror/keymaps/__tests__/vim.test.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-/* Copyright 2024 Marimo. All rights reserved. */
-import { describe, expect, it } from "vitest";
-import { parseVimrc } from "../vim";
-// @ts-expect-error: no declaration file
-import dedent from "string-dedent";
-
-describe("parseVimrc", () => {
- it("should parse normal mode mappings", () => {
- const content = `
- " This is a comment
- map j gj
- nmap k gk
- `;
-
- const mappings = parseVimrc(dedent(content));
- expect(mappings).toEqual([
- { key: "j", action: "gj", context: "normal" },
- { key: "k", action: "gk", context: "normal" },
- ]);
- });
-
- it("should parse insert mode mappings", () => {
- const content = `
- imap jj <Esc>
- imap jk <Esc>
- `;
-
- const mappings = parseVimrc(dedent(content));
- expect(mappings).toEqual([
- { key: "jj", action: "<Esc>", context: "insert" },
- { key: "jk", action: "<Esc>", context: "insert" },
- ]);
- });
-
- it("should handle quoted keys and actions", () => {
- const content = `
- map "j" "gj"
- imap "jj" "<Esc>"
- `;
-
- const mappings = parseVimrc(dedent(content));
- expect(mappings).toEqual([
- { key: "j", action: "gj", context: "normal" },
- { key: "jj", action: "<Esc>", context: "insert" },
- ]);
- });
-
- it("should skip invalid mappings", () => {
- const content = `
- map
- map j
- map k
- `;
-
- const mappings = parseVimrc(dedent(content));
- expect(mappings).toEqual([]);
- });
-
- it("should handle empty content", () => {
- const content = "";
- const mappings = parseVimrc(content);
- expect(mappings).toEqual([]);
- });
-
- it("should handle only comments", () => {
- const content = `
- " This is a comment
- " Another comment
- `;
-
- const mappings = parseVimrc(dedent(content));
- expect(mappings).toEqual([]);
- });
-});
diff --git a/frontend/src/core/codemirror/keymaps/__tests__/vimrc.test.ts b/frontend/src/core/codemirror/keymaps/__tests__/vimrc.test.ts
new file mode 100644
index 0000000000..6aa0edf3e8
--- /dev/null
+++ b/frontend/src/core/codemirror/keymaps/__tests__/vimrc.test.ts
@@ -0,0 +1,121 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, expect, it, vi } from "vitest";
+import { parseVimrc } from "../vimrc";
+// @ts-expect-error: no declaration file
+import dedent from "string-dedent";
+
+describe("parseVimrc", () => {
+ it("should parse mappings with no mode", () => {
+ const content = `
+ " This is a comment
+ map j gj
+ noremap k gk
+ unmap k
+ mapclear
+ `;
+
+ const err = vi.fn();
+ const mappings = parseVimrc(dedent(content), err);
+ expect(mappings).toEqual([
+ { name: "map", args: { lhs: "j", rhs: "gj" } },
+ { name: "noremap", args: { lhs: "k", rhs: "gk" } },
+ { name: "unmap", args: { lhs: "k" } },
+ { name: "mapclear" },
+ ]);
+ expect(err.mock.calls.length).toEqual(0);
+ });
+
+ it("should parse normal mode mappings", () => {
+ const content = `
+ nmap j gj
+ nnoremap k gk
+ nunmap k
+ nmapclear
+ `;
+
+ const err = vi.fn();
+ const mappings = parseVimrc(dedent(content), err);
+ expect(mappings).toEqual([
+ { name: "nmap", args: { lhs: "j", rhs: "gj" }, mode: "normal" },
+ { name: "nnoremap", args: { lhs: "k", rhs: "gk" }, mode: "normal" },
+ { name: "nunmap", args: { lhs: "k" }, mode: "normal" },
+ { name: "nmapclear", mode: "normal" },
+ ]);
+ expect(err.mock.calls.length).toEqual(0);
+ });
+
+ it("should parse insert mode mappings", () => {
+ const content = `
+ imap jj <Esc>
+ inoremap jk <Esc>
+ iunmap jj
+ imapclear
+ `;
+
+ const err = vi.fn();
+ const mappings = parseVimrc(dedent(content), err);
+ expect(mappings).toEqual([
+ { name: "imap", args: { lhs: "jj", rhs: "<Esc>" }, mode: "insert" },
+ { name: "inoremap", args: { lhs: "jk", rhs: "<Esc>" }, mode: "insert" },
+ { name: "iunmap", args: { lhs: "jj" }, mode: "insert" },
+ { name: "imapclear", mode: "insert" },
+ ]);
+ expect(err.mock.calls.length).toEqual(0);
+ });
+
+ // because " is a valid key
+ it("should handle quotes as keys", () => {
+ const content = `
+ map "j "0p
+ unmap "j
+ `;
+
+ const err = vi.fn();
+ const mappings = parseVimrc(dedent(content), err);
+ expect(mappings).toEqual([
+ { name: "map", args: { lhs: '"j', rhs: '"0p' } },
+ { name: "unmap", args: { lhs: '"j' } },
+ ]);
+ expect(err.mock.calls.length).toEqual(0);
+ });
+
+ it("should skip invalid mappings", () => {
+ const content = `
+ map
+ map j
+ unmap k j
+ mapclear arg
+ `;
+
+ const err = vi.fn();
+ const mappings = parseVimrc(dedent(content), err);
+ expect(mappings).toEqual([
+ { name: "unmap", args: { lhs: "k" } },
+ // Ideally mapclear should not appear here
+ { name: "mapclear" },
+ // The vim behavior lhs = "l j", is not achievable with the current regexp split
+ // { name: "unmap", args: { lhs: "k j" } },
+ ]);
+ expect(err.mock.calls.length).toEqual(2);
+ });
+
+ it("should handle empty content", () => {
+ const content = "";
+ const err = vi.fn();
+ const mappings = parseVimrc(content, err);
+ expect(mappings).toEqual([]);
+ expect(err.mock.calls.length).toEqual(0);
+ });
+
+ it("should handle only comments", () => {
+ const content = `
+ " This is a comment
+ " Another comment
+ `;
+
+ const err = vi.fn();
+ const mappings = parseVimrc(dedent(content), err);
+ expect(mappings).toEqual([]);
+ expect(err.mock.calls.length).toEqual(0);
+ });
+});
diff --git a/frontend/src/core/codemirror/keymaps/vim.ts b/frontend/src/core/codemirror/keymaps/vim.ts
index 725d630233..bbc28d1460 100644
--- a/frontend/src/core/codemirror/keymaps/vim.ts
+++ b/frontend/src/core/codemirror/keymaps/vim.ts
@@ -22,6 +22,7 @@ import { cellActionsState, cellIdState } from "../cells/state";
import { sendFileDetails } from "@/core/network/requests";
import { store } from "@/core/state/jotai";
import { resolvedMarimoConfigAtom } from "@/core/config/config";
+import { parseVimrc, type VimCommand } from "./vimrc";
export function vimKeymapExtension(): Extension[] {
addCustomVimCommandsOnce();
@@ -114,54 +115,6 @@ const addCustomVimCommandsOnce = once(() => {
});
});
-interface VimrcMapping {
- key: string;
- action: string;
- context: "normal" | "insert";
-}
-
-/**
- * Parses a vimrc file into a list of mappings
- *
- * @param content - The content of the vimrc file
- * @returns A list of mappings
- */
-export function parseVimrc(content: string): VimrcMapping[] {
- const mappings: VimrcMapping[] = [];
- const lines = content.split("\n");
-
- for (const line of lines) {
- // Skip comments and empty lines
- if (line.startsWith('"') || line.trim() === "") {
- continue;
- }
-
- // Handle key mappings
- if (
- line.startsWith("map") ||
- line.startsWith("nmap") ||
- line.startsWith("imap")
- ) {
- const [, key, action] = line.split(/\s+/);
- if (!key || !action) {
- continue;
- }
-
- // Remove quotes if present
- const cleanKey = key.replaceAll(/["']/g, "");
- const cleanAction = action.replaceAll(/["']/g, "");
-
- mappings.push({
- key: cleanKey,
- action: cleanAction,
- context: line.startsWith("imap") ? "insert" : "normal",
- });
- }
- }
-
- return mappings;
-}
-
const loadVimrcOnce = once(async () => {
const config = store.get(resolvedMarimoConfigAtom);
const vimrc = config.keymap?.vimrc;
@@ -177,22 +130,109 @@ const loadVimrcOnce = once(async () => {
Logger.error(`Failed to load vimrc from ${vimrc}`);
return;
}
-
- const mappings = parseVimrc(content);
- for (const mapping of mappings) {
- Vim.mapCommand(
- mapping.key,
- "action",
- mapping.action,
- {},
- { context: mapping.context },
- );
- }
+ const vimCommands = parseVimrc(content, Logger.warn);
+ applyVimCommands(vimCommands);
} catch (error) {
Logger.error("Failed to load vimrc:", error);
}
});
+function applyVimCommands(vimCommands: VimCommand[]) {
+ // map, noremap and unmap can be used without ctx.
+ // It is an important behavior that we want to use.
+
+ function map(command: VimCommand) {
+ if (!command.args) {
+ Logger.warn(
+ `Could not execute vimrc command "${command.name}: expected arguments"`,
+ );
+ return;
+ }
+ if (!command.args.lhs || !command.args.rhs) {
+ Logger.warn(
+ `Could not execute vimrc command "${command.name}: expected arguments"`,
+ );
+ return;
+ }
+ if (command.mode) {
+ Vim.map(command.args.lhs, command.args.rhs, command.mode);
+ } else {
+ //@ts-expect-error We can use this without providing context (mode)
+ Vim.map(command.args.lhs, command.args.rhs);
+ }
+ }
+
+ function noremap(command: VimCommand) {
+ if (!command.args) {
+ Logger.warn(
+ `Could not execute vimrc command "${command.name}: expected arguments"`,
+ );
+ return;
+ }
+ if (!command.args.lhs || !command.args.rhs) {
+ Logger.warn(
+ `Could not execute vimrc command "${command.name}: expected arguments"`,
+ );
+ return;
+ }
+ if (command.mode) {
+ Vim.noremap(command.args.lhs, command.args.rhs, command.mode);
+ } else {
+ //@ts-expect-error We can use this without providing context (mode)
+ Vim.noremap(command.args.lhs, command.args.rhs);
+ }
+ }
+
+ function unmap(command: VimCommand) {
+ if (!command.args) {
+ Logger.warn(
+ `Could not execute vimrc command "${command.name}: expected arguments"`,
+ );
+ return;
+ }
+ if (!command.args.lhs) {
+ Logger.warn(
+ `Could not execute vimrc command "${command.name}: expected arguments"`,
+ );
+ return;
+ }
+ if (command.mode) {
+ Vim.unmap(command.args.lhs, command.mode);
+ } else {
+ //@ts-expect-error We can use this without providing context (mode)
+ Vim.unmap(command.args.lhs);
+ }
+ }
+
+ function mapclear(command: VimCommand) {
+ if (command.mode) {
+ Vim.mapclear(command.mode);
+ } else {
+ Vim.mapclear();
+ }
+ }
+
+ for (const command of vimCommands) {
+ if ("map|nmap|vmap|imap".split("|").includes(command.name)) {
+ map(command);
+ } else if (
+ "noremap|nnoremap|vnoremap|inoremap".split("|").includes(command.name)
+ ) {
+ noremap(command);
+ } else if ("unmap|nunmap|vunmap|iunmap".split("|").includes(command.name)) {
+ unmap(command);
+ } else if (
+ "mapclear|nmapclear|vmapclear|imapclear".split("|").includes(command.name)
+ ) {
+ mapclear(command);
+ } else {
+ Logger.warn(
+ `Could not execute vimrc command "${command.name}: unknown command"`,
+ );
+ }
+ }
+}
+
class CodeMirrorVimSync {
private instances = new Set<EditorView>();
private isBroadcasting = false;
diff --git a/frontend/src/core/codemirror/keymaps/vimrc.ts b/frontend/src/core/codemirror/keymaps/vimrc.ts
new file mode 100644
index 0000000000..2726bbed14
--- /dev/null
+++ b/frontend/src/core/codemirror/keymaps/vimrc.ts
@@ -0,0 +1,149 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+export interface VimCommandSchema {
+ mode?: VimMode;
+ args?: string[];
+}
+
+export interface VimCommand {
+ name: string;
+ args?: VimCommandArgs;
+ mode?: VimMode;
+}
+
+export interface VimCommandArgs {
+ [key: string]: string;
+}
+
+export type VimMode = "normal" | "visual" | "insert";
+
+export const KnownCommands: { [key: string]: VimCommandSchema } = {
+ map: {
+ args: ["lhs", "rhs"],
+ },
+ nmap: {
+ mode: "normal",
+ args: ["lhs", "rhs"],
+ },
+ vmap: {
+ mode: "visual",
+ args: ["lhs", "rhs"],
+ },
+ imap: {
+ mode: "insert",
+ args: ["lhs", "rhs"],
+ },
+
+ noremap: {
+ args: ["lhs", "rhs"],
+ },
+ nnoremap: {
+ mode: "normal",
+ args: ["lhs", "rhs"],
+ },
+ vnoremap: {
+ mode: "visual",
+ args: ["lhs", "rhs"],
+ },
+ inoremap: {
+ mode: "insert",
+ args: ["lhs", "rhs"],
+ },
+
+ unmap: {
+ args: ["lhs"],
+ },
+ nunmap: {
+ mode: "normal",
+ args: ["lhs"],
+ },
+ vunmap: {
+ mode: "visual",
+ args: ["lhs"],
+ },
+ iunmap: {
+ mode: "insert",
+ args: ["lhs"],
+ },
+
+ mapclear: {},
+ nmapclear: {
+ mode: "normal",
+ },
+ vmapclear: {
+ mode: "visual",
+ },
+ imapclear: {
+ mode: "insert",
+ },
+};
+
+export type ParseError = (msg: string) => void;
+
+/**
+ * Parses a vimrc file into a list of mappings
+ * Does not stop parsing when errors occur, instead just skips the faulty line
+ *
+ * @param content - The content of the vimrc file
+ * @param parseError - Optional logger that gets called on parse errors
+ * @returns A list of mappings
+ */
+export function parseVimrc(
+ vimrc: string,
+ parseError?: ParseError,
+): VimCommand[] {
+ const commands: VimCommand[] = [];
+
+ for (const line of vimrc.split("\n")) {
+ if (line.startsWith('"') || line.trim() === "") {
+ continue;
+ }
+ const command = parseCommand(line, parseError);
+ if (command) {
+ commands.push(command);
+ }
+ }
+
+ return commands;
+}
+
+function parseCommand(
+ line: string,
+ parseError?: ParseError,
+): VimCommand | undefined {
+ const words = line.split(/\s+/);
+
+ const commandName = words[0];
+ let currentWord = 0;
+
+ if (commandName in KnownCommands) {
+ const schema = KnownCommands[commandName];
+
+ const args: VimCommandArgs = {};
+ for (const argName of schema.args || []) {
+ currentWord += 1;
+ if (currentWord < words.length) {
+ args[argName] = words[currentWord];
+ } else {
+ if (parseError) {
+ parseError(
+ `Not enough arguments for "${commandName}" command: "${line}"`,
+ );
+ }
+ return;
+ }
+ }
+
+ const command: VimCommand = { name: commandName };
+ if ("args" in schema) {
+ command.args = args;
+ }
+ if ("mode" in schema) {
+ command.mode = schema.mode;
+ }
+ return command;
+ }
+ if (parseError) {
+ parseError(`Unknown vimrc command: "${line}"`);
+ }
+ return;
+}