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.

cleanup: Refactor codemirror setup, add snapshot tests for duplicate keys (#71)

Myles Scolnick1b154f2c6951
diff --git a/frontend/src/core/codemirror/__tests__/__snapshots__/setup.test.ts.snap b/frontend/src/core/codemirror/__tests__/__snapshots__/setup.test.ts.snap
new file mode 100644
index 0000000000..78823c7dbf
--- /dev/null
+++ b/frontend/src/core/codemirror/__tests__/__snapshots__/setup.test.ts.snap
@@ -0,0 +1,204 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`snapshot all duplicate keymaps > default keymaps 2`] = `
+{
+ "ArrowDown": [
+ {
+ "key": "ArrowDown",
+ "run": "<no name>",
+ },
+ {
+ "key": "ArrowDown",
+ "preventDefault": true,
+ "run": "cursorLineDown",
+ "shift": "selectLineDown",
+ },
+ ],
+ "ArrowUp": [
+ {
+ "key": "ArrowUp",
+ "run": "<no name>",
+ },
+ {
+ "key": "ArrowUp",
+ "preventDefault": true,
+ "run": "cursorLineUp",
+ "shift": "selectLineUp",
+ },
+ ],
+ "Backspace": [
+ {
+ "key": "Backspace",
+ "run": "deleteCharBackward",
+ "shift": "deleteCharBackward",
+ },
+ {
+ "key": "Backspace",
+ "run": "deleteBracketPair",
+ },
+ ],
+ "Enter": [
+ {
+ "key": "Enter",
+ "run": "acceptCompletion",
+ },
+ {
+ "key": "Enter",
+ "run": "<no name>",
+ },
+ ],
+ "Escape": [
+ {
+ "key": "Escape",
+ "run": "closeCompletion",
+ },
+ {
+ "key": "Escape",
+ "run": "simplifySelection",
+ },
+ {
+ "key": "Escape",
+ "preventDefault": true,
+ "run": "run",
+ },
+ {
+ "key": "Escape",
+ "preventDefault": false,
+ "run": "closeFindReplacePanel",
+ },
+ ],
+ "PageDown": [
+ {
+ "key": "PageDown",
+ "run": "<no name>",
+ },
+ {
+ "key": "PageDown",
+ "run": "cursorPageDown",
+ "shift": "selectPageDown",
+ },
+ ],
+ "PageUp": [
+ {
+ "key": "PageUp",
+ "run": "<no name>",
+ },
+ {
+ "key": "PageUp",
+ "run": "cursorPageUp",
+ "shift": "selectPageUp",
+ },
+ ],
+ "Tab": [
+ {
+ "key": "Tab",
+ "preventDefault": true,
+ "run": "run",
+ },
+ {
+ "key": "Tab",
+ "run": "indentMore",
+ "shift": "indentLess",
+ },
+ ],
+}
+`;
+
+exports[`snapshot all duplicate keymaps > vim keymaps 2`] = `
+{
+ "ArrowDown": [
+ {
+ "key": "ArrowDown",
+ "run": "<no name>",
+ },
+ {
+ "key": "ArrowDown",
+ "preventDefault": true,
+ "run": "cursorLineDown",
+ "shift": "selectLineDown",
+ },
+ ],
+ "ArrowUp": [
+ {
+ "key": "ArrowUp",
+ "run": "<no name>",
+ },
+ {
+ "key": "ArrowUp",
+ "preventDefault": true,
+ "run": "cursorLineUp",
+ "shift": "selectLineUp",
+ },
+ ],
+ "Backspace": [
+ {
+ "key": "Backspace",
+ "run": "deleteCharBackward",
+ "shift": "deleteCharBackward",
+ },
+ {
+ "key": "Backspace",
+ "run": "deleteBracketPair",
+ },
+ ],
+ "Enter": [
+ {
+ "key": "Enter",
+ "run": "acceptCompletion",
+ },
+ {
+ "key": "Enter",
+ "run": "<no name>",
+ },
+ ],
+ "Escape": [
+ {
+ "key": "Escape",
+ "run": "closeCompletion",
+ },
+ {
+ "key": "Escape",
+ "run": "simplifySelection",
+ },
+ {
+ "key": "Escape",
+ "preventDefault": false,
+ "run": "closeFindReplacePanel",
+ },
+ ],
+ "PageDown": [
+ {
+ "key": "PageDown",
+ "run": "<no name>",
+ },
+ {
+ "key": "PageDown",
+ "run": "cursorPageDown",
+ "shift": "selectPageDown",
+ },
+ ],
+ "PageUp": [
+ {
+ "key": "PageUp",
+ "run": "<no name>",
+ },
+ {
+ "key": "PageUp",
+ "run": "cursorPageUp",
+ "shift": "selectPageUp",
+ },
+ ],
+ "Tab": [
+ {
+ "key": "Tab",
+ "preventDefault": true,
+ "run": "run",
+ },
+ {
+ "key": "Tab",
+ "run": "indentMore",
+ "shift": "indentLess",
+ },
+ ],
+}
+`;
diff --git a/frontend/src/core/codemirror/__tests__/setup.test.ts b/frontend/src/core/codemirror/__tests__/setup.test.ts
new file mode 100644
index 0000000000..ce2e29fe5b
--- /dev/null
+++ b/frontend/src/core/codemirror/__tests__/setup.test.ts
@@ -0,0 +1,107 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { describe, expect, test } from "vitest";
+import { CodeMirrorSetupOpts, setupCodeMirror } from "../cm";
+import { EditorState, Extension } from "@codemirror/state";
+import { keymap } from "@codemirror/view";
+import { CellId } from "@/core/model/ids";
+import { Objects } from "@/utils/objects";
+
+function namedFunction(name: string) {
+ const fn = () => false;
+ Object.defineProperty(fn, "name", { value: name });
+ return fn;
+}
+
+function setup(config: Partial<CodeMirrorSetupOpts> = {}): Extension[] {
+ return setupCodeMirror({
+ cellId: "0" as CellId,
+ showPlaceholder: false,
+ cellMovementCallbacks: {
+ onRun: namedFunction("onRun"),
+ deleteCell: namedFunction("deleteCell"),
+ createAbove: namedFunction("createAbove"),
+ createBelow: namedFunction("createBelow"),
+ moveUp: namedFunction("moveUp"),
+ moveDown: namedFunction("moveDown"),
+ focusUp: namedFunction("focusUp"),
+ focusDown: namedFunction("focusDown"),
+ sendToTop: namedFunction("sendToTop"),
+ sendToBottom: namedFunction("sendToBottom"),
+ moveToNextCell: namedFunction("moveToNextCell"),
+ },
+ cellCodeCallbacks: {
+ updateCellCode: namedFunction("updateCellCode"),
+ },
+ completionConfig: {
+ activate_on_typing: false,
+ },
+ keymapConfig: {
+ preset: "default",
+ },
+ theme: "light",
+ ...config,
+ });
+}
+
+function prettyPrintKeymaps(state: EditorState) {
+ const keymaps = state.facet(keymap).flat();
+ const prettyKeymaps = keymaps.map((keymap) => {
+ const { key, run, any, shift, ...rest } = keymap;
+ return {
+ key: key?.toString(),
+ ...(any ? { any: any.name || "<no name>" } : {}),
+ ...(run ? { run: run.name || "<no name>" } : {}),
+ ...(shift ? { shift: shift.name || "<no name>" } : {}),
+ ...rest,
+ };
+ });
+ return prettyKeymaps;
+}
+
+function getDuplicateKeymaps(state: EditorState) {
+ const prettyKeymaps = prettyPrintKeymaps(state);
+ const groupBy = Objects.groupBy(
+ prettyKeymaps,
+ (keymap) => keymap.key,
+ (keymap) => keymap
+ );
+ const duplicates = Objects.fromEntries(
+ Object.entries(groupBy).filter(([key, value]) => value.length > 1)
+ );
+ return duplicates;
+}
+
+describe("snapshot all duplicate keymaps", () => {
+ // This test just ensures we are not accidentally overlapping keymaps
+ // without handling it (precedence or otherwise).
+
+ test("default keymaps", () => {
+ const extensions = setup();
+ const duplicates = getDuplicateKeymaps(
+ EditorState.create({ extensions: extensions })
+ );
+ // Total duplicates:
+ // if this changes, please make sure to validate they are not conflicting
+ expect(Object.values(duplicates).flat().length).toMatchInlineSnapshot("18");
+ expect(duplicates).toMatchSnapshot();
+ });
+
+ test("vim keymaps", () => {
+ const extensions = setup({
+ keymapConfig: { preset: "vim" },
+ });
+ const duplicates = getDuplicateKeymaps(
+ EditorState.create({ extensions: extensions })
+ );
+ // Total duplicates:
+ // if this changes, please make sure to validate they are not conflicting
+ expect(Object.values(duplicates).flat().length).toMatchInlineSnapshot("17");
+ expect(duplicates).toMatchSnapshot();
+ });
+});
+
+test("placeholder adds another extension", () => {
+ const withPlaceholder = setup({ showPlaceholder: true }).flat();
+ const withoutPlaceholder = setup({ showPlaceholder: false }).flat();
+ expect(withPlaceholder.length - 1).toBe(withoutPlaceholder.length);
+});
diff --git a/frontend/src/core/codemirror/cells/extensions.ts b/frontend/src/core/codemirror/cells/extensions.ts
new file mode 100644
index 0000000000..55f9ae07c2
--- /dev/null
+++ b/frontend/src/core/codemirror/cells/extensions.ts
@@ -0,0 +1,182 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { HOTKEYS } from "@/core/hotkeys/hotkeys";
+import { KeyBinding, keymap } from "@codemirror/view";
+import { EditorView } from "codemirror";
+import { CellId } from "@/core/model/ids";
+import { Extension, Prec } from "@codemirror/state";
+import { formatKeymapExtension } from "../extensions";
+
+export interface MovementCallbacks {
+ onRun: () => void;
+ deleteCell: () => void;
+ createAbove: () => void;
+ createBelow: () => void;
+ moveUp: () => void;
+ moveDown: () => void;
+ focusUp: () => void;
+ focusDown: () => void;
+ sendToTop: (cellId: CellId) => void;
+ sendToBottom: (cellId: CellId) => void;
+ moveToNextCell: (cellId: CellId, before: boolean) => void;
+}
+
+/**
+ * Extensions for cell movement
+ */
+export function cellMovementBundle(
+ cellId: CellId,
+ callbacks: MovementCallbacks
+): Extension[] {
+ const {
+ onRun,
+ deleteCell,
+ createAbove,
+ createBelow,
+ moveUp,
+ moveDown,
+ focusUp,
+ focusDown,
+ sendToTop,
+ sendToBottom,
+ moveToNextCell,
+ } = callbacks;
+
+ const hotkeys: KeyBinding[] = [
+ {
+ key: HOTKEYS.getHotkey("cell.run").key,
+ preventDefault: true,
+ run: () => {
+ onRun();
+ return true;
+ },
+ },
+ {
+ key: HOTKEYS.getHotkey("cell.runAndNewBelow").key,
+ preventDefault: true,
+ run: (ev) => {
+ onRun();
+ ev.contentDOM.blur();
+ moveToNextCell(cellId, /*before=*/ false);
+ return true;
+ },
+ },
+ {
+ key: HOTKEYS.getHotkey("cell.runAndNewAbove").key,
+ preventDefault: true,
+ run: (ev) => {
+ onRun();
+ ev.contentDOM.blur();
+ moveToNextCell(cellId, /*before=*/ true);
+ return true;
+ },
+ },
+ {
+ key: HOTKEYS.getHotkey("cell.delete").key,
+ preventDefault: true,
+ run: (cm) => {
+ // Cannot delete non-empty cells for safety
+ if (cm.state.doc.length === 0) {
+ deleteCell();
+ }
+ // shortcuts.delete (shift-backspace) overlaps with
+ // defaultKeymap's deleteCharBackward (backspace); we don't want
+ // shift-backspace to trigger character deletion, because otherwise
+ // users might accidentally delete their whole notebook if they
+ // absent-mindedly held these keys. That's why we always return true.
+ return true;
+ },
+ },
+ {
+ key: HOTKEYS.getHotkey("cell.moveDown").key,
+ preventDefault: true,
+ run: () => {
+ moveDown();
+ return true;
+ },
+ },
+ {
+ key: HOTKEYS.getHotkey("cell.moveUp").key,
+ preventDefault: true,
+ run: () => {
+ moveUp();
+ return true;
+ },
+ },
+ {
+ key: HOTKEYS.getHotkey("cell.focusDown").key,
+ preventDefault: true,
+ run: () => {
+ focusDown();
+ return true;
+ },
+ },
+ {
+ key: HOTKEYS.getHotkey("cell.focusUp").key,
+ preventDefault: true,
+ run: () => {
+ focusUp();
+ return true;
+ },
+ },
+ {
+ key: HOTKEYS.getHotkey("cell.sendToBottom").key,
+ preventDefault: true,
+ run: () => {
+ sendToBottom(cellId);
+ return true;
+ },
+ },
+ {
+ key: HOTKEYS.getHotkey("cell.sendToTop").key,
+ preventDefault: true,
+ run: () => {
+ sendToTop(cellId);
+ return true;
+ },
+ },
+ {
+ key: HOTKEYS.getHotkey("cell.createAbove").key,
+ preventDefault: true,
+ run: (ev) => {
+ ev.contentDOM.blur();
+ createAbove();
+ return true;
+ },
+ },
+ {
+ key: HOTKEYS.getHotkey("cell.createBelow").key,
+ preventDefault: true,
+ run: (ev) => {
+ ev.contentDOM.blur();
+ createBelow();
+ return true;
+ },
+ },
+ ];
+
+ // Highest priority so that we can override the default keymap
+ return [Prec.highest(keymap.of(hotkeys))];
+}
+
+export interface CodeCallbacks {
+ updateCellCode: (cellId: CellId, code: string) => void;
+}
+
+/**
+ * Extensions for cell code editing
+ */
+export function cellCodeEditingBundle(
+ cellId: CellId,
+ callbacks: CodeCallbacks
+): Extension[] {
+ const { updateCellCode } = callbacks;
+
+ const onChangePlugin = EditorView.updateListener.of((update) => {
+ if (update.docChanged) {
+ const nextCode = update.state.doc.toString();
+ updateCellCode(cellId, nextCode);
+ }
+ });
+
+ return [onChangePlugin, formatKeymapExtension(cellId, updateCellCode)];
+}
diff --git a/frontend/src/core/codemirror/cm.ts b/frontend/src/core/codemirror/cm.ts
index d114b86500..a0cf29c89c 100644
--- a/frontend/src/core/codemirror/cm.ts
+++ b/frontend/src/core/codemirror/cm.ts
@@ -42,14 +42,62 @@ import {
EditorView,
} from "@codemirror/view";
-import { EditorState, Extension } from "@codemirror/state";
+import { EditorState, Extension, Prec } from "@codemirror/state";
import { oneDark } from "@codemirror/theme-one-dark";
-import { CompletionConfig } from "../config";
+import { CompletionConfig, KeymapConfig } from "../config";
import { Theme } from "../../theme/useTheme";
import { completer } from "@/core/codemirror/completion/completer";
import { findReplaceBundle } from "./find-replace/extension";
+import {
+ CodeCallbacks,
+ MovementCallbacks,
+ cellCodeEditingBundle,
+ cellMovementBundle,
+} from "./cells/extensions";
+import { CellId } from "../model/ids";
+import { keymapBundle } from "./keymaps/keymaps";
+import {
+ scrollActiveLineIntoView,
+ smartPlaceholderExtension,
+} from "./extensions";
+
+export interface CodeMirrorSetupOpts {
+ cellId: CellId;
+ showPlaceholder: boolean;
+ cellMovementCallbacks: MovementCallbacks;
+ cellCodeCallbacks: CodeCallbacks;
+ completionConfig: CompletionConfig;
+ keymapConfig: KeymapConfig;
+ theme: Theme;
+}
+
+/**
+ * Setup CodeMirror for a cell
+ */
+export const setupCodeMirror = ({
+ cellId,
+ showPlaceholder,
+ cellMovementCallbacks,
+ cellCodeCallbacks,
+ completionConfig,
+ keymapConfig,
+ theme,
+}: CodeMirrorSetupOpts): Extension[] => {
+ return [
+ // Editor keymaps (vim or defaults) based on user config
+ keymapBundle(keymapConfig, cellMovementCallbacks),
+ // Cell editing
+ cellMovementBundle(cellId, cellMovementCallbacks),
+ cellCodeEditingBundle(cellId, cellCodeCallbacks),
+ // Comes last so that it can be overridden
+ basicBundle(completionConfig, theme),
+ showPlaceholder
+ ? Prec.highest(smartPlaceholderExtension("import marimo as mo"))
+ : [],
+ ];
+};
// Customize python to support folding some additional syntax nodes
const customizedPython = pythonLanguage.configure({
@@ -63,11 +111,25 @@ const customizedPython = pythonLanguage.configure({
});
// Based on codemirror's basicSetup extension
-export const setup = (
+export const basicBundle = (
completionConfig: CompletionConfig,
theme: Theme
): Extension[] => {
return [
+ ///// View
+ EditorView.lineWrapping,
+ drawSelection(),
+ dropCursor(),
+ highlightActiveLine(),
+ highlightActiveLineGutter(),
+ highlightSpecialChars(),
+ lineNumbers(),
+ rectangularSelection(),
+ tooltips({ position: "absolute" }),
+ scrollActiveLineIntoView(),
+ theme === "dark" ? oneDark : [],
+
+ ///// Language Support
// Whether or not to require keypress to activate autocompletion (default
// keymap is Ctrl+Space)
autocompletion({
@@ -81,24 +143,25 @@ export const setup = (
closeOnBlur: false,
override: [completer],
}),
- tooltips({ position: "absolute" }),
- EditorView.lineWrapping,
- lineNumbers(),
- highlightActiveLineGutter(),
- highlightSpecialChars(),
- history(),
foldGutter(),
- drawSelection(),
- dropCursor(),
- theme === "dark" ? oneDark : [],
- EditorState.allowMultipleSelections.of(true),
+ closeBrackets(),
+ keymap.of(closeBracketsKeymap),
+ bracketMatching(),
indentOnInput(),
indentUnit.of(" "),
syntaxHighlighting(defaultHighlightStyle, { fallback: true }),
- bracketMatching(),
- closeBrackets(),
- rectangularSelection(),
- highlightActiveLine(),
+ keymap.of([...foldKeymap, ...lintKeymap]),
+
+ ///// Python Support
+ new LanguageSupport(customizedPython, [
+ customizedPython.data.of({ autocomplete: localCompletionSource }),
+ customizedPython.data.of({ autocomplete: globalCompletion }),
+ ]),
+
+ ///// Editing
+ history(),
+ EditorState.allowMultipleSelections.of(true),
+ findReplaceBundle(),
keymap.of([
{
key: "Tab",
@@ -108,18 +171,7 @@ export const setup = (
preventDefault: true,
},
]),
- keymap.of([
- ...closeBracketsKeymap,
- ...historyKeymap,
- ...foldKeymap,
- ...lintKeymap,
- indentWithTab,
- ]),
- findReplaceBundle(),
- new LanguageSupport(customizedPython, [
- customizedPython.data.of({ autocomplete: localCompletionSource }),
- customizedPython.data.of({ autocomplete: globalCompletion }),
- ]),
+ keymap.of([...historyKeymap, indentWithTab]),
];
};
diff --git a/frontend/src/core/codemirror/editing/commands.ts b/frontend/src/core/codemirror/editing/commands.ts
new file mode 100644
index 0000000000..3e65c54984
--- /dev/null
+++ b/frontend/src/core/codemirror/editing/commands.ts
@@ -0,0 +1,25 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { foldAll, unfoldAll } from "@codemirror/language";
+import { EditorView, Command } from "@codemirror/view";
+import { Nullable } from "vitest";
+
+export type BulkCommand = (targets: Array<Nullable<EditorView>>) => boolean;
+
+/**
+ * Make a bulk command from a single {@type Command} that applies
+ * the given command to all targets.
+ */
+export function makeBulkCommand(command: Command) {
+ return (targets: Array<Nullable<EditorView>>) => {
+ let changed = false;
+ for (const target of targets) {
+ if (target) {
+ changed = command(target) || changed;
+ }
+ }
+ return changed;
+ };
+}
+
+export const foldAllBulk = makeBulkCommand(foldAll);
+export const unfoldAllBulk = makeBulkCommand(unfoldAll);
diff --git a/frontend/src/core/codemirror/extensions.ts b/frontend/src/core/codemirror/extensions.ts
index 2b11cb28a6..db398a3723 100644
--- a/frontend/src/core/codemirror/extensions.ts
+++ b/frontend/src/core/codemirror/extensions.ts
@@ -72,6 +72,13 @@ export function formatKeymapExtension(
]);
}
+/**
+ * Scroll the active line into view when the editor is resized,
+ * with an offset.
+ *
+ * This is necessary when typings at the edges of the editor
+ * and the user is blocked by the hovering action bar.
+ */
export function scrollActiveLineIntoView() {
return EditorView.updateListener.of((update) => {
// A new line was added, scroll the active line into view
diff --git a/frontend/src/core/codemirror/keymaps/keymaps.ts b/frontend/src/core/codemirror/keymaps/keymaps.ts
index dcc142c468..b79999e8c5 100644
--- a/frontend/src/core/codemirror/keymaps/keymaps.ts
+++ b/frontend/src/core/codemirror/keymaps/keymaps.ts
@@ -13,7 +13,7 @@ export function keymapBundle(
callbacks: {
deleteCell: () => void;
}
-): Extension {
+): Extension[] {
switch (config.preset) {
case "default":
return [
diff --git a/frontend/src/core/state/cells.ts b/frontend/src/core/state/cells.ts
index 4466767841..dc1a1f5d2b 100644
--- a/frontend/src/core/state/cells.ts
+++ b/frontend/src/core/state/cells.ts
@@ -12,6 +12,7 @@ import { arrayMove } from "@dnd-kit/sortable";
import { CellId } from "../model/ids";
import { prepareCellForExecution, transitionCell } from "./cell";
import { store } from "./jotai";
+import { foldAllBulk, unfoldAllBulk } from "../codemirror/editing/commands";
/* The array of cells on the page, together with a history of
* deleted cells to implement an "undo delete" action
@@ -450,16 +451,16 @@ function reducer(state: CellsAndHistory, action: CellAction): CellsAndHistory {
};
}
}
- case "FOLD_ALL":
- state.present.forEach((cell) => {
- cell.ref.current?.foldAll();
- });
+ case "FOLD_ALL": {
+ const targets = state.present.map((cell) => cell.ref.current?.editorView);
+ foldAllBulk(targets);
return state;
- case "UNFOLD_ALL":
- state.present.forEach((cell) => {
- cell.ref.current?.unfoldAll();
- });
+ }
+ case "UNFOLD_ALL": {
+ const targets = state.present.map((cell) => cell.ref.current?.editorView);
+ unfoldAllBulk(targets);
return state;
+ }
default:
return state;
}
diff --git a/frontend/src/editor/Cell.tsx b/frontend/src/editor/Cell.tsx
index 84f50f8e8d..d3f55d6156 100644
--- a/frontend/src/editor/Cell.tsx
+++ b/frontend/src/editor/Cell.tsx
@@ -1,9 +1,8 @@
/* Copyright 2023 Marimo. All rights reserved. */
import { closeCompletion, completionStatus } from "@codemirror/autocomplete";
import { historyField } from "@codemirror/commands";
-import { foldAll, unfoldAll } from "@codemirror/language";
-import { EditorState, Prec, StateEffect } from "@codemirror/state";
-import { keymap, EditorView, KeyBinding } from "@codemirror/view";
+import { EditorState, StateEffect } from "@codemirror/state";
+import { EditorView } from "@codemirror/view";
import {
memo,
FocusEvent,
@@ -17,7 +16,7 @@ import {
} from "react";
import { sendRun } from "@/core/network/requests";
-import { autocompletionKeymap, setup } from "@/core/codemirror/cm";
+import { autocompletionKeymap, setupCodeMirror } from "@/core/codemirror/cm";
import { UserConfig } from "../core/config";
import { CellState } from "../core/model/cells";
@@ -30,11 +29,6 @@ import { DeleteButton } from "./cell/DeleteButton";
import { CellStatusComponent } from "./cell/CellStatus";
import clsx from "clsx";
import { renderShortcut } from "../components/shortcuts/renderShortcut";
-import {
- formatKeymapExtension,
- scrollActiveLineIntoView,
- smartPlaceholderExtension,
-} from "../core/codemirror/extensions";
import { useCellRenderCount } from "../hooks/useCellRenderCount";
import { Functions } from "../utils/functions";
import { Logger } from "../utils/Logger";
@@ -42,8 +36,6 @@ import { SerializedEditorState } from "../core/codemirror/types";
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";
import { CellActions } from "./cell/cell-actions";
/**
@@ -54,14 +46,6 @@ export interface CellHandle {
* The CodeMirror editor view.
*/
editorView: EditorView;
- /**
- * Folds all code in the editor.
- */
- foldAll: () => boolean;
- /**
- * Unfolds all code in the editor.
- */
- unfoldAll: () => boolean;
/**
* Get the serialized editor state.
*/
@@ -175,18 +159,6 @@ const CellComponent = (
get editorView() {
return derefNotNull(editorView);
},
- foldAll() {
- if (editorView.current !== null) {
- return foldAll(derefNotNull(editorView));
- }
- return false;
- },
- unfoldAll() {
- if (editorView.current !== null) {
- return unfoldAll(derefNotNull(editorView));
- }
- return false;
- },
editorStateJSON: () => {
return derefNotNull(editorView).state.toJSON({ history: historyField });
},
@@ -234,150 +206,39 @@ const CellComponent = (
);
useEffect(() => {
- const cellEditingHotkeys: KeyBinding[] = [
- {
- key: HOTKEYS.getHotkey("cell.run").key,
- preventDefault: true,
- run: () => {
- onRun();
- return true;
- },
- },
- {
- key: HOTKEYS.getHotkey("cell.runAndNewBelow").key,
- preventDefault: true,
- run: (ev) => {
- onRun();
- ev.contentDOM.blur();
- moveToNextCell(cellId, /*before=*/ false);
- return true;
- },
- },
- {
- key: HOTKEYS.getHotkey("cell.runAndNewAbove").key,
- preventDefault: true,
- run: (ev) => {
- onRun();
- ev.contentDOM.blur();
- moveToNextCell(cellId, /*before=*/ true);
- return true;
- },
- },
- {
- key: HOTKEYS.getHotkey("cell.delete").key,
- preventDefault: true,
- run: (cm) => {
- // Cannot delete running cells, since we're waiting for their output.
- // Cannot delete non-empty cells for safety
- if (!runningOrQueuedRef.current && cm.state.doc.length === 0) {
- deleteCell(cellId);
- }
- // shortcuts.delete (shift-backspace) overlaps with
- // defaultKeymap's deleteCharBackward (backspace); we don't want
- // shift-backspace to trigger character deletion, because otherwise
- // users might accidentally delete their whole notebook if they
- // absent-mindedly held these keys. That's why we always return true.
- return true;
- },
- },
- {
- key: HOTKEYS.getHotkey("cell.moveDown").key,
- preventDefault: true,
- run: () => {
- moveDown();
- return true;
- },
- },
- {
- key: HOTKEYS.getHotkey("cell.moveUp").key,
- preventDefault: true,
- run: () => {
- moveUp();
- return true;
- },
- },
- {
- key: HOTKEYS.getHotkey("cell.focusDown").key,
- preventDefault: true,
- run: () => {
- focusDown();
- return true;
- },
- },
- {
- key: HOTKEYS.getHotkey("cell.focusUp").key,
- preventDefault: true,
- run: () => {
- focusUp();
- return true;
- },
- },
- {
- key: HOTKEYS.getHotkey("cell.sendToBottom").key,
- preventDefault: true,
- run: () => {
- sendToBottom(cellId);
- return true;
- },
- },
- {
- key: HOTKEYS.getHotkey("cell.sendToTop").key,
- preventDefault: true,
- run: () => {
- sendToTop(cellId);
- return true;
- },
- },
- {
- key: HOTKEYS.getHotkey("cell.createAbove").key,
- preventDefault: true,
- run: (ev) => {
- ev.contentDOM.blur();
- createAbove();
- return true;
- },
+ const deleteCellIfNotRunning = () => {
+ // Cannot delete running cells, since we're waiting for their output.
+ if (!runningOrQueuedRef.current) {
+ deleteCell(cellId);
+ return true;
+ }
+ return false;
+ };
+
+ const extensions = setupCodeMirror({
+ cellId,
+ showPlaceholder,
+ cellCodeCallbacks: {
+ updateCellCode,
},
- {
- key: HOTKEYS.getHotkey("cell.createBelow").key,
- preventDefault: true,
- run: (ev) => {
- ev.contentDOM.blur();
- createBelow();
- return true;
- },
+ cellMovementCallbacks: {
+ onRun,
+ deleteCell: deleteCellIfNotRunning,
+ createAbove,
+ createBelow,
+ moveUp,
+ moveDown,
+ focusUp,
+ focusDown,
+ sendToTop,
+ sendToBottom,
+ moveToNextCell,
},
- ];
-
- const onChangePlugin = EditorView.updateListener.of((update) => {
- if (update.docChanged) {
- const nextCode = update.state.doc.toString();
- updateCellCode(cellId, nextCode);
- }
+ completionConfig: userConfig.completion,
+ keymapConfig: userConfig.keymap,
+ theme,
});
- const extensions = [
- // 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
- ? Prec.highest(smartPlaceholderExtension("import marimo as mo"))
- : [],
- ];
-
// Should focus will be true if its a newly created editor
let shouldFocus: boolean;
if (serializedEditorState === null) {
diff --git a/frontend/src/stories/editor.stories.tsx b/frontend/src/stories/editor.stories.tsx
index ac211d0459..5c07a84b33 100644
--- a/frontend/src/stories/editor.stories.tsx
+++ b/frontend/src/stories/editor.stories.tsx
@@ -3,7 +3,7 @@ import type { Meta, StoryObj } from "@storybook/react";
import { useEffect, useRef } from "react";
import { EditorState, Extension } from "@codemirror/state";
import { EditorView, basicSetup } from "codemirror";
-import { setup } from "../core/codemirror/cm";
+import { basicBundle } from "../core/codemirror/cm";
import { python } from "@codemirror/lang-python";
const meta: Meta = {
@@ -57,7 +57,10 @@ export const Primary: Story = {
render: (args, ctx) => (
<div className="Cell m-20 w-[60%] overflow-hidden">
<Editor
- extensions={setup({ activate_on_typing: false }, ctx.globals.theme)}
+ extensions={basicBundle(
+ { activate_on_typing: false },
+ ctx.globals.theme
+ )}
/>
</div>
),