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.

feat: support vimrc from the user config (#4473)

Myles Scolnick769601559852
diff --git a/configs/.vimrc b/configs/.vimrc
new file mode 100644
index 0000000000..2626379946
--- /dev/null
+++ b/configs/.vimrc
@@ -0,0 +1,2 @@
+" For testing "
+imap kj <Esc>
diff --git a/docs/guides/editor_features/overview.md b/docs/guides/editor_features/overview.md
index 958c987d9f..b3914a6496 100644
--- a/docs/guides/editor_features/overview.md
+++ b/docs/guides/editor_features/overview.md
@@ -40,6 +40,29 @@ marimo supports vim keybindings.
- `gd` - go to definition
- `dd` - when a cell is empty, delete it
+- `:w` - to save the notebook
+
+**Custom vimrc:**
+
+You can customize your vim experience by adding a `.vimrc` configuration in the user settings or pyproject.toml
+
+/// tab | User config
+
+```toml title="marimo.toml"
+[keymap]
+vimrc = /User/absolute/path/to/.vimrc
+```
+
+///
+
+/// tab | pyproject.toml
+
+```toml title="pyproject.toml"
+[tool.marimo.keymap]
+vimrc = relative/path/.vimrc
+```
+
+///
## Overview panels
diff --git a/frontend/src/core/codemirror/keymaps/__tests__/vim.test.ts b/frontend/src/core/codemirror/keymaps/__tests__/vim.test.ts
new file mode 100644
index 0000000000..323b7d277f
--- /dev/null
+++ b/frontend/src/core/codemirror/keymaps/__tests__/vim.test.ts
@@ -0,0 +1,74 @@
+/* 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/vim.ts b/frontend/src/core/codemirror/keymaps/vim.ts
index 181ceb0d6d..725d630233 100644
--- a/frontend/src/core/codemirror/keymaps/vim.ts
+++ b/frontend/src/core/codemirror/keymaps/vim.ts
@@ -19,9 +19,13 @@ import { goToDefinitionAtCursorPosition } from "../go-to-definition/utils";
import { once } from "@/utils/once";
import { onIdle } from "@/utils/idle";
import { cellActionsState, cellIdState } from "../cells/state";
+import { sendFileDetails } from "@/core/network/requests";
+import { store } from "@/core/state/jotai";
+import { resolvedMarimoConfigAtom } from "@/core/config/config";
export function vimKeymapExtension(): Extension[] {
addCustomVimCommandsOnce();
+ loadVimrcOnce();
return [
keymap.of([
@@ -110,6 +114,85 @@ 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;
+ if (!vimrc) {
+ return;
+ }
+
+ try {
+ Logger.log(`Loading vimrc from ${vimrc}`);
+ const response = await sendFileDetails({ path: vimrc });
+ const content = response.contents;
+ if (!content) {
+ 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 },
+ );
+ }
+ } catch (error) {
+ Logger.error("Failed to load vimrc:", error);
+ }
+});
+
class CodeMirrorVimSync {
private instances = new Set<EditorView>();
private isBroadcasting = false;
diff --git a/marimo/_config/config.py b/marimo/_config/config.py
index 25327b24d6..1e2540e2aa 100644
--- a/marimo/_config/config.py
+++ b/marimo/_config/config.py
@@ -83,10 +83,12 @@ class KeymapConfig(TypedDict):
- `preset`: one of `"default"` or `"vim"`
- `overrides`: a dict of keymap actions to their keymap override
+ - `vimrc`: path to a vimrc file to load keymaps from
"""
preset: Literal["default", "vim"]
overrides: NotRequired[dict[str, str]]
+ vimrc: NotRequired[Optional[str]]
OnCellChangeType = Literal["lazy", "autorun"]
diff --git a/marimo/_config/manager.py b/marimo/_config/manager.py
index d0822c59ea..bf9a90bfca 100644
--- a/marimo/_config/manager.py
+++ b/marimo/_config/manager.py
@@ -185,6 +185,7 @@ class ProjectConfigManager(PartialMarimoConfigReader):
project_config = self._resolve_pythonpath(project_config)
project_config = self._resolve_dotenv(project_config)
project_config = self._resolve_custom_css(project_config)
+ project_config = self._resolve_vimrc(project_config)
except Exception as e:
LOGGER.warning("Failed to read project config: %s", e)
return {}
@@ -264,6 +265,27 @@ class ProjectConfigManager(PartialMarimoConfigReader):
"display": {**display, "custom_css": resolved_custom_css},
}
+ def _resolve_vimrc(
+ self, config: PartialMarimoConfig
+ ) -> PartialMarimoConfig:
+ if self.pyproject_path is None:
+ return config
+
+ if "keymap" not in config:
+ return config
+
+ keymap = config["keymap"]
+ vimrc = keymap.get("vimrc")
+
+ if not isinstance(vimrc, str):
+ return config
+
+ resolved_vimrc = str((self.pyproject_path.parent / vimrc).absolute())
+ return {
+ **config,
+ "keymap": {**keymap, "vimrc": resolved_vimrc},
+ }
+
class ScriptConfigManager(PartialMarimoConfigReader):
"""Read the script configuration following PEP 723
diff --git a/openapi/api.yaml b/openapi/api.yaml
index a100865ebb..445bfd9367 100644
--- a/openapi/api.yaml
+++ b/openapi/api.yaml
@@ -1466,6 +1466,9 @@ components:
- default
- vim
type: string
+ vimrc:
+ nullable: true
+ type: string
required:
- preset
type: object
@@ -2503,7 +2506,7 @@ components:
type: object
info:
title: marimo API
- version: 0.12.7
+ version: 0.12.8
openapi: 3.1.0
paths:
/@file/{filename_and_length}:
diff --git a/openapi/src/api.ts b/openapi/src/api.ts
index 29d0679eb4..de7a415bdc 100644
--- a/openapi/src/api.ts
+++ b/openapi/src/api.ts
@@ -2943,6 +2943,7 @@ export interface components {
};
/** @enum {string} */
preset: "default" | "vim";
+ vimrc?: string | null;
};
language_servers?: {
pylsp?: {
diff --git a/pyproject.toml b/pyproject.toml
index 48c32987ab..796433a1be 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -525,4 +525,7 @@ dataframes = "rich"
watcher_on_save = "autorun"
output_max_bytes = 10_000_000
std_stream_max_bytes = 2_000_000
-dotenv = [".env.testing"]
\ No newline at end of file
+dotenv = [".env.testing"]
+
+[tool.marimo.keymap]
+vimrc = "configs/.vimrc"