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.

improvement: allow pasting full marimo applications in a cell (#3273)

Myles Scolnicke1b33c2193db
diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsx
index f128a44a5d..6bef93f92d 100644
--- a/frontend/src/components/editor/cell/code/cell-editor.tsx
+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx
@@ -172,6 +172,17 @@ const CellEditorInternal = ({
deleteCell: handleDelete,
createAbove,
createBelow,
+ createManyBelow: (cells) => {
+ for (const code of [...cells].reverse()) {
+ createNewCell({
+ code,
+ before: false,
+ cellId: cellId,
+ // If the code already exists, skip creation
+ skipIfCodeExists: true,
+ });
+ }
+ },
moveUp,
moveDown,
focusUp,
diff --git a/frontend/src/components/editor/chrome/panels/snippets-panel.tsx b/frontend/src/components/editor/chrome/panels/snippets-panel.tsx
index 201f36ae64..32b955e7b5 100644
--- a/frontend/src/components/editor/chrome/panels/snippets-panel.tsx
+++ b/frontend/src/components/editor/chrome/panels/snippets-panel.tsx
@@ -108,6 +108,8 @@ const SnippetViewer: React.FC<{ snippet: Snippet }> = ({ snippet }) => {
code: section.code,
before: false,
cellId: lastFocusedCellId ?? "__end__",
+ // If the code already exists, skip creation
+ skipIfCodeExists: true,
});
}
}
diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.ts
index 37050bfafe..cfb907cd7e 100644
--- a/frontend/src/core/cells/__tests__/cells.test.ts
+++ b/frontend/src/core/cells/__tests__/cells.test.ts
@@ -1710,4 +1710,46 @@ describe("cell reducer", () => {
expect(state.cellRuntime[secondCellId].output).toBeNull();
expect(state.cellRuntime[secondCellId].consoleOutputs).toEqual([]);
});
+
+ it("skips creating new cell if code exists and skipIfCodeExists is true", () => {
+ // Add initial cell with code
+ actions.updateCellCode({
+ cellId: firstCellId,
+ code: "import numpy as np",
+ formattingChange: false,
+ });
+
+ // Try to create new cell with same code and skipIfCodeExists
+ actions.createNewCell({
+ cellId: "__end__",
+ code: "import numpy as np",
+ before: false,
+ skipIfCodeExists: true,
+ });
+
+ // Should still only have one cell
+ expect(state.cellIds.inOrderIds.length).toBe(1);
+ expect(formatCells(state)).toMatchInlineSnapshot(`
+ "
+ [0] 'import numpy as np'
+ "
+ `);
+
+ // Verify we can still add cell with different code
+ actions.createNewCell({
+ cellId: "__end__",
+ code: "import pandas as pd",
+ before: false,
+ skipIfCodeExists: true,
+ });
+
+ expect(state.cellIds.inOrderIds.length).toBe(2);
+ expect(formatCells(state)).toMatchInlineSnapshot(`
+ "
+ [0] 'import numpy as np'
+
+ [1] 'import pandas as pd'
+ "
+ `);
+ });
});
diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.ts
index 15a2a1587b..a43013b52e 100644
--- a/frontend/src/core/cells/cells.ts
+++ b/frontend/src/core/cells/cells.ts
@@ -195,13 +195,26 @@ const {
createNewCell: (
state,
action: {
+ /** The target cell ID to create a new cell relative to. Can be:
+ * - A CellId string for an existing cell
+ * - "__end__" to append at the end of the first column
+ * - {type: "__end__", columnId} to append at the end of a specific column
+ */
cellId: CellId | "__end__" | { type: "__end__"; columnId: CellColumnId };
+ /** Whether to insert before (true) or after (false) the target cell */
before: boolean;
+ /** Initial code content for the new cell */
code?: string;
+ /** The last executed code for the new cell */
lastCodeRun?: string;
+ /** Timestamp of the last execution */
lastExecutionTime?: number;
+ /** Optional custom ID for the new cell. Auto-generated if not provided */
newCellId?: CellId;
+ /** Whether to focus the new cell after creation */
autoFocus?: boolean;
+ /** If true, skip creation if code already exists */
+ skipIfCodeExists?: boolean;
},
) => {
const {
@@ -211,11 +224,21 @@ const {
lastCodeRun = null,
lastExecutionTime = null,
autoFocus = true,
+ skipIfCodeExists = false,
} = action;
let columnId: CellColumnId;
let cellIndex: number;
+ // If skipIfCodeExists is true, check if the code already exists in the notebook
+ if (skipIfCodeExists) {
+ for (const cellId of state.cellIds.inOrderIds) {
+ if (state.cellData[cellId]?.code === code) {
+ return state;
+ }
+ }
+ }
+
if (cellId === "__end__") {
const column = state.cellIds.atOrThrow(0);
columnId = column.id;
diff --git a/frontend/src/core/codemirror/__tests__/setup.test.ts b/frontend/src/core/codemirror/__tests__/setup.test.ts
index 6cbe48433e..84cfb7eaf7 100644
--- a/frontend/src/core/codemirror/__tests__/setup.test.ts
+++ b/frontend/src/core/codemirror/__tests__/setup.test.ts
@@ -30,6 +30,7 @@ function getOpts() {
deleteCell: namedFunction("deleteCell"),
createAbove: namedFunction("createAbove"),
createBelow: namedFunction("createBelow"),
+ createManyBelow: namedFunction("createManyBelow"),
moveUp: namedFunction("moveUp"),
moveDown: namedFunction("moveDown"),
focusUp: namedFunction("focusUp"),
diff --git a/frontend/src/core/codemirror/cells/extensions.ts b/frontend/src/core/codemirror/cells/extensions.ts
index 1f36d57f78..9b9261109a 100644
--- a/frontend/src/core/codemirror/cells/extensions.ts
+++ b/frontend/src/core/codemirror/cells/extensions.ts
@@ -18,6 +18,7 @@ export interface MovementCallbacks
deleteCell: () => void;
createAbove: () => void;
createBelow: () => void;
+ createManyBelow: (content: string[]) => void;
moveUp: () => void;
moveDown: () => void;
focusUp: () => void;
diff --git a/frontend/src/core/codemirror/cm.ts b/frontend/src/core/codemirror/cm.ts
index b5b715be71..e121df6663 100644
--- a/frontend/src/core/codemirror/cm.ts
+++ b/frontend/src/core/codemirror/cm.ts
@@ -56,8 +56,9 @@ import { historyCompartment } from "./editing/extensions";
import { goToDefinitionBundle } from "./go-to-definition/extension";
import type { HotkeyProvider } from "../hotkeys/hotkeys";
import { lightTheme } from "./theme/light";
-import { dndBundle } from "./dnd/extension";
+import { dndBundle } from "./misc/dnd";
import { jupyterHelpExtension } from "./compat/jupyter";
+import { pasteBundle } from "./misc/paste";
export interface CodeMirrorSetupOpts {
cellId: CellId;
@@ -87,6 +88,7 @@ export const setupCodeMirror = (opts: CodeMirrorSetupOpts): Extension[] => {
// Editor keymaps (vim or defaults) based on user config
keymapBundle(keymapConfig, cellMovementCallbacks),
dndBundle(),
+ pasteBundle(),
jupyterHelpExtension(),
// Cell editing
cellMovementBundle(cellId, cellMovementCallbacks, hotkeys),
diff --git a/frontend/src/core/codemirror/misc/__tests__/dnd.test.ts b/frontend/src/core/codemirror/misc/__tests__/dnd.test.ts
new file mode 100644
index 0000000000..13b5b12109
--- /dev/null
+++ b/frontend/src/core/codemirror/misc/__tests__/dnd.test.ts
@@ -0,0 +1,111 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+/* eslint-disable @typescript-eslint/no-explicit-any */
+import { EditorView } from "@codemirror/view";
+import { dndBundle } from "../dnd";
+import { describe, beforeEach, afterEach, it, expect } from "vitest";
+
+describe("dnd", () => {
+ let view: EditorView;
+
+ beforeEach(() => {
+ const el = document.createElement("div");
+ view = new EditorView({
+ parent: el,
+ });
+ });
+
+ afterEach(() => {
+ view.destroy();
+ });
+
+ it("handles text file drops", () => {
+ const extension = dndBundle();
+ const handlers = extension[0] as any;
+ const dropHandler = handlers.domEventHandlers.drop;
+
+ const file = new File(["test content"], "test.txt", { type: "text/plain" });
+ const event = new DragEvent("drop", {
+ dataTransfer: new DataTransfer(),
+ });
+ event.dataTransfer?.items.add(file);
+
+ const result = dropHandler(event, view);
+ expect(result).toBe(true);
+ });
+
+ it("handles image file drops", () => {
+ const extension = dndBundle();
+ const handlers = extension[0] as any;
+ const dropHandler = handlers.domEventHandlers.drop;
+
+ const file = new File([""], "test.png", { type: "image/png" });
+ const event = new DragEvent("drop", {
+ dataTransfer: new DataTransfer(),
+ });
+ event.dataTransfer?.items.add(file);
+
+ const result = dropHandler(event, view);
+ expect(result).toBe(true);
+ });
+
+ it("handles plain text drops", () => {
+ const extension = dndBundle();
+ const handlers = extension[0] as any;
+ const dropHandler = handlers.domEventHandlers.drop;
+
+ const event = new DragEvent("drop", {
+ dataTransfer: new DataTransfer(),
+ clientX: 0,
+ clientY: 0,
+ });
+ event.dataTransfer?.setData("text/plain", "dropped text");
+
+ const result = dropHandler(event, view);
+ expect(result).toBe(true);
+ });
+});
+
+class DragEvent extends Event {
+ dataTransfer: DataTransfer;
+ clientX: number;
+ clientY: number;
+
+ constructor(
+ type: string,
+ {
+ dataTransfer,
+ clientX,
+ clientY,
+ }: { dataTransfer?: DataTransfer; clientX?: number; clientY?: number } = {},
+ ) {
+ super(type);
+ this.dataTransfer = dataTransfer || new DataTransfer();
+ this.clientX = clientX || 0;
+ this.clientY = clientY || 0;
+ }
+}
+
+class DataTransfer {
+ data: Record<string, string> = {};
+ _items: File[] = [];
+
+ setData(type: string, data: string) {
+ this.data[type] = data;
+ }
+
+ get items() {
+ return {
+ add: (file: File) => {
+ this._items.push(file);
+ },
+ };
+ }
+
+ get files() {
+ return this._items;
+ }
+
+ getData(type: string) {
+ return this.data[type];
+ }
+}
diff --git a/frontend/src/core/codemirror/misc/__tests__/paste.test.ts b/frontend/src/core/codemirror/misc/__tests__/paste.test.ts
new file mode 100644
index 0000000000..7774414ec4
--- /dev/null
+++ b/frontend/src/core/codemirror/misc/__tests__/paste.test.ts
@@ -0,0 +1,236 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, it, expect, vi } from "vitest";
+import { extractCells, pasteBundle } from "../paste";
+import { EditorView } from "@codemirror/view";
+import { EditorState } from "@codemirror/state";
+import { movementCallbacksState } from "../../config/extension";
+import type { MovementCallbacks } from "../../cells/extensions";
+
+describe("extractCells", () => {
+ it("returns empty array for non-marimo text", () => {
+ expect(extractCells("regular python code")).toEqual([]);
+ expect(extractCells("")).toEqual([]);
+ });
+
+ it("extracts single cell content", () => {
+ const input = `
+import marimo as mo
+app = mo.App()
+
+def _():
+ x = 1
+ y = 2
+ return (x, y)
+`;
+ expect(extractCells(input)).toEqual(["x = 1\ny = 2"]);
+ });
+
+ it("extracts multiple cells", () => {
+ const input = `
+import marimo as mo
+app = mo.App()
+
+def _():
+ import numpy as np
+ return np
+
+def _(np):
+ data = np.array([1, 2, 3])
+ result = data * 2
+ return result
+
+if __name__ == "__main__":
+ app.run()
+`;
+ expect(extractCells(input)).toEqual([
+ "import numpy as np",
+ "data = np.array([1, 2, 3])\nresult = data * 2",
+ ]);
+ });
+
+ it("handles empty cells", () => {
+ const input = `
+def _():
+ return
+
+def _():
+ x = 1
+ return x
+
+def _():
+ return
+`;
+ expect(extractCells(input)).toEqual(["x = 1"]);
+ });
+
+ it("preserves indentation", () => {
+ const input = `
+def _():
+ if True:
+ nested = 1
+ if nested:
+ deep = 2
+ return
+`;
+ expect(extractCells(input)).toEqual([
+ "if True:\n nested = 1\n if nested:\n deep = 2",
+ ]);
+ });
+
+ it("handles cells with args", () => {
+ const input = `
+def named_one():
+ slider = mo.ui.slider(1, 10)
+ button = mo.ui.button("Click")
+ return slider, button
+
+def named_two(slider, button):
+ mo.hstack([
+ slider,
+ button
+ ])
+ return
+`;
+ expect(extractCells(input)).toEqual([
+ 'slider = mo.ui.slider(1, 10)\nbutton = mo.ui.button("Click")',
+ "mo.hstack([\n slider,\n button\n])",
+ ]);
+ });
+
+ it("handles cells with multi-line args", () => {
+ const input = `
+def _(
+ a,
+ b,
+ c,
+):
+ x = a + b + c
+ return x
+`;
+ expect(extractCells(input)).toEqual(["x = a + b + c"]);
+ });
+
+ it("handles cells with multi-line args and return", () => {
+ const input = `
+def _(
+ a,
+ b,
+ c,
+):
+ x = a + b + c
+ return (
+ x,
+ y,
+ )
+`;
+ expect(extractCells(input)).toEqual(["x = a + b + c"]);
+ });
+
+ it("handles cells with config", () => {
+ const input = `
[email protected](hide_code=True, column=2)
+def foo():
+ x = mo.ui.slider(1, 10)
+ return x
+`;
+ expect(extractCells(input)).toEqual(["x = mo.ui.slider(1, 10)"]);
+ });
+});
+
+// Mock ClipboardEvent and DataTransfer
+class MockDataTransfer {
+ private data: Record<string, string> = {};
+ setData(format: string, data: string) {
+ this.data[format] = data;
+ }
+ getData(format: string) {
+ return this.data[format];
+ }
+}
+
+class MockClipboardEvent extends Event {
+ clipboardData: MockDataTransfer;
+ constructor(type: string, init?: { clipboardData?: MockDataTransfer }) {
+ super(type);
+ this.clipboardData = init?.clipboardData || new MockDataTransfer();
+ }
+}
+
+describe("pasteBundle", () => {
+ it("handles pasting marimo app code", () => {
+ const createManyBelow = vi.fn();
+ const extension = pasteBundle();
+ const view = new EditorView({
+ state: EditorState.create({
+ doc: "",
+ extensions: [
+ extension,
+ movementCallbacksState.of({
+ createManyBelow,
+ } as Partial<MovementCallbacks> as MovementCallbacks),
+ ],
+ }),
+ });
+
+ // Mount the view to a DOM element
+ // const container = document.createElement("div");
+
+ const clipboardData = new MockDataTransfer();
+ clipboardData.setData(
+ "text/plain",
+ `
+def _():
+ x = 1
+ return x
+`,
+ );
+ const event = new MockClipboardEvent("paste", { clipboardData });
+
+ // HACK: manually add the paste event listener
+ // @ts-expect-error extension not typed
+ view.dom.onpaste = (evt) => extension[0].domEventHandlers.paste(evt, view);
+ view.dom.dispatchEvent(event);
+
+ expect(createManyBelow).toHaveBeenCalledWith(["x = 1"]);
+ });
+
+ it("ignores non-marimo pastes", () => {
+ const createManyBelow = vi.fn();
+ const extension = pasteBundle();
+ const view = new EditorView({
+ state: EditorState.create({
+ doc: "",
+ extensions: [
+ extension,
+ movementCallbacksState.of({
+ createManyBelow,
+ } as Partial<MovementCallbacks> as MovementCallbacks),
+ ],
+ }),
+ });
+
+ const clipboardData = new MockDataTransfer();
+ clipboardData.setData("text/plain", "regular code");
+ const event = new MockClipboardEvent("paste", { clipboardData });
+
+ // HACK: manually add the paste event listener
+ // @ts-expect-error extension not typed
+ view.dom.onpaste = (evt) => extension[0].domEventHandlers.paste(evt, view);
+
+ view.dom.dispatchEvent(event);
+
+ expect(createManyBelow).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/core/codemirror/dnd/extension.ts b/frontend/src/core/codemirror/misc/dnd.ts
similarity index 96%
rename from frontend/src/core/codemirror/dnd/extension.ts
rename to frontend/src/core/codemirror/misc/dnd.ts
index 9fa8736ab4..70438e3064 100644
--- a/frontend/src/core/codemirror/dnd/extension.ts
+++ b/frontend/src/core/codemirror/misc/dnd.ts
@@ -3,7 +3,7 @@ import type { Extension } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { insertImage, insertTextFile } from "../markdown/commands";
-export function dndBundle(): Extension {
+export function dndBundle(): Extension[] {
return [
EditorView.domEventHandlers({
drop: (event: DragEvent, view: EditorView) => {
diff --git a/frontend/src/core/codemirror/misc/paste.ts b/frontend/src/core/codemirror/misc/paste.ts
new file mode 100644
index 0000000000..96c083aa43
--- /dev/null
+++ b/frontend/src/core/codemirror/misc/paste.ts
@@ -0,0 +1,181 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import type { Extension } from "@codemirror/state";
+import { EditorView } from "@codemirror/view";
+import { movementCallbacksState } from "../config/extension";
+
+export function pasteBundle(): Extension[] {
+ return [
+ EditorView.domEventHandlers({
+ paste: (event: ClipboardEvent, view: EditorView) => {
+ const text = event.clipboardData?.getData("text/plain");
+ if (!text?.includes("@app.cell")) {
+ return false;
+ }
+
+ const cells = extractCells(text);
+ if (cells.length === 0) {
+ return false;
+ }
+
+ const movementCallbacks = view.state.facet(movementCallbacksState);
+ movementCallbacks.createManyBelow(cells);
+ return true;
+ },
+ }),
+ ];
+}
+
+/**
+ * Extract the cells from a marimo app.
+ */
+export function extractCells(text: string): string[] {
+ // Quick check if this looks like a marimo app
+ if (!text.includes("@app.cell")) {
+ return [];
+ }
+
+ const cells: string[] = [];
+ const lines = text.split("\n");
+ let currentCell: string[] = [];
+ let inCell = false;
+ let skipLines = 0;
+ let inMultilineArgs = false;
+ let inMultilineReturn = false;
+ let parenCount = 0;
+
+ // Pre-compile regex patterns
+ const leadingParenRegex = /\(/g;
+ const trailingParenRegex = /\)/g;
+ const cellEndMarkers = new Set(["@"]);
+
+ function countParens(line: string): number {
+ return (
+ (line.match(leadingParenRegex) || []).length -
+ (line.match(trailingParenRegex) || []).length
+ );
+ }
+
+ function finalizeCellIfNeeded() {
+ if (currentCell.length === 0) {
+ return;
+ }
+
+ // Remove trailing returns
+ while (
+ currentCell.length > 0 &&
+ currentCell[currentCell.length - 1].trim().startsWith("return")
+ ) {
+ currentCell.pop();
+ }
+
+ // Only add non-empty cells
+ if (currentCell.some((l) => l.trim() !== "")) {
+ cells.push(dedent(currentCell.join("\n")));
+ }
+ currentCell = [];
+ }
+
+ for (const line of lines) {
+ const trimmed = line.trim();
+
+ // Skip empty lines between cells
+ if (!trimmed && !inCell) {
+ continue;
+ }
+
+ // Start of a new cell
+ if (trimmed.startsWith("@app.cell")) {
+ finalizeCellIfNeeded();
+ inCell = true;
+ skipLines = 1; // Skip the def line
+ continue;
+ }
+
+ // Handle function definition and args
+ if (skipLines > 0) {
+ if (
+ trimmed.startsWith("def") &&
+ trimmed.includes("(") &&
+ !trimmed.includes("):")
+ ) {
+ inMultilineArgs = true;
+ parenCount = countParens(trimmed);
+ }
+ skipLines--;
+ continue;
+ }
+
+ // Track multi-line arguments
+ if (inMultilineArgs) {
+ parenCount += countParens(trimmed);
+ if (parenCount === 0) {
+ inMultilineArgs = false;
+ }
+ continue;
+ }
+
+ if (!inCell) {
+ continue;
+ }
+
+ // Handle cell content
+ if (cellEndMarkers.has(trimmed[0]) || trimmed.startsWith("if __name__")) {
+ finalizeCellIfNeeded();
+ inCell = trimmed.startsWith("@");
+ continue;
+ }
+
+ // Handle return statements
+ if (trimmed.startsWith("return")) {
+ if (trimmed.includes("(") && !trimmed.endsWith(")")) {
+ inMultilineReturn = true;
+ parenCount = countParens(trimmed);
+ }
+ continue;
+ }
+
+ if (inMultilineReturn) {
+ parenCount += countParens(trimmed);
+ if (parenCount === 0) {
+ inMultilineReturn = false;
+ }
+ continue;
+ }
+
+ // Add line to current cell
+ currentCell.push(line);
+ }
+
+ // Handle last cell
+ finalizeCellIfNeeded();
+
+ return cells;
+}
+
+function dedent(text: string): string {
+ const lines = text.split("\n");
+ if (lines.length === 0) {
+ return "";
+ }
+
+ // Cache non-empty lines
+ const nonEmptyLines = lines.filter((line) => line.trim().length > 0);
+ if (nonEmptyLines.length === 0) {
+ return "";
+ }
+
+ const leadingSpaceRegex = /^\s*/;
+ const minIndent = Math.min(
+ ...nonEmptyLines.map(
+ (line) =>
+ line.match(leadingSpaceRegex)?.[0].length ?? Number.POSITIVE_INFINITY,
+ ),
+ );
+
+ return minIndent === 0
+ ? text.trim()
+ : lines
+ .map((line) => line.slice(minIndent))
+ .join("\n")
+ .trim();
+}
diff --git a/frontend/vite.config.mts b/frontend/vite.config.mts
index 647cbeecd1..59514edeb6 100644
--- a/frontend/vite.config.mts
+++ b/frontend/vite.config.mts
@@ -22,11 +22,9 @@ const htmlDevPlugin = (): Plugin => {
// Add react-scan in dev mode
if (isDev) {
- // For latest, use:
- // '<head>\n<script src="https://unpkg.com/react-scan/dist/auto.global.js"></script>',
html = html.replace(
"<head>",
- '<head>\n<script src="https://unpkg.com/[email protected]/dist/auto.global.js"></script>',
+ '<head>\n<script src="https://unpkg.com/react-scan/dist/auto.global.js"></script>',
);
}