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.

fix(vim): Show cursor only in last focused cell (#5457)

Trevor Manz517e6d3539a1
diff --git a/frontend/src/core/codemirror/keymaps/vim.ts b/frontend/src/core/codemirror/keymaps/vim.ts
index f2852ada85..8795ce8ea5 100644
--- a/frontend/src/core/codemirror/keymaps/vim.ts
+++ b/frontend/src/core/codemirror/keymaps/vim.ts
@@ -22,6 +22,7 @@ import {
isAtStartOfEditor,
isInVimNormalMode,
} from "../utils";
+import { VimCursorVisibilityPlugin } from "../vim/cursor-visibility";
import { parseVimrc, type VimCommand } from "./vimrc";
export function vimKeymapExtension(): Extension[] {
@@ -94,6 +95,7 @@ export function vimKeymapExtension(): Extension[] {
},
};
}),
+ ViewPlugin.define((view) => new VimCursorVisibilityPlugin({ view })),
];
}
diff --git a/frontend/src/core/codemirror/vim/cursor-visibility.ts b/frontend/src/core/codemirror/vim/cursor-visibility.ts
new file mode 100644
index 0000000000..d70bfd1b74
--- /dev/null
+++ b/frontend/src/core/codemirror/vim/cursor-visibility.ts
@@ -0,0 +1,51 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import type { EditorView, PluginValue } from "@codemirror/view";
+
+let lastFocusedEditorRef: WeakRef<EditorView> | null = null;
+
+/** Options for {@linkcode VimCursorVisibilityPlugin}. */
+interface VimCursorVisibilityPluginOptions {
+ /** The editor view to manage Vim cursor visibility. */
+ view: EditorView;
+}
+
+/**
+ * A CodeMirror plugin that manages vim cursor visibility.
+ *
+ * Ensures that the vim cursor (block cursor in normal mode) is only
+ * visible in the last focused editor. All other editors will have
+ * their vim cursors hidden entirely, preventing multiple cursors
+ * from appearing across all cells when vim mode is enabled.
+ */
+export class VimCursorVisibilityPlugin implements PluginValue {
+ private view: EditorView;
+ private abortController = new AbortController();
+
+ constructor(options: VimCursorVisibilityPluginOptions) {
+ this.view = options.view;
+ this.view.dom.addEventListener(
+ "focus",
+ () => {
+ lastFocusedEditorRef = new WeakRef(this.view);
+ },
+ {
+ signal: this.abortController.signal,
+ capture: true,
+ },
+ );
+ this.update();
+ }
+
+ update() {
+ const vimCursorLayer = this.view.dom.querySelector(".cm-vimCursorLayer");
+ if (vimCursorLayer instanceof HTMLElement) {
+ const isLastFocused = lastFocusedEditorRef?.deref() === this.view;
+ vimCursorLayer.style.display = isLastFocused ? "" : "none";
+ }
+ }
+
+ destroy(): void {
+ this.abortController.abort();
+ }
+}