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
docs: add marimo-embed-inline (#3261)
Myles Scolnickb61eee2f2bc4
diff --git a/docs/api/inputs/code_editor.md b/docs/api/inputs/code_editor.mdindex 117b1b109b..9b50351270 100644--- a/docs/api/inputs/code_editor.md+++ b/docs/api/inputs/code_editor.md@@ -1,14 +1,7 @@# Code Editor-/// marimo-embed--```python-def __():- mo.ui.code_editor(label="Code Editor", language="python")- return-```-+/// marimo-embed-file+ filepath: examples/ui/code_editor.py///::: marimo.ui.code_editordiff --git a/docs/blocks.py b/docs/blocks.pyindex d733eabdcf..4b684012f2 100644--- a/docs/blocks.py+++ b/docs/blocks.py@@ -4,22 +4,21 @@ from typing import Any, Dict, List, Union, castimport urllib.parsefrom pymdownx.blocks import BlocksExtension # type: ignore-from pymdownx.blocks.block import Block, type_string_in # type: ignore+from pymdownx.blocks.block import Block, type_string, type_string_in # type: ignore-class MarimoEmbedBlock(Block):- NAME: str = "marimo-embed"+class BaseMarimoBlock(Block):+ """Base class for marimo embed blocks"""+OPTIONS: Dict[str, List[Union[str, Any]]] = {"size": ["medium",type_string_in(["small", "medium", "large", "xlarge", "xxlarge"]),],- "app_width": ["wide", type_string_in(["wide", "full", "compact"])],"mode": ["read", type_string_in(["read", "edit"])],}def on_create(self, parent: etree.Element) -> etree.Element:- # Create container divcontainer = etree.SubElement(parent, "div")container.set("class", "marimo-embed-container")return container@@ -27,30 +26,14 @@ class MarimoEmbedBlock(Block):def on_add(self, block: etree.Element) -> etree.Element:return block- def on_end(self, block: etree.Element) -> None:- # Extract the Python code- code = block.text.strip() if block.text else ""-- # Remove ```python if present- if code.startswith("```python"):- code = code[9:] # first 9 characters are ```python- code = code[:-3] # last 3 characters are ```-- # Dedent the code- code = textwrap.dedent(code)-- # Create iframe element- size: str = cast(str, self.options["size"])- app_width: str = cast(str, self.options["app_width"])- mode: str = cast(str, self.options["mode"])- url = create_marimo_iframe(code=code, app_width=app_width, mode=mode)-+ def _create_iframe(self, block: etree.Element, url: str) -> None:# Clear existing contentblock.text = Nonefor child in block:block.remove(child)# Add iframe+ size: str = cast(str, self.options["size"])iframe = etree.SubElement(block, "iframe")iframe.set("class", f"demo {size}")iframe.set("src", url)@@ -67,14 +50,79 @@ class MarimoEmbedBlock(Block):return "raw"+class MarimoEmbedBlock(BaseMarimoBlock):+ NAME: str = "marimo-embed"+ OPTIONS: Dict[str, List[Union[str, Any]]] = {+ **BaseMarimoBlock.OPTIONS,+ "app_width": ["wide", type_string_in(["wide", "full", "compact"])],+ }++ def on_end(self, block: etree.Element) -> None:+ code = block.text.strip() if block.text else ""+ if code.startswith("```python"):+ code = code[9:]+ code = code[:-3]+ code = textwrap.dedent(code)++ app_width: str = cast(str, self.options["app_width"])+ mode: str = cast(str, self.options["mode"])+ url = create_marimo_app_url(+ code=create_marimo_app_code(code=code, app_width=app_width),+ mode=mode,+ )+ self._create_iframe(block, url)+++class MarimoEmbedFileBlock(BaseMarimoBlock):+ NAME: str = "marimo-embed-file"+ OPTIONS: Dict[str, List[Union[str, Any]]] = {+ **BaseMarimoBlock.OPTIONS,+ "filepath": ["", type_string],+ "show_source": ["true", type_string_in(["true", "false"])],+ }++ def on_end(self, block: etree.Element) -> None:+ filepath = cast(str, self.options["filepath"])+ if not filepath:+ raise ValueError("File path must be provided")++ # Read from project root+ try:+ with open(filepath, "r") as f:+ code = f.read()+ except FileNotFoundError:+ raise ValueError(f"File not found: {filepath}")++ mode: str = cast(str, self.options["mode"])+ url = create_marimo_app_url(code=code, mode=mode)+ self._create_iframe(block, url)++ # Add source code section if enabled+ show_source: str = cast(str, self.options.get("show_source", "true"))+ if show_source == "true":+ details = etree.SubElement(block, "details")+ summary = etree.SubElement(details, "summary")+ summary.text = f"Source code for `{filepath}`"++ # TODO: figure out syntax highlighting+ # md_text = f"\n\n```python\n{code}\n```\n\n"+ # result = self.md.htmlStash.store(self.md.convert(md_text))+ # container.text = result++ container = etree.SubElement(details, "pre")+ container.set("class", "marimo-source-code")+ code_block = etree.SubElement(container, "code")+ code_block.set("class", "language-python")+ code_block.text = code++def uri_encode_component(code: str) -> str:return urllib.parse.quote(code, safe="~()*!.'")-def create_marimo_iframe(+def create_marimo_app_code(*,code: str,- mode: str = "read",app_width: str = "wide",) -> str:header = "\n".join(@@ -92,14 +140,18 @@ def create_marimo_iframe(" return",])- body = header + code- encoded_code = uri_encode_component(body)+ return header + code+++def create_marimo_app_url(code: str, mode: str = "read") -> str:+ encoded_code = uri_encode_component(code)return f"https://marimo.app/?code={encoded_code}&embed=true&mode={mode}"class MarimoBlocksExtension(BlocksExtension):def extendMarkdownBlocks(self, md: Any, block_mgr: Any) -> None:block_mgr.register(MarimoEmbedBlock, self.getConfigs())+ block_mgr.register(MarimoEmbedFileBlock, self.getConfigs())def makeExtension(*args: Any, **kwargs: Any) -> MarimoBlocksExtension:diff --git a/docs/pyproject.toml b/docs/pyproject.tomlindex 60c361e595..88676b2f9c 100644--- a/docs/pyproject.toml+++ b/docs/pyproject.toml@@ -4,8 +4,8 @@ requires = ["hatchling"][project]dependencies = []-name = "docs"-version = "0.0.1"+name = "marimo_docs"+version = "0.1.0"[tool.hatch.build.targets.wheel]include = ["blocks.py"]diff --git a/mkdocs.yml b/mkdocs.ymlindex 2c8077d7cf..0f84918550 100644--- a/mkdocs.yml+++ b/mkdocs.yml@@ -27,6 +27,7 @@ extra_css:extra_javascript:- _static/js/analytics.jsmarkdown_extensions:+ - blocks:MarimoBlocksExtension- admonition- attr_list- def_list@@ -62,7 +63,6 @@ markdown_extensions:- pymdownx.tasklist:custom_checkbox: true- pymdownx.tilde- - blocks:MarimoBlocksExtension- mkdocs-clicknav:- Marimo: index.mddiff --git a/pyproject.toml b/pyproject.tomlindex 33c1a7a188..e96cce4acb 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -248,9 +248,12 @@ python = ["3.9", "3.10", "3.11", "3.12"][tool.hatch.envs.docs]features = ["dev", "docs"]dependencies = [- "docs @ file://docs",+ "marimo_docs @ file://docs",]+[tool.uv.sources]+marimo_docs = { path = "./docs", editable = true }+[tool.hatch.envs.docs.scripts]build = "mkdocs build {args}"serve = "mkdocs serve --clean {args}"