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
fix: more md conversion edge cases (#4764)
Myles Scolnick311968f1cf6a
diff --git a/frontend/src/core/codemirror/language/__tests__/extension.test.ts b/frontend/src/core/codemirror/language/__tests__/extension.test.tsindex ad914a38ec..8ea45707a5 100644--- a/frontend/src/core/codemirror/language/__tests__/extension.test.ts+++ b/frontend/src/core/codemirror/language/__tests__/extension.test.ts@@ -145,9 +145,9 @@ describe("switchLanguage", () => {expect(mockEditor.state.doc.toString()).toMatchInlineSnapshot(`"mo.md(r"""- print('Hello')- print('Goodbye')- """+ print('Hello')+ print('Goodbye')+ """)"`);diff --git a/frontend/src/core/codemirror/language/__tests__/markdown.test.ts b/frontend/src/core/codemirror/language/__tests__/markdown.test.tsindex 06f4b41acf..8110c5aebe 100644--- a/frontend/src/core/codemirror/language/__tests__/markdown.test.ts+++ b/frontend/src/core/codemirror/language/__tests__/markdown.test.ts@@ -170,6 +170,36 @@ describe("MarkdownLanguageAdapter", () => {expect(offset).toBe(8);expect(adapter.lastQuotePrefix).toBe("r");});++ it("should preserve indentation in f-strings", () => {+ const pythonCode =+ 'mo.md(\n f"""\n```python\n{some_variable}\n```\n"""\n)';+ const [innerCode, offset] = adapter.transformIn(pythonCode);+ expect(innerCode).toBe("```python\n{some_variable}\n```");+ expect(offset).toBe(15);+ expect(adapter.lastQuotePrefix).toBe("f");++ // Transform out+ const [outerCode, outerOffset] = adapter.transformOut(innerCode);+ expect(outerCode).toMatch(pythonCode);+ expect(outerOffset).toBe(17);+ });++ it("should handle f-strings", () => {+ const pythonCode = 'mo.md(f"""# Title\n{some_variable}""")';+ const [innerCode, offset] = adapter.transformIn(pythonCode);+ expect(innerCode).toBe("# Title\n{some_variable}");+ expect(offset).toBe(10);+ expect(adapter.lastQuotePrefix).toBe("f");+ });++ it("should handle rf-strings", () => {+ const pythonCode = 'mo.md(rf"""# Title\n{some_variable}""")';+ const [innerCode, offset] = adapter.transformIn(pythonCode);+ expect(innerCode).toBe("# Title\n{some_variable}");+ expect(offset).toBe(11);+ expect(adapter.lastQuotePrefix).toBe("rf");+ });});describe("transformOut", () => {@@ -204,8 +234,8 @@ describe("MarkdownLanguageAdapter", () => {expect(wrappedCode).toMatchInlineSnapshot(`"mo.md("""- "Hello" world- """+ "Hello" world+ """)"`);expect(offset).toBe(16);@@ -218,8 +248,8 @@ describe("MarkdownLanguageAdapter", () => {expect(wrappedCode).toMatchInlineSnapshot(`"mo.md("""- Hello "world"- """+ Hello "world"+ """)"`);expect(offset).toBe(16);@@ -232,10 +262,10 @@ describe("MarkdownLanguageAdapter", () => {expect(wrappedCode).toMatchInlineSnapshot(`"mo.md("""- # Markdown Title+ # Markdown Title- Some content here.- """+ Some content here.+ """)"`);expect(offset).toBe(16);@@ -274,6 +304,36 @@ describe("MarkdownLanguageAdapter", () => {expect(wrappedCode).toBe(pythonCode);expect(offset).toBe(10);});++ it("should handle f-strings in transformOut", () => {+ const code = "# Title\n{some_variable}";+ adapter.lastQuotePrefix = "f";+ const [wrappedCode, offset] = adapter.transformOut(code);+ expect(wrappedCode).toMatchInlineSnapshot(`+ "mo.md(+ f"""+ # Title+ {some_variable}+ """+ )"+ `);+ expect(offset).toBe(17);+ });++ it("should handle rf-strings in transformOut", () => {+ const code = "# Title\n{some_variable}";+ adapter.lastQuotePrefix = "rf";+ const [wrappedCode, offset] = adapter.transformOut(code);+ expect(wrappedCode).toMatchInlineSnapshot(`+ "mo.md(+ rf"""+ # Title+ {some_variable}+ """+ )"+ `);+ expect(offset).toBe(18);+ });});describe("isSupported", () => {@@ -284,6 +344,8 @@ describe("MarkdownLanguageAdapter", () => {"mo.md()","mo.md('')",'mo.md("")',+ 'mo.md(""" hi """)',+ "mo.md(''' hi ''')","mo.md(f'hello world')",'mo.md(f"hello world")',"mo.md(r'hello world')",@@ -292,12 +354,30 @@ describe("MarkdownLanguageAdapter", () => {'mo.md(rf"hello world")',"mo.md(fr'hello world')",'mo.md(fr"hello world")',+ 'mo.md(f"""\n```python\n{some_variable}\n```\n""")',+ "mo.md(f'''\n```python\n{some_variable}\n```\n''')",+ 'mo.md(rf"""\n```python\n{some_variable}\n```\n""")',+ "mo.md(rf'''\n```python\n{some_variable}\n```\n''')",+ 'mo.md(f"""{np.random.randint(0, 10)}""")',];for (const format of VALID_FORMATS) {expect(adapter.isSupported(format)).toBe(true);}});+ it("should return true for complex nested markdown", () => {+ const pythonCode = String.raw`+ mo.md(+ rf"""+ \`\`\`python+ {pathlib.Path(__file__).read_text(encoding="utf-8")}+ \`\`\`+ """+ )+ `;+ expect(adapter.isSupported(pythonCode)).toBe(true);+ });+it("should return false for unsupported string formats", () => {const pythonCode = 'print("Hello, World!")';expect(adapter.isSupported(pythonCode)).toBe(false);diff --git a/frontend/src/core/codemirror/language/markdown.ts b/frontend/src/core/codemirror/language/markdown.tsindex a09a18273b..728e582fa8 100644--- a/frontend/src/core/codemirror/language/markdown.ts+++ b/frontend/src/core/codemirror/language/markdown.ts@@ -18,7 +18,6 @@ import { once } from "lodash-es";import { enhancedMarkdownExtension } from "../markdown/extension";import type { CompletionConfig } from "@/core/config/config-schema";import type { HotkeyProvider } from "@/core/hotkeys/hotkeys";-import { indentOneTab } from "./utils/indentOneTab";import {QUOTE_PREFIX_KINDS,type QuotePrefixKind,@@ -122,44 +121,76 @@ export class MarkdownLanguageAdapter implements LanguageAdapter {// Multiline codeconst start = `mo.md(\n ${prefix}"""\n`;- const end = `\n """\n)`;- return [start + indentOneTab(escapedCode) + end, start.length + 1];+ const end = `\n"""\n)`;+ return [start + escapedCode + end, start.length + 1];}isSupported(pythonCode: string): boolean {- if (pythonCode.trim() === "") {+ pythonCode = pythonCode.trim();++ // Empty strings are supported+ if (pythonCode === "") {return true;}- if (pythonCode.trim() === "mo.md()") {- return true;+ // Must start with mo.md(+ if (!pythonCode.startsWith("mo.md(")) {+ return false;}- // Handle mo.md("foo"), mo.plain_text("bar") in the same line- // If it starts with mo.md, but we have more than one function call, return false- if (pythonCode.trim().startsWith("mo.md(")) {- const tree = pythonLanguage.parser.parse(pythonCode);- let functionCallCount = 0;-- // Parse the code using Lezer to check for multiple function calls- tree.iterate({- enter: (node) => {- if (node.name === "CallExpression") {- functionCallCount++;- if (functionCallCount > 1) {- return false; // Stop iterating if we've found more than one function call- }- }- },- });-- // If the function call count is greater than 1, we don't want to show "view as markdown"- if (functionCallCount > 1) {- return false;- }+ // Empty function calls are supported+ if (pythonCode === "mo.md()") {+ return true;}- return regexes.some(([, regex]) => regex.test(pythonCode));+ // Parse the code using Lezer and check for the exact match of mo.md() signature+ const tree = pythonLanguage.parser.parse(pythonCode);++ // This is the exact match of mo.md() signature+ const enterOrder: Array<{ match: string | RegExp; stop?: boolean }> = [+ { match: "Script" },+ { match: "ExpressionStatement" },+ { match: "CallExpression" },+ { match: "MemberExpression" },+ { match: "VariableName" },+ { match: "." },+ { match: "PropertyName" },+ { match: "ArgList" },+ { match: "(" },+ { match: /String|FormatString/, stop: true },+ { match: ")" },+ ];++ let isValid = true;++ // Parse the code using Lezer to check for multiple function calls and string content+ tree.iterate({+ enter: (node) => {+ const current = enterOrder.shift();+ if (current === undefined) {+ // If our list is empty, but we are still going+ // then this is not a valid call+ isValid = false;+ return false;+ }++ const match = current.match;++ if (typeof match === "string") {+ isValid = isValid && match === node.name;+ return isValid && !current.stop;+ }++ if (!match.test(node.name)) {+ isValid = false;+ return isValid && !current.stop;+ }++ return isValid && !current.stop;+ },+ });++ return isValid;}getExtension(diff --git a/frontend/src/plugins/core/RenderHTML.tsx b/frontend/src/plugins/core/RenderHTML.tsxindex bec844acde..0fe08edd6b 100644--- a/frontend/src/plugins/core/RenderHTML.tsx+++ b/frontend/src/plugins/core/RenderHTML.tsx@@ -80,7 +80,7 @@ const addCopyButtonToCodehilite: TransformFn = (const CopyableCode = ({ children }: { children: ReactNode }) => {const id = useId();return (- <div className="relative group" id={id}>+ <div className="relative group codehilite" id={id}>{children}<CopyClipboardIcon