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.

improve: Move highlighted code to newly created cells (#2484)

Wasim Sandhu25afc557aac4
diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsx
index cc2b9d49d9..c833a9c926 100644
--- a/frontend/src/components/editor/Cell.tsx
+++ b/frontend/src/components/editor/Cell.tsx
@@ -243,12 +243,22 @@ const CellComponent = (
const createBelow = useCallback(
(opts: { code?: string } = {}) =>
- createNewCell({ cellId, before: false, ...opts }),
+ createNewCell({
+ cellId,
+ before: false,
+ ...opts,
+ includeSelectionAsInitialCode: true,
+ }),
[cellId, createNewCell],
);
const createAbove = useCallback(
(opts: { code?: string } = {}) =>
- createNewCell({ cellId, before: true, ...opts }),
+ createNewCell({
+ cellId,
+ before: true,
+ ...opts,
+ includeSelectionAsInitialCode: true,
+ }),
[cellId, createNewCell],
);
diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsx
index 4aeb1503a9..1616894084 100644
--- a/frontend/src/components/editor/cell/code/cell-editor.tsx
+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx
@@ -107,11 +107,21 @@ const CellEditorInternal = ({
});
const createBelow = useCallback(
- () => createNewCell({ cellId, before: false }),
+ () =>
+ createNewCell({
+ cellId,
+ before: false,
+ includeSelectionAsInitialCode: true,
+ }),
[cellId, createNewCell],
);
const createAbove = useCallback(
- () => createNewCell({ cellId, before: true }),
+ () =>
+ createNewCell({
+ cellId,
+ before: true,
+ includeSelectionAsInitialCode: true,
+ }),
[cellId, createNewCell],
);
const moveDown = useCallback(
diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.ts
index e67925d60a..50850a9267 100644
--- a/frontend/src/core/cells/__tests__/cells.test.ts
+++ b/frontend/src/core/cells/__tests__/cells.test.ts
@@ -50,7 +50,9 @@ const { initialNotebookState, reducer, createActions } = exportedForTesting;
function formatCells(notebook: NotebookState) {
const cells = notebookCells(notebook);
- return `\n${cells.map((cell) => [`key: ${cell.id}`, `code: '${cell.code}'`].join("\n")).join("\n\n")}`;
+ return `\n${cells
+ .map((cell) => [`key: ${cell.id}`, `code: '${cell.code}'`].join("\n"))
+ .join("\n\n")}`;
}
function createEditor(content: string) {
@@ -1276,4 +1278,130 @@ describe("cell reducer", () => {
const cell = cells[0];
expect(cell.consoleOutputs).toEqual([STDOUT1, STDOUT2]);
});
+
+ describe("can create a cell using selected code", () => {
+ const firstLine = "import marimo as mo";
+ const secondLine = "import pandas as pd";
+ const thirdLine = "import numpy as np";
+
+ let editor: EditorView | undefined;
+ let secondCellId: CellId;
+
+ beforeEach(() => {
+ actions.createNewCell({
+ cellId: firstCellId,
+ before: false,
+ code: `${firstLine}\n${secondLine}\n${thirdLine}`,
+ });
+ secondCellId = state.cellIds.atOrThrow(1);
+ editor = state.cellHandles[secondCellId].current?.editorView;
+ });
+
+ it("includeSelectionAsInitialCode is true and there is selection", () => {
+ if (!editor) {
+ throw new Error("Editor not found");
+ }
+ editor.dispatch({
+ selection: {
+ anchor: editor.state.doc.line(2).from,
+ head: editor.state.doc.line(2).to,
+ },
+ });
+
+ const { from, to } = editor.state.selection.main;
+ const highlighted = editor.state.doc.toString().slice(from, to);
+ expect(highlighted).toBe(secondLine);
+
+ actions.createNewCell({
+ cellId: secondCellId,
+ before: false,
+ includeSelectionAsInitialCode: true,
+ });
+ expect(formatCells(state)).toMatchInlineSnapshot(`
+ "
+ key: 0
+ code: ''
+
+ key: 1
+ code: '${firstLine}\n${thirdLine}'
+
+ key: 2
+ code: '${secondLine}'"
+ `);
+ });
+
+ it("includeSelectionAsInitialCode is false and there is selection", () => {
+ if (!editor) {
+ throw new Error("Editor not found");
+ }
+ editor.dispatch({
+ selection: {
+ anchor: editor.state.doc.line(2).from,
+ head: editor.state.doc.line(2).to,
+ },
+ });
+ actions.createNewCell({
+ cellId: secondCellId,
+ before: false,
+ includeSelectionAsInitialCode: false,
+ });
+ expect(formatCells(state)).toMatchInlineSnapshot(`
+ "
+ key: 0
+ code: ''
+
+ key: 1
+ code: '${firstLine}\n${secondLine}\n${thirdLine}'
+
+ key: 2
+ code: ''"
+ `);
+ });
+
+ it("includeSelectionAsInitialCode is true and there is no selection", () => {
+ if (!editor) {
+ throw new Error("Editor not found");
+ }
+ editor.dispatch({ selection: { anchor: 0, head: 0 } });
+ actions.createNewCell({
+ cellId: secondCellId,
+ before: false,
+ includeSelectionAsInitialCode: true,
+ });
+ expect(formatCells(state)).toMatchInlineSnapshot(`
+ "
+ key: 0
+ code: ''
+
+ key: 1
+ code: '${firstLine}\n${secondLine}\n${thirdLine}'
+
+ key: 2
+ code: ''"
+ `);
+ });
+
+ it("includeSelectionAsInitialCode is false and there is no selection", () => {
+ if (!editor) {
+ throw new Error("Editor not found");
+ }
+ editor.dispatch({ selection: { anchor: 0, head: 0 } });
+ actions.createNewCell({
+ cellId: secondCellId,
+ before: false,
+ includeSelectionAsInitialCode: false,
+ });
+ expect(formatCells(state)).toMatchInlineSnapshot(`
+ "
+ key: 0
+ code: ''
+
+ key: 1
+ code: '${firstLine}\n${secondLine}\n${thirdLine}'
+
+ key: 2
+ code: ''"
+ `);
+ });
+ });
});
diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.ts
index 4e1f0a26b8..1e887f996a 100644
--- a/frontend/src/core/cells/cells.ts
+++ b/frontend/src/core/cells/cells.ts
@@ -31,6 +31,7 @@ import { clamp } from "@/utils/math";
import type { LayoutState } from "../layout/layout";
import { notebookIsRunning, notebookQueueOrRunningCount } from "./utils";
import {
+ extractHighlightedCode,
splitEditor,
updateEditorCodeFromPython,
} from "../codemirror/language/utils";
@@ -45,6 +46,7 @@ import { syncCellIds } from "../network/requests";
import { kioskModeAtom } from "../mode";
import { CollapsibleTree } from "@/utils/id-tree";
import { isEqual } from "lodash-es";
+import type { EditorView } from "@codemirror/view";
export const SCRATCH_CELL_ID = "__scratch__" as CellId;
@@ -197,6 +199,7 @@ const {
lastExecutionTime?: number;
newCellId?: CellId;
autoFocus?: boolean;
+ includeSelectionAsInitialCode?: boolean;
},
) => {
const {
@@ -206,6 +209,7 @@ const {
lastCodeRun = null,
lastExecutionTime = null,
autoFocus = true,
+ includeSelectionAsInitialCode,
} = action;
const newCellId = action.newCellId || CellId.create();
const index =
@@ -214,6 +218,29 @@ const {
: state.cellIds.topLevelIds.indexOf(cellId);
const insertionIndex = before ? index : index + 1;
+ let newCellCode = code;
+
+ if (includeSelectionAsInitialCode) {
+ const id = cellId as CellId;
+ const editorView = state.cellHandles[id].current?.editorView;
+ if (editorView) {
+ const result = extractHighlightedCode(editorView);
+ if (result != null) {
+ const [highlighted, leftover] = result;
+ newCellCode = highlighted === "" ? code : highlighted;
+ updateEditorCodeFromPython(editorView, leftover);
+ state.cellData = {
+ ...state.cellData,
+ [id]: {
+ ...state.cellData[id],
+ code: leftover,
+ edited: true,
+ },
+ };
+ }
+ }
+ }
+
return {
...state,
cellIds: state.cellIds.insert(newCellId, insertionIndex),
@@ -221,10 +248,10 @@ const {
...state.cellData,
[newCellId]: createCell({
id: newCellId,
- code,
+ code: newCellCode,
lastCodeRun,
lastExecutionTime,
- edited: Boolean(code) && code !== lastCodeRun,
+ edited: Boolean(newCellCode) && newCellCode !== lastCodeRun,
}),
},
cellRuntime: {
@@ -1029,9 +1056,13 @@ export const getAllEditorViews = () => {
.filter(Boolean);
};
-export const getCellEditorView = (cellId: CellId) => {
+export const getCellEditorView = (cellId: CellId): EditorView | undefined => {
const { cellHandles } = store.get(notebookAtom);
- return cellHandles[cellId].current?.editorView;
+ const cellHandle = cellHandles[cellId];
+ if (!cellHandle) {
+ return;
+ }
+ return cellHandle.current?.editorView;
};
export function isUninstantiated(
diff --git a/frontend/src/core/codemirror/language/__tests__/utils.test.ts b/frontend/src/core/codemirror/language/__tests__/utils.test.ts
index 389aa0d5e9..ebc3dfc3db 100644
--- a/frontend/src/core/codemirror/language/__tests__/utils.test.ts
+++ b/frontend/src/core/codemirror/language/__tests__/utils.test.ts
@@ -3,13 +3,16 @@ import {
getEditorCodeAsPython,
updateEditorCodeFromPython,
splitEditor,
+ extractHighlightedCode,
} from "../utils";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
-import { describe, it, expect } from "vitest";
+import { describe, it, expect, beforeAll } from "vitest";
import { adaptiveLanguageConfiguration, switchLanguage } from "../extension";
import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";
import type { MovementCallbacks } from "../../cells/extensions";
+import { store } from "@/core/state/jotai";
+import { capabilitiesAtom } from "@/core/config/capabilities";
function createEditor(doc: string) {
return new EditorView({
@@ -147,3 +150,219 @@ describe("splitEditor", () => {
expect(result.afterCursorCode).toEqual('mo.md(f"""{b}!""")');
});
});
+
+describe("extractHighlightedCode", () => {
+ const pyLineOne = "import marimo as mo";
+ const pyLineTwo = "import pandas as pd";
+ const pyLineThree = "import numpy as np";
+ const pythonCode = `${pyLineOne}\n${pyLineTwo}\n${pyLineThree}`;
+
+ const sqlLineOne = "SELECT * FROM table";
+ const sqlLineTwo = "WHERE column = value";
+ const sqlLineThree = "ORDER BY column";
+ const sqlCode = `df = mo.sql("""${sqlLineOne}\n${sqlLineTwo}\n${sqlLineThree}""")`;
+
+ const mdLineOne = "Hello, World!";
+ const mdLineTwo = "Goodbye, World!";
+ const mdLineThree = "Hello, Goodbye!";
+ const markdownCode = `mo.md('${mdLineOne}\n${mdLineTwo}\n${mdLineThree}')`;
+
+ function getExtraction(editor: EditorView) {
+ const result = extractHighlightedCode(editor);
+ if (!result) {
+ throw new Error("Result is null");
+ }
+ return result;
+ }
+
+ beforeAll(() => {
+ store.set(capabilitiesAtom, {
+ sql: true,
+ terminal: true,
+ });
+ });
+
+ it("extracts highlighted Python code at start", () => {
+ const mockEditor = createEditor(pythonCode);
+ mockEditor.dispatch({
+ selection: {
+ anchor: mockEditor.state.doc.line(1).from,
+ head: mockEditor.state.doc.line(2).to,
+ },
+ });
+ const [highlighted, leftover] = getExtraction(mockEditor);
+ expect(highlighted).toEqual(`${pyLineOne}\n${pyLineTwo}`);
+ expect(leftover).toEqual(`\n${pyLineThree}`);
+ });
+
+ it("extracts highlighted Python code in middle", () => {
+ const mockEditor = createEditor(pythonCode);
+ mockEditor.dispatch({
+ selection: {
+ anchor: mockEditor.state.doc.line(2).from,
+ head: mockEditor.state.doc.line(2).to,
+ },
+ });
+ const [highlighted, leftover] = getExtraction(mockEditor);
+ expect(highlighted).toEqual(pyLineTwo);
+ expect(leftover).toEqual(`${pyLineOne}\n${pyLineThree}`);
+ });
+
+ it("extracts highlighted Python code at end", () => {
+ const mockEditor = createEditor(pythonCode);
+ mockEditor.dispatch({
+ selection: {
+ anchor: mockEditor.state.doc.line(3).from,
+ head: mockEditor.state.doc.line(3).to,
+ },
+ });
+ const [highlighted, leftover] = getExtraction(mockEditor);
+ expect(highlighted).toEqual(pyLineThree);
+ expect(leftover).toEqual(`${pyLineOne}\n${pyLineTwo}`);
+ });
+
+ it("extracts no highlighted Python code if none", () => {
+ const mockEditor = createEditor(pythonCode);
+ mockEditor.dispatch({ selection: { anchor: 0, head: 0 } });
+ const result = extractHighlightedCode(mockEditor);
+ expect(result).toEqual(null);
+ });
+
+ it("extracts highlighted SQL code at start", () => {
+ const mockEditor = createEditor(sqlCode);
+ switchLanguage(mockEditor, "sql");
+ mockEditor.dispatch({
+ selection: {
+ anchor: mockEditor.state.doc.line(1).from,
+ head: mockEditor.state.doc.line(2).to,
+ },
+ });
+ const [highlighted, leftover] = getExtraction(mockEditor);
+ expect(leftover).toEqual(`df = mo.sql(
+ """
+
+ ${sqlLineThree}
+ """\n)`);
+ expect(highlighted).toEqual(`df = mo.sql(
+ """
+ ${sqlLineOne}
+ ${sqlLineTwo}
+ """\n)`);
+ });
+
+ it("extracts highlighted SQL code in middle", () => {
+ const mockEditor = createEditor(sqlCode);
+ switchLanguage(mockEditor, "sql");
+ mockEditor.dispatch({
+ selection: {
+ anchor: mockEditor.state.doc.line(2).from,
+ head: mockEditor.state.doc.line(2).to,
+ },
+ });
+ const [highlighted, leftover] = getExtraction(mockEditor);
+ expect(highlighted).toEqual(`df = mo.sql(
+ """
+ ${sqlLineTwo}
+ """\n)`);
+ expect(leftover).toEqual(`df = mo.sql(
+ """
+ ${sqlLineOne}
+ ${sqlLineThree}
+ """\n)`);
+ });
+
+ it("extracts highlighted SQL code at end", () => {
+ const mockEditor = createEditor(sqlCode);
+ switchLanguage(mockEditor, "sql");
+ mockEditor.dispatch({
+ selection: {
+ anchor: mockEditor.state.doc.line(3).from,
+ head: mockEditor.state.doc.line(3).to,
+ },
+ });
+ const [highlighted, leftover] = getExtraction(mockEditor);
+ expect(highlighted).toEqual(`df = mo.sql(
+ """
+ ${sqlLineThree}
+ """\n)`);
+ expect(leftover).toEqual(`df = mo.sql(
+ """
+ ${sqlLineOne}
+ ${sqlLineTwo}
+ """\n)`);
+ });
+
+ it("extracts no highlighted SQL code if none", () => {
+ const mockEditor = createEditor(sqlCode);
+ switchLanguage(mockEditor, "sql");
+ mockEditor.dispatch({ selection: { anchor: 0, head: 0 } });
+ const result = extractHighlightedCode(mockEditor);
+ expect(result).toEqual(null);
+ });
+
+ it("extracts highlighted Markdown code at start", () => {
+ const mockEditor = createEditor(markdownCode);
+ switchLanguage(mockEditor, "markdown");
+ mockEditor.dispatch({
+ selection: {
+ anchor: mockEditor.state.doc.line(1).from,
+ head: mockEditor.state.doc.line(2).to,
+ },
+ });
+ const [highlighted, leftover] = getExtraction(mockEditor);
+ expect(leftover).toEqual(`mo.md(
+ """
+
+ ${mdLineThree}
+ """\n)`);
+ expect(highlighted).toEqual(`mo.md(
+ """
+ ${mdLineOne}
+ ${mdLineTwo}
+ """\n)`);
+ });
+
+ it("extracts highlighted Markdown code in middle", () => {
+ const mockEditor = createEditor(markdownCode);
+ switchLanguage(mockEditor, "markdown");
+ mockEditor.dispatch({
+ selection: {
+ anchor: mockEditor.state.doc.line(2).from,
+ head: mockEditor.state.doc.line(2).to,
+ },
+ });
+ const [highlighted, leftover] = getExtraction(mockEditor);
+ expect(highlighted).toEqual(`mo.md("""${mdLineTwo}""")`);
+ expect(leftover).toEqual(`mo.md(
+ """
+ ${mdLineOne}
+ ${mdLineThree}
+ """\n)`);
+ });
+
+ it("extracts highlighted Markdown code at end", () => {
+ const mockEditor = createEditor(markdownCode);
+ switchLanguage(mockEditor, "markdown");
+ mockEditor.dispatch({
+ selection: {
+ anchor: mockEditor.state.doc.line(3).from,
+ head: mockEditor.state.doc.line(3).to,
+ },
+ });
+ const [highlighted, leftover] = getExtraction(mockEditor);
+ expect(highlighted).toEqual(`mo.md("""${mdLineThree}""")`);
+ expect(leftover).toEqual(`mo.md(
+ """
+ ${mdLineOne}
+ ${mdLineTwo}
+ """\n)`);
+ });
+
+ it("extracts no highlighted Markdown code if none", () => {
+ const mockEditor = createEditor(markdownCode);
+ switchLanguage(mockEditor, "markdown");
+ mockEditor.dispatch({ selection: { anchor: 0, head: 0 } });
+ const result = extractHighlightedCode(mockEditor);
+ expect(result).toEqual(null);
+ });
+});
diff --git a/frontend/src/core/codemirror/language/utils.ts b/frontend/src/core/codemirror/language/utils.ts
index b316165779..264d1ebc79 100644
--- a/frontend/src/core/codemirror/language/utils.ts
+++ b/frontend/src/core/codemirror/language/utils.ts
@@ -69,3 +69,21 @@ export function splitEditor(editor: EditorView) {
afterCursorCode,
};
}
+
+export function extractHighlightedCode(editor: EditorView) {
+ const code = editor.state.doc.toString();
+ let { from, to } = editor.state.selection.main;
+ if (from === to) {
+ return null;
+ }
+ const highlighted = getEditorCodeAsPython(editor, from, to);
+
+ from = code[from - 1] === "\n" ? from - 1 : from;
+ to = code[to + 1] === "\n" ? to + 1 : to;
+ editor.dispatch({
+ changes: { from, to, insert: "" },
+ });
+
+ const leftover = getEditorCodeAsPython(editor);
+ return [highlighted, leftover];
+}