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.

feat: marimo edit/run markdown.md (#1332)

Dylan Madisetti579ffbd67e29
diff --git a/MANIFEST.in b/MANIFEST.in
index cfa41e0868..7c87bbeb5b 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -1,5 +1,6 @@
recursive-include marimo/_static *
recursive-include marimo/_lsp *
+recursive-include marimo/_tutorials *
include marimo/py.typed
include third_party.txt
include third_party_licenses.txt
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index 331c63c7fb..f774d40159 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -575,11 +575,17 @@ class InternalApp:
for cell_id, code, name, config in zip(
cell_ids, codes, names, configs
):
+ cell = None
+ # If the cell exists, the cell data should be set.
+ cell_data = self._app._cell_manager._cell_data.get(cell_id)
+ if cell_data is not None:
+ cell = cell_data.cell
new_cell_manager.register_cell(
cell_id=cell_id,
code=code,
name=name,
config=config,
+ cell=cell,
)
self._app._cell_manager = new_cell_manager
return self
diff --git a/marimo/_ast/codegen.py b/marimo/_ast/codegen.py
index 2092f3260a..0cc94b49f9 100644
--- a/marimo/_ast/codegen.py
+++ b/marimo/_ast/codegen.py
@@ -13,6 +13,7 @@ from marimo._ast.app import App, _AppConfig
from marimo._ast.cell import CellConfig, CellImpl
from marimo._ast.compiler import compile_cell
from marimo._ast.visitor import Name
+from marimo._cli.convert.markdown import convert_from_md_to_app
if TYPE_CHECKING:
from collections.abc import Sequence
@@ -150,6 +151,7 @@ def generate_filecontents(
names: list[str],
cell_configs: list[CellConfig],
config: Optional[_AppConfig] = None,
+ header_comments: Optional[str] = None,
) -> str:
"""Translates a sequences of codes (cells) to a Python file"""
cell_data: list[Union[CellImpl, tuple[str, CellConfig]]] = []
@@ -193,6 +195,8 @@ def generate_filecontents(
+ indent_text("app.run()")
)
+ if header_comments:
+ filecontents = header_comments.rstrip() + "\n\n" + filecontents
return filecontents + "\n"
@@ -211,6 +215,9 @@ def get_app(filename: Optional[str]) -> Optional[App]:
if not contents:
return None
+ if filename.endswith(".md"):
+ return convert_from_md_to_app(contents)
+
spec = importlib.util.spec_from_file_location("marimo_app", filename)
if spec is None:
raise RuntimeError("Failed to load module spec")
diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.py
index bb61867073..08356b213c 100644
--- a/marimo/_cli/cli.py
+++ b/marimo/_cli/cli.py
@@ -1,12 +1,11 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-import inspect
import json
import os
import pathlib
import tempfile
-from typing import Any, Literal, Optional
+from typing import Any, Optional, get_args
import click
@@ -24,6 +23,12 @@ from marimo._server.file_router import AppFileRouter
from marimo._server.model import SessionMode
from marimo._server.start import start
from marimo._server.tokens import AuthToken
+from marimo._tutorials import (
+ PythonTutorial,
+ Tutorial,
+ get_tutorial_source,
+ tutorial_order,
+)
from marimo._utils.marimo_path import MarimoPath
DEVELOPMENT_MODE = False
@@ -476,15 +481,8 @@ tutorials, starting with the intro:
Recommended sequence:
\b
- - intro
- - dataflow
- - ui
- - markdown
- - plots
- - layout
- - fileformat
- - for-jupyter-users
"""
+ + "\n".join(f" - {name}" for name in tutorial_order)
)
@click.option(
"-p",
@@ -526,18 +524,7 @@ Recommended sequence:
@click.argument(
"name",
required=True,
- type=click.Choice(
- [
- "intro",
- "dataflow",
- "ui",
- "markdown",
- "plots",
- "layout",
- "fileformat",
- "for-jupyter-users",
- ]
- ),
+ type=click.Choice(tutorial_order),
)
def tutorial(
port: Optional[int],
@@ -545,41 +532,12 @@ def tutorial(
headless: bool,
token: bool,
token_password: Optional[str],
- name: Literal[
- "intro",
- "dataflow",
- "ui",
- "markdown",
- "plots",
- "layout",
- "fileformat",
- "for-jupyter-users",
- ],
+ name: Tutorial,
) -> None:
- from marimo._tutorials import (
- dataflow,
- fileformat,
- intro,
- layout,
- marimo_for_jupyter_users,
- markdown,
- plots,
- ui,
- )
-
- tutorials = {
- "intro": intro,
- "dataflow": dataflow,
- "ui": ui,
- "markdown": markdown,
- "plots": plots,
- "layout": layout,
- "fileformat": fileformat,
- "for-jupyter-users": marimo_for_jupyter_users,
- }
- source = inspect.getsource(tutorials[name])
+ source = get_tutorial_source(name)
d = tempfile.TemporaryDirectory()
- fname = os.path.join(d.name, name + ".py")
+ extension = "py" if name in get_args(PythonTutorial) else "md"
+ fname = os.path.join(d.name, f"{name}.{extension}")
path = MarimoPath(fname)
path.write_text(source)
diff --git a/marimo/_cli/convert/markdown.py b/marimo/_cli/convert/markdown.py
index 72faeb56bb..c36fa727de 100644
--- a/marimo/_cli/convert/markdown.py
+++ b/marimo/_cli/convert/markdown.py
@@ -2,7 +2,8 @@
from __future__ import annotations
import re
-from typing import Any, Callable, Literal, Optional
+from dataclasses import dataclass
+from typing import Any, Callable, Literal, Optional, Union
# Native to python
from xml.etree.ElementTree import Element, SubElement
@@ -24,8 +25,9 @@ from pymdownx.superfences import ( # type: ignore
)
from marimo._ast import codegen
-from marimo._ast.app import _AppConfig
-from marimo._ast.cell import CellConfig
+from marimo._ast.app import App, InternalApp, _AppConfig
+from marimo._ast.cell import Cell, CellConfig
+from marimo._ast.compiler import compile_cell
from marimo._cli.convert.utils import markdown_to_marimo
# CSafeLoader is faster than SafeLoader.
@@ -34,9 +36,12 @@ try:
except ImportError:
from yaml import SafeLoader # type: ignore[assignment]
+
MARIMO_MD = "marimo-md"
MARIMO_CODE = "marimo-code"
+ConvertKeys = Union[Literal["marimo"], Literal["marimo-app"]]
+
def _is_code_tag(text: str) -> bool:
head = text.split("\n")[0].strip()
@@ -60,7 +65,7 @@ def formatted_code_block(
)
-def _tree_to_app(root: Element) -> str:
+def app_config_from_root(root: Element) -> _AppConfig:
# Extract meta data from root attributes.
config_keys = {"title": "app_title", "marimo-layout": "layout_file"}
config = {
@@ -70,26 +75,88 @@ def _tree_to_app(root: Element) -> str:
}
# Try to pass on other attributes as is
config.update({k: v for k, v in root.items() if k not in config_keys})
+ # Remove values particular to markdown saves.
+ config.pop("marimo-version", None)
+ return _AppConfig.from_untrusted_dict(config)
+
+
+def get_source_from_tag(tag: Element) -> str:
+ source = tag.text if tag.text else ""
+ if tag.tag == MARIMO_MD:
+ # Only check here to allow for empty code blocks.
+ if not (source and source.strip()):
+ return ""
+ source = markdown_to_marimo(source)
+ else:
+ assert tag.tag == MARIMO_CODE, f"Unknown tag: {tag.tag}"
+ return source
+
+
+def get_cell_config_from_tag(tag: Element, **defaults: bool) -> CellConfig:
+ boolean_attrs = {
+ **defaults,
+ **{k: v == "true" for k, v in tag.attrib.items()},
+ }
+ return CellConfig.from_dict(boolean_attrs)
+
+
+# TODO: Consider upstreaming some logic such that this isn't such a terrible
+# hack. At some point rewriting / overriding the markdown parser would be a
+# better idea than all these little work arounds.
+@dataclass
+class SafeWrap:
+ app: App
+
+ def strip(self) -> App:
+ return self.app
+
+
+def _tree_to_app_obj(root: Element) -> SafeWrap:
+ app_config = app_config_from_root(root)
+ app = InternalApp(App(**app_config.asdict()))
+
+ for child in root:
+ name = child.get("name", "__")
+ # Default to hiding markdown cells.
+ cell_config = get_cell_config_from_tag(
+ child, hide_code=child.tag == MARIMO_MD
+ )
+ source = get_source_from_tag(child)
- app_config = _AppConfig.from_untrusted_dict(config)
+ cell_id = app.cell_manager.create_cell_id()
+ try:
+ cell_impl = compile_cell(source, cell_id)
+ cell_impl.configure(cell_config)
+ cell = Cell(_name=name, _cell=cell_impl)
+
+ app.cell_manager._register_cell(
+ cell,
+ app=app,
+ )
+ except SyntaxError:
+ # Cannot use register_unparsable_cell, since there is an
+ # expectation of a dedent and newlines.
+ app.cell_manager.register_cell(
+ cell_id=cell_id,
+ code=source,
+ config=cell_config,
+ name=name or "__",
+ cell=None,
+ )
+
+ return SafeWrap(app._app)
+
+
+def _tree_to_app(root: Element) -> str:
+ app_config = app_config_from_root(root)
sources: list[str] = []
names: list[str] = []
cell_config: list[CellConfig] = []
for child in root:
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)
+ cell_config.append(get_cell_config_from_tag(child))
+ sources.append(get_source_from_tag(child))
return codegen.generate_filecontents(
sources,
@@ -141,8 +208,9 @@ class MarimoParser(IdentityParser):
meta: dict[str, Any]
- output_formats: dict[Literal["marimo"], Callable[[Element], str]] = { # type: ignore[assignment, misc]
+ output_formats: dict[ConvertKeys, Callable[[Element], Union[str, App]]] = { # type: ignore[assignment, misc]
"marimo": _tree_to_app,
+ "marimo-app": _tree_to_app_obj,
}
def __init__(self, *args: Any, **kwargs: Any) -> None:
@@ -360,6 +428,10 @@ class ExpandAndClassifyProcessor(BlockProcessor):
blocks.clear()
+def convert_from_md_to_app(text: str) -> App:
+ return MarimoParser(output_format="marimo-app").convert(text) # type: ignore[arg-type, return-value]
+
+
def convert_from_md(text: str) -> str:
return MarimoParser(output_format="marimo").convert(text) # type: ignore[arg-type]
diff --git a/marimo/_cli/file_path.py b/marimo/_cli/file_path.py
index 4b0611488e..0346dd4d31 100644
--- a/marimo/_cli/file_path.py
+++ b/marimo/_cli/file_path.py
@@ -48,8 +48,8 @@ def validate_name(
"""
Validate the name of the file to be edited/run.
- If its an existing path, check that it is a valid Python file.
- If its a URL, we download it to a temporary file and return
+ If it's an existing path, check that it is a valid notebook file.
+ If it's a URL, we download it to a temporary file and return
the path to that file.
Args:
@@ -95,9 +95,10 @@ def validate_name(
"Invalid NAME - %s is not a Python or Markdown file" % name
)
- if is_github_src(name, ext=".py"):
- temp_dir = TemporaryDirectory()
- return _handle_github_src(name, temp_dir), temp_dir
+ for ext in (".py", ".md"):
+ if is_github_src(name, ext=ext):
+ temp_dir = TemporaryDirectory()
+ return _handle_github_src(name, temp_dir), temp_dir
if is_url(name):
temp_dir = TemporaryDirectory()
diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.py
index 43b5dbd815..df6a6fd4ba 100644
--- a/marimo/_server/export/exporter.py
+++ b/marimo/_server/export/exporter.py
@@ -155,6 +155,8 @@ class Exporter:
import yaml
from marimo._ast.app import _AppConfig
+ from marimo._ast.cell import Cell
+ from marimo._ast.compiler import compile_cell
from marimo._cli.convert.markdown import (
formatted_code_block,
is_sanitized_markdown,
@@ -194,8 +196,26 @@ class Exporter:
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.
+ # No "cell" typically means not parseable. However newly added
+ # cells require compilation before cell is set.
+ # TODO: Refactor so it doesn't occur in export (codegen
+ # does this too)
+ if not cell:
+ try:
+ cell_impl = compile_cell(
+ code, cell_id=str(cell_data.cell_id)
+ ).configure(cell_data.config)
+ cell = Cell(
+ _cell=cell_impl,
+ _name=cell_data.name,
+ _app=file_manager.app,
+ )
+ cell_data.cell = cell
+ except SyntaxError:
+ pass
+
+ # Definitely no "cell"; 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.
diff --git a/marimo/_server/file_manager.py b/marimo/_server/file_manager.py
index 78375febef..dfcd98e699 100644
--- a/marimo/_server/file_manager.py
+++ b/marimo/_server/file_manager.py
@@ -6,7 +6,7 @@ from typing import Any, Dict, Optional
from marimo import _loggers
from marimo._ast import codegen
-from marimo._ast.app import App, InternalApp
+from marimo._ast.app import App, InternalApp, _AppConfig
from marimo._ast.cell import CellConfig
from marimo._runtime.layout.layout import (
LayoutConfig,
@@ -60,12 +60,9 @@ class AppFileManager:
self,
filename: str,
contents: str = "",
- header_comments: Optional[str] = None,
) -> None:
try:
with open(filename, "w", encoding="utf-8") as f:
- if header_comments:
- f.write(header_comments.rstrip() + "\n\n")
f.write(contents)
except Exception as err:
raise HTTPException(
@@ -85,6 +82,39 @@ class AppFileManager:
),
) from err
+ def _save_file(
+ self,
+ filename: str,
+ codes: list[str],
+ names: list[str],
+ configs: list[CellConfig],
+ app_config: _AppConfig,
+ ) -> None:
+ LOGGER.debug("Saving app to %s", filename)
+ if filename.endswith(".md"):
+ # TODO: Remember just proof of concept, potentially needs
+ # restructuring.
+ from marimo._server.export.exporter import Exporter
+
+ contents, _ = Exporter().export_as_md(self)
+ else:
+ # Header might be better kept on the AppConfig side, opposed to
+ # reparsing it. Also would allow for md equivalent in a field like
+ # `description`.
+ header_comments = codegen.get_header_comments(filename)
+ # try to save the app under the name `filename`
+ contents = codegen.generate_filecontents(
+ codes,
+ names,
+ cell_configs=configs,
+ config=app_config,
+ header_comments=header_comments,
+ )
+ self._create_file(filename, contents)
+
+ if self._is_unnamed():
+ self.rename(filename)
+
@staticmethod
def _load_app(path: Optional[str]) -> InternalApp:
"""Read the app from the file."""
@@ -141,15 +171,13 @@ class AppFileManager:
# of file), instead of overwriting the whole file.
new_config = self.app.update_config(config)
if self.filename is not None:
- # Try to save the app under the name `self.filename`
- contents = codegen.generate_filecontents(
- codes=list(self.app.cell_manager.codes()),
- names=list(self.app.cell_manager.names()),
- cell_configs=list(self.app.cell_manager.configs()),
- config=new_config,
+ self._save_file(
+ self.filename,
+ list(self.app.cell_manager.codes()),
+ list(self.app.cell_manager.names()),
+ list(self.app.cell_manager.configs()),
+ new_config,
)
- header_comments = codegen.get_header_comments(self.filename)
- self._create_file(self.filename, contents, header_comments)
def save(self, request: SaveRequest) -> None:
"""Save the current app."""
@@ -188,19 +216,9 @@ class AppFileManager:
# We don't remove the layout file from the disk to avoid
# deleting state that the user might want to keep
self.app.update_config({"layout_file": None})
- # try to save the app under the name `filename`
- contents = codegen.generate_filecontents(
- codes,
- names,
- cell_configs=configs,
- config=self.app.config,
+ return self._save_file(
+ filename, codes, names, configs, self.app.config
)
- LOGGER.debug("Saving app to %s", filename)
- header_comments = codegen.get_header_comments(filename)
- self._create_file(filename, contents, header_comments)
-
- if self._is_unnamed():
- self.rename(filename)
def to_code(self) -> str:
"""Read the contents of the unsaved file."""
diff --git a/marimo/_tutorials/__init__.py b/marimo/_tutorials/__init__.py
index be52407b50..563b063361 100644
--- a/marimo/_tutorials/__init__.py
+++ b/marimo/_tutorials/__init__.py
@@ -1 +1,47 @@
# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import inspect
+import os
+from typing import get_args, Literal, Union
+
+
+PythonTutorial = Literal[
+ "intro",
+ "dataflow",
+ "ui",
+ "markdown",
+ "plots",
+ "layout",
+ "fileformat",
+ "for-jupyter-users",
+]
+
+MarkdownTutorial = Literal["markdown-format",]
+Tutorial = Union[PythonTutorial, MarkdownTutorial]
+tutorial_order: list[Tutorial] = [
+ "intro",
+ "dataflow",
+ "ui",
+ "markdown",
+ "plots",
+ "layout",
+ "fileformat",
+ "markdown-format",
+ "for-jupyter-users",
+]
+assert set(tutorial_order) == set(get_args(PythonTutorial)) | set(get_args(MarkdownTutorial)), "Tutorial missing"
+
+
+def get_tutorial_source(name: Tutorial) -> str:
+ if name in get_args(PythonTutorial):
+ name = name.replace("-", "_")
+ # from marimo._tutorials import <name>
+ tutorial = getattr(__import__("marimo._tutorials", fromlist=[name]),
+ name)
+ return inspect.getsource(tutorial)
+ assert name in get_args(MarkdownTutorial)
+ name = name.replace("-", "_")
+ file = os.path.join(os.path.dirname(__file__), f"{name}.md")
+ with open(file, "r", encoding="utf8") as f:
+ return f.read()
diff --git a/marimo/_tutorials/marimo_for_jupyter_users.py b/marimo/_tutorials/for_jupyter_users.py
similarity index 99%
rename from marimo/_tutorials/marimo_for_jupyter_users.py
rename to marimo/_tutorials/for_jupyter_users.py
index 580a4c16a7..4e5ef3fbbe 100644
--- a/marimo/_tutorials/marimo_for_jupyter_users.py
+++ b/marimo/_tutorials/for_jupyter_users.py
@@ -2,7 +2,7 @@
import marimo
__generated_with = "0.3.12"
-app = marimo.App()
+app = marimo.App(app_title="marimo for Jupyter users")
@app.cell(hide_code=True)
diff --git a/marimo/_tutorials/markdown_format.md b/marimo/_tutorials/markdown_format.md
new file mode 100644
index 0000000000..bd44ead630
--- /dev/null
+++ b/marimo/_tutorials/markdown_format.md
@@ -0,0 +1,196 @@
+---
+title: Markdown
+marimo-version: 0.4.11
+---
+
+# marimo in Markdown!
+
+Everything in marimo is pure Python, but sometimes, annotating your notebook
+in markdown can be a little cumbersome.
+<!---->
+For example, here's the code that rendered the above title and
+paragraph:
+
+````md
+```{python}
+mo.md(
+ '''
+ # marimo in Markdown!
+
+ Everything in marimo is pure Python, but sometimes, annotating your notebook
+ in markdown can be a little cumbersome.
+ '''
+)
+```
+````
+
+with markdown notebook support for marimo, you can write and save markdown
+directly, and marimo will execute the necessary Python code for you behind the
+scenes. This allows you to focus on prose, and not formatting your text in a block
+string.
+<!---->
+## Python cells in markdown
+
+When you do need to create a Python cell in the markdown format, you can use a
+special code block:
+
+````md
+```{python}
+import matplotlib.pyplot as plt
+plt.plot([1, 2, 3, 4])
+```
+````
+
+This will create the following cell:
+
+```{.python.marimo}
+import matplotlib.pyplot as plt
+plt.plot([1, 2, 3, 4])
+plt.gca()
+```
+
+As long as your code block contains the word `python` in a brace, like
+`{python}`, or `{.python note="Whatever you want"}`, marimo will treat it as a
+Python cell.
+<!---->
+## Exporting from Python
+
+Do you have a notebook that you think might better be suited for a markdown notebook?
+You can export your notebook to markdown by running the following code:
+
+```bash
+$ marimo export md my_marimo.py > my_marimo.md
+```
+
+by default, marimo will extract your markdown cells, and wrap your Python cells
+in `{.python.marimo}` code blocks. Although `{python}` might be more concise,
+this format is chosen such that code highlighting will work in your favourite
+IDE.
+<!---->
+## `mo` tricks and tips
+
+You can break up markdown into multiple cells by using an empty html tag `<!---->`:
+<!---->
+View the source of this notebook to see how this cell was created.
+<!---->
+You can still hide and disable code cells in markdown notebooks:
+
+````md
+```{python hide_code="true"}
+import pandas as pd
+pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
+```
+````
+
+```{.python.marimo hide_code="true"}
+import pandas as pd
+pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
+```
+
+````md
+```{python disabled="true"}
+print("This code cell is disabled, there should be no output!")
+```
+````
+
+```{.python.marimo disabled="true"}
+print("This code cell is disabled, there should be no output!")
+```
+
+Additionally, marimo knows when your code has a syntax issue:
+
+````md
+```{python}
+print("This code cell has a syntax error"
+```
+````
+
+and on notebook save, will annotate the cell for you:
+
+````md
+```{python unparseable="true"}
+print("This code cell has a syntax error"
+```
+````
+
+```{.python.marimo unparsable="true"}
+print("This code cell has a syntax error"
+```
+
+## Limitations of the markdown format
+
+marimo's markdown support treats markdown as just plain old markdown. This
+means that trying to use string interpolation (like this `f"{'🍃' * 7}"`) will
+just give you the raw string. This is a benefit, as you can clearly delineate
+what values are supposed to be computed, and what values are static;
+
+and there's nothing stopping you from executing python to achieve the same effect,
+
+```{.python.marimo}
+'🍃' * 7
+```
+
+### Limitations on conversion
+
+Whenever you try to implement a cell block like this:
+
+````md
+```{python}
+mo.md("This is a markdown cell")
+```
+````
+
+The markdown format will know to automatically keep this as markdown. However,
+some ambiguous cases can't be converted to markdown like this:
+
+````{.python.marimo}
+mo.md("""
+ This is a markdown cell with an execution block in it
+ ```{python}
+ # To ambiguous to convert
+ ```
+ """)
+````
+
+It's not likely that you'll run into this issue, but rest assured that marimo
+is working behind the scenes to keep your notebooks unambiguous and clean as
+possible.
+<!---->
+### More limitations
+
+Since the markdown notebook really is just markdown, you can't import from a
+markdown notebook cells like you can in a python notebook; but you can still
+give your cells a name:
+
+````md
+```{python name="maybe"}
+# 🎵 Hey, I just met you, and this is crazy
+```
+````
+
+```{.python.marimo name="maybe"}
+# But here's my `cell_id`, so call me, `maybe` 🎶
+```
+
+you can even run a notebook:
+
+```bash
+$ marimo run my_marimo.md
+```
+
+the markdown format is supposed to lower the barrier for writing text heavy
+documents, it's not meant to be a full replacement for the python notebook
+format. You can always convert back to a python notebook if you need to:
+
+```bash
+$ marimo convert my_marimo.md > my_marimo.py
+```
+<!---->
+## More?!
+
+Be sure to checkout the markdown.py tutorial for more information on to type-set
+and render markdown in marimo.
+
+```{.python.marimo hide_code="true"}
+import marimo as mo
+```
diff --git a/tests/_cli/snapshots/marimo_for_jupyter_users.md.txt b/tests/_cli/snapshots/marimo_for_jupyter_users.md.txt
index 5ef04c8928..6711759104 100644
--- a/tests/_cli/snapshots/marimo_for_jupyter_users.md.txt
+++ b/tests/_cli/snapshots/marimo_for_jupyter_users.md.txt
@@ -1,5 +1,5 @@
---
-title: Marimo For Jupyter Users
+title: marimo for Jupyter users
marimo-version: 0.0.0
---
diff --git a/tests/_cli/test_cli.py b/tests/_cli/test_cli.py
index bdddd89a43..d51eb63cb1 100644
--- a/tests/_cli/test_cli.py
+++ b/tests/_cli/test_cli.py
@@ -316,6 +316,59 @@ def test_cli_tutorial() -> None:
_check_contents(p, b"intro.py", contents)
+def test_cli_md_tutorial() -> None:
+ port = _get_port()
+ p = subprocess.Popen(
+ [
+ "marimo",
+ "tutorial",
+ "markdown-format",
+ "-p",
+ str(port),
+ "--headless",
+ "--no-token",
+ ]
+ )
+ contents = _try_fetch(port)
+ _check_contents(p, b"marimo-mode data-mode='edit'", contents)
+ _check_contents(
+ p, f"marimo-version data-version='{__version__}'".encode(), contents
+ )
+ _check_contents(p, b"markdown-format.md", contents)
+
+
+def test_cli_md_run(temp_md_marimo_file: str) -> None:
+ port = _get_port()
+ p = subprocess.Popen(
+ ["marimo", "run", temp_md_marimo_file, "-p", str(port), "--headless"]
+ )
+ contents = _try_fetch(port)
+ _check_contents(p, b"marimo-mode data-mode='read'", contents)
+ _check_contents(
+ p, f"marimo-version data-version='{__version__}'".encode(), contents
+ )
+
+
+def test_cli_md_edit(temp_md_marimo_file: str) -> None:
+ port = _get_port()
+ p = subprocess.Popen(
+ [
+ "marimo",
+ "edit",
+ temp_md_marimo_file,
+ "-p",
+ str(port),
+ "--no-token",
+ "--headless",
+ ]
+ )
+ contents = _try_fetch(port)
+ _check_contents(p, b"marimo-mode data-mode='edit'", contents)
+ _check_contents(
+ p, f"marimo-version data-version='{__version__}'".encode(), contents
+ )
+
+
def test_cli_custom_host() -> None:
port = _get_port()
host = "localhost"
diff --git a/tests/_cli/test_cli_export.py b/tests/_cli/test_cli_export.py
index 5016a80449..e79ab26ed8 100644
--- a/tests/_cli/test_cli_export.py
+++ b/tests/_cli/test_cli_export.py
@@ -216,7 +216,7 @@ class TestExportHtmlSmokeTests:
def test_export_marimo_for_jupyter_users(
self, tmp_path: pathlib.Path
) -> None:
- from marimo._tutorials import marimo_for_jupyter_users as mod
+ from marimo._tutorials import for_jupyter_users as mod
file = tmp_path / "mod.py"
file.write_text(inspect.getsource(mod), encoding="utf-8")
diff --git a/tests/_cli/test_markdown_conversion.py b/tests/_cli/test_markdown_conversion.py
index 2cb9ed5cc2..1a26fd247a 100644
--- a/tests/_cli/test_markdown_conversion.py
+++ b/tests/_cli/test_markdown_conversion.py
@@ -15,12 +15,12 @@ from marimo._server.export import export_as_md
from marimo._server.export.utils import format_filename_title
# Just a handful of scripts to test
-from marimo._tutorials import dataflow, marimo_for_jupyter_users
+from marimo._tutorials import dataflow, for_jupyter_users
from marimo._utils.marimo_path import MarimoPath
from tests.mocks import snapshotter
modules = {
- "marimo_for_jupyter_users": marimo_for_jupyter_users,
+ "marimo_for_jupyter_users": for_jupyter_users,
"dataflow": dataflow,
}
diff --git a/tests/_cli/test_tutorial.py b/tests/_cli/test_tutorial.py
new file mode 100644
index 0000000000..a24455334a
--- /dev/null
+++ b/tests/_cli/test_tutorial.py
@@ -0,0 +1,14 @@
+# Copyright 2024 Marimo. All rights reserved.
+"""
+Sanity check that tutorials are parsable / accessible.
+"""
+
+from __future__ import annotations
+
+from marimo._tutorials import get_tutorial_source, tutorial_order
+
+
+def test_tutorial_source() -> None:
+ for tutorial in tutorial_order:
+ source = get_tutorial_source(tutorial)
+ assert source
diff --git a/tests/_smoke_tests/test_run_as_script.py b/tests/_smoke_tests/test_run_as_script.py
index 1fa096daf6..9aeca71014 100644
--- a/tests/_smoke_tests/test_run_as_script.py
+++ b/tests/_smoke_tests/test_run_as_script.py
@@ -113,7 +113,7 @@ class TestRunTutorialsAsScripts:
def test_run_marimo_for_jupyter_users_tutorial(
self, tmp_path: pathlib.Path
) -> None:
- from marimo._tutorials import marimo_for_jupyter_users as mod
+ from marimo._tutorials import for_jupyter_users as mod
file = tmp_path / "mod.py"
file.write_text(inspect.getsource(mod))
diff --git a/tests/conftest.py b/tests/conftest.py
index bf15b53830..ab56dbcd34 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -300,6 +300,39 @@ def temp_marimo_file_with_md() -> Generator[str, None, None]:
tmp_dir.cleanup()
+def temp_md_marimo_file() -> Generator[str, None, None]:
+ tmp_dir = TemporaryDirectory()
+ tmp_file = tmp_dir.name + "/notebook.md"
+ content = inspect.cleandoc(
+ """
+ ---
+ title: Notebook
+ marimo-version: 0.0.0
+ ---
+
+ # This is a markdown document.
+ <!---->
+ This is a another cell.
+
+ ```{.python.marimo}
+ import marimo as mo
+ ```
+
+ ```{.python.marimo}
+ slider = mo.ui.slider(0, 10)
+ ```
+ """
+ )
+
+ try:
+ with open(tmp_file, "w") as f:
+ f.write(content)
+ yield tmp_file
+ finally:
+ tmp_dir.cleanup()
+
+
# Factory to create ExecutionRequests and abstract away cell ID
class ExecReqProvider:
def __init__(self) -> None: