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
feat: toggle between markdown formats and set r-string as default (#4648)
Shahmir Varqhabdd8ba9d04ca
diff --git a/frontend/src/core/codemirror/language/__tests__/markdown.test.ts b/frontend/src/core/codemirror/language/__tests__/markdown.test.tsindex e292392215..06f4b41acf 100644--- a/frontend/src/core/codemirror/language/__tests__/markdown.test.ts+++ b/frontend/src/core/codemirror/language/__tests__/markdown.test.ts@@ -1,6 +1,7 @@/* Copyright 2024 Marimo. All rights reserved. */import { expect, describe, it } from "vitest";import { MarkdownLanguageAdapter } from "../markdown";+import { getQuotePrefix } from "../panel";const adapter = new MarkdownLanguageAdapter();@@ -180,6 +181,14 @@ describe("MarkdownLanguageAdapter", () => {expect(offset).toBe(9);});+ it("defaults to r-string when there is no last quote prefix", () => {+ const adapter = new MarkdownLanguageAdapter();+ const code = "Hello world";+ const [wrappedCode, offset] = adapter.transformOut(code);+ expect(wrappedCode).toBe(`mo.md(r"""Hello world""")`);+ expect(offset).toBe(10);+ });+it("single line", () => {const code = "Hello world";adapter.lastQuotePrefix = "";@@ -270,15 +279,23 @@ describe("MarkdownLanguageAdapter", () => {describe("isSupported", () => {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 markdown string formats", () => {- expect(adapter.isSupported("mo.md(f'hello world')")).toBe(false);- expect(adapter.isSupported('mo.md(f"hello world")')).toBe(false);+ const VALID_FORMATS = [+ pythonCode,+ "mo.md()",+ "mo.md('')",+ 'mo.md("")',+ "mo.md(f'hello world')",+ 'mo.md(f"hello world")',+ "mo.md(r'hello world')",+ 'mo.md(r"hello world")',+ "mo.md(rf'hello world')",+ 'mo.md(rf"hello world")',+ "mo.md(fr'hello world')",+ 'mo.md(fr"hello world")',+ ];+ for (const format of VALID_FORMATS) {+ expect(adapter.isSupported(format)).toBe(true);+ }});it("should return false for unsupported string formats", () => {@@ -327,3 +344,34 @@ describe("MarkdownLanguageAdapter", () => {});});});++describe("getQuotePrefix", () => {+ it("should return the correct quote prefix when checked", () => {+ expect(getQuotePrefix("", true, "r")).toBe("r");+ expect(getQuotePrefix("", true, "f")).toBe("f");+ expect(getQuotePrefix("r", true, "f")).toBe("rf");+ expect(getQuotePrefix("f", true, "r")).toBe("rf");+ });++ it("should return the correct quote prefix when unchecked", () => {+ expect(getQuotePrefix("r", false, "r")).toBe("");+ expect(getQuotePrefix("f", false, "f")).toBe("");+ expect(getQuotePrefix("rf", false, "r")).toBe("f");+ expect(getQuotePrefix("rf", false, "f")).toBe("r");+ });++ it("should return the correct quote prefix even when not possible to toggle", () => {+ expect(getQuotePrefix("", false, "r")).toBe("");+ expect(getQuotePrefix("", false, "f")).toBe("");+ expect(getQuotePrefix("r", false, "f")).toBe("r");+ expect(getQuotePrefix("f", false, "r")).toBe("f");++ expect(getQuotePrefix("rf", true, "r")).toBe("rf");+ expect(getQuotePrefix("rf", true, "f")).toBe("rf");+ expect(getQuotePrefix("f", true, "f")).toBe("f");+ expect(getQuotePrefix("r", true, "r")).toBe("r");++ expect(getQuotePrefix("", false, "")).toBe("");+ expect(getQuotePrefix("", true, "")).toBe("");+ });+});diff --git a/frontend/src/core/codemirror/language/markdown.ts b/frontend/src/core/codemirror/language/markdown.tsindex e051397b97..63b7285905 100644--- a/frontend/src/core/codemirror/language/markdown.ts+++ b/frontend/src/core/codemirror/language/markdown.ts@@ -19,7 +19,11 @@ 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 { type QuotePrefixKind, splitQuotePrefix } from "./utils/quotes";+import {+ QUOTE_PREFIX_KINDS,+ type QuotePrefixKind,+ splitQuotePrefix,+} from "./utils/quotes";import { markdownAutoRunExtension } from "../cells/extensions";import type { PlaceholderType } from "../config/extension";import type { CellId } from "@/core/cells/ids";@@ -35,12 +39,7 @@ const quoteKinds = [];// explode into all combinations-//-// A note on f-strings:-//-// f-strings are not yet supported due to bad interactions with-// string escaping, LaTeX, and loss of Python syntax highlighting-const pairs = ["", "r"].flatMap((prefix) =>+const pairs = QUOTE_PREFIX_KINDS.flatMap((prefix) =>quoteKinds.map(([start, end]) => [prefix + start, end]),);@@ -64,7 +63,7 @@ export class MarkdownLanguageAdapter implements LanguageAdapter {return `mo.md(r"""\n${markdown}\n""")`;}- lastQuotePrefix: QuotePrefixKind = "";+ lastQuotePrefix: QuotePrefixKind = "r";transformIn(pythonCode: string): [string, number] {pythonCode = pythonCode.trim();@@ -181,12 +180,12 @@ export class MarkdownLanguageAdapter implements LanguageAdapter {// Find all { } groupingsconst pattern = /{(.*?)}/g;- let match: RegExpExecArray | null;-- while ((match = pattern.exec(text)) !== null) {+ let match: RegExpExecArray | null = pattern.exec(text);+ while (match !== null) {const start = match.index + 1;const end = pattern.lastIndex - 1;overlays.push({ from: start, to: end });+ match = pattern.exec(text);}if (overlays.length === 0) {@@ -218,6 +217,10 @@ export class MarkdownLanguageAdapter implements LanguageAdapter {python().support,];}++ setQuotePrefix(prefix: QuotePrefixKind) {+ this.lastQuotePrefix = prefix;+ }}const emojiCompletionSource: CompletionSource = async (context) => {diff --git a/frontend/src/core/codemirror/language/panel.tsx b/frontend/src/core/codemirror/language/panel.tsxindex 59236995ba..17a4392e45 100644--- a/frontend/src/core/codemirror/language/panel.tsx+++ b/frontend/src/core/codemirror/language/panel.tsx@@ -10,7 +10,12 @@ import {INTERNAL_SQL_ENGINES,} from "@/core/datasets/data-source-connections";import { useAtomValue } from "jotai";-import { AlertCircle, CircleHelpIcon, PaintRollerIcon } from "lucide-react";+import {+ AlertCircle,+ CircleHelpIcon,+ InfoIcon,+ PaintRollerIcon,+} from "lucide-react";import {Select,SelectContent,@@ -28,6 +33,9 @@ import type { DataSourceConnection } from "@/core/kernel/messages";import { formatSQL } from "../format";import { Button } from "@/components/ui/button";import { Tooltip, TooltipProvider } from "@/components/ui/tooltip";+import { MarkdownLanguageAdapter } from "./markdown";+import type { QuotePrefixKind } from "./utils/quotes";+import { Checkbox } from "@/components/ui/checkbox";const Divider = () => <div className="h-4 border-r border-border" />;@@ -117,6 +125,52 @@ export const LanguagePanelComponent: React.FC<{);}+ if (languageAdapter instanceof MarkdownLanguageAdapter) {+ showDivider = true;+ const lastQuotePrefix = languageAdapter.lastQuotePrefix;+ const togglePrefix = (+ prefix: QuotePrefixKind,+ checked: boolean | string,+ ) => {+ if (typeof checked !== "boolean") {+ return;+ }+ const newPrefix = getQuotePrefix(lastQuotePrefix, checked, prefix);+ languageAdapter.setQuotePrefix(newPrefix);+ triggerUpdate();+ };++ actions = (+ <div className="flex flex-row w-full justify-end gap-1.5 items-center">+ <div className="flex items-center gap-1.5">+ <span>r</span>+ <Checkbox+ aria-label="Toggle raw string"+ className="w-3 h-3"+ checked={lastQuotePrefix.includes("r")}+ onCheckedChange={(checked) => {+ togglePrefix("r", checked);+ }}+ />+ </div>+ <div className="flex items-center gap-1.5">+ <span>f</span>+ <Checkbox+ aria-label="Toggle f-string"+ className="w-3 h-3"+ checked={lastQuotePrefix.includes("f")}+ onCheckedChange={(checked) => {+ togglePrefix("f", checked);+ }}+ />+ </div>+ <Tooltip content={<MarkdownQuotePrefixTooltip />}>+ <InfoIcon className="w-3 h-3" />+ </Tooltip>+ </div>+ );+ }+return (<TooltipProvider><div className="flex justify-between items-center gap-4 pl-2 pt-2">@@ -128,6 +182,69 @@ export const LanguagePanelComponent: React.FC<{);};+// Based on the current quote prefix and the checkbox state, return the new quote prefix+export function getQuotePrefix(+ currentQuotePrefix: QuotePrefixKind,+ checked: boolean,+ prefix: QuotePrefixKind,+) {+ let newQuotePrefix = currentQuotePrefix;+ if (checked) {+ // Add a prefix+ if (currentQuotePrefix === "") {+ newQuotePrefix = prefix;+ } else if (currentQuotePrefix !== "rf" && prefix !== currentQuotePrefix) {+ newQuotePrefix = "rf";+ }+ } else {+ // Removing a prefix+ if (currentQuotePrefix === prefix) {+ // Removing the only prefix+ newQuotePrefix = "";+ } else if (currentQuotePrefix === "rf") {+ newQuotePrefix = prefix === "r" ? "f" : "r";+ }+ }++ return newQuotePrefix;+}++const MarkdownQuotePrefixTooltip: React.FC = () => {+ return (+ <div className="flex flex-col gap-3.5">+ <section className="flex flex-col gap-0.5">+ <header className="flex items-center gap-1">+ <code className="text-xs px-1 py-0.5 bg-[var(--slate-2)] rounded">+ r+ </code>+ <span className="font-semibold">Raw String</span>+ </header>+ <p className="text-sm text-muted-foreground">+ Write LaTeX without escaping special characters+ </p>+ <pre className="text-xs bg-[var(--slate-2)] p-2 rounded">+ \alpha \beta+ </pre>+ </section>++ <section className="flex flex-col gap-0.5">+ <header className="flex items-center gap-1">+ <code className="text-xs px-1 py-0.5 bg-[var(--slate-2)] rounded">+ f+ </code>+ <span className="font-semibold">Format String</span>+ </header>+ <p className="text-sm text-muted-foreground">+ Interpolate Python values+ </p>+ <pre className="text-xs bg-[var(--slate-2)] p-2 rounded">+ Hello {"{name}"}! 😁+ </pre>+ </section>+ </div>+ );+};+interface SelectProps {languageAdapter: SQLLanguageAdapter;onChange: (engine: ConnectionName) => void;