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: map jupyter magic to helpful descriptions (#3262)

Myles Scolnickb5a36b69f896
diff --git a/frontend/src/components/editor/chrome/panels/constants.ts b/frontend/src/components/editor/chrome/panels/constants.ts
new file mode 100644
index 0000000000..0e7a515c7e
--- /dev/null
+++ b/frontend/src/components/editor/chrome/panels/constants.ts
@@ -0,0 +1,2 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+export const PACKAGES_INPUT_ID = "packages-install-input";
diff --git a/frontend/src/components/editor/chrome/panels/packages-panel.tsx b/frontend/src/components/editor/chrome/panels/packages-panel.tsx
index 97553d606a..b7b118bb0b 100644
--- a/frontend/src/components/editor/chrome/panels/packages-panel.tsx
+++ b/frontend/src/components/editor/chrome/panels/packages-panel.tsx
@@ -27,6 +27,7 @@ import { cn } from "@/utils/cn";
import { Kbd } from "@/components/ui/kbd";
import { Events } from "@/utils/events";
import { copyToClipboard } from "@/utils/copy";
+import { PACKAGES_INPUT_ID } from "./constants";
export const PackagesPanel: React.FC = () => {
const [config] = useResolvedMarimoConfig();
@@ -94,6 +95,7 @@ const InstallPackageForm: React.FC<{
<div className="flex items-center w-full border-b">
<SearchInput
placeholder={`Install packages with ${packageManager}...`}
+ id={PACKAGES_INPUT_ID}
icon={
loading ? (
<Spinner
diff --git a/frontend/src/components/editor/chrome/state.ts b/frontend/src/components/editor/chrome/state.ts
index 73904efa81..6c33cc80ee 100644
--- a/frontend/src/components/editor/chrome/state.ts
+++ b/frontend/src/components/editor/chrome/state.ts
@@ -84,6 +84,8 @@ export function useChromeActions() {
return useActions();
}
+export { chromeAtom };
+
/**
* This is exported for testing purposes only.
*/
diff --git a/frontend/src/core/codemirror/cm.ts b/frontend/src/core/codemirror/cm.ts
index d582495e74..b5b715be71 100644
--- a/frontend/src/core/codemirror/cm.ts
+++ b/frontend/src/core/codemirror/cm.ts
@@ -57,6 +57,7 @@ import { goToDefinitionBundle } from "./go-to-definition/extension";
import type { HotkeyProvider } from "../hotkeys/hotkeys";
import { lightTheme } from "./theme/light";
import { dndBundle } from "./dnd/extension";
+import { jupyterHelpExtension } from "./compat/jupyter";
export interface CodeMirrorSetupOpts {
cellId: CellId;
@@ -86,6 +87,7 @@ export const setupCodeMirror = (opts: CodeMirrorSetupOpts): Extension[] => {
// Editor keymaps (vim or defaults) based on user config
keymapBundle(keymapConfig, cellMovementCallbacks),
dndBundle(),
+ jupyterHelpExtension(),
// Cell editing
cellMovementBundle(cellId, cellMovementCallbacks, hotkeys),
cellCodeEditingBundle(cellId, cellCodeCallbacks, hotkeys),
diff --git a/frontend/src/core/codemirror/compat/__tests__/jupyter.test.ts b/frontend/src/core/codemirror/compat/__tests__/jupyter.test.ts
new file mode 100644
index 0000000000..8a47046e3d
--- /dev/null
+++ b/frontend/src/core/codemirror/compat/__tests__/jupyter.test.ts
@@ -0,0 +1,120 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { jupyterHelpExtension } from "../jupyter";
+import { EditorState } from "@codemirror/state";
+import { EditorView } from "@codemirror/view";
+import { store } from "@/core/state/jotai";
+import { toast } from "@/components/ui/use-toast";
+import { saveUserConfig } from "@/core/network/requests";
+
+// Mock dependencies
+vi.mock("@/core/state/jotai", () => ({
+ store: {
+ get: vi.fn(),
+ set: vi.fn(),
+ },
+}));
+
+vi.mock("@/components/ui/use-toast", () => ({
+ toast: vi.fn(),
+}));
+
+vi.mock("@/core/network/requests", () => ({
+ saveUserConfig: vi.fn().mockResolvedValue({}),
+}));
+
+describe("jupyterHelpExtension", () => {
+ let view: EditorView;
+
+ beforeEach(() => {
+ // Reset mocks
+ vi.clearAllMocks();
+
+ // Setup basic editor state and view
+ const state = EditorState.create({
+ doc: "",
+ extensions: [jupyterHelpExtension()],
+ });
+ view = new EditorView({ state });
+ });
+
+ it("handles pip install command", () => {
+ // Simulate typing !pip install
+ view.dispatch({
+ changes: { from: 0, insert: "!pip install" },
+ selection: { anchor: 12 },
+ });
+
+ expect(store.set).toHaveBeenCalled();
+ expect(toast).toHaveBeenCalledWith({
+ title: "Package Installation",
+ description: expect.any(Object),
+ });
+ });
+
+ it("handles uv pip install command", () => {
+ view.dispatch({
+ changes: { from: 0, insert: "!uv pip install" },
+ selection: { anchor: 15 },
+ });
+
+ expect(store.set).toHaveBeenCalled();
+ expect(toast).toHaveBeenCalledWith({
+ title: "Package Installation",
+ description: expect.any(Object),
+ });
+ });
+
+ it("handles autoreload commands", async () => {
+ // @ts-expect-error eh typescript
+ store.get.mockReturnValue({ runtime: {} });
+
+ // Test autorun mode
+ view.dispatch({
+ changes: { from: 0, insert: "%load_ext autoreload 2" },
+ selection: { anchor: "%load_ext autoreload 2".length },
+ });
+
+ expect(saveUserConfig).toHaveBeenCalledWith({
+ config: expect.objectContaining({
+ runtime: { auto_reload: "autorun" },
+ }),
+ });
+
+ // Test lazy mode
+ view.dispatch({
+ changes: { from: 0, insert: "%load_ext autoreload 1" },
+ selection: { anchor: "%load_ext autoreload 1".length },
+ });
+
+ expect(saveUserConfig).toHaveBeenCalledWith({
+ config: expect.objectContaining({
+ runtime: { auto_reload: "lazy" },
+ }),
+ });
+
+ // Test off mode
+ view.dispatch({
+ changes: { from: 0, insert: "%load_ext autoreload 0" },
+ selection: { anchor: "%load_ext autoreload 0".length },
+ });
+
+ expect(saveUserConfig).toHaveBeenCalledWith({
+ config: expect.objectContaining({
+ runtime: { auto_reload: "off" },
+ }),
+ });
+ });
+
+ it("handles ls command with warning", () => {
+ view.dispatch({
+ changes: { from: 0, insert: "!ls " },
+ selection: { anchor: "!ls ".length },
+ });
+
+ expect(toast).toHaveBeenCalledWith({
+ title: "Listing files",
+ description: expect.any(Object),
+ });
+ });
+});
diff --git a/frontend/src/core/codemirror/compat/jupyter.tsx b/frontend/src/core/codemirror/compat/jupyter.tsx
new file mode 100644
index 0000000000..db76bc7777
--- /dev/null
+++ b/frontend/src/core/codemirror/compat/jupyter.tsx
@@ -0,0 +1,161 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import type { Extension } from "@codemirror/state";
+import { EditorView } from "@codemirror/view";
+import { toast } from "../../../components/ui/use-toast";
+import { store } from "@/core/state/jotai";
+import { chromeAtom } from "@/components/editor/chrome/state";
+import { saveUserConfig } from "@/core/network/requests";
+import type { UserConfig } from "@/core/config/config-schema";
+import { userConfigAtom } from "@/core/config/config";
+import { PACKAGES_INPUT_ID } from "@/components/editor/chrome/panels/constants";
+
+interface ReplaceCommand {
+ match: string;
+ onMatch: () => void;
+ title: string;
+ description: React.ReactNode;
+}
+
+export function jupyterHelpExtension(): Extension {
+ // Function to update the module reload mode
+ // Updates local config and saves to server
+ const handleUpdateModuleReload = async (mode: "lazy" | "autorun" | "off") => {
+ const config = store.get(userConfigAtom);
+ const newConfig: UserConfig = {
+ ...config,
+ runtime: {
+ ...config.runtime,
+ auto_reload: mode,
+ },
+ };
+ await saveUserConfig({ config: newConfig }).then(() =>
+ store.set(userConfigAtom, newConfig),
+ );
+ };
+
+ const focusPackagesInput = () => {
+ requestAnimationFrame(() => {
+ const input = document.getElementById(PACKAGES_INPUT_ID);
+ if (input) {
+ input.focus();
+ }
+ });
+ };
+
+ const commands: ReplaceCommand[] = [
+ {
+ match: "!pip install",
+ onMatch: () => {
+ store.set(chromeAtom, (prev) => ({
+ ...prev,
+ isSidebarOpen: true,
+ selectedPanel: "packages",
+ }));
+
+ focusPackagesInput();
+ },
+ title: "Package Installation",
+ description: (
+ <>
+ The package manager sidebar has been opened.
+ <br />
+ Install packages directly from there instead.
+ </>
+ ),
+ },
+ {
+ match: "!uv pip install",
+ onMatch: () => {
+ store.set(chromeAtom, (prev) => ({
+ ...prev,
+ isSidebarOpen: true,
+ selectedPanel: "packages",
+ }));
+
+ focusPackagesInput();
+ },
+ title: "Package Installation",
+ description: (
+ <>
+ The package manager sidebar has been opened.
+ <br />
+ Install packages directly from there instead.
+ </>
+ ),
+ },
+ {
+ match: "%load_ext autoreload 2",
+ onMatch: async () => {
+ await handleUpdateModuleReload("autorun");
+ },
+ title: "Module reload",
+ description: (
+ <>
+ Module reload mode set to <b>autorun</b> - module changes will re-run
+ the cells that import them.
+ </>
+ ),
+ },
+ {
+ match: "%load_ext autoreload 1",
+ onMatch: async () => {
+ await handleUpdateModuleReload("lazy");
+ },
+ title: "Module reload",
+ description: (
+ <>
+ Module reload mode set to <b>lazy</b> - module changes will mark the
+ cells that import them as stale.
+ </>
+ ),
+ },
+ {
+ match: "%load_ext autoreload 0",
+ onMatch: async () => {
+ await handleUpdateModuleReload("off");
+ },
+ title: "Module reload",
+ description: (
+ <>Module reload disabled - module changes will not be detected.</>
+ ),
+ },
+ {
+ match: "!ls",
+ onMatch: () => {
+ // noop
+ },
+ title: "Listing files",
+ description: (
+ <>
+ Shell commands are not directly supported.
+ <br />
+ Use <code>import subprocess; subprocess.run(['ls'])</code> instead.
+ </>
+ ),
+ },
+ ];
+
+ const commandMap = new Map(commands.map((cmd) => [cmd.match, cmd]));
+
+ return EditorView.updateListener.of((update) => {
+ if (update.docChanged) {
+ const cursor = update.state.selection.main;
+ // Get text from the start of the line to the cursor
+ const doc = update.state.doc;
+ const line = doc.lineAt(cursor.head);
+ const text = doc.sliceString(line.from, cursor.anchor).trim();
+
+ const cmd = commandMap.get(text);
+ if (cmd) {
+ // Execute the command
+ cmd.onMatch();
+
+ // Show toast
+ toast({
+ title: cmd.title,
+ description: cmd.description,
+ });
+ }
+ }
+ });
+}