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: start cell editor in markdown if is markdown-compatible (#1401)

Myles Scolnick7fd3b4e63817
diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsx
index e38f226df1..501f606bee 100644
--- a/frontend/src/components/editor/cell/code/cell-editor.tsx
+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx
@@ -19,10 +19,11 @@ import { UserConfig } from "@/core/config/config-schema";
import { Theme } from "@/theme/useTheme";
import {
LanguageAdapters,
+ getInitialLanguageAdapter,
languageAdapterState,
reconfigureLanguageEffect,
+ switchLanguage,
} from "@/core/codemirror/language/extension";
-import { derefNotNull } from "@/utils/dereference";
import { LanguageToggle } from "./language-toggle";
import { cn } from "@/utils/cn";
import { saveCellConfig } from "@/core/network/requests";
@@ -82,7 +83,9 @@ const CellEditorInternal = ({
editorViewRef,
hidden,
}: CellEditorProps) => {
- const [canUseMarkdown, setCanUseMarkdown] = useState(false);
+ const [canUseMarkdown, setCanUseMarkdown] = useState(() => {
+ return LanguageAdapters.markdown().isSupported(code);
+ });
const [aiCompletionCell, setAiCompletionCell] = useAtom(aiCompletionCellAtom);
const [languageAdapter, setLanguageAdapter] =
useState<LanguageAdapter["type"]>();
@@ -238,6 +241,11 @@ const CellEditorInternal = ({
}),
});
shouldFocus = true;
+ // Initialize the language adapter
+ switchLanguage(
+ editorViewRef.current,
+ getInitialLanguageAdapter(editorViewRef.current.state).type,
+ );
} else {
editorViewRef.current.dispatch({
effects: [
@@ -261,6 +269,11 @@ const CellEditorInternal = ({
{ history: historyField },
),
});
+ // Initialize the language adapter
+ switchLanguage(
+ editorViewRef.current,
+ getInitialLanguageAdapter(editorViewRef.current.state).type,
+ );
shouldFocus = true;
// Clear the serialized state so that we don't re-create the editor next time
clearSerializedEditorState({ cellId });
@@ -286,6 +299,7 @@ const CellEditorInternal = ({
});
});
}
+
// We don't want to re-run this effect when `allowFocus` or `code` changes
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
@@ -339,10 +353,10 @@ const CellEditorInternal = ({
className="relative w-full"
onFocus={() => setLastFocusedCellId(cellId)}
>
- {canUseMarkdown && (
+ {canUseMarkdown && !hidden && (
<div className="absolute top-1 right-1">
<LanguageToggle
- editorView={derefNotNull(editorViewRef)}
+ editorView={editorViewRef.current}
languageAdapter={languageAdapter}
canUseMarkdown={canUseMarkdown}
/>
diff --git a/frontend/src/components/editor/cell/code/language-toggle.tsx b/frontend/src/components/editor/cell/code/language-toggle.tsx
index 0748bf5b8c..68b1ded80e 100644
--- a/frontend/src/components/editor/cell/code/language-toggle.tsx
+++ b/frontend/src/components/editor/cell/code/language-toggle.tsx
@@ -9,7 +9,7 @@ import { startCase } from "lodash-es";
import { LanguageAdapter } from "@/core/codemirror/language/types";
interface Props {
- editorView: EditorView;
+ editorView: EditorView | null;
canUseMarkdown: boolean;
languageAdapter: LanguageAdapter["type"] | undefined;
}
@@ -40,6 +40,9 @@ export const LanguageToggle: React.FC<Props> = ({
fill={"var(--sky-11)"}
fontSize={20}
onClick={() => {
+ if (!editorView) {
+ return;
+ }
switchLanguage(editorView, otherLanguage);
}}
/>
diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.ts
index a4a88fc52f..8f983637eb 100644
--- a/frontend/src/core/cells/cells.ts
+++ b/frontend/src/core/cells/cells.ts
@@ -156,15 +156,18 @@ const {
} = createReducerAndAtoms(initialNotebookState, {
createNewCell: (
state,
- action: { cellId: CellId | "__end__"; before: boolean; code?: string },
+ action: { cellId: CellId | "__end__"; before: boolean; code?: string, newCellId?: CellId},
) => {
const { cellId, before, code } = action;
+ let { newCellId } = action;
const index =
cellId === "__end__"
? state.cellIds.length - 1
: state.cellIds.indexOf(cellId);
const insertionIndex = before ? index : index + 1;
- const newCellId = CellId.create();
+ if (!newCellId) {
+ newCellId = CellId.create();
+ }
return {
...state,
diff --git a/frontend/src/core/codemirror/language/__tests__/markdown.test.ts b/frontend/src/core/codemirror/language/__tests__/markdown.test.ts
index eb48b6e979..0831f39e12 100644
--- a/frontend/src/core/codemirror/language/__tests__/markdown.test.ts
+++ b/frontend/src/core/codemirror/language/__tests__/markdown.test.ts
@@ -217,6 +217,9 @@ describe("MarkdownLanguageAdapter", () => {
it("should return true for supported markdown string formats", () => {
const pythonCode = 'mo.md("""# Markdown Title\n\nSome content here.""")';
expect(adapter.isSupported(pythonCode)).toBe(true);
+ expect(adapter.isSupported("mo.md()")).toBe(true);
+ expect(adapter.isSupported("mo.md('')")).toBe(true);
+ expect(adapter.isSupported('mo.md("")')).toBe(true);
});
it("should return false for unsupported string formats", () => {
diff --git a/frontend/src/core/codemirror/language/extension.ts b/frontend/src/core/codemirror/language/extension.ts
index 49d0bf429e..5e1f948c68 100644
--- a/frontend/src/core/codemirror/language/extension.ts
+++ b/frontend/src/core/codemirror/language/extension.ts
@@ -15,6 +15,7 @@ import { completionConfigState } from "../config/extension";
import { historyCompartment } from "../editing/extensions";
import { history } from "@codemirror/commands";
import { formattingChangeEffect } from "../format";
+import { getEditorCodeAsPython } from "./utils";
export const LanguageAdapters: Record<
LanguageAdapter["type"],
@@ -165,6 +166,20 @@ export function adaptiveLanguageConfiguration(
];
}
+export function getInitialLanguageAdapter(state: EditorView["state"]) {
+ const doc = getEditorCodeAsPython({ state });
+ // Empty doc defaults to Python
+ if (!doc.trim()) {
+ return LanguageAdapters.python();
+ }
+
+ if (LanguageAdapters.markdown().isSupported(doc)) {
+ return LanguageAdapters.markdown();
+ }
+
+ return LanguageAdapters.python();
+}
+
/**
* Switch the language of the editor.
*/
diff --git a/frontend/src/core/codemirror/language/markdown.ts b/frontend/src/core/codemirror/language/markdown.ts
index 0d376eb2ee..614ad63f31 100644
--- a/frontend/src/core/codemirror/language/markdown.ts
+++ b/frontend/src/core/codemirror/language/markdown.ts
@@ -91,6 +91,10 @@ export class MarkdownLanguageAdapter implements LanguageAdapter {
}
isSupported(pythonCode: string): boolean {
+ if (pythonCode.trim() === "mo.md()") {
+ return true;
+ }
+
const markdownLines = pythonCode
.trim()
.split("\n")
diff --git a/frontend/src/core/codemirror/language/utils.ts b/frontend/src/core/codemirror/language/utils.ts
index 72d79b6446..30d8447300 100644
--- a/frontend/src/core/codemirror/language/utils.ts
+++ b/frontend/src/core/codemirror/language/utils.ts
@@ -1,13 +1,14 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { EditorView } from "@codemirror/view";
import { languageAdapterState } from "./extension";
+import { EditorState } from "@codemirror/state";
/**
* Get the editor code as Python
* Handles when the editor has a different language adapter
*/
export function getEditorCodeAsPython(
- editor: EditorView,
+ editor: { state: EditorState},
fromPos?: number,
toPos?: number,
): string {