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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
improvement: make it clearer/possible to convert to SQL and markdown (#2878)
Myles Scolnick6b69e8e4e45e
diff --git a/frontend/src/components/editor/actions/useCellActionButton.tsx b/frontend/src/components/editor/actions/useCellActionButton.tsxindex c574d55d22..42169b01e3 100644--- a/frontend/src/components/editor/actions/useCellActionButton.tsx+++ b/frontend/src/components/editor/actions/useCellActionButton.tsx@@ -2,11 +2,7 @@import { downloadCellOutput } from "@/components/export/export-output-button";import { Switch } from "@/components/ui/switch";import { formatEditorViews } from "@/core/codemirror/format";-import {- canToggleToLanguage,- getCurrentLanguageAdapter,- toggleToLanguage,-} from "@/core/codemirror/language/commands";+import { toggleToLanguage } from "@/core/codemirror/language/commands";import {hasOnlyOneCellAtom,useCellActions,@@ -58,6 +54,7 @@ import { useDeleteCellCallback } from "../cell/useDeleteCell";import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";import type { CellConfig, RuntimeState } from "@/core/network/types";import { kioskModeAtom } from "@/core/mode";+import { switchLanguage } from "@/core/codemirror/language/extension";export interface CellActionButtonPropsextends Pick<CellData, "name" | "config"> {@@ -100,7 +97,6 @@ export function useCellActionButtons({ cell }: Props) {const { cellId, config, getEditorView, name, hasOutput, status } = cell;const cellIdx = cellIds.inOrderIds.indexOf(cellId);- const editorView = getEditorView();const toggleDisabled = async () => {const newConfig = { disabled: !config.disabled };@@ -112,7 +108,7 @@ export function useCellActionButtons({ cell }: Props) {const newConfig: Partial<CellConfig> = { hide_code: !config.hide_code };await saveCellConfig({ configs: { [cellId]: newConfig } });updateCellConfig({ cellId, config: newConfig });-+ const editorView = getEditorView();// If we're hiding the code, we should blur the editor// otherwise, we should focus itif (editorView) {@@ -202,56 +198,13 @@ export function useCellActionButtons({ cell }: Props) {label: "Format cell",hotkey: "cell.format",handle: () => {+ const editorView = getEditorView();if (!editorView) {return;}formatEditorViews({ [cellId]: editorView }, updateCellCode);},},- {- icon: <MarkdownIcon />,- label: "View as Markdown",- hotkey: "cell.viewAsMarkdown",- // We allow them to toggle to markdown in Python- // even if its not wrapped in a mo.md- hidden: getCurrentLanguageAdapter(editorView) !== "python",- handle: () => {- if (!editorView) {- return;- }- maybeAddMarimoImport(autoInstantiate, createCell);-- toggleToLanguage(editorView, "markdown", { force: true });- },- },- {- icon: <DatabaseIcon size={13} strokeWidth={1.5} />,- label: "View as SQL",- hidden: !canToggleToLanguage(editorView, "sql"),- handle: () => {- if (!editorView) {- return;- }- toggleToLanguage(editorView, "sql");- },- },- {- icon: <PythonIcon />,- label: "View as Python",- // If we're in markdown mode, we should use the markdown hotkey- hotkey:- getCurrentLanguageAdapter(editorView) === "markdown"- ? "cell.viewAsMarkdown"- : undefined,- hidden: !canToggleToLanguage(editorView, "python"),- handle: () => {- if (!editorView) {- return;- }- maybeAddMarimoImport(autoInstantiate, createCell);- toggleToLanguage(editorView, "python");- },- },{icon: config.hide_code ? (<EyeIcon size={13} strokeWidth={1.5} />@@ -281,6 +234,47 @@ export function useCellActionButtons({ cell }: Props) {},],+ // View as+ [+ {+ icon: <MarkdownIcon />,+ label: "Convert to Markdown",+ hotkey: "cell.viewAsMarkdown",+ handle: () => {+ const editorView = getEditorView();+ if (!editorView) {+ return;+ }+ maybeAddMarimoImport(autoInstantiate, createCell);+ switchLanguage(editorView, "markdown", { keepCodeAsIs: true });+ },+ },+ {+ icon: <DatabaseIcon size={13} strokeWidth={1.5} />,+ label: "Convert to SQL",+ handle: () => {+ const editorView = getEditorView();+ if (!editorView) {+ return;+ }+ maybeAddMarimoImport(autoInstantiate, createCell);+ switchLanguage(editorView, "sql", { keepCodeAsIs: true });+ },+ },+ {+ icon: <PythonIcon />,+ label: "Toggle as Python",+ handle: () => {+ const editorView = getEditorView();+ if (!editorView) {+ return;+ }+ maybeAddMarimoImport(autoInstantiate, createCell);+ toggleToLanguage(editorView, "python", { force: true });+ },+ },+ ],+// Movement[{diff --git a/frontend/src/components/editor/cell/CreateCellButton.tsx b/frontend/src/components/editor/cell/CreateCellButton.tsxindex 535217213d..77067c2823 100644--- a/frontend/src/components/editor/cell/CreateCellButton.tsx+++ b/frontend/src/components/editor/cell/CreateCellButton.tsx@@ -66,7 +66,7 @@ const CreateCellButtonContextMenu = (props: {onClick({ code: "" });}}>- <div className="mr-3">+ <div className="mr-3 text-muted-foreground"><PythonIcon /></div>Python cell@@ -79,7 +79,7 @@ const CreateCellButtonContextMenu = (props: {onClick({ code: new MarkdownLanguageAdapter().defaultCode });}}>- <div className="mr-3">+ <div className="mr-3 text-muted-foreground"><MarkdownIcon /></div>Markdown cell@@ -91,7 +91,7 @@ const CreateCellButtonContextMenu = (props: {onClick({ code: new SQLLanguageAdapter().defaultCode });}}>- <div className="mr-3">+ <div className="mr-3 text-muted-foreground"><DatabaseIcon size={13} strokeWidth={1.5} /></div>SQL celldiff --git a/frontend/src/components/editor/cell/cell-actions.tsx b/frontend/src/components/editor/cell/cell-actions.tsxindex fdde555c23..c0a3d2bf65 100644--- a/frontend/src/components/editor/cell/cell-actions.tsx+++ b/frontend/src/components/editor/cell/cell-actions.tsx@@ -87,7 +87,9 @@ const CellActionsDropdownInternal = (><div className="flex items-center flex-1">{action.icon && (- <div className="mr-2 w-5">{action.icon}</div>+ <div className="mr-2 w-5 text-muted-foreground">+ {action.icon}+ </div>)}<div className="flex-1">{action.label}</div><div className="flex-shrink-0 text-sm">diff --git a/frontend/src/components/editor/cell/cell-context-menu.tsx b/frontend/src/components/editor/cell/cell-context-menu.tsxindex 8b67045843..5eac28433c 100644--- a/frontend/src/components/editor/cell/cell-context-menu.tsx+++ b/frontend/src/components/editor/cell/cell-context-menu.tsx@@ -127,7 +127,9 @@ export const CellActionsContextMenu = ({ children, ...props }: Props) => {><div className="flex items-center flex-1">{action.icon && (- <div className="mr-2 w-5">{action.icon}</div>+ <div className="mr-2 w-5 text-muted-foreground">+ {action.icon}+ </div>)}<div className="flex-1">{action.label}</div><div className="flex-shrink-0 text-sm">diff --git a/frontend/src/components/editor/cell/code/icons.tsx b/frontend/src/components/editor/cell/code/icons.tsxindex fe6597b66c..0d6fca103c 100644--- a/frontend/src/components/editor/cell/code/icons.tsx+++ b/frontend/src/components/editor/cell/code/icons.tsx@@ -7,6 +7,7 @@ export const PythonIcon = (props: SVGProps<SVGSVGElement>) => (xmlns="http://www.w3.org/2000/svg"width="1em"height="1em"+ fill="currentColor"viewBox="0 0 448 512"{...props}>diff --git a/frontend/src/components/editor/cell/code/language-toggle.tsx b/frontend/src/components/editor/cell/code/language-toggle.tsxindex aeefd4b0f4..a6eef09ccc 100644--- a/frontend/src/components/editor/cell/code/language-toggle.tsx+++ b/frontend/src/components/editor/cell/code/language-toggle.tsx@@ -26,23 +26,20 @@ export const LanguageToggles: React.FC<LanguageTogglesProps> = ({onAfterToggle,}) => {const canUseMarkdown = useMemo(- () => new MarkdownLanguageAdapter().isSupported(code),+ () => new MarkdownLanguageAdapter().isSupported(code) || code.trim() === "",[code],);const canUseSQL = useMemo(- () => new SQLLanguageAdapter().isSupported(code),+ () => new SQLLanguageAdapter().isSupported(code) || code.trim() === "",[code],);return (- <div className="absolute right-2 top-2 z-20 flex hover-action">+ <div className="absolute right-3 top-2 z-20 flex hover-action gap-1"><LanguageToggleeditorView={editorView}currentLanguageAdapter={currentLanguageAdapter}- // Prefer showing markdown over SQL when both are supported- canSwitchToLanguage={- canUseSQL && currentLanguageAdapter === "python" && !canUseMarkdown- }+ canSwitchToLanguage={canUseSQL && currentLanguageAdapter === "python"}icon={<DatabaseIconcolor={"var(--sky-11)"}diff --git a/frontend/src/components/icons/multi-icon.tsx b/frontend/src/components/icons/multi-icon.tsxindex 6b50c6c3be..feaf8332a2 100644--- a/frontend/src/components/icons/multi-icon.tsx+++ b/frontend/src/components/icons/multi-icon.tsx@@ -17,8 +17,8 @@ export const MultiIcon = ({}: PropsWithChildren<MultiIconProps>) => {const [first, second] = React.Children.toArray(children);const positioning = layerTop- ? "top-[-1px] left-[-1px]"- : "bottom-[-1px] right-[-1px]";+ ? "top-[-2px] left-[-2px]"+ : "bottom-[-2px] right-[-2px]";return (<div className="multi-icon relative w-fit">{first}diff --git a/frontend/src/core/codemirror/language/__tests__/extension.test.ts b/frontend/src/core/codemirror/language/__tests__/extension.test.tsindex 6b6ce2b6dc..32765bcb91 100644--- a/frontend/src/core/codemirror/language/__tests__/extension.test.ts+++ b/frontend/src/core/codemirror/language/__tests__/extension.test.ts@@ -3,14 +3,17 @@ import { beforeAll, describe, expect, it } from "vitest";import {adaptiveLanguageConfiguration,getInitialLanguageAdapter,+ languageAdapterState,+ switchLanguage,} from "../extension";import { EditorState } from "@codemirror/state";import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";import type { MovementCallbacks } from "../../cells/extensions";import { store } from "@/core/state/jotai";import { capabilitiesAtom } from "@/core/config/capabilities";+import { EditorView } from "@codemirror/view";-function createState(content: string) {+function createState(content: string, selection?: { anchor: number }) {const state = EditorState.create({doc: content,extensions: [@@ -26,6 +29,7 @@ function createState(content: string) {cellMovementCallbacks: {} as MovementCallbacks,}),],+ selection,});return state;@@ -57,3 +61,109 @@ describe("getInitialLanguageAdapter", () => {expect(getInitialLanguageAdapter(state).type).toBe("sql");});});++describe("switchLanguage", () => {+ it("handles keepCodeAsIs is true", () => {+ const state = createState("print('Hello')\nprint('Goodbye')", {+ anchor: 2,+ });+ const mockEditor = new EditorView({ state });+ switchLanguage(mockEditor, "python", { keepCodeAsIs: true });+ expect(mockEditor.state.field(languageAdapterState).type).toBe("python");+ expect(mockEditor.state.doc.toString()).toEqual(+ "print('Hello')\nprint('Goodbye')",+ );++ // Check that the cursor position is maintained+ expect(mockEditor.state.selection.main.from).toEqual(2);++ // Check that the language adapter is updated+ expect(getInitialLanguageAdapter(mockEditor.state).type).toBe("python");++ // Switch to markdown+ switchLanguage(mockEditor, "markdown", { keepCodeAsIs: true });+ expect(mockEditor.state.field(languageAdapterState).type).toBe("markdown");+ expect(mockEditor.state.doc.toString()).toEqual(+ "print('Hello')\nprint('Goodbye')",+ );++ // Switch back to python+ switchLanguage(mockEditor, "python", { keepCodeAsIs: true });+ expect(mockEditor.state.field(languageAdapterState).type).toBe("python");+ expect(mockEditor.state.doc.toString()).toEqual(+ "print('Hello')\nprint('Goodbye')",+ );++ // Check that the cursor position is maintained+ expect(mockEditor.state.selection.main.from).toEqual(2);++ // Switch to sql+ switchLanguage(mockEditor, "sql", { keepCodeAsIs: true });+ expect(mockEditor.state.field(languageAdapterState).type).toBe("sql");+ expect(mockEditor.state.doc.toString()).toEqual(+ "print('Hello')\nprint('Goodbye')",+ );++ // Check that the cursor position is maintained+ expect(mockEditor.state.selection.main.from).toEqual(2);++ // Switch back to python+ switchLanguage(mockEditor, "python", { keepCodeAsIs: true });+ expect(mockEditor.state.field(languageAdapterState).type).toBe("python");+ expect(mockEditor.state.doc.toString()).toEqual(+ "print('Hello')\nprint('Goodbye')",+ );++ // Check that the cursor position is maintained+ expect(mockEditor.state.selection.main.from).toEqual(2);+ });++ it("handles keepCodeAsIs is false", () => {+ const state = createState("print('Hello')\nprint('Goodbye')", {+ anchor: 2,+ });+ const mockEditor = new EditorView({ state });+ switchLanguage(mockEditor, "python", { keepCodeAsIs: false });+ expect(mockEditor.state.doc.toString()).toEqual(+ "print('Hello')\nprint('Goodbye')",+ );++ // Check that the cursor position is maintained+ expect(mockEditor.state.selection.main.from).toEqual(2);++ // Switch to markdown+ switchLanguage(mockEditor, "markdown", { keepCodeAsIs: false });+ expect(mockEditor.state.doc.toString()).toEqual(+ "print('Hello')\nprint('Goodbye')",+ );++ // Switch back to python+ switchLanguage(mockEditor, "python", { keepCodeAsIs: false });+ expect(mockEditor.state.doc.toString()).toMatchInlineSnapshot(`+ "mo.md(+ """+ print('Hello')+ print('Goodbye')+ """+ )"+ `);++ // Switch to sql+ switchLanguage(mockEditor, "sql", { keepCodeAsIs: false });+ expect(mockEditor.state.doc.toString()).toMatchInlineSnapshot(`+ "print('Hello')+ print('Goodbye')"+ `);++ // Switch back to python+ switchLanguage(mockEditor, "python", { keepCodeAsIs: false });+ expect(mockEditor.state.doc.toString()).toMatchInlineSnapshot(`+ "_df = mo.sql(+ f"""+ print('Hello')+ print('Goodbye')+ """+ )"+ `);+ });+});diff --git a/frontend/src/core/codemirror/language/__tests__/sql.test.ts b/frontend/src/core/codemirror/language/__tests__/sql.test.tsindex e1c040e50f..86a1b37bc8 100644--- a/frontend/src/core/codemirror/language/__tests__/sql.test.ts+++ b/frontend/src/core/codemirror/language/__tests__/sql.test.ts@@ -55,11 +55,11 @@ describe("SQLLanguageAdapter", () => {expect(offset).toBe(20);});- it("should throw if no sql is detected", () => {+ it("should return as is if not sql", () => {const pythonCode = 'next_df = print("Hello, World!")';- expect(() =>- adapter.transformIn(pythonCode),- ).toThrowErrorMatchingInlineSnapshot("[Error: Not supported]");+ const [innerCode, offset] = adapter.transformIn(pythonCode);+ expect(innerCode).toBe('next_df = print("Hello, World!")');+ expect(offset).toBe(0);});it("should handle an empty string", () => {diff --git a/frontend/src/core/codemirror/language/commands.ts b/frontend/src/core/codemirror/language/commands.tsindex 77bcd78f92..47e9d67266 100644--- a/frontend/src/core/codemirror/language/commands.ts+++ b/frontend/src/core/codemirror/language/commands.ts@@ -29,6 +29,11 @@ export function canToggleToLanguage(return false;}+ // If there is no code, we can always toggle to any language+ if (editorView.state.doc.toString().trim() === "") {+ return true;+ }+return LanguageAdapters[language]().isSupported(getEditorCodeAsPython(editorView),);diff --git a/frontend/src/core/codemirror/language/extension.ts b/frontend/src/core/codemirror/language/extension.tsindex bc466c8897..5a9ee5defe 100644--- a/frontend/src/core/codemirror/language/extension.ts+++ b/frontend/src/core/codemirror/language/extension.ts@@ -96,7 +96,9 @@ function languageToggle() {return false;}- updateLanguageAdapterAndCode(cm, nextLanguage);+ updateLanguageAdapterAndCode(cm, nextLanguage, {+ keepCodeAsIs: false,+ });return true;},},@@ -107,6 +109,7 @@ function languageToggle() {function updateLanguageAdapterAndCode(view: EditorView,nextLanguage: LanguageAdapter,+ opts: { keepCodeAsIs: boolean },) {const currentLanguage = view.state.field(languageAdapterState);const code = view.state.doc.toString();@@ -114,15 +117,25 @@ function updateLanguageAdapterAndCode(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);-- // Update the cursor positionlet cursor = view.state.selection.main.head;- cursor += cursorDiff1;- cursor -= cursorDiff2;- cursor = clamp(cursor, 0, newCode.length);++ // If keepCodeAsIs is true, we just keep the original code+ // but update the language.+ // If keepCodeAsIs is false, we need to transform the code+ // from the current language to the next language and update+ // the cursor position.+ let finalCode: string;+ if (opts.keepCodeAsIs) {+ finalCode = code;+ } else {+ const [codeOut, cursorDiff1] = currentLanguage.transformOut(code);+ const [newCode, cursorDiff2] = nextLanguage.transformIn(codeOut);+ // Update the cursor position+ cursor += cursorDiff1;+ cursor -= cursorDiff2;+ cursor = clamp(cursor, 0, newCode.length);+ finalCode = newCode;+ }// Update the stateview.dispatch({@@ -144,7 +157,7 @@ function updateLanguageAdapterAndCode(changes: {from: 0,to: view.state.doc.length,- insert: newCode,+ insert: finalCode,},selection: EditorSelection.cursor(cursor),});@@ -232,9 +245,18 @@ export function getInitialLanguageAdapter(state: EditorView["state"]) {export function switchLanguage(view: EditorView,language: LanguageAdapter["type"],+ opts: { keepCodeAsIs?: boolean } = {},) {+ // If the existing language is the same as the new language, do nothing+ const currentLanguage = view.state.field(languageAdapterState);+ if (currentLanguage.type === language) {+ return;+ }+const newLanguage = LanguageAdapters[language];- updateLanguageAdapterAndCode(view, newLanguage());+ updateLanguageAdapterAndCode(view, newLanguage(), {+ keepCodeAsIs: opts.keepCodeAsIs ?? false,+ });}/**diff --git a/frontend/src/core/codemirror/language/sql.ts b/frontend/src/core/codemirror/language/sql.tsindex 2c77b81875..a00b4d624e 100644--- a/frontend/src/core/codemirror/language/sql.ts+++ b/frontend/src/core/codemirror/language/sql.ts@@ -19,6 +19,7 @@ import {upgradePrefixKind,} from "./utils/quotes";import { capabilitiesAtom } from "@/core/config/capabilities";+import { MarkdownLanguageAdapter } from "./markdown";const quoteKinds = [['"""', '"""'],@@ -59,7 +60,11 @@ export class SQLLanguageAdapter implements LanguageAdapter {transformIn(pythonCode: string): [string, number] {if (!this.isSupported(pythonCode)) {- throw new Error("Not supported");+ // Attempt to remove any markdown wrappers+ const [transformedCode, offset] =+ new MarkdownLanguageAdapter().transformIn(pythonCode);+ // Just return the original code+ return [transformedCode, offset];}pythonCode = pythonCode.trim();diff --git a/scripts/release.sh b/scripts/release.shindex ce48daa200..7aac3974b7 100755--- a/scripts/release.sh+++ b/scripts/release.sh@@ -102,7 +102,7 @@ if confirm "Push changes to remote?"; thenfi# Create and push tag-if confirm "Create and push tag v$NEW_VERSION?"; then+if confirm "Create and push tag $NEW_VERSION?"; thengit tag -a "$NEW_VERSION" -m "release: $NEW_VERSION"git push origin --tagsecho -e "${GREEN}✓ Tag pushed successfully${NC}"@@ -110,3 +110,6 @@ fi# Final success messageecho -e "\n${BOLD}${GREEN}🎉 Release $NEW_VERSION completed successfully! 🎉${NC}\n"+echo -e "${YELLOW}Don't forget to:${NC}"+echo " 1. Monitor the release: https://github.com/marimo-team/marimo/actions/workflows/release.yml"+echo " 2. Draft the release notes: https://github.com/marimo-team/marimo/releases/new?tag=$NEW_VERSION"