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.

fix: allow converting to markdown when empty (#1588)

Myles Scolnick192c021bc2ca
diff --git a/frontend/src/components/editor/RecoveryButton.tsx b/frontend/src/components/editor/RecoveryButton.tsx
index dd6b3109ff..a8f5dc0b8e 100644
--- a/frontend/src/components/editor/RecoveryButton.tsx
+++ b/frontend/src/components/editor/RecoveryButton.tsx
@@ -44,7 +44,10 @@ const RecoveryModal = (props: {
<DialogTitle className="text-accent mb-6">
Download unsaved changes?
</DialogTitle>
- <DialogDescription className="markdown">
+ <DialogDescription
+ className="markdown break-words"
+ style={{ wordBreak: "break-word" }}
+ >
<p>This app has unsaved changes. To recover:</p>
<ol>
diff --git a/frontend/src/components/editor/renderers/vertical-layout/useDelayVisibility.ts b/frontend/src/components/editor/renderers/vertical-layout/useDelayVisibility.ts
index 63db445a3e..67734b8769 100644
--- a/frontend/src/components/editor/renderers/vertical-layout/useDelayVisibility.ts
+++ b/frontend/src/components/editor/renderers/vertical-layout/useDelayVisibility.ts
@@ -1,6 +1,6 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { AppMode } from "@/core/mode";
-import { getAllEditorViews } from "@/core/cells/cells";
+import { getNotebook } from "@/core/cells/cells";
import { useState, useEffect } from "react";
export function useDelayVisibility(numCells: number, mode: AppMode) {
@@ -28,8 +28,14 @@ export function useDelayVisibility(numCells: number, mode: AppMode) {
}
function focusFirstEditor() {
- const editors = getAllEditorViews();
- if (editors.length > 0) {
- editors[0].focus();
+ const { cellIds, cellData, cellHandles } = getNotebook();
+ // Focus on the first cell if it's been mounted and is not hidden
+ for (const cellId of cellIds) {
+ const handle = cellHandles[cellId];
+ const hidden = cellData[cellId].config.hide_code;
+ if (!hidden && handle?.current?.editorView) {
+ handle.current.editorView.focus();
+ return;
+ }
}
}
diff --git a/frontend/src/components/ui/dialog.tsx b/frontend/src/components/ui/dialog.tsx
index 0ab9553d15..20d61d8a61 100644
--- a/frontend/src/components/ui/dialog.tsx
+++ b/frontend/src/components/ui/dialog.tsx
@@ -56,7 +56,7 @@ const DialogContent = React.forwardRef<
<DialogPrimitive.Content
ref={ref}
className={cn(
- "fixed z-50 grid w-full gap-4 rounded-b-lg border bg-background p-6 shadow-sm animate-in data-[state=open]:fade-in-90 data-[state=open]:slide-in-from-bottom-10 sm:max-w-lg sm:rounded-lg sm:zoom-in-90 data-[state=open]:sm:slide-in-from-bottom-0",
+ "fixed z-50 grid w-full gap-4 rounded-b-lg border bg-background p-6 shadow-sm animate-in data-[state=open]:fade-in-90 data-[state=open]:slide-in-from-bottom-10 sm:max-w-2xl sm:mx-4 sm:rounded-lg sm:zoom-in-90 data-[state=open]:sm:slide-in-from-bottom-0",
className,
)}
{...restoreFocus}
diff --git a/frontend/src/core/codemirror/__tests__/setup.test.ts b/frontend/src/core/codemirror/__tests__/setup.test.ts
index 065b43c53a..5643d7be26 100644
--- a/frontend/src/core/codemirror/__tests__/setup.test.ts
+++ b/frontend/src/core/codemirror/__tests__/setup.test.ts
@@ -6,6 +6,7 @@ import { keymap } from "@codemirror/view";
import type { CellId } from "@/core/cells/ids";
import { Objects } from "@/utils/objects";
import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";
+import { PythonLanguageAdapter } from "../language/python";
vi.mock("@/core/config/config", () => ({
parseAppConfig: () => ({}),
@@ -18,8 +19,8 @@ function namedFunction(name: string) {
return fn;
}
-function setup(config: Partial<CodeMirrorSetupOpts> = {}): Extension[] {
- return setupCodeMirror({
+function getOpts() {
+ return {
cellId: "0" as CellId,
showPlaceholder: false,
enableAI: false,
@@ -53,8 +54,11 @@ function setup(config: Partial<CodeMirrorSetupOpts> = {}): Extension[] {
},
hotkeys: new OverridingHotkeyProvider({}),
theme: "light",
- ...config,
- });
+ } as const;
+}
+
+function setup(config: Partial<CodeMirrorSetupOpts> = {}): Extension[] {
+ return setupCodeMirror({ ...getOpts(), ...config });
}
function prettyPrintKeymaps(state: EditorState) {
@@ -115,13 +119,43 @@ describe("snapshot all duplicate keymaps", () => {
});
test("placeholder adds another extension", () => {
- const withPlaceholder = setup({ showPlaceholder: true }).flat();
- const withoutPlaceholder = setup({ showPlaceholder: false }).flat();
- expect(withPlaceholder.length - 1).toBe(withoutPlaceholder.length);
+ const opts = getOpts();
+ const withAI = new PythonLanguageAdapter()
+ .getExtension(
+ opts.completionConfig,
+ opts.hotkeys,
+ "marimo-import",
+ opts.cellMovementCallbacks,
+ )
+ .flat();
+ const withoutAI = new PythonLanguageAdapter()
+ .getExtension(
+ opts.completionConfig,
+ opts.hotkeys,
+ "none",
+ opts.cellMovementCallbacks,
+ )
+ .flat();
+ expect(withAI.length - 1).toBe(withoutAI.length);
});
test("ai adds more extensions", () => {
- const withAI = setup({ enableAI: true }).flat();
- const withoutAI = setup({ enableAI: false }).flat();
+ const opts = getOpts();
+ const withAI = new PythonLanguageAdapter()
+ .getExtension(
+ opts.completionConfig,
+ opts.hotkeys,
+ "ai",
+ opts.cellMovementCallbacks,
+ )
+ .flat();
+ const withoutAI = new PythonLanguageAdapter()
+ .getExtension(
+ opts.completionConfig,
+ opts.hotkeys,
+ "none",
+ opts.cellMovementCallbacks,
+ )
+ .flat();
expect(withAI.length - 2).toBe(withoutAI.length);
});
diff --git a/frontend/src/core/codemirror/cm.ts b/frontend/src/core/codemirror/cm.ts
index 4fb22312cc..5bf9d066bc 100644
--- a/frontend/src/core/codemirror/cm.ts
+++ b/frontend/src/core/codemirror/cm.ts
@@ -54,10 +54,6 @@ import { copilotBundle } from "./copilot/extension";
import { hintTooltip } from "./completion/hints";
import { adaptiveLanguageConfiguration } from "./language/extension";
import { historyCompartment } from "./editing/extensions";
-import {
- clickablePlaceholderExtension,
- smartPlaceholderExtension,
-} from "./placeholder/extensions";
import { goToDefinitionBundle } from "./go-to-definition/extension";
import { HotkeyProvider } from "../hotkeys/hotkeys";
@@ -76,17 +72,15 @@ export interface CodeMirrorSetupOpts {
/**
* Setup CodeMirror for a cell
*/
-export const setupCodeMirror = ({
- cellId,
- showPlaceholder,
- enableAI,
- cellMovementCallbacks,
- cellCodeCallbacks,
- completionConfig,
- keymapConfig,
- theme,
- hotkeys,
-}: CodeMirrorSetupOpts): Extension[] => {
+export const setupCodeMirror = (opts: CodeMirrorSetupOpts): Extension[] => {
+ const {
+ cellId,
+ cellMovementCallbacks,
+ cellCodeCallbacks,
+ keymapConfig,
+ hotkeys,
+ } = opts;
+
return [
// Editor keymaps (vim or defaults) based on user config
keymapBundle(keymapConfig, cellMovementCallbacks),
@@ -94,19 +88,9 @@ export const setupCodeMirror = ({
cellMovementBundle(cellId, cellMovementCallbacks, hotkeys),
cellCodeEditingBundle(cellId, cellCodeCallbacks, hotkeys),
// Comes last so that it can be overridden
- basicBundle(completionConfig, theme, hotkeys),
+ basicBundle(opts),
// Underline cmd+clickable placeholder
goToDefinitionBundle(),
- showPlaceholder
- ? Prec.highest(smartPlaceholderExtension("import marimo as mo"))
- : enableAI
- ? clickablePlaceholderExtension({
- beforeText: "Start coding or ",
- linkText: "generate",
- afterText: " with AI.",
- onClick: cellMovementCallbacks.aiCellCompletion,
- })
- : [],
];
};
@@ -125,11 +109,9 @@ const startCompletionAtEndOfLine = (cm: EditorView): boolean => {
};
// Based on codemirror's basicSetup extension
-export const basicBundle = (
- completionConfig: CompletionConfig,
- theme: Theme,
- hotkeys: HotkeyProvider,
-): Extension[] => {
+export const basicBundle = (opts: CodeMirrorSetupOpts): Extension[] => {
+ const { theme, hotkeys } = opts;
+
return [
///// View
EditorView.lineWrapping,
@@ -164,7 +146,7 @@ export const basicBundle = (
keymap.of([...foldKeymap, ...lintKeymap]),
///// Language Support
- adaptiveLanguageConfiguration(completionConfig, hotkeys),
+ adaptiveLanguageConfiguration(opts),
///// Editing
historyCompartment.of(history()),
diff --git a/frontend/src/core/codemirror/config/extension.ts b/frontend/src/core/codemirror/config/extension.ts
index 892f14045b..362d2a9f84 100644
--- a/frontend/src/core/codemirror/config/extension.ts
+++ b/frontend/src/core/codemirror/config/extension.ts
@@ -2,6 +2,7 @@
import { CompletionConfig } from "@/core/config/config-schema";
import { HotkeyProvider } from "@/core/hotkeys/hotkeys";
import { Facet } from "@codemirror/state";
+import { MovementCallbacks } from "../cells/extensions";
export const completionConfigState = Facet.define<
CompletionConfig,
@@ -16,3 +17,15 @@ export const hotkeysProviderState = Facet.define<
>({
combine: (values) => values[0],
});
+
+export type PlaceholderType = "marimo-import" | "ai" | "none";
+export const placeholderState = Facet.define<PlaceholderType, PlaceholderType>({
+ combine: (values) => values[0],
+});
+
+export const movementCallbacksState = Facet.define<
+ MovementCallbacks,
+ MovementCallbacks
+>({
+ combine: (values) => values[0],
+});
diff --git a/frontend/src/core/codemirror/copilot/extension.ts b/frontend/src/core/codemirror/copilot/extension.ts
index aaf05750d4..dc05e037c2 100644
--- a/frontend/src/core/codemirror/copilot/extension.ts
+++ b/frontend/src/core/codemirror/copilot/extension.ts
@@ -23,6 +23,11 @@ export const copilotBundle = (): Extension => {
return "";
}
+ // If no text, don't fetch
+ if (view.doc.length === 0) {
+ return "";
+ }
+
// wait 10ms so that the view is updated first
await new Promise((resolve) => setTimeout(resolve, 10));
diff --git a/frontend/src/core/codemirror/language/__tests__/utils.test.ts b/frontend/src/core/codemirror/language/__tests__/utils.test.ts
index f7c1d0d34c..0e057f2a26 100644
--- a/frontend/src/core/codemirror/language/__tests__/utils.test.ts
+++ b/frontend/src/core/codemirror/language/__tests__/utils.test.ts
@@ -9,19 +9,23 @@ import { EditorView } from "@codemirror/view";
import { describe, it, expect } from "vitest";
import { adaptiveLanguageConfiguration, switchLanguage } from "../extension";
import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";
+import { MovementCallbacks } from "../../cells/extensions";
function createEditor(doc: string) {
return new EditorView({
state: EditorState.create({
doc,
extensions: [
- adaptiveLanguageConfiguration(
- {
+ adaptiveLanguageConfiguration({
+ completionConfig: {
activate_on_typing: true,
copilot: false,
},
- new OverridingHotkeyProvider({}),
- ),
+ hotkeys: new OverridingHotkeyProvider({}),
+ showPlaceholder: true,
+ enableAI: true,
+ cellMovementCallbacks: {} as MovementCallbacks,
+ }),
],
}),
});
diff --git a/frontend/src/core/codemirror/language/extension.ts b/frontend/src/core/codemirror/language/extension.ts
index 1e68e37562..33fa95f65e 100644
--- a/frontend/src/core/codemirror/language/extension.ts
+++ b/frontend/src/core/codemirror/language/extension.ts
@@ -14,12 +14,15 @@ import { CompletionConfig } from "@/core/config/config-schema";
import {
completionConfigState,
hotkeysProviderState,
+ movementCallbacksState,
+ placeholderState,
} from "../config/extension";
import { historyCompartment } from "../editing/extensions";
import { history } from "@codemirror/commands";
import { formattingChangeEffect } from "../format";
import { getEditorCodeAsPython } from "./utils";
import { HotkeyProvider } from "@/core/hotkeys/hotkeys";
+import { CodeMirrorSetupOpts } from "../cm";
export const LanguageAdapters: Record<
LanguageAdapter["type"],
@@ -104,7 +107,8 @@ function updateLanguageAdapterAndCode(
const code = view.state.doc.toString();
const completionConfig = view.state.facet(completionConfigState);
const hotkeysProvider = view.state.facet(hotkeysProviderState);
-
+ const placeholderType = view.state.facet(placeholderState);
+ const movementCallbacks = view.state.facet(movementCallbacksState);
// Update the code
const [codeOut, cursorDiff1] = currentLanguage.transformOut(code);
const [newCode, cursorDiff2] = nextLanguage.transformIn(codeOut);
@@ -120,7 +124,12 @@ function updateLanguageAdapterAndCode(
effects: [
setLanguageAdapter.of(nextLanguage),
languageCompartment.reconfigure(
- nextLanguage.getExtension(completionConfig, hotkeysProvider),
+ nextLanguage.getExtension(
+ completionConfig,
+ hotkeysProvider,
+ placeholderType,
+ movementCallbacks,
+ ),
),
// Clear history
historyCompartment.reconfigure([]),
@@ -159,15 +168,44 @@ function createLanguagePanel(view: EditorView): Panel {
* Set of extensions to enable adaptive language configuration.
*/
export function adaptiveLanguageConfiguration(
- completionConfig: CompletionConfig,
- hotkeysProvider: HotkeyProvider,
+ opts: Pick<
+ CodeMirrorSetupOpts,
+ | "completionConfig"
+ | "hotkeys"
+ | "showPlaceholder"
+ | "enableAI"
+ | "cellMovementCallbacks"
+ >,
) {
+ const {
+ showPlaceholder,
+ enableAI,
+ completionConfig,
+ hotkeys,
+ cellMovementCallbacks,
+ } = opts;
+
+ const placeholderType = showPlaceholder
+ ? "marimo-import"
+ : enableAI
+ ? "ai"
+ : "none";
+
return [
+ // Store state
completionConfigState.of(completionConfig),
- hotkeysProviderState.of(hotkeysProvider),
+ hotkeysProviderState.of(hotkeys),
+ placeholderState.of(placeholderType),
+ movementCallbacksState.of(cellMovementCallbacks),
+ // Language adapter
languageToggle(completionConfig),
languageCompartment.of(
- LanguageAdapters.python().getExtension(completionConfig, hotkeysProvider),
+ LanguageAdapters.python().getExtension(
+ completionConfig,
+ hotkeys,
+ placeholderType,
+ cellMovementCallbacks,
+ ),
),
languageAdapterState,
];
@@ -204,7 +242,14 @@ export function reconfigureLanguageEffect(
hotkeysProvider: HotkeyProvider,
) {
const language = view.state.field(languageAdapterState);
+ const placeholderType = view.state.facet(placeholderState);
+ const movementCallbacks = view.state.facet(movementCallbacksState);
return languageCompartment.reconfigure(
- language.getExtension(completionConfig, hotkeysProvider),
+ language.getExtension(
+ completionConfig,
+ hotkeysProvider,
+ placeholderType,
+ movementCallbacks,
+ ),
);
}
diff --git a/frontend/src/core/codemirror/language/markdown.ts b/frontend/src/core/codemirror/language/markdown.ts
index b9b78dd3aa..a5f5b3b69b 100644
--- a/frontend/src/core/codemirror/language/markdown.ts
+++ b/frontend/src/core/codemirror/language/markdown.ts
@@ -93,6 +93,10 @@ export class MarkdownLanguageAdapter implements LanguageAdapter {
}
isSupported(pythonCode: string): boolean {
+ if (pythonCode.trim() === "") {
+ return true;
+ }
+
if (pythonCode.trim() === "mo.md()") {
return true;
}
@@ -113,7 +117,7 @@ export class MarkdownLanguageAdapter implements LanguageAdapter {
getExtension(
_completionConfig: CompletionConfig,
hotkeys: HotkeyProvider,
- ): Extension {
+ ): Extension[] {
return [
markdown({
codeLanguages: languages,
diff --git a/frontend/src/core/codemirror/language/python.ts b/frontend/src/core/codemirror/language/python.ts
index 7242d5c62e..c2a9255822 100644
--- a/frontend/src/core/codemirror/language/python.ts
+++ b/frontend/src/core/codemirror/language/python.ts
@@ -1,5 +1,5 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { Extension } from "@codemirror/state";
+import { Extension, Prec } from "@codemirror/state";
import { LanguageAdapter } from "./types";
import {
pythonLanguage,
@@ -14,6 +14,13 @@ import {
import { CompletionConfig } from "@/core/config/config-schema";
import { autocompletion } from "@codemirror/autocomplete";
import { completer } from "../completion/completer";
+import { HotkeyProvider } from "@/core/hotkeys/hotkeys";
+import { PlaceholderType } from "../config/extension";
+import {
+ smartPlaceholderExtension,
+ clickablePlaceholderExtension,
+} from "../placeholder/extensions";
+import { MovementCallbacks } from "../cells/extensions";
/**
* Language adapter for Python.
@@ -33,7 +40,12 @@ export class PythonLanguageAdapter implements LanguageAdapter {
return true;
}
- getExtension(completionConfig: CompletionConfig): Extension {
+ getExtension(
+ completionConfig: CompletionConfig,
+ _hotkeys: HotkeyProvider,
+ placeholderType: PlaceholderType,
+ cellMovementCallbacks: MovementCallbacks,
+ ): Extension[] {
return [
// Whether or not to require keypress to activate autocompletion (default
// keymap is Ctrl+Space)
@@ -49,6 +61,16 @@ export class PythonLanguageAdapter implements LanguageAdapter {
override: [completer],
}),
customPythonLanguageSupport(),
+ placeholderType === "marimo-import"
+ ? Prec.highest(smartPlaceholderExtension("import marimo as mo"))
+ : placeholderType === "ai"
+ ? clickablePlaceholderExtension({
+ beforeText: "Start coding or ",
+ linkText: "generate",
+ afterText: " with AI.",
+ onClick: cellMovementCallbacks.aiCellCompletion,
+ })
+ : [],
];
}
}
diff --git a/frontend/src/core/codemirror/language/types.ts b/frontend/src/core/codemirror/language/types.ts
index b0a08e8c52..4340c8c53c 100644
--- a/frontend/src/core/codemirror/language/types.ts
+++ b/frontend/src/core/codemirror/language/types.ts
@@ -2,6 +2,8 @@
import { CompletionConfig } from "@/core/config/config-schema";
import { HotkeyProvider } from "@/core/hotkeys/hotkeys";
import { Extension } from "@codemirror/state";
+import { PlaceholderType } from "../config/extension";
+import { MovementCallbacks } from "../cells/extensions";
/**
* A language adapter is a class that can transform code from one language to
@@ -16,5 +18,7 @@ export interface LanguageAdapter {
getExtension(
completionConfig: CompletionConfig,
hotkeys: HotkeyProvider,
- ): Extension;
+ placeholderType: PlaceholderType,
+ movementCallbacks: MovementCallbacks,
+ ): Extension[];
}
diff --git a/frontend/src/stories/editor.stories.tsx b/frontend/src/stories/editor.stories.tsx
index 5b78f8b20d..d9b42fe8d3 100644
--- a/frontend/src/stories/editor.stories.tsx
+++ b/frontend/src/stories/editor.stories.tsx
@@ -4,7 +4,7 @@ import { useEffect, useRef } from "react";
import { EditorState, Extension } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import CodeMirror from "@uiw/react-codemirror";
-import { basicBundle } from "../core/codemirror/cm";
+import { CodeMirrorSetupOpts, basicBundle } from "../core/codemirror/cm";
import { python } from "@codemirror/lang-python";
import { CopilotConfig } from "@/core/codemirror/copilot/copilot-config";
import { copilotBundle } from "@/core/codemirror/copilot/extension";
@@ -61,11 +61,11 @@ export const Primary: Story = {
render: (args, ctx) => (
<div className="Cell m-20 w-[60%] overflow-hidden">
<Editor
- extensions={basicBundle(
- { activate_on_typing: false, copilot: false },
- ctx.globals.theme,
- new OverridingHotkeyProvider({}),
- )}
+ extensions={basicBundle({
+ completionConfig: { activate_on_typing: false, copilot: false },
+ theme: ctx.globals.theme,
+ hotkeys: new OverridingHotkeyProvider({}),
+ } as unknown as CodeMirrorSetupOpts)}
/>
</div>
),