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: add config for vim keybindings (#53)

Myles Scolnicke0e51a3c01b8
diff --git a/frontend/package.json b/frontend/package.json
index 5bc5e0f964..fbc687239c 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -50,6 +50,7 @@
"@radix-ui/react-tooltip": "^1.0.6",
"@radix-ui/react-use-controllable-state": "^1.0.1",
"@react-aria/focus": "^3.14.0",
+ "@replit/codemirror-vim": "^6.0.14",
"@storybook/addon-styling": "^1.3.7",
"@tanstack/react-table": "^8.9.3",
"@textea/json-viewer": "^3.1.1",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index e4b77015f6..0b2314b434 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -122,6 +122,9 @@ dependencies:
'@react-aria/focus':
specifier: ^3.14.0
version: 3.14.0([email protected])
+ '@replit/codemirror-vim':
+ specifier: ^6.0.14
+ version: 6.0.14(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])
'@storybook/addon-styling':
specifier: ^1.3.7
@@ -4143,6 +4146,22 @@ packages:
react: 18.2.0
dev: false
+ /@replit/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected]):
+ resolution: {integrity: sha512-wwhqhvL76FdRTdwfUWpKCbv0hkp2fvivfMosDVlL/popqOiNLtUhL02ThgHZH8mus/NkVr5Mj582lyFZqQrjOA==}
+ peerDependencies:
+ '@codemirror/commands': ^6.0.0
+ '@codemirror/language': ^6.1.0
+ '@codemirror/search': ^6.2.0
+ '@codemirror/state': ^6.0.1
+ '@codemirror/view': ^6.0.3
+ dependencies:
+ '@codemirror/commands': 6.2.5
+ '@codemirror/language': 6.9.0
+ '@codemirror/search': 6.5.2
+ '@codemirror/state': 6.2.1
+ '@codemirror/view': 6.18.0
+ dev: false
+
resolution: {integrity: sha512-pTd9rIsP92h+B6wWwFbW8RkZv4hiR/xKsqre4SIuAOaOEQRxi0lqLke9k2/7WegC85GgUs9pjmOjCUi3In4vwA==}
engines: {node: '>=14.0.0'}
diff --git a/frontend/public/mockServiceWorker.js b/frontend/public/mockServiceWorker.js
index 36a9927457..d8bc3ace34 100644
--- a/frontend/public/mockServiceWorker.js
+++ b/frontend/public/mockServiceWorker.js
@@ -2,7 +2,7 @@
/* tslint:disable */
/**
- * Mock Service Worker (1.2.3).
+ * Mock Service Worker (1.3.0).
* @see https://github.com/mswjs/msw
* - Please do NOT modify this file.
* - Please do NOT serve this file on production.
diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsx
index 0ff555acda..1160d98117 100644
--- a/frontend/src/components/app-config/user-config-form.tsx
+++ b/frontend/src/components/app-config/user-config-form.tsx
@@ -17,6 +17,8 @@ import { toast } from "../ui/use-toast";
import { saveUserConfig } from "../../core/network/requests";
import { useUserConfig } from "../../core/state/config";
import { ThemeToggle } from "./theme-toggle";
+import { NativeSelect } from "../ui/native-select";
+import { KEYMAP_PRESETS } from "@/core/codemirror/keymaps/keymaps";
export const UserConfigForm: React.FC = () => {
const [config, setConfig] = useUserConfig();
@@ -106,6 +108,28 @@ export const UserConfigForm: React.FC = () => {
</div>
)}
/>
+ <FormField
+ control={form.control}
+ name="keymap.preset"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Keymap</FormLabel>
+ <FormControl>
+ <NativeSelect
+ onChange={(e) => field.onChange(e.target.value)}
+ value={field.value}
+ >
+ {KEYMAP_PRESETS.map((option) => (
+ <option value={option} key={option}>
+ {option}
+ </option>
+ ))}
+ </NativeSelect>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
</form>
<ThemeToggle />
</Form>
diff --git a/frontend/src/core/codemirror/cm.ts b/frontend/src/core/codemirror/cm.ts
index 994eb6dc46..d114b86500 100644
--- a/frontend/src/core/codemirror/cm.ts
+++ b/frontend/src/core/codemirror/cm.ts
@@ -7,7 +7,6 @@ import {
} from "@codemirror/autocomplete";
import {
history,
- defaultKeymap,
historyKeymap,
indentWithTab,
indentMore,
@@ -111,22 +110,11 @@ export const setup = (
]),
keymap.of([
...closeBracketsKeymap,
- ...defaultKeymap,
...historyKeymap,
...foldKeymap,
...lintKeymap,
indentWithTab,
]),
- keymap.of([
- {
- key: "Escape",
- preventDefault: true,
- run: (cm) => {
- cm.contentDOM.blur();
- return true;
- },
- },
- ]),
findReplaceBundle(),
new LanguageSupport(customizedPython, [
customizedPython.data.of({ autocomplete: localCompletionSource }),
diff --git a/frontend/src/core/codemirror/find-replace/extension.ts b/frontend/src/core/codemirror/find-replace/extension.ts
index f60b63ad52..3474ea0cb8 100644
--- a/frontend/src/core/codemirror/find-replace/extension.ts
+++ b/frontend/src/core/codemirror/find-replace/extension.ts
@@ -12,7 +12,8 @@ export function findReplaceBundle() {
keymap.of([
{
key: "Escape",
- preventDefault: true,
+ // This is needed for Vim to go back to normal mode
+ preventDefault: false,
run: closeFindReplacePanel,
},
{
diff --git a/frontend/src/core/codemirror/keymaps/keymaps.ts b/frontend/src/core/codemirror/keymaps/keymaps.ts
new file mode 100644
index 0000000000..dcc142c468
--- /dev/null
+++ b/frontend/src/core/codemirror/keymaps/keymaps.ts
@@ -0,0 +1,102 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { KeymapConfig } from "@/core/config";
+import { logNever } from "@/utils/assertNever";
+import { defaultKeymap } from "@codemirror/commands";
+import { Extension, Prec } from "@codemirror/state";
+import { EditorView, keymap } from "@codemirror/view";
+import { vim, Vim } from "@replit/codemirror-vim";
+
+export const KEYMAP_PRESETS = ["default", "vim"] as const;
+
+export function keymapBundle(
+ config: KeymapConfig,
+ callbacks: {
+ deleteCell: () => void;
+ }
+): Extension {
+ switch (config.preset) {
+ case "default":
+ return [
+ keymap.of(defaultKeymap),
+ keymap.of([
+ {
+ key: "Escape",
+ preventDefault: true,
+ run: (cm) => {
+ cm.contentDOM.blur();
+ return true;
+ },
+ },
+ ]),
+ ];
+ case "vim":
+ // Delete a cell with :dcell
+ Vim.defineEx("dcell", "dcell", () => {
+ callbacks.deleteCell();
+ });
+ return [
+ // delete the cell on double press of "d", if the cell is empty
+ Prec.highest(
+ doubleCharacterListener(
+ "d",
+ (view) => view.state.doc.toString() === "",
+ (view) => {
+ if (view.state.doc.toString() === "") {
+ callbacks.deleteCell();
+ return true;
+ }
+ return false;
+ }
+ )
+ ),
+ vim({ status: false }),
+ keymap.of(defaultKeymap),
+ ];
+ default:
+ logNever(config.preset);
+ return [];
+ }
+}
+
+/**
+ * Listen for a double keypress of a character and call a callback.
+ */
+function doubleCharacterListener(
+ character: string,
+ predicate: (view: EditorView) => boolean,
+ onDoubleCharacter: (view: EditorView) => boolean
+): Extension {
+ let lastKey = "";
+ let lastKeyTime = 0;
+ return keymap.of([
+ {
+ any: (view, event) => {
+ const key = event.key;
+ const time = event.timeStamp;
+
+ // Different key or false predicate
+ if (key !== character || !predicate(view)) {
+ lastKey = "";
+ lastKeyTime = 0;
+ return false;
+ }
+
+ // Second keypress
+ if (lastKey === character && time - lastKeyTime < 500) {
+ const result = onDoubleCharacter(view);
+ // Was handled
+ if (result) {
+ lastKey = "";
+ lastKeyTime = 0;
+ return true;
+ }
+ }
+
+ // Track keypress
+ lastKey = key;
+ lastKeyTime = time;
+ return false;
+ },
+ },
+ ]);
+}
diff --git a/frontend/src/core/config.ts b/frontend/src/core/config.ts
index 8519c93f35..07eb5ccd16 100644
--- a/frontend/src/core/config.ts
+++ b/frontend/src/core/config.ts
@@ -15,10 +15,14 @@ export const UserConfigSchema = z.object({
.transform((millis) => Math.max(millis, 1000))
.default(1000),
}),
+ keymap: z.object({
+ preset: z.enum(["default", "vim"]).default("default"),
+ }),
});
export type UserConfig = z.infer<typeof UserConfigSchema>;
export type SaveConfig = UserConfig["save"];
export type CompletionConfig = UserConfig["completion"];
+export type KeymapConfig = UserConfig["keymap"];
export const AppConfigSchema = z.object({
width: z.enum(["full", "normal"]).default("normal"),
diff --git a/frontend/src/editor/Cell.tsx b/frontend/src/editor/Cell.tsx
index 3b06a2e610..f849c346b8 100644
--- a/frontend/src/editor/Cell.tsx
+++ b/frontend/src/editor/Cell.tsx
@@ -43,6 +43,7 @@ import { CellDragHandle, SortableCell } from "./SortableCell";
import { CellId, HTMLCellId } from "../core/model/ids";
import { Theme } from "../theme/useTheme";
import { HOTKEYS } from "@/core/hotkeys/hotkeys";
+import { keymapBundle } from "@/core/codemirror/keymaps/keymaps";
/**
* Imperative interface of the cell.
@@ -354,9 +355,21 @@ const CellComponent = (
});
const extensions = [
- ...setup(userConfig.completion, theme),
+ // Our keymap goes first
Prec.highest(keymap.of(cellEditingHotkeys)),
Prec.highest(formatKeymapExtension(cellId, updateCellCode)),
+ // Then editor keymaps (vim or defaults) based on user config
+ keymapBundle(userConfig.keymap, {
+ deleteCell: () => {
+ // Cannot delete running cells, since we're waiting for their output.
+ if (!runningOrQueuedRef.current) {
+ deleteCell(cellId);
+ }
+ return true;
+ },
+ }),
+ // Default setup
+ ...setup(userConfig.completion, theme),
scrollActiveLineIntoView(),
onChangePlugin,
showPlaceholder
@@ -421,6 +434,7 @@ const CellComponent = (
}, [
cellId,
userConfig.completion.activate_on_typing,
+ userConfig.keymap,
theme,
showPlaceholder,
initialContents,
diff --git a/frontend/src/stories/cell.stories.tsx b/frontend/src/stories/cell.stories.tsx
index 3c409ead3c..25a0234aea 100644
--- a/frontend/src/stories/cell.stories.tsx
+++ b/frontend/src/stories/cell.stories.tsx
@@ -46,6 +46,9 @@ const props: CellProps = {
autosave: "off",
autosave_delay: 1000,
},
+ keymap: {
+ preset: "default",
+ },
},
};
diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts
index 11bfb4c1fa..e54058fac3 100644
--- a/frontend/vite.config.ts
+++ b/frontend/vite.config.ts
@@ -21,6 +21,9 @@ const htmlDevPlugin = (): Plugin => {
autosave: "off",
autosave_delay: 0,
},
+ keymap: {
+ preset: "default",
+ },
})
)
.replace(`{{ app_config }}`, JSON.stringify({}))
diff --git a/marimo/_smoke_tests/layout.py b/marimo/_smoke_tests/layout.py
index 6f3ed3f25e..504eeeaa5d 100644
--- a/marimo/_smoke_tests/layout.py
+++ b/marimo/_smoke_tests/layout.py
@@ -1,7 +1,7 @@
# Copyright 2023 Marimo. All rights reserved.
import marimo
-__generated_with = "0.1.0"
+__generated_with = "0.1.3"
app = marimo.App()
diff --git a/marimo/config/_config.py b/marimo/config/_config.py
index d16f583816..eb52c8f18e 100644
--- a/marimo/config/_config.py
+++ b/marimo/config/_config.py
@@ -44,6 +44,18 @@ class SaveConfig(TypedDict, total=False):
autosave_delay: int
+@mddoc
+class KeymapConfig(TypedDict, total=False):
+ """Configuration for keymaps.
+
+ **Keys.**
+
+ - `preset`: one of `"default"` or `"vim"`
+ """
+
+ preset: Literal["default", "vim"]
+
+
@mddoc
class MarimoConfig(TypedDict, total=False):
"""Configuration for the marimo editor.
@@ -67,19 +79,24 @@ class MarimoConfig(TypedDict, total=False):
- `completion`: a `CompletionConfig`
- `save`: a `SaveConfig`
+ - `keymap`: a `KeymapConfig`
"""
completion: CompletionConfig
save: SaveConfig
+ keymap: KeymapConfig
_DEFAULT_CONFIG: MarimoConfig = {
"completion": {"activate_on_typing": True},
"save": {"autosave": "after_delay", "autosave_delay": 1000},
+ "keymap": {"preset": "default"},
}
_USER_CONFIG: Optional[MarimoConfig] = None
-ConfigType = TypeVar("ConfigType", MarimoConfig, SaveConfig, CompletionConfig)
+ConfigType = TypeVar(
+ "ConfigType", MarimoConfig, SaveConfig, CompletionConfig, KeymapConfig
+)
# TODO(akshayka): Type-safety, can't index into TypedDict with nonliteral