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.

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

Akshay Agrawal3f2d45234817
diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsx
index c833a9c926..cc2b9d49d9 100644
--- a/frontend/src/components/editor/Cell.tsx
+++ b/frontend/src/components/editor/Cell.tsx
@@ -243,22 +243,12 @@ const CellComponent = (
const createBelow = useCallback(
(opts: { code?: string } = {}) =>
- createNewCell({
- cellId,
- before: false,
- ...opts,
- includeSelectionAsInitialCode: true,
- }),
+ createNewCell({ cellId, before: false, ...opts }),
[cellId, createNewCell],
);
const createAbove = useCallback(
(opts: { code?: string } = {}) =>
- createNewCell({
- cellId,
- before: true,
- ...opts,
- includeSelectionAsInitialCode: true,
- }),
+ createNewCell({ cellId, before: true, ...opts }),
[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 db0bb695a2..c64a634433 100644
--- a/frontend/src/components/editor/cell/code/cell-editor.tsx
+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx
@@ -107,21 +107,11 @@ const CellEditorInternal = ({
});
const createBelow = useCallback(
- () =>
- createNewCell({
- cellId,
- before: false,
- includeSelectionAsInitialCode: true,
- }),
+ () => createNewCell({ cellId, before: false }),
[cellId, createNewCell],
);
const createAbove = useCallback(
- () =>
- createNewCell({
- cellId,
- before: true,
- includeSelectionAsInitialCode: true,
- }),
+ () => createNewCell({ cellId, before: 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 3fb79c4a46..57fb1cc1d6 100644
--- a/frontend/src/core/cells/__tests__/cells.test.ts
+++ b/frontend/src/core/cells/__tests__/cells.test.ts
@@ -50,9 +50,7 @@ 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) {
@@ -1335,130 +1333,4 @@ 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 7fb5b688f9..c6e9da8a90 100644
--- a/frontend/src/core/cells/cells.ts
+++ b/frontend/src/core/cells/cells.ts
@@ -31,7 +31,6 @@ import { clamp } from "@/utils/math";
import type { LayoutState } from "../layout/layout";
import { notebookIsRunning, notebookQueueOrRunningCount } from "./utils";
import {
- extractHighlightedCode,
splitEditor,
updateEditorCodeFromPython,
} from "../codemirror/language/utils";
@@ -46,7 +45,6 @@ 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;
@@ -199,7 +197,6 @@ const {
lastExecutionTime?: number;
newCellId?: CellId;
autoFocus?: boolean;
- includeSelectionAsInitialCode?: boolean;
},
) => {
const {
@@ -209,7 +206,6 @@ const {
lastCodeRun = null,
lastExecutionTime = null,
autoFocus = true,
- includeSelectionAsInitialCode,
} = action;
const newCellId = action.newCellId || CellId.create();
const index =
@@ -218,29 +214,6 @@ 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),
@@ -248,10 +221,10 @@ const {
...state.cellData,
[newCellId]: createCell({
id: newCellId,
- code: newCellCode,
+ code,
lastCodeRun,
lastExecutionTime,
- edited: Boolean(newCellCode) && newCellCode !== lastCodeRun,
+ edited: Boolean(code) && code !== lastCodeRun,
}),
},
cellRuntime: {
@@ -1061,13 +1034,9 @@ export const getAllEditorViews = () => {
.filter(Boolean);
};
-export const getCellEditorView = (cellId: CellId): EditorView | undefined => {
+export const getCellEditorView = (cellId: CellId) => {
const { cellHandles } = store.get(notebookAtom);
- const cellHandle = cellHandles[cellId];
- if (!cellHandle) {
- return;
- }
- return cellHandle.current?.editorView;
+ return cellHandles[cellId].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 ebc3dfc3db..389aa0d5e9 100644
--- a/frontend/src/core/codemirror/language/__tests__/utils.test.ts
+++ b/frontend/src/core/codemirror/language/__tests__/utils.test.ts
@@ -3,16 +3,13 @@ import {
getEditorCodeAsPython,
updateEditorCodeFromPython,
splitEditor,
- extractHighlightedCode,
} from "../utils";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
-import { describe, it, expect, beforeAll } from "vitest";
+import { describe, it, expect } 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({
@@ -150,219 +147,3 @@ 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 264d1ebc79..b316165779 100644
--- a/frontend/src/core/codemirror/language/utils.ts
+++ b/frontend/src/core/codemirror/language/utils.ts
@@ -69,21 +69,3 @@ 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];
-}