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(export): support Markdown flavors in session export (#10368)
Péter Gyarmati878e008828bc
diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.tsindex 221970a22c..0e961981d4 100644--- a/frontend/src/core/network/types.ts+++ b/frontend/src/core/network/types.ts@@ -17,6 +17,8 @@ export type CellConfig = schemas["CellConfig"];export type RuntimeState = schemas["CellNotification"]["status"];export type CodeCompletionRequest = schemas["CodeCompletionRequest"];export type DeleteCellRequest = schemas["DeleteCellRequest"];+export type AutoExportAsMarkdownRequest =+ schemas["AutoExportAsMarkdownRequest"];export type ExportAsHTMLRequest = schemas["ExportAsHTMLRequest"];export type ExportAsMarkdownRequest = schemas["ExportAsMarkdownRequest"];export type ExportAsIPYNBRequest = schemas["ExportAsIPYNBRequest"];@@ -221,7 +223,7 @@ export interface EditRequests {) => Promise<ExportedFile<string>>;exportAsPDF: (request: ExportAsPDFRequest) => Promise<ExportedFile<Blob>>;autoExportAsHTML: (request: ExportAsHTMLRequest) => Promise<null>;- autoExportAsMarkdown: (request: ExportAsMarkdownRequest) => Promise<null>;+ autoExportAsMarkdown: (request: AutoExportAsMarkdownRequest) => Promise<null>;autoExportAsIPYNB: (request: ExportAsIPYNBRequest) => Promise<null>;updateCellOutputs: (request: UpdateCellOutputsRequest) => Promise<null>;// Package requestsdiff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.pyindex d8fd239b60..4867a84147 100644--- a/marimo/_cli/development/commands.py+++ b/marimo/_cli/development/commands.py@@ -352,6 +352,7 @@ def _generate_server_api_schema() -> dict[str, Any]:completion.AiCompletionRequest,completion.AiInlineCompletionRequest,completion.ChatRequest,+ export.AutoExportAsMarkdownRequest,export.ExportAsHTMLRequest,export.ExportAsMarkdownRequest,export.ExportAsScriptRequest,diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.pyindex 791528991b..4471a33225 100644--- a/marimo/_pyodide/pyodide_session.py+++ b/marimo/_pyodide/pyodide_session.py@@ -36,11 +36,10 @@ from marimo._runtime.commands import (from marimo._runtime.marimo_pdb import MarimoPdbfrom marimo._schemas.export import (ExportAsHTMLRequest,+ ExportAsMarkdownRequest,ExportedFile,to_html_export_options,-)-from marimo._schemas.export_options import (- MarkdownExportOptions,+ to_markdown_export_options,)from marimo._server.files.os_file_system import OSFileSystemfrom marimo._server.models.files import (@@ -419,11 +418,16 @@ class PyodideBridge:)def export_markdown(self, request: str) -> str:- del request+ parsed = self._parse(request, ExportAsMarkdownRequest)+ filename = self.session.app_manager.filenameresult = export_markdown(MarkdownExportRequest(notebook=self.session.app_manager.app.to_ir(),- options=MarkdownExportOptions(),+ options=to_markdown_export_options(+ parsed,+ filename=filename,+ source_filename=filename,+ ),))return self._dump(diff --git a/marimo/_schemas/export.py b/marimo/_schemas/export.pyindex 0363de5405..e00ebce998 100644--- a/marimo/_schemas/export.py+++ b/marimo/_schemas/export.py@@ -3,10 +3,12 @@ from __future__ import annotationsimport msgspec+from marimo._convert.markdown.flavor.base import MarkdownFlavorNamefrom marimo._messaging.mimetypes import MimeBundleTuplefrom marimo._schemas.export_options import (ExportPDFPreset,HTMLExportOptions,+ MarkdownExportOptions,PDFRasterServer,)from marimo._types.ids import CellId_t@@ -39,6 +41,24 @@ class ExportAsIPYNBRequest(msgspec.Struct, rename="camel"):class ExportAsMarkdownRequest(msgspec.Struct, rename="camel"):download: bool+ flavor: MarkdownFlavorName | None = None+++class AutoExportAsMarkdownRequest(msgspec.Struct, rename="camel"):+ download: bool+++def to_markdown_export_options(+ request: ExportAsMarkdownRequest,+ *,+ filename: str | None = None,+ source_filename: str | None = None,+) -> MarkdownExportOptions:+ return MarkdownExportOptions(+ flavor=request.flavor,+ filename=filename,+ source_filename=source_filename,+ )class ExportAsPDFRequest(msgspec.Struct, rename="camel"):diff --git a/marimo/_server/api/endpoints/export.py b/marimo/_server/api/endpoints/export.pyindex bc514c4041..fb4d87dfe4 100644--- a/marimo/_server/api/endpoints/export.py+++ b/marimo/_server/api/endpoints/export.py@@ -44,6 +44,7 @@ from marimo._schemas.export import (ExportAsScriptRequest,UpdateCellOutputsRequest,to_html_export_options,+ to_markdown_export_options,)from marimo._schemas.export_options import (IPYNBExportOptions,@@ -318,7 +319,8 @@ async def export_as_markdown(result = export_markdown(MarkdownExportRequest(notebook=app_file_manager.app.to_ir(),- options=MarkdownExportOptions(+ options=to_markdown_export_options(+ body,filename=app_file_manager.filename,source_filename=app_file_manager.filename,),@@ -408,7 +410,7 @@ async def auto_export_as_markdown(content:application/json:schema:- $ref: "#/components/schemas/ExportAsMarkdownRequest"+ $ref: "#/components/schemas/AutoExportAsMarkdownRequest"responses:200:description: Export the notebook as a markdowndiff --git a/packages/openapi/api.yaml b/packages/openapi/api.yamlindex 5ac5051665..36321596e8 100644--- a/packages/openapi/api.yaml+++ b/packages/openapi/api.yaml@@ -255,6 +255,14 @@ components:required: []title: AnthropicConfigtype: object+ AutoExportAsMarkdownRequest:+ properties:+ download:+ type: boolean+ required:+ - download+ title: AutoExportAsMarkdownRequest+ type: objectBannerNotification:description: "Persistent banner message at top of notebook.\n\n Attributes:\n\\ title: Banner title.\n description: Banner body (may contain\@@ -1743,6 +1751,15 @@ components:properties:download:type: boolean+ flavor:+ anyOf:+ - enum:+ - mdx+ - mystmd+ - pymdown+ - qmd+ - type: 'null'+ default: nullrequired:- downloadtitle: ExportAsMarkdownRequest@@ -6358,7 +6375,7 @@ paths:content:application/json:schema:- $ref: '#/components/schemas/ExportAsMarkdownRequest'+ $ref: '#/components/schemas/AutoExportAsMarkdownRequest'responses:200:content:diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.tsindex 4cf2cd2e22..73706ff35c 100644--- a/packages/openapi/src/api.ts+++ b/packages/openapi/src/api.ts@@ -821,7 +821,7 @@ export interface paths {};requestBody?: {content: {- "application/json": components["schemas"]["ExportAsMarkdownRequest"];+ "application/json": components["schemas"]["AutoExportAsMarkdownRequest"];};};responses: {@@ -3705,6 +3705,10 @@ export interface components {AnthropicConfig: {api_key?: string;};+ /** AutoExportAsMarkdownRequest */+ AutoExportAsMarkdownRequest: {+ download: boolean;+ };/*** BannerNotification* @description Persistent banner message at top of notebook.@@ -4632,6 +4636,8 @@ export interface components {/** ExportAsMarkdownRequest */ExportAsMarkdownRequest: {download: boolean;+ /** @default null */+ flavor?: ("mdx" | "mystmd" | "pymdown" | "qmd") | null;};/** ExportAsPDFRequest */ExportAsPDFRequest: {diff --git a/tests/_pyodide/test_pyodide_session.py b/tests/_pyodide/test_pyodide_session.pyindex 78086b251c..4b6fa27a3b 100644--- a/tests/_pyodide/test_pyodide_session.py+++ b/tests/_pyodide/test_pyodide_session.py@@ -1042,16 +1042,30 @@ def test_pyodide_bridge_export_html(assert len(exported_file["contents"]) > 0+ ("flavor", "expected_filename", "expected_fence"),+ [+ (None, "test.md", "```python {.marimo}"),+ ("qmd", "test.qmd", "```{marimo .python"),+ ],+)def test_pyodide_bridge_export_markdown(pyodide_bridge: PyodideBridge,+ flavor: str | None,+ expected_filename: str,+ expected_fence: str,) -> None:"""Test exporting markdown through the bridge."""- result = pyodide_bridge.export_markdown("{}")+ request = {"download": False}+ if flavor is not None:+ request["flavor"] = flavor++ result = pyodide_bridge.export_markdown(json.dumps(request))exported_file = json.loads(result)- assert exported_file["filename"] == "test.md"+ assert exported_file["filename"] == expected_filenameassert exported_file["mediaType"] == "text/plain; charset=utf-8"- assert len(exported_file["contents"]) > 0+ assert expected_fence in exported_file["contents"]async def test_pyodide_bridge_read_snippets(diff --git a/tests/_server/api/endpoints/test_export.py b/tests/_server/api/endpoints/test_export.pyindex e638fd1729..c310bf6e8d 100644--- a/tests/_server/api/endpoints/test_export.py+++ b/tests/_server/api/endpoints/test_export.py@@ -12,6 +12,7 @@ from typing import TYPE_CHECKINGimport pytestfrom marimo import __version__+from marimo._convert.markdown.flavor.base import MarkdownFlavorNamefrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._export.requests import PDFExportRequest, PDFRasterizationRequestfrom marimo._messaging.cell_output import CellChannel, CellOutput@@ -250,6 +251,42 @@ def test_export_markdown_uses_qmd_filename(assert response.headers["Content-Type"] == "text/plain; charset=utf-8"+@with_session(SESSION_ID)+def test_export_markdown_uses_requested_flavor(+ client: TestClient,+ *,+ temp_marimo_file: str,+) -> None:+ session = get_session_manager(client).get_session(SESSION_ID)+ assert session+ session.app_file_manager.filename = temp_marimo_file++ cases: list[tuple[MarkdownFlavorName, str, str]] = [+ ("pymdown", ".md", "```python {.marimo}"),+ ("qmd", ".qmd", "```{marimo .python"),+ ("mystmd", ".myst.md", "```{marimo} python"),+ ("mdx", ".mdx", "```python marimo"),+ ]+ for flavor, expected_suffix, expected_fence in cases:+ response = client.post(+ "/api/export/markdown",+ headers=HEADERS,+ json={+ "download": False,+ "flavor": flavor,+ },+ )++ expected_filename = f"{Path(temp_marimo_file).stem}{expected_suffix}"+ assert response.status_code == 200+ assert expected_fence in response.text+ assert (+ response.headers["Content-Disposition"]+ == f"inline; filename*=UTF-8''{expected_filename}"+ )+ assert response.headers["Content-Type"] == "text/plain; charset=utf-8"++@pytest.mark.skipif(not DependencyManager.nbformat.has(), reason="nbformat not installed")