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: auto-import marimo for markdown (#1404)

Myles Scolnickfe2c2a54253b
diff --git a/frontend/src/components/editor/actions/useCellActionButton.tsx b/frontend/src/components/editor/actions/useCellActionButton.tsx
index b467a1067a..dac451f469 100644
--- a/frontend/src/components/editor/actions/useCellActionButton.tsx
+++ b/frontend/src/components/editor/actions/useCellActionButton.tsx
@@ -25,12 +25,12 @@ import {
EyeOffIcon,
SparklesIcon,
} from "lucide-react";
-import { ActionButton } from "./types";
+import type { ActionButton } from "./types";
import { MultiIcon } from "@/components/icons/multi-icon";
-import { CellConfig, CellData, CellStatus } from "@/core/cells/types";
-import { CellId } from "@/core/cells/ids";
+import type { CellConfig, CellData, CellStatus } from "@/core/cells/types";
+import type { CellId } from "@/core/cells/ids";
import { saveCellConfig } from "@/core/network/requests";
-import { EditorView } from "@codemirror/view";
+import type { EditorView } from "@codemirror/view";
import { useRunCell } from "../cell/useRunCells";
import { NameCellInput } from "./name-cell-input";
import { useAtomValue, useSetAtom } from "jotai";
@@ -43,8 +43,9 @@ import {
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { MarkdownIcon, PythonIcon } from "../cell/code/icons";
-import { aiEnabledAtom } from "@/core/config/config";
+import { aiEnabledAtom, autoInstantiateAtom } from "@/core/config/config";
import { useDeleteCellCallback } from "../cell/useDeleteCell";
+import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";
export interface CellActionButtonProps
extends Pick<CellData, "name" | "config"> {
@@ -75,6 +76,7 @@ export function useCellActionButtons({ cell }: Props) {
const { openModal } = useImperativeModal();
const setAiCompletionCell = useSetAtom(aiCompletionCellAtom);
const aiEnabled = useAtomValue(aiEnabledAtom);
+ const autoInstantiate = useAtomValue(autoInstantiateAtom);
if (!cell) {
return [];
}
@@ -206,6 +208,7 @@ export function useCellActionButtons({ cell }: Props) {
if (!editorView) {
return;
}
+ maybeAddMarimoImport(autoInstantiate, createCell);
toggleMarkdown(cellId, editorView, updateCellCode);
},
},
diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsx
index 501f606bee..f7509bba1d 100644
--- a/frontend/src/components/editor/cell/code/cell-editor.tsx
+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx
@@ -13,10 +13,14 @@ import React, {
import { setupCodeMirror } from "@/core/codemirror/cm";
import useEvent from "react-use-event-hook";
-import { CellActions, useCellActions } from "@/core/cells/cells";
-import { CellRuntimeState, CellData, CellConfig } from "@/core/cells/types";
-import { UserConfig } from "@/core/config/config-schema";
-import { Theme } from "@/theme/useTheme";
+import { type CellActions, useCellActions } from "@/core/cells/cells";
+import type {
+ CellRuntimeState,
+ CellData,
+ CellConfig,
+} from "@/core/cells/types";
+import type { UserConfig } from "@/core/config/config-schema";
+import type { Theme } from "@/theme/useTheme";
import {
LanguageAdapters,
getInitialLanguageAdapter,
@@ -29,11 +33,13 @@ import { cn } from "@/utils/cn";
import { saveCellConfig } from "@/core/network/requests";
import { HideCodeButton } from "../../code/readonly-python-code";
import { AiCompletionEditor } from "./ai-completion-editor";
-import { useAtom, useSetAtom } from "jotai";
+import { useAtom, useAtomValue, useSetAtom } from "jotai";
import { aiCompletionCellAtom } from "@/core/ai/state";
import { mergeRefs } from "@/utils/mergeRefs";
import { lastFocusedCellIdAtom } from "@/core/cells/focus";
-import { LanguageAdapter } from "@/core/codemirror/language/types";
+import type { LanguageAdapter } from "@/core/codemirror/language/types";
+import { autoInstantiateAtom } from "@/core/config/config";
+import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";
export interface CellEditorProps
extends Pick<CellRuntimeState, "status">,
@@ -137,6 +143,10 @@ const CellEditorInternal = ({
updateCellConfig({ cellId, config: newConfig });
return newConfig.hide_code || false;
});
+ const autoInstantiate = useAtomValue(autoInstantiateAtom);
+ const afterToggleMarkdown = useEvent(() => {
+ maybeAddMarimoImport(autoInstantiate, createNewCell);
+ });
const extensions = useMemo(() => {
const extensions = setupCodeMirror({
@@ -145,6 +155,7 @@ const CellEditorInternal = ({
enableAI: Boolean(userConfig.ai.open_ai?.api_key),
cellCodeCallbacks: {
updateCellCode,
+ afterToggleMarkdown,
},
cellMovementCallbacks: {
onRun: runCell,
@@ -224,6 +235,7 @@ const CellEditorInternal = ({
handleDelete,
runCell,
setAiCompletionCell,
+ afterToggleMarkdown,
]);
useEffect(() => {
@@ -359,6 +371,7 @@ const CellEditorInternal = ({
editorView={editorViewRef.current}
languageAdapter={languageAdapter}
canUseMarkdown={canUseMarkdown}
+ onAfterToggleMarkdown={afterToggleMarkdown}
/>
</div>
)}
diff --git a/frontend/src/components/editor/cell/code/language-toggle.tsx b/frontend/src/components/editor/cell/code/language-toggle.tsx
index 68b1ded80e..25bf059342 100644
--- a/frontend/src/components/editor/cell/code/language-toggle.tsx
+++ b/frontend/src/components/editor/cell/code/language-toggle.tsx
@@ -1,23 +1,25 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { switchLanguage } from "@/core/codemirror/language/extension";
-import { EditorView } from "@codemirror/view";
-import React from "react";
+import type { EditorView } from "@codemirror/view";
+import type React from "react";
import { MarkdownIcon, PythonIcon } from "./icons";
import { Button } from "@/components/ui/button";
import { Tooltip } from "@/components/ui/tooltip";
import { startCase } from "lodash-es";
-import { LanguageAdapter } from "@/core/codemirror/language/types";
+import type { LanguageAdapter } from "@/core/codemirror/language/types";
interface Props {
editorView: EditorView | null;
canUseMarkdown: boolean;
languageAdapter: LanguageAdapter["type"] | undefined;
+ onAfterToggleMarkdown: () => void;
}
export const LanguageToggle: React.FC<Props> = ({
editorView,
languageAdapter,
canUseMarkdown,
+ onAfterToggleMarkdown,
}) => {
if (!canUseMarkdown && languageAdapter !== "markdown") {
return null;
@@ -44,6 +46,7 @@ export const LanguageToggle: React.FC<Props> = ({
return;
}
switchLanguage(editorView, otherLanguage);
+ onAfterToggleMarkdown();
}}
/>
</Button>
diff --git a/frontend/src/core/cells/__tests__/add-missing-import.test.ts b/frontend/src/core/cells/__tests__/add-missing-import.test.ts
new file mode 100644
index 0000000000..9adfa35d80
--- /dev/null
+++ b/frontend/src/core/cells/__tests__/add-missing-import.test.ts
@@ -0,0 +1,61 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { variablesAtom } from "@/core/variables/state";
+import { createStore } from "jotai";
+import { it, describe, expect, vi } from "vitest";
+import { maybeAddMissingImport } from "../add-missing-import";
+import type { Variables } from "@/core/variables/types";
+import { type NotebookState, notebookAtom } from "../cells";
+import type { CellId } from "../ids";
+import type { CellData } from "../types";
+
+const CELL_IDS = ["1" as CellId];
+
+describe("maybeAddMissingImport", () => {
+ it("should not add an import if the variable is already in the variables state", () => {
+ const appStore = createStore();
+ appStore.set(variablesAtom, { mo: {} } as Variables);
+ const onAddImport = vi.fn();
+ maybeAddMissingImport("marimo", "mo", onAddImport, appStore);
+ expect(onAddImport).not.toHaveBeenCalled();
+ });
+
+ const VALID_IMPORTS = [
+ "import marimo as mo",
+ "import marimo as mo\nimport marimo as mo",
+ "import marimo as mo",
+ ];
+ it.each(VALID_IMPORTS)(
+ "should not add an import if the import statement already exists in the notebook",
+ (code) => {
+ const appStore = createStore();
+ appStore.set(variablesAtom, {} as Variables);
+ appStore.set(notebookAtom, {
+ cellData: {
+ ["1" as CellId]: {
+ code: code,
+ } as CellData,
+ },
+ cellIds: CELL_IDS,
+ } as NotebookState);
+ const onAddImport = vi.fn();
+ maybeAddMissingImport("marimo", "mo", onAddImport, appStore);
+ expect(onAddImport).not.toHaveBeenCalled();
+ },
+ );
+
+ it("should add an import if the variable is not in the variables state and the import statement does not exist in the notebook", () => {
+ const appStore = createStore();
+ appStore.set(variablesAtom, {} as Variables);
+ appStore.set(notebookAtom, {
+ cellData: {
+ ["1" as CellId]: {
+ code: "mo.md('hello')",
+ } as CellData,
+ },
+ cellIds: CELL_IDS,
+ } as NotebookState);
+ const onAddImport = vi.fn();
+ maybeAddMissingImport("marimo", "mo", onAddImport, appStore);
+ expect(onAddImport).toHaveBeenCalledWith("import marimo as mo");
+ });
+});
diff --git a/frontend/src/core/cells/add-missing-import.ts b/frontend/src/core/cells/add-missing-import.ts
new file mode 100644
index 0000000000..6e18031156
--- /dev/null
+++ b/frontend/src/core/cells/add-missing-import.ts
@@ -0,0 +1,62 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { sendRun } from "../network/requests";
+import { store } from "../state/jotai";
+import { variablesAtom } from "../variables/state";
+import { type CellActions, notebookAtom } from "./cells";
+import { CellId } from "./ids";
+
+/**
+ * Checks if any Python imports are missing from the current file and adds them if necessary.
+ * @param moduleName The name of the module to import.
+ * @param variableName The name of the variable to import.
+ */
+export function maybeAddMissingImport(
+ moduleName: string,
+ variableName: string,
+ onAddImport: (importStatement: string) => void,
+ appStore: typeof store = store,
+): boolean {
+ // If variableName is already in the variables state,
+ // then the import is not missing (or the name has been taken).
+ const variables = appStore.get(variablesAtom);
+ if (variableName in variables) {
+ return false;
+ }
+
+ // Check if the import statement already exists in the notebook.
+ const { cellData, cellIds } = appStore.get(notebookAtom);
+ const regex = new RegExp(
+ `import[ \t]+${moduleName}[ \t]+as[ \t]+${variableName}`,
+ "g",
+ );
+ for (const cell of cellIds) {
+ if (regex.test(cellData[cell].code)) {
+ return false;
+ }
+ }
+
+ const importStatement = `import ${moduleName} as ${variableName}`;
+ onAddImport(importStatement);
+
+ return true;
+}
+
+export function maybeAddMarimoImport(
+ autoRun: boolean,
+ createNewCell: CellActions["createNewCell"],
+): boolean {
+ return maybeAddMissingImport("marimo", "mo", (importStatement) => {
+ const cellId = CellId.create();
+ createNewCell({
+ cellId: "__end__",
+ before: false,
+ code: importStatement,
+ lastCodeRun: autoRun ? importStatement : undefined,
+ newCellId: cellId,
+ autoFocus: false,
+ });
+ if (autoRun) {
+ void sendRun([cellId], [importStatement]);
+ }
+ });
+}
diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.ts
index 8f983637eb..64731e8d7b 100644
--- a/frontend/src/core/cells/cells.ts
+++ b/frontend/src/core/cells/cells.ts
@@ -1,11 +1,11 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { atom, useAtom, useAtomValue } from "jotai";
-import { ReducerWithoutAction, createRef } from "react";
-import { CellMessage } from "../kernel/messages";
+import { type ReducerWithoutAction, createRef } from "react";
+import type { CellMessage } from "../kernel/messages";
import {
- CellConfig,
- CellRuntimeState,
- CellData,
+ type CellConfig,
+ type CellRuntimeState,
+ type CellData,
createCell,
createCellRuntimeState,
} from "./types";
@@ -22,16 +22,16 @@ import { createReducerAndAtoms } from "../../utils/createReducer";
import { arrayInsert, arrayDelete } from "@/utils/arrays";
import { foldAllBulk, unfoldAllBulk } from "../codemirror/editing/commands";
import { mergeOutlines } from "../dom/outline";
-import { CellHandle } from "@/components/editor/Cell";
+import type { CellHandle } from "@/components/editor/Cell";
import { Logger } from "@/utils/Logger";
import { Objects } from "@/utils/objects";
import { splitAtom, selectAtom } from "jotai/utils";
import { isStaticNotebook, parseStaticState } from "../static/static-state";
-import { CellLog, getCellLogsForMessage } from "./logs";
+import { type CellLog, getCellLogsForMessage } from "./logs";
import { deserializeBase64, deserializeJson } from "@/utils/json/base64";
import { historyField } from "@codemirror/commands";
import { clamp } from "@/utils/math";
-import { LayoutState } from "../layout/layout";
+import type { LayoutState } from "../layout/layout";
import { notebookIsRunning } from "./utils";
import {
getEditorCodeAsPython,
@@ -156,18 +156,28 @@ const {
} = createReducerAndAtoms(initialNotebookState, {
createNewCell: (
state,
- action: { cellId: CellId | "__end__"; before: boolean; code?: string, newCellId?: CellId},
+ action: {
+ cellId: CellId | "__end__";
+ before: boolean;
+ code?: string;
+ lastCodeRun?: string;
+ newCellId?: CellId;
+ autoFocus?: boolean;
+ },
) => {
- const { cellId, before, code } = action;
- let { newCellId } = action;
+ const {
+ cellId,
+ before,
+ code,
+ lastCodeRun = null,
+ autoFocus = true,
+ } = action;
+ const newCellId = action.newCellId || CellId.create();
const index =
cellId === "__end__"
? state.cellIds.length - 1
: state.cellIds.indexOf(cellId);
const insertionIndex = before ? index : index + 1;
- if (!newCellId) {
- newCellId = CellId.create();
- }
return {
...state,
@@ -177,7 +187,8 @@ const {
[newCellId]: createCell({
id: newCellId,
code,
- edited: Boolean(code),
+ lastCodeRun,
+ edited: Boolean(code) && code !== lastCodeRun,
}),
},
cellRuntime: {
@@ -188,7 +199,7 @@ const {
...state.cellHandles,
[newCellId]: createRef(),
},
- scrollKey: newCellId,
+ scrollKey: autoFocus ? newCellId : null,
};
},
moveCell: (state, action: { cellId: CellId; before: boolean }) => {
@@ -201,7 +212,8 @@ const {
cellIds: [cell, ...state.cellIds.slice(1)],
scrollKey: cellId,
};
- } else if (!before && index === state.cellIds.length - 1) {
+ }
+ if (!before && index === state.cellIds.length - 1) {
return {
...state,
cellIds: [...state.cellIds.slice(0, -1), cell],
@@ -329,40 +341,40 @@ const {
undoDeleteCell: (state) => {
if (state.history.length === 0) {
return state;
- } else {
- const mostRecentlyDeleted = state.history[state.history.length - 1];
-
- const {
- name,
- serializedEditorState = { doc: "" },
- index,
- } = mostRecentlyDeleted;
- const cellId = CellId.create();
- const undoCell = createCell({
- id: cellId,
- name,
- code: serializedEditorState.doc,
- edited: serializedEditorState.doc.trim().length > 0,
- serializedEditorState,
- });
- return {
- ...state,
- cellIds: arrayInsert(state.cellIds, index, cellId),
- cellData: {
- ...state.cellData,
- [cellId]: undoCell,
- },
- cellRuntime: {
- ...state.cellRuntime,
- [cellId]: createCellRuntimeState(),
- },
- cellHandles: {
- ...state.cellHandles,
- [cellId]: createRef(),
- },
- history: state.history.slice(0, -1),
- };
}
+
+ const mostRecentlyDeleted = state.history[state.history.length - 1];
+
+ const {
+ name,
+ serializedEditorState = { doc: "" },
+ index,
+ } = mostRecentlyDeleted;
+ const cellId = CellId.create();
+ const undoCell = createCell({
+ id: cellId,
+ name,
+ code: serializedEditorState.doc,
+ edited: serializedEditorState.doc.trim().length > 0,
+ serializedEditorState,
+ });
+ return {
+ ...state,
+ cellIds: arrayInsert(state.cellIds, index, cellId),
+ cellData: {
+ ...state.cellData,
+ [cellId]: undoCell,
+ },
+ cellRuntime: {
+ ...state.cellRuntime,
+ [cellId]: createCellRuntimeState(),
+ },
+ cellHandles: {
+ ...state.cellHandles,
+ [cellId]: createRef(),
+ },
+ history: state.history.slice(0, -1),
+ };
},
clearSerializedEditorState: (state, action: { cellId: CellId }) => {
const { cellId } = action;
@@ -530,7 +542,9 @@ const {
};
// Create a new cell at the beginning; again, no need to update
// scrollKey
- } else if (nextCellIndex === -1 && !noCreate) {
+ }
+
+ if (nextCellIndex === -1 && !noCreate) {
const newCellId = CellId.create();
return {
...state,
@@ -548,47 +562,47 @@ const {
[newCellId]: createRef(),
},
};
- } else {
- const nextCellId = state.cellIds[nextCellIndex];
- // Just focus, no state change
- focusAndScrollCellIntoView({
- cellId: nextCellId,
- cell: state.cellHandles[nextCellId],
- config: state.cellData[nextCellId].config,
- codeFocus: before ? "bottom" : "top",
- });
- return state;
}
+
+ const nextCellId = state.cellIds[nextCellIndex];
+ // Just focus, no state change
+ focusAndScrollCellIntoView({
+ cellId: nextCellId,
+ cell: state.cellHandles[nextCellId],
+ config: state.cellData[nextCellId].config,
+ codeFocus: before ? "bottom" : "top",
+ });
+ return state;
},
scrollToTarget: (state) => {
// Scroll to the specified cell and clear the scroll key.
const scrollKey = state.scrollKey;
if (scrollKey === null) {
return state;
- } else {
- const index = state.cellIds.indexOf(scrollKey);
-
- // Special-case scrolling to the end of the page: bug in Chrome where
- // browser fails to scrollIntoView an element at the end of a long page
- if (index === state.cellIds.length - 1) {
- const cellId = state.cellIds[state.cellIds.length - 1];
- state.cellHandles[cellId].current?.editorView.focus();
- scrollToBottom();
- } else {
- const nextCellId = state.cellIds[index];
- focusAndScrollCellIntoView({
- cellId: nextCellId,
- cell: state.cellHandles[nextCellId],
- config: state.cellData[nextCellId].config,
- codeFocus: undefined,
- });
- }
+ }
- return {
- ...state,
- scrollKey: null,
- };
+ const index = state.cellIds.indexOf(scrollKey);
+
+ // Special-case scrolling to the end of the page: bug in Chrome where
+ // browser fails to scrollIntoView an element at the end of a long page
+ if (index === state.cellIds.length - 1) {
+ const cellId = state.cellIds[state.cellIds.length - 1];
+ state.cellHandles[cellId].current?.editorView.focus();
+ scrollToBottom();
+ } else {
+ const nextCellId = state.cellIds[index];
+ focusAndScrollCellIntoView({
+ cellId: nextCellId,
+ cell: state.cellHandles[nextCellId],
+ config: state.cellData[nextCellId].config,
+ codeFocus: undefined,
+ });
}
+
+ return {
+ ...state,
+ scrollKey: null,
+ };
},
foldAll: (state) => {
const targets = Object.values(state.cellHandles).map(
diff --git a/frontend/src/core/codemirror/__tests__/setup.test.ts b/frontend/src/core/codemirror/__tests__/setup.test.ts
index c03433c835..e4385e73ac 100644
--- a/frontend/src/core/codemirror/__tests__/setup.test.ts
+++ b/frontend/src/core/codemirror/__tests__/setup.test.ts
@@ -1,9 +1,9 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { describe, expect, test, vi } from "vitest";
-import { CodeMirrorSetupOpts, setupCodeMirror } from "../cm";
-import { EditorState, Extension } from "@codemirror/state";
+import { type CodeMirrorSetupOpts, setupCodeMirror } from "../cm";
+import { EditorState, type Extension } from "@codemirror/state";
import { keymap } from "@codemirror/view";
-import { CellId } from "@/core/cells/ids";
+import type { CellId } from "@/core/cells/ids";
import { Objects } from "@/utils/objects";
vi.mock("@/core/config/config", () => ({
@@ -40,6 +40,7 @@ function setup(config: Partial<CodeMirrorSetupOpts> = {}): Extension[] {
},
cellCodeCallbacks: {
updateCellCode: namedFunction("updateCellCode"),
+ afterToggleMarkdown: namedFunction("afterToggleMarkdown"),
},
completionConfig: {
activate_on_typing: false,
diff --git a/frontend/src/core/codemirror/cells/extensions.ts b/frontend/src/core/codemirror/cells/extensions.ts
index 3cfed77918..6d509a0493 100644
--- a/frontend/src/core/codemirror/cells/extensions.ts
+++ b/frontend/src/core/codemirror/cells/extensions.ts
@@ -1,10 +1,10 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { HOTKEYS } from "@/core/hotkeys/hotkeys";
-import { EditorView, KeyBinding, keymap } from "@codemirror/view";
-import { CellId, HTMLCellId } from "@/core/cells/ids";
-import { Extension, Prec } from "@codemirror/state";
+import { EditorView, type KeyBinding, keymap } from "@codemirror/view";
+import { type CellId, HTMLCellId } from "@/core/cells/ids";
+import { type Extension, Prec } from "@codemirror/state";
import { formatKeymapExtension } from "../extensions";
-import { CellActions } from "@/core/cells/cells";
+import type { CellActions } from "@/core/cells/cells";
import { getEditorCodeAsPython } from "../language/utils";
import { formattingChangeEffect } from "../format";
import { closeCompletion, completionStatus } from "@codemirror/autocomplete";
@@ -263,6 +263,7 @@ export function cellMovementBundle(
export interface CodeCallbacks {
updateCellCode: CellActions["updateCellCode"];
+ afterToggleMarkdown: () => void;
}
/**
@@ -290,5 +291,5 @@ export function cellCodeEditingBundle(
}
});
- return [onChangePlugin, formatKeymapExtension(cellId, updateCellCode)];
+ return [onChangePlugin, formatKeymapExtension(cellId, callbacks)];
}
diff --git a/frontend/src/core/codemirror/extensions.ts b/frontend/src/core/codemirror/extensions.ts
index a0b43d65db..fb8d23598a 100644
--- a/frontend/src/core/codemirror/extensions.ts
+++ b/frontend/src/core/codemirror/extensions.ts
@@ -1,19 +1,20 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { EditorView, keymap } from "@codemirror/view";
-import { CellId } from "../cells/ids";
+import type { CellId } from "../cells/ids";
import { formatEditorViews, toggleMarkdown } from "./format";
import { smartScrollIntoView } from "../../utils/scroll";
import { HOTKEYS } from "@/core/hotkeys/hotkeys";
-import { CellActions } from "../cells/cells";
import { invariant } from "@/utils/invariant";
+import type { CodeCallbacks } from "./cells/extensions";
/**
* Add a keymap to format the code in the editor.
*/
export function formatKeymapExtension(
cellId: CellId,
- updateCellCode: CellActions["updateCellCode"],
+ callbacks: CodeCallbacks,
) {
+ const { updateCellCode, afterToggleMarkdown } = callbacks;
return keymap.of([
{
key: HOTKEYS.getHotkey("cell.format").key,
@@ -27,8 +28,11 @@ export function formatKeymapExtension(
key: HOTKEYS.getHotkey("cell.viewAsMarkdown").key,
preventDefault: true,
run: (ev) => {
- toggleMarkdown(cellId, ev, updateCellCode);
- return true;
+ const response = toggleMarkdown(cellId, ev, updateCellCode);
+ if (response === "markdown") {
+ afterToggleMarkdown();
+ }
+ return response !== false;
},
},
]);
diff --git a/frontend/src/core/codemirror/format.ts b/frontend/src/core/codemirror/format.ts
index a047354e77..c83c4a9993 100644
--- a/frontend/src/core/codemirror/format.ts
+++ b/frontend/src/core/codemirror/format.ts
@@ -1,9 +1,10 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { EditorView } from "@codemirror/view";
-import { CellId } from "../cells/ids";
+
+import type { EditorView } from "@codemirror/view";
+import type { CellId } from "../cells/ids";
import { Objects } from "../../utils/objects";
import { sendFormat } from "../network/requests";
-import { CellActions, getNotebook } from "../cells/cells";
+import { type CellActions, getNotebook } from "../cells/cells";
import { notebookCellEditorViews } from "../cells/utils";
import {
getEditorCodeAsPython,
@@ -16,7 +17,7 @@ import {
languageAdapterState,
switchLanguage,
} from "./language/extension";
-import { LanguageAdapter } from "./language/types";
+import type { LanguageAdapter } from "./language/types";
export const formattingChangeEffect = StateEffect.define<boolean>();
@@ -86,16 +87,17 @@ export function toggleMarkdown(
cellId: CellId,
editorView: EditorView,
updateCellCode: CellActions["updateCellCode"],
-) {
+): "python" | "markdown" | false {
// If already in markdown mode, switch to python
if (getEditorViewMode(editorView) === "markdown") {
switchLanguage(editorView, "python");
- return;
+ return "python";
}
if (!canToggleMarkdown(editorView)) {
- return;
+ return false;
}
+
if (getEditorCodeAsPython(editorView).trim() === "") {
const blankMd = 'mo.md(rf"")';
updateCellCode({
@@ -105,5 +107,7 @@ export function toggleMarkdown(
});
updateEditorCodeFromPython(editorView, blankMd);
}
+
switchLanguage(editorView, "markdown");
+ return "markdown";
}
diff --git a/frontend/src/core/codemirror/language/utils.ts b/frontend/src/core/codemirror/language/utils.ts
index 30d8447300..14a36365b4 100644
--- a/frontend/src/core/codemirror/language/utils.ts
+++ b/frontend/src/core/codemirror/language/utils.ts
@@ -8,7 +8,7 @@ import { EditorState } from "@codemirror/state";
* Handles when the editor has a different language adapter
*/
export function getEditorCodeAsPython(
- editor: { state: EditorState},
+ editor: { state: EditorState },
fromPos?: number,
toPos?: number,
): string {
diff --git a/frontend/src/core/config/config.ts b/frontend/src/core/config/config.ts
index 5c1e6b5a56..37ff8d3b76 100644
--- a/frontend/src/core/config/config.ts
+++ b/frontend/src/core/config/config.ts
@@ -1,8 +1,8 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { atom, useAtom, useSetAtom } from "jotai";
import {
- AppConfig,
- UserConfig,
+ type AppConfig,
+ type UserConfig,
parseAppConfig,
parseUserConfig,
} from "./config-schema";
@@ -13,6 +13,10 @@ import { store } from "../state/jotai";
*/
export const userConfigAtom = atom<UserConfig>(parseUserConfig());
+export const autoInstantiateAtom = atom((get) => {
+ return get(userConfigAtom).runtime.auto_instantiate;
+});
+
/**
* Returns the user config.
*/
diff --git a/frontend/src/core/variables/state.ts b/frontend/src/core/variables/state.ts
index 64c48df258..e955815499 100644
--- a/frontend/src/core/variables/state.ts
+++ b/frontend/src/core/variables/state.ts
@@ -1,7 +1,7 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { createReducerAndAtoms } from "@/utils/createReducer";
-import { Variable, VariableName, Variables } from "./types";
+import type { Variable, VariableName, Variables } from "./types";
import { useAtomValue } from "jotai";
function initialState(): Variables {
@@ -68,6 +68,8 @@ export function useVariablesActions() {
return useActions();
}
+export { variablesAtom };
+
export const exportedForTesting = {
reducer,
createActions,