Skip to content

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.

Persist App state + Cell state in md conversions (#1326)

Dylan Madisetti6421f0296ccd
diff --git a/marimo/_cli/convert/markdown.py b/marimo/_cli/convert/markdown.py
index 1c0eb9d5b4..72faeb56bb 100644
--- a/marimo/_cli/convert/markdown.py
+++ b/marimo/_cli/convert/markdown.py
@@ -2,12 +2,11 @@
from __future__ import annotations
import re
-from typing import Any, Callable, Literal
+from typing import Any, Callable, Literal, Optional
# Native to python
from xml.etree.ElementTree import Element, SubElement
-# Note: yaml is also a python builtin
import yaml
# Markdown is a dependency of marimo, as such we utilize it as much as possible
@@ -24,8 +23,10 @@ from pymdownx.superfences import ( # type: ignore
SuperFencesCodeExtension,
)
+from marimo._ast import codegen
from marimo._ast.app import _AppConfig
-from marimo._cli.convert.utils import generate_from_sources, markdown_to_marimo
+from marimo._ast.cell import CellConfig
+from marimo._cli.convert.utils import markdown_to_marimo
# CSafeLoader is faster than SafeLoader.
try:
@@ -42,35 +43,60 @@ def _is_code_tag(text: str) -> bool:
return bool(re.search(r"\{.*python.*\}", head))
-def formatted_code_block(code: str) -> str:
+def formatted_code_block(
+ code: str, attributes: Optional[dict[str, str]] = None
+) -> str:
+ """Wraps code in a fenced code block with marimo attributes."""
+ if attributes is None:
+ attributes = {}
+ attribute_str = " ".join(
+ [""] + [f'{key}="{value}"' for key, value in attributes.items()]
+ )
guard = "```"
while guard in code:
guard += "`"
- return "\n".join([f"""{guard}{{.python.marimo}}""", code, guard, ""])
+ return "\n".join(
+ [f"""{guard}{{.python.marimo{attribute_str}}}""", code, guard, ""]
+ )
def _tree_to_app(root: Element) -> str:
# Extract meta data from root attributes.
- config_keys = {"title": "app_title"}
+ config_keys = {"title": "app_title", "marimo-layout": "layout_file"}
config = {
config_keys[key]: value
for key, value in root.items()
if key in config_keys
}
+ # Try to pass on other attributes as is
+ config.update({k: v for k, v in root.items() if k not in config_keys})
+
app_config = _AppConfig.from_untrusted_dict(config)
- sources = []
+ sources: list[str] = []
+ names: list[str] = []
+ cell_config: list[CellConfig] = []
for child in root:
- source = child.text
- if not (source and source.strip()):
- continue
+ names.append(child.get("name", "__"))
+ boolean_attrs = {k: v == "true" for k, v in child.attrib.items()}
+ cell_config.append(CellConfig.from_dict(boolean_attrs))
+
+ source = child.text if child.text else ""
if child.tag == MARIMO_MD:
+ # Only check here to allow for empty code blocks.
+ if not (source and source.strip()):
+ continue
source = markdown_to_marimo(source)
else:
assert child.tag == MARIMO_CODE, f"Unknown tag: {child.tag}"
sources.append(source)
- return generate_from_sources(sources, app_config)
+ return codegen.generate_filecontents(
+ sources,
+ names,
+ cell_config,
+ config=app_config,
+ )
class IdentityParser(Markdown):
@@ -297,17 +323,38 @@ class ExpandAndClassifyProcessor(BlockProcessor):
# Superfences replaces code blocks with a placeholder,
# Check for the placeholder, and ensure it is a marimo code block,
# otherwise consider it as markdown.
- if HTML_PLACEHOLDER_RE.match(line.strip()):
- lookup = line.strip()[1:-1]
- code = self.stash[lookup][0]
- if _is_code_tag(code):
+ if not HTML_PLACEHOLDER_RE.match(line.strip()):
+ # Use <!----> to indicate a separation between cells.
+ if line.strip() == "<!---->":
add_paragraph()
- code_block = SubElement(parent, MARIMO_CODE)
- code_block.text = "\n".join(code.split("\n")[1:-1])
- else:
- text.extend(code.split("\n"))
- else:
+ continue
text.append(line)
+ continue
+
+ lookup = line.strip()[1:-1]
+ code = self.stash[lookup][0]
+ if not _is_code_tag(code):
+ text.extend(code.split("\n"))
+ continue
+
+ # Definitively a code block, so add the previous markdown.
+ add_paragraph()
+
+ code_block = SubElement(parent, MARIMO_CODE)
+ block_lines = code.split("\n")
+ code_block.text = "\n".join(block_lines[1:-1])
+ # Extract attributes from the code block.
+ # Blocks are expected to be like this:
+ # {.python.marimo disabled="true"}
+ fence_start = RE_NESTED_FENCE_START.match(block_lines[0])
+ if fence_start:
+ # attrs is a bit of a misnomer, matches
+ # .python.marimo disabled="true"
+ inner = fence_start.group("attrs")
+ if inner:
+ code_block.attrib = dict(
+ re.findall(r'(\w+)="([^"]*)"', inner)
+ )
add_paragraph()
# Flush to indicate all blocks have been processed.
blocks.clear()
diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.py
index 8a67f9c635..75b51d04f3 100644
--- a/marimo/_server/export/exporter.py
+++ b/marimo/_server/export/exporter.py
@@ -3,7 +3,6 @@ from __future__ import annotations
import mimetypes
import os
-from textwrap import dedent
from typing import cast
from marimo import __version__
@@ -123,39 +122,67 @@ class Exporter:
return code, download_filename
def export_as_md(self, file_manager: AppFileManager) -> tuple[str, str]:
+ import yaml
+
+ from marimo._ast.app import _AppConfig
from marimo._cli.convert.markdown import (
formatted_code_block,
is_sanitized_markdown,
)
- # TODO: Provide filter or kernel in header such that markdown documents
- # are executable.
- document = [
- dedent(
- f"""
- ---
- title: {get_app_title(file_manager)}
- marimo-version: {__version__}
- ---"""
- ).strip(),
- "",
- ]
+ # TODO: Provide filter or kernel in yaml header such that markdown
+ # documents are executable.
+
+ # Put data from AppFileManager into the yaml header.
+ ignored_keys = {"app_title", "layout_file"}
+ metadata = {
+ "title": get_app_title(file_manager),
+ "marimo-version": __version__,
+ "marimo-layout": file_manager.app.config.layout_file,
+ }
+ # Get values defined in _AppConfig without explicitly extracting keys,
+ # as long as it isn't the default.
+ metadata.update(
+ {
+ k: v
+ for k, v in file_manager.app.config.asdict().items()
+ if k not in ignored_keys and v != _AppConfig.__dict__[k]
+ }
+ )
+
+ header = yaml.dump(
+ {k: v for k, v in metadata.items() if v is not None},
+ sort_keys=False,
+ )
+ document = ["---", header.strip(), "---", ""]
previous_was_markdown = False
for cell_data in file_manager.app.cell_manager.cell_data():
cell = cell_data.cell
code = cell_data.code
+ # Config values are opt in, so only include if they are set.
+ attributes = cell_data.config.asdict()
+ attributes = {k: "true" for k, v in attributes.items() if v}
+ if cell_data.name != "__":
+ attributes["name"] = cell_data.name
+ # No "cell" means not parseable. As such, treat as code, as
+ # everything in marimo is code.
if cell:
markdown = get_markdown_from_cell(cell, code)
# Unsanitized markdown is forced to code.
if markdown and is_sanitized_markdown(markdown):
+ # Use blank HTML comment to separate markdown codeblocks
+ if previous_was_markdown:
+ document.append("<!---->")
previous_was_markdown = True
document.append(markdown)
continue
- # Add a blank line between markdown and code
- if previous_was_markdown:
- document.append("")
- previous_was_markdown = False
- document.append(formatted_code_block(code))
+ else:
+ attributes["unparsable"] = "true"
+ # Add a blank line between markdown and code
+ if previous_was_markdown:
+ document.append("")
+ previous_was_markdown = False
+ document.append(formatted_code_block(code, attributes))
download_filename = get_download_filename(file_manager, ".md")
return "\n".join(document).strip(), download_filename
diff --git a/tests/_cli/snapshots/broken.txt b/tests/_cli/snapshots/broken.txt
index 3dc7982a5e..04bb48df46 100644
--- a/tests/_cli/snapshots/broken.txt
+++ b/tests/_cli/snapshots/broken.txt
@@ -3,6 +3,14 @@ title: Notebook
marimo-version: 0.0.0
---
+```{.python.marimo unparsable="true"}
+return
+```
+
+```{.python.marimo unparsable="true"}
+partial_statement =
+```
+
```{.python.marimo}
valid_statement = 1
```
diff --git a/tests/_cli/snapshots/dataflow.md.txt b/tests/_cli/snapshots/dataflow.md.txt
index 036c0b79f1..402c555118 100644
--- a/tests/_cli/snapshots/dataflow.md.txt
+++ b/tests/_cli/snapshots/dataflow.md.txt
@@ -11,6 +11,7 @@ automatically.
To provide reactive execution, marimo creates a dataflow graph out of your
cells.
+<!---->
## References and definitions
A marimo notebook is a directed acyclic graph in which nodes represent
@@ -25,12 +26,13 @@ global variables defined by the former cell.
The rule for reactive execution can be restated in terms of the graph: when
a cell is run, its descendants are run automatically.
+<!---->
### Example
The next four cells plot a sine wave with a given period and amplitude.
Each cell is labeled with its refs and defs.
-```{.python.marimo}
+```{.python.marimo hide_code="true"}
mo.accordion(
{
"Tip: inspecting refs and defs": f"""
@@ -111,6 +113,7 @@ mo.md(
🌊 **Try it!** In the above cells, try changing the value `period` or
`ampltitude`, then click the run button ( ▷ ) to register your changes.
See what happens to the sine wave.
+<!---->
Here is the dataflow graph for the cells that make the sine wave plot, plus
the cells that import libraries. Each cell is labeled with its defs.
@@ -132,17 +135,20 @@ the cells that import libraries. Each cell is labeled with its defs.
```
The last cell, which doesn't define anything, produces the plot.
+<!---->
## Dataflow programming
marimo's runtime rule has some important consequences that may seem
surprising if you are not used to dataflow programming. We list these
below.
+<!---->
### Execution order is not cell order
The order in which cells are executed is determined entirely by the
dataflow graph. This makes marimo notebooks more reproducible than
traditional notebooks. It also lets you place boilerplate, like
imports or long markdown strings, at the bottom of the editor.
+<!---->
### Global variable names must be unique
Every global variable can be defined by only one cell. Without this
@@ -164,6 +170,7 @@ planet
**🌊 Try it!** In the previous cell, change the name `planet` to `home`,
then run the cell.
+<!---->
Because defs must be unique, global variables cannot be modified with
operators like `+=` or `-=` in cells other than the one that created
them; these operators count as redefinitions of a name.
@@ -262,7 +269,7 @@ state = namespace()
state.number = 0
```
-```{.python.marimo}
+```{.python.marimo hide_code="true"}
mo.accordion(
{
"Why not track attributes?": """
@@ -280,7 +287,7 @@ In Python, it's impossible to know whether code will
mutate an object without running it. So: mutations (such as
appending to a list) will not trigger reactive execution.
-```{.python.marimo}
+```{.python.marimo hide_code="true"}
mo.accordion(
{
"Tip (advanced): mutable state": (
@@ -318,7 +325,7 @@ Check out the tutorial on interactivity for a tour of UI elements:
marimo tutorial ui
```
-```{.python.marimo}
+```{.python.marimo hide_code="true"}
matplotlib_installed = False
numpy_installed = False
@@ -337,7 +344,7 @@ except ModuleNotFoundError:
pass
```
-````{.python.marimo}
+````{.python.marimo hide_code="true"}
tips = {
"Use global variables sparingly": (
"""
diff --git a/tests/_cli/snapshots/marimo_for_jupyter_users.md.txt b/tests/_cli/snapshots/marimo_for_jupyter_users.md.txt
index 20b46b0b77..5ef04c8928 100644
--- a/tests/_cli/snapshots/marimo_for_jupyter_users.md.txt
+++ b/tests/_cli/snapshots/marimo_for_jupyter_users.md.txt
@@ -7,6 +7,7 @@ marimo-version: 0.0.0
This notebook explains important differences between Jupyter and marimo. If you're
familiar with Jupyter and are trying out marimo for the first time, read on!
+<!---->
## Reactive execution
The biggest difference between marimo and Jupyter is *reactive execution*.
@@ -29,6 +30,7 @@ references. When you execute one cell, marimo automatically executes all other
cells that depend on it, not unlike a spreadsheet.
In contrast, Jupyter requires you to manually run each cell.
+<!---->
### Why?
Reactive execution frees you from the tedious task of manually re-running cells.
@@ -40,6 +42,7 @@ It also ensures that your code and outputs remain in sync:
program memory. Affected cells are automatically invalidated.
This makes marimo notebooks as reproducible as regular Python scripts.
+<!---->
## Interactive elements built-in
marimo comes with a [large library of UI elements](https://docs.marimo.io/guides/interactivity.html) that are automatically
@@ -66,6 +69,7 @@ reactive execution model: interactions automatically trigger execution of
cells that refer to them.
In contrast, Jupyter's lack of reactivity makes IPyWidgets difficult to use.
+<!---->
## Shareable as apps
marimo notebooks can be shared as read-only web apps: just serve it with
@@ -77,6 +81,7 @@ at the command-line.
Not every marimo notebook needs to be shared as an app, but marimo makes it
seamless to do so if you want to. In this way, marimo works as a replacement
for both Jupyter and Streamlit.
+<!---->
## Cell order
In marimo, cells can be arranged in any order — marimo figures out the one true way to execute them based on variable declarations and references (in a ["topologically sorted"](https://en.wikipedia.org/wiki/Topological_sorting#:~:text=In%20computer%20science%2C%20a%20topological,before%20v%20in%20the%20ordering.) order)
@@ -92,6 +97,7 @@ z = mo.ui.slider(1, 10, label="$z$"); z
This lets you arrange your cells in the way that makes the most sense to you. For example, put helper functions and imports at the bottom of a notebook, like an appendix.
In contrast, Jupyter notebooks implicitly assume a top-to-bottom execution order.
+<!---->
## Re-assigning variables
marimo disallows variable re-assignment. Here is something commonly done in Jupyter notebooks that cannot be done in marimo:
@@ -115,6 +121,7 @@ If you run into this error, here are your options:
1. combine definitions into one cell
2. prefix variables with an underscore (`_df`) to make them local to the cell
3. wrap your code in functions, or give your variables more descriptive names
+<!---->
## Markdown
marimo only has Python cells, but you can still write Markdown: `import marimo as mo` and use `mo.md` to write Markdown.
@@ -133,6 +140,7 @@ how to render its own elements, and you can use `mo.as_html` to render other
objects, like plots.
_Tip: toggle a markdown view via `Cmd/Ctrl-Shift-M` in an empty cell._
+<!---->
## Notebook files
Jupyter saves notebooks as JSON files, with outputs serialized in them. This is helpful as a record of your plots and other results, but makes notebooks difficult to version and reuse.
@@ -146,6 +154,7 @@ marimo does _not_ save your outputs in the file; if you want them saved, make su
### marimo notebooks are versionable with git
marimo is designed so that small changes in your code yield small git diffs!
+<!---->
## Parting thoughts
marimo is a **reinvention** of the Python notebook as a reproducible, interactive, and shareable Python program, instead of an error-prone scratchpad.
diff --git a/tests/_cli/snapshots/unsafe-doc.md.txt b/tests/_cli/snapshots/unsafe-doc.md.txt
index 71ff2828a1..702d9adc16 100644
--- a/tests/_cli/snapshots/unsafe-doc.md.txt
+++ b/tests/_cli/snapshots/unsafe-doc.md.txt
@@ -18,14 +18,48 @@ print("Hello, World!")
```marimo run convert document.md```
+```{.python.marimo unparsable="true"}
+it's an unparsable cell
+```
+
<!-- Actually markdown -->
```{python} `
print("Hello, World!")
-<!-- Normal code block -->
+<!-- Disabled code block -->
-```{.python.marimo}
+```{.python.marimo disabled="true"}
+1 + 1
+```
+
+<!-- Hidden code block -->
+
+```{.python.marimo hide_code="true"}
1 + 1
```
+<!-- Empty code block -->
+
+```{.python.marimo}
+
+```
+
+<!-- Improperly nested code block -->
+
+````{.python.marimo unparsable="true"}
+"""
+```{python}
+print("Hello, World!")
+````
+
+\"\"\"
+```
+
+<!-- Improperly nested code block -->
+```{python}
+````{python}
+print("Hello, World!")
+````
+```
+
-->
\ No newline at end of file
diff --git a/tests/_cli/snapshots/unsafe-doc.py.txt b/tests/_cli/snapshots/unsafe-doc.py.txt
index 4aeabcc93a..ce8c805dab 100644
--- a/tests/_cli/snapshots/unsafe-doc.py.txt
+++ b/tests/_cli/snapshots/unsafe-doc.py.txt
@@ -32,18 +32,50 @@ def __(mo):
-->
```marimo run convert document.md```
+ """
+ )
+ return
+
+app._unparsable_cell(
+ r"""
+ it's an unparsable cell
+ """,
+ name="__"
+)
+
+
+def __(mo):
+ mo.md(
+ r"""
<!-- Actually markdown -->
```{python} `
print("Hello, World!")
- <!-- Normal code block -->
+ <!-- Disabled code block -->
"""
)
return
[email protected](disabled=True)
+def __():
+ 1 + 1
+ return
+
+
@app.cell
+def __(mo):
+ mo.md(
+ r"""
+ <!-- Hidden code block -->
+ """
+ )
+ return
+
+
[email protected](hide_code=True)
def __():
1 + 1
return
@@ -53,6 +85,51 @@ def __():
def __(mo):
mo.md(
r"""
+ <!-- Empty code block -->
+ """
+ )
+ return
+
+
+def __():
+ return
+
+
+def __(mo):
+ mo.md(
+ r"""
+ <!-- Improperly nested code block -->
+ """
+ )
+ return
+
+
+app._unparsable_cell(
+ r"""
+ \"\"\"
+ ```{python}
+ print(\"Hello, World!\")
+ """,
+ name="__"
+)
+
+
+def __(mo):
+ mo.md(
+ r"""
+ \"\"\"
+ ```
+
+ <!-- Improperly nested code block -->
+ ```{python}
+ ````{python}
+ print("Hello, World!")
+ ````
+ ```
+
-->
"""
)
diff --git a/tests/_cli/test_markdown_conversion.py b/tests/_cli/test_markdown_conversion.py
index e0f7e644f6..ef42f0852e 100644
--- a/tests/_cli/test_markdown_conversion.py
+++ b/tests/_cli/test_markdown_conversion.py
@@ -2,6 +2,7 @@
from __future__ import annotations
import os
+import re
import sys
import tempfile
from textwrap import dedent
@@ -49,7 +50,7 @@ def convert_from_py(py: str) -> str:
os.remove(tempfile_name)
title = format_filename_title(tempfile_name)
- output = output.replace(title, "Test Notebook")
+ output = re.sub(rf"'?{title}'?", "Test Notebook", output)
return sanitized_version(output)
@@ -243,15 +244,44 @@ def test_md_to_python_code_injection() -> None:
```marimo run convert document.md```
+ ```{python}
+ it's an unparsable cell
+ ```
+
<!-- Actually markdown -->
```{python} `
print("Hello, World!")
- <!-- Normal code block -->
- ```{python}
+ <!-- Disabled code block -->
+ ```{python disabled="true"}
+ 1 + 1
+ ```
+
+ <!-- Hidden code block -->
+ ```{python hide_code="true"}
1 + 1
```
+ <!-- Empty code block -->
+ ```{python}
+ ```
+
+ <!-- Improperly nested code block -->
+ ```{python}
+ \"""
+ ```{python}
+ print("Hello, World!")
+ ```
+ \"""
+ ```
+
+ <!-- Improperly nested code block -->
+ ```{python}
+ ````{python}
+ print("Hello, World!")
+ ````
+ ```
+
-->
"""[1:]
)