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: convert and export from markdown (#1296)

Dylan Madisettie267a322a72f
diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.py
index 33d111402a..7c39ae0867 100644
--- a/marimo/_cli/cli.py
+++ b/marimo/_cli/cli.py
@@ -13,7 +13,7 @@ import click
import marimo._cli.cli_validators as validators
from marimo import __version__, _loggers
from marimo._ast import codegen
-from marimo._cli import ipynb_to_marimo
+from marimo._cli.convert.commands import convert
from marimo._cli.envinfo import get_system_info
from marimo._cli.export.commands import export
from marimo._cli.file_path import validate_name
@@ -502,29 +502,6 @@ def tutorial(
)
[email protected]("ipynb", type=str, required=True)
-def convert(ipynb: str) -> None:
- """Convert a Jupyter notebook to a marimo notebook.
-
- The argument may be either a path to a local .ipynb file,
- or an .ipynb file hosted on GitHub.
-
- Example usage:
-
- marimo convert your_nb.ipynb > your_nb.py
-
- After conversion, you can open the notebook in the editor:
-
- marimo edit your_nb.py
-
- Since marimo is different from traditional notebooks, once in the editor,
- you may need to fix errors like multiple definition errors or cycle
- errors.
- """
- print(ipynb_to_marimo.convert_from_path(ipynb))
-
-
@main.command()
def env() -> None:
"""Print out environment information for debugging purposes.
@@ -536,4 +513,5 @@ def env() -> None:
print(json.dumps(get_system_info(), indent=2))
+main.command()(convert)
main.add_command(export)
diff --git a/marimo/_cli/convert/commands.py b/marimo/_cli/convert/commands.py
new file mode 100644
index 0000000000..a00eadb1af
--- /dev/null
+++ b/marimo/_cli/convert/commands.py
@@ -0,0 +1,50 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from pathlib import Path
+
+import click
+
+from marimo._cli.convert.ipynb import convert_from_ipynb
+from marimo._cli.convert.markdown import convert_from_md
+from marimo._cli.convert.utils import load_external_file
+
+
[email protected]("filename", required=True)
+def convert(
+ filename: str,
+) -> None:
+ r"""Convert a Jupyter notebook or Markdown file to a marimo notebook.
+
+ The argument may be either a path to a local .ipynb/.md file,
+ or an .ipynb/.md file hosted on GitHub.
+
+ Example usage:
+
+ marimo convert your_nb.ipynb > your_nb.py
+
+ or
+
+ marimo convert your_nb.md > your_nb.py
+
+ Jupyter notebook conversion will strip out all outputs. Markdown cell
+ conversion with occur on the presence of `\`\`\`{python}` code blocks.
+ After conversion, you can open the notebook in the editor:
+
+ marimo edit your_nb.py
+
+ Since marimo is different from traditional notebooks, once in the editor,
+ you may need to fix errors like multiple definition errors or cycle
+ errors.
+ """
+ ext = Path(filename).suffix
+ if ext not in (".ipynb", ".md", ".qmd"):
+ raise click.UsageError("File must be an .ipynb or .md file")
+
+ text = load_external_file(filename, ext)
+ if ext == ".ipynb":
+ notebook = convert_from_ipynb(text)
+ else:
+ assert ext in (".md", ".qmd")
+ notebook = convert_from_md(text)
+ click.echo(notebook)
diff --git a/marimo/_cli/convert/ipynb.py b/marimo/_cli/convert/ipynb.py
new file mode 100644
index 0000000000..2987664e82
--- /dev/null
+++ b/marimo/_cli/convert/ipynb.py
@@ -0,0 +1,36 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import json
+
+from marimo._cli.convert.utils import (
+ generate_from_sources,
+ load_external_file,
+ markdown_to_marimo,
+)
+
+
+def convert_from_ipynb(raw_notebook: str) -> str:
+ notebook = json.loads(raw_notebook)
+ sources = []
+ has_markdown = False
+ for cell in notebook["cells"]:
+ source = (
+ cell["source"]
+ if isinstance(cell["source"], str)
+ else "".join(cell["source"])
+ )
+ if cell["cell_type"] == "markdown":
+ has_markdown = True
+ source = markdown_to_marimo(source)
+ sources.append(source)
+
+ if has_markdown:
+ sources.append("import marimo as mo")
+
+ return generate_from_sources(sources)
+
+
+def convert_from_ipynb_file(file_path: str) -> str:
+ raw_notebook = load_external_file(file_path, "ipynb")
+ return convert_from_ipynb(raw_notebook)
diff --git a/marimo/_cli/convert/markdown.py b/marimo/_cli/convert/markdown.py
new file mode 100644
index 0000000000..14933dd804
--- /dev/null
+++ b/marimo/_cli/convert/markdown.py
@@ -0,0 +1,218 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import re
+from typing import Any, Callable, Literal
+
+# 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
+# to parse markdown.
+from markdown import Markdown
+from markdown.blockparser import BlockParser
+from markdown.blockprocessors import BlockProcessor
+from markdown.preprocessors import Preprocessor
+from markdown.util import HTML_PLACEHOLDER_RE, Registry
+
+# As are extensions
+from pymdownx.superfences import SuperFencesCodeExtension # type: ignore
+
+from marimo._ast.app import _AppConfig
+from marimo._cli.convert.utils import generate_from_sources, markdown_to_marimo
+
+# CSafeLoader is faster than SafeLoader.
+try:
+ from yaml import CSafeLoader as SafeLoader
+except ImportError:
+ from yaml import SafeLoader # type: ignore[assignment]
+
+MARIMO_MD = "marimo-md"
+MARIMO_CODE = "marimo-code"
+
+
+def _is_code_tag(text: str) -> bool:
+ head = text.split("\n")[0].strip()
+ return bool(re.search(r"\{.*python.*\}", head))
+
+
+def _tree_to_app(root: Element) -> str:
+ # Extract meta data from root attributes.
+ config_keys = {"title": "app_title"}
+ config = {
+ config_keys[key]: value
+ for key, value in root.items()
+ if key in config_keys
+ }
+ app_config = _AppConfig.from_untrusted_dict(config)
+
+ sources = []
+ for child in root:
+ source = child.text
+ if not (source and source.strip()):
+ continue
+ if child.tag == MARIMO_MD:
+ 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)
+
+
+class MarimoParser(Markdown):
+ """Parses Markdown to marimo notebook."""
+
+ # Considering how ubiquitous "markdown" is, it's a little surprising the
+ # internal structure isn't cleaner/ more modular. This "monkey-patching"
+ # is comparable to some of the code in markdown extensions- and given this
+ # library has been around since 2004, the internals should be relatively
+ # stable.
+ output_formats: dict[Literal["marimo"], Callable[[Element], str]] = { # type: ignore[assignment, misc]
+ "marimo": _tree_to_app,
+ }
+ meta: dict[str, Any]
+
+ def build_parser(self) -> MarimoParser:
+ """
+ Creates blank registries as a base.
+
+ Note that evoked by itself, will create an infinite loop, since
+ block-parsers will never dequeue the extracted blocks.
+ """
+ self.preprocessors = Registry()
+ self.parser = BlockParser(self)
+ self.inlinePatterns = Registry()
+ self.treeprocessors = Registry()
+ self.postprocessors = Registry()
+ return self
+
+
+class FrontMatterPreprocessor(Preprocessor):
+ """Preprocessor for to extract YAML front matter.
+
+ The built-in MetaPreprocessor does not handle frontmatter yaml properly, so
+ this is a custom implementation.
+
+ Like the built-in MetaPreprocessor, this preprocessor extracts yaml and
+ stores it in the Markdown's metadata attribute. Inspired by conversation
+ and linked project in github/Python-Markdown/markdown/497. See docdown
+ (BSD-3) or python-frontmatter (MIT) for similar implementations.
+ """
+
+ def __init__(self, md: MarimoParser):
+ super().__init__(md)
+ self.md = md
+ self.md.meta = {}
+ # Regex captures loose yaml for frontmatter
+ # Should match the following:
+ # ---
+ # title: "Title"
+ # whatever
+ # ---
+ self.yaml_front_matter_regex = re.compile(
+ r"^---\s*\n(.*?\n?)(?:---)\s*\n", re.UNICODE | re.DOTALL
+ )
+
+ def run(self, lines: list[str]) -> list[str]:
+ if not lines:
+ return lines
+
+ doc = "\n".join(lines)
+ result = self.yaml_front_matter_regex.match(doc)
+
+ if result:
+ yaml_content = result.group(1)
+ try:
+ meta = yaml.load(yaml_content, SafeLoader)
+ if isinstance(meta, dict):
+ self.md.meta = meta # type: ignore[attr-defined]
+ doc = doc[result.end() :].lstrip("\n")
+ # If there's an error in parsing YAML, ignore the meta and proceed.
+ except yaml.YAMLError as e:
+ raise e
+ return doc.split("\n")
+
+
+class ExpandAndClassifyProcessor(BlockProcessor):
+ """Separates code blocks and markdown blocks."""
+
+ stash: dict[str, Any]
+
+ def test(*_args: Any) -> bool:
+ return True
+
+ def run(self, parent: Element, blocks: list[str]) -> None:
+ # Copy app metadata to the parent element.
+ for key, value in self.parser.md.meta.items(): # type: ignore[attr-defined]
+ if isinstance(value, str):
+ parent.set(key, value)
+
+ text: list[str] = []
+
+ def add_paragraph() -> None:
+ if not text:
+ return
+ # An additional line break is added before code blocks.
+ if text[-1].strip() == "":
+ text.pop()
+ if not text:
+ return
+ paragraph = SubElement(parent, MARIMO_MD)
+ paragraph.text = "\n".join(text).strip()
+ text.clear()
+
+ # Operate on line basis, not block basis, but use block processor
+ # instead of preprocessor, because we still want to operate on the
+ # xml tree.
+ for line in "\n\n".join(blocks).split("\n"):
+ # 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):
+ 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:
+ text.append(line)
+ add_paragraph()
+ # Flush to indicate all blocks have been processed.
+ blocks.clear()
+
+
+def _build_marimo_parser() -> MarimoParser:
+ # Build here opposed to the parent class since there is intermediate logic
+ # after the parser is built, and it is more clear here what is registered.
+ md = MarimoParser(output_format="marimo") # type: ignore[arg-type]
+ md.stripTopLevelTags = False
+
+ # Note: MetaPreprocessor does not properly handle frontmatter yaml, so
+ # cleanup occurs in the block-processor.
+ md.preprocessors.register(FrontMatterPreprocessor(md), "frontmatter", 100)
+ fences_ext = SuperFencesCodeExtension()
+ fences_ext.extendMarkdown(md)
+ # TODO: Consider adding the admonition extension, and integrating it with
+ # mo.markdown callouts.
+
+ block_processors = ExpandAndClassifyProcessor(md.parser)
+ block_processors.stash = fences_ext.stash.stash
+ md.parser.blockprocessors.register(
+ block_processors, "marimo-processor", 10
+ )
+
+ return md
+
+
+def convert_from_md(text: str) -> str:
+ if not text:
+ raise ValueError("No content found in markdown.")
+ md = _build_marimo_parser()
+ return md.convert(text)
diff --git a/marimo/_cli/convert/utils.py b/marimo/_cli/convert/utils.py
new file mode 100644
index 0000000000..4e8bfff168
--- /dev/null
+++ b/marimo/_cli/convert/utils.py
@@ -0,0 +1,50 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import urllib.request
+from typing import Optional
+
+from marimo._ast import codegen
+from marimo._ast.app import _AppConfig
+from marimo._ast.cell import CellConfig
+from marimo._cli.file_path import get_github_src_url, is_github_src
+
+
+def load_external_file(file_path: str, ext: str) -> str:
+ notebook: str = ""
+ if is_github_src(file_path, ext=ext):
+ notebook = (
+ urllib.request.urlopen(get_github_src_url(file_path))
+ .read()
+ .decode("utf-8")
+ )
+ else:
+ with open(file_path, "r", encoding="utf-8") as f:
+ notebook = f.read()
+
+ return notebook
+
+
+def markdown_to_marimo(source: str) -> str:
+ source = source.replace('"""', '\\"\\"\\"')
+ return "\n".join(
+ [
+ "mo.md(",
+ # r-string: a backslash is just a backslash!
+ codegen.indent_text('r"""'),
+ codegen.indent_text(source),
+ codegen.indent_text('"""'),
+ ")",
+ ]
+ )
+
+
+def generate_from_sources(
+ sources: list[str], config: Optional[_AppConfig] = None
+) -> str:
+ return codegen.generate_filecontents(
+ sources,
+ ["__" for _ in sources],
+ [CellConfig() for _ in range(len(sources))],
+ config=config,
+ )
diff --git a/marimo/_cli/export/commands.py b/marimo/_cli/export/commands.py
index 4372b737fb..c0a03afa96 100644
--- a/marimo/_cli/export/commands.py
+++ b/marimo/_cli/export/commands.py
@@ -3,12 +3,14 @@ from __future__ import annotations
import asyncio
from pathlib import Path
+from typing import Callable
import click
from marimo._cli.parse_args import parse_args
from marimo._cli.print import green
-from marimo._server.export.utils import (
+from marimo._server.export import (
+ export_as_md,
export_as_script,
run_app_then_export_as_html,
)
@@ -22,6 +24,57 @@ def export() -> None:
pass
+def watch_and_export(
+ name: str,
+ output: str,
+ watch: bool,
+ export_callback: Callable[[str], str],
+) -> None:
+ if watch and not output:
+ raise click.UsageError(
+ "Cannot use --watch without providing "
+ + "an output file with --output."
+ )
+
+ def write_data(data: str) -> None:
+ if output:
+ # Make dirs if needed
+ maybe_make_dirs(output)
+ with open(output, "w") as f:
+ f.write(data)
+ f.close()
+ else:
+ click.echo(data)
+ return
+
+ # No watch, just run once
+ if not watch:
+ data = export_callback(name)
+ write_data(data)
+ return
+
+ async def on_file_changed(file_path: Path) -> None:
+ click.echo(
+ f"File {str(file_path)} changed. Re-exporting to {green(output)}"
+ )
+ data = export_callback(str(file_path))
+ write_data(data)
+
+ async def start() -> None:
+ # Watch the file for changes
+ watcher = FileWatcher.create(Path(name), on_file_changed)
+ click.echo(f"Watching {green(name)} for changes...")
+ watcher.start()
+ try:
+ # Run forever
+ while True:
+ await asyncio.sleep(1)
+ except KeyboardInterrupt:
+ watcher.stop()
+
+ asyncio_run(start())
+
+
@click.command(
help="""Run a notebook and export it as an HTML file.
@@ -76,55 +129,18 @@ def html(
"""
Run a notebook and export it as an HTML file.
"""
- if watch and not output:
- raise click.UsageError(
- "Cannot use --watch without providing "
- + "an output file with --output."
- )
-
- def write_html(html: str) -> None:
- if output:
- # Make dirs if needed
- maybe_make_dirs(output)
- with open(output, "w") as f:
- f.write(html)
- f.close()
- else:
- click.echo(html)
cli_args = parse_args(args)
- # No watch, just run once
- if not watch:
+
+ def export_callback(file_path: str) -> str:
(html, _filename) = asyncio_run(
run_app_then_export_as_html(
- name, include_code=include_code, cli_args=cli_args
+ file_path, include_code=include_code, cli_args=cli_args
)
)
- write_html(html)
- return
+ return html
- async def on_file_changed(file_path: Path) -> None:
- click.echo(
- f"File {str(file_path)} changed. Re-exporting to {green(output)}"
- )
- (html, _filename) = await run_app_then_export_as_html(
- str(file_path), include_code=include_code, cli_args=cli_args
- )
- write_html(html)
-
- async def start() -> None:
- # Watch the file for changes
- watcher = FileWatcher.create(Path(name), on_file_changed)
- click.echo(f"Watching {green(name)} for changes...")
- watcher.start()
- try:
- # Run forever
- while True:
- await asyncio.sleep(1)
- except KeyboardInterrupt:
- watcher.stop()
-
- asyncio_run(start())
+ return watch_and_export(name, output, watch, export_callback)
@click.command(
@@ -172,49 +188,65 @@ def script(
"""
Export a marimo notebook as a flat script, in topological order.
"""
- if watch and not output:
- raise click.UsageError(
- "Cannot use --watch without providing "
- + "an output file with --output."
- )
- def write_script(script: str) -> None:
- if output:
- # Make dirs if needed
- maybe_make_dirs(output)
- with open(output, "w") as f:
- f.write(script)
- f.close()
- else:
- click.echo(script)
+ def export_callback(file_path: str) -> str:
+ return export_as_script(file_path)[0]
- # No watch, just run once
- if not watch:
- (html, _filename) = export_as_script(name)
- write_script(html)
- return
+ return watch_and_export(name, output, watch, export_callback)
- async def on_file_changed(file_path: Path) -> None:
- click.echo(
- f"File {str(file_path)} changed. Re-exporting to {green(output)}"
- )
- (script, _filename) = export_as_script(str(file_path))
- write_script(script)
- async def start() -> None:
- # Watch the file for changes
- watcher = FileWatcher.create(Path(name), on_file_changed)
- click.echo(f"Watching {green(name)} for changes...")
- watcher.start()
- try:
- # Run forever
- while True:
- await asyncio.sleep(1)
- except KeyboardInterrupt:
- watcher.stop()
+ help="""
+Export a marimo notebook as a code fenced Markdown file.
- asyncio_run(start())
+Example:
+
+ \b
+ * marimo export md notebook.py -o notebook.md
+
+Watch for changes and regenerate the script on modification:
+
+ \b
+ * marimo export md notebook.py -o notebook.md --watch
+"""
+)
+ "--watch/--no-watch",
+ default=False,
+ show_default=True,
+ type=bool,
+ help="""
+ Watch notebook for changes and regenerate the script on modification.
+ If watchdog is installed, it will be used to watch the file.
+ Otherwise, file watcher will poll the file every 1s.
+ """,
+)
+ "-o",
+ "--output",
+ type=str,
+ default=None,
+ help="""
+ Output file to save the script to.
+ If not provided, markdown will be printed to stdout.
+ """,
+)
[email protected]("name", required=True)
+def md(
+ name: str,
+ output: str,
+ watch: bool,
+) -> None:
+ """
+ Export a marimo notebook as a code fenced markdown document.
+ """
+
+ def export_callback(file_path: str) -> str:
+ return export_as_md(file_path)[0]
+
+ return watch_and_export(name, output, watch, export_callback)
export.add_command(html)
export.add_command(script)
+export.add_command(md)
diff --git a/marimo/_cli/ipynb_to_marimo.py b/marimo/_cli/ipynb_to_marimo.py
deleted file mode 100644
index 3938204a72..0000000000
--- a/marimo/_cli/ipynb_to_marimo.py
+++ /dev/null
@@ -1,57 +0,0 @@
-# Copyright 2024 Marimo. All rights reserved.
-from __future__ import annotations
-
-import json
-import urllib.request
-from typing import Any
-
-from marimo._ast import codegen
-from marimo._ast.cell import CellConfig
-from marimo._cli.file_path import get_github_src_url, is_github_src
-
-
-def convert_from_path(ipynb_path: str) -> str:
- if is_github_src(ipynb_path, ext=".ipynb"):
- notebook = json.loads(
- urllib.request.urlopen(get_github_src_url(ipynb_path))
- .read()
- .decode("utf-8")
- )
- else:
- with open(ipynb_path, "r", encoding="utf-8") as f:
- notebook = json.loads(f.read())
-
- return convert(notebook)
-
-
-def convert(notebook: dict[str, Any]) -> str:
- sources = []
- has_markdown = False
- for cell in notebook["cells"]:
- source = (
- cell["source"]
- if isinstance(cell["source"], str)
- else "".join(cell["source"])
- )
- if cell["cell_type"] == "markdown":
- has_markdown = True
- source = source.replace('"""', '\\"\\"\\"')
- source = "\n".join(
- [
- "mo.md(",
- # r-string: a backslash is just a backslash!
- codegen.indent_text('r"""'),
- codegen.indent_text(source),
- codegen.indent_text('"""'),
- ")",
- ]
- )
- sources.append(source)
- if has_markdown:
- sources.append("import marimo as mo")
-
- return codegen.generate_filecontents(
- sources,
- ["__" for _ in sources],
- [CellConfig() for _ in range(len(sources))],
- )
diff --git a/marimo/_islands/island_generator.py b/marimo/_islands/island_generator.py
index 2a4ab5053f..d0eed0814c 100644
--- a/marimo/_islands/island_generator.py
+++ b/marimo/_islands/island_generator.py
@@ -231,7 +231,7 @@ class MarimoIslandGenerator:
- App: The built app.
"""
- from marimo._server.export.utils import run_app_until_completion
+ from marimo._server.export import run_app_until_completion
from marimo._server.file_manager import AppFileManager
if self.has_run:
diff --git a/marimo/_output/md.py b/marimo/_output/md.py
index b64de49ab2..bcaec94f15 100644
--- a/marimo/_output/md.py
+++ b/marimo/_output/md.py
@@ -58,7 +58,7 @@ def _md(text: str, apply_markdown_class: bool = True) -> Html:
# Links
ExternalLinksExtension(),
],
- extension_configs=extension_configs,
+ extension_configs=extension_configs, # type: ignore[arg-type]
).strip()
# replace <p> tags with <span> as HTML doesn't allow nested <div>s in <p>s
html_text = html_text.replace("<p>", '<span class="paragraph">').replace(
diff --git a/marimo/_server/export/__init__.py b/marimo/_server/export/__init__.py
new file mode 100644
index 0000000000..08ed3f312b
--- /dev/null
+++ b/marimo/_server/export/__init__.py
@@ -0,0 +1,133 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import asyncio
+from typing import Callable
+
+from marimo._config.manager import UserConfigManager
+from marimo._messaging.ops import MessageOperation
+from marimo._messaging.types import KernelMessage
+from marimo._runtime.requests import AppMetadata, SerializedCLIArgs
+from marimo._server.export.exporter import Exporter
+from marimo._server.file_manager import AppFileManager
+from marimo._server.file_router import AppFileRouter
+from marimo._server.model import ConnectionState, SessionConsumer, SessionMode
+from marimo._server.models.export import ExportAsHTMLRequest
+from marimo._server.models.models import InstantiateRequest
+from marimo._server.sessions import Session
+
+
+def export_as_script(
+ filename: str,
+) -> tuple[str, str]:
+ file_router = AppFileRouter.from_filename(filename)
+ file_key = file_router.get_unique_file_key()
+ assert file_key is not None
+ file_manager = file_router.get_file_manager(file_key)
+
+ return Exporter().export_as_script(file_manager)
+
+
+def export_as_md(
+ filename: str,
+) -> tuple[str, str]:
+ file_router = AppFileRouter.from_filename(filename)
+ file_key = file_router.get_unique_file_key()
+ assert file_key is not None
+ file_manager = file_router.get_file_manager(file_key)
+
+ return Exporter().export_as_md(file_manager)
+
+
+async def run_app_then_export_as_html(
+ filename: str,
+ include_code: bool,
+ cli_args: SerializedCLIArgs,
+) -> tuple[str, str]:
+ # Create a file router and file manager
+ file_router = AppFileRouter.from_filename(filename)
+ file_key = file_router.get_unique_file_key()
+ assert file_key is not None
+ file_manager = file_router.get_file_manager(file_key)
+
+ config = UserConfigManager()
+ session = await run_app_until_completion(file_manager, cli_args)
+ # Export the session as HTML
+ html, filename = Exporter().export_as_html(
+ file_manager=session.app_file_manager,
+ session_view=session.session_view,
+ display_config=config.get_config()["display"],
+ request=ExportAsHTMLRequest(
+ include_code=include_code,
+ download=False,
+ files=[],
+ ),
+ )
+ return html, filename
+
+
+async def run_app_until_completion(
+ file_manager: AppFileManager,
+ cli_args: SerializedCLIArgs,
+) -> Session:
+ instantiated_event = asyncio.Event()
+
+ # Create a no-op session consumer
+ class NoopSessionConsumer(SessionConsumer):
+ def on_start(
+ self,
+ check_alive: Callable[[], None],
+ ) -> Callable[[KernelMessage], None]:
+ del check_alive
+
+ def listener(message: KernelMessage) -> None:
+ if message[0] == "completed-run":
+ instantiated_event.set()
+
+ return listener
+
+ def on_stop(self) -> None:
+ pass
+
+ async def write_operation(self, op: MessageOperation) -> None:
+ pass
+
+ def connection_state(self) -> ConnectionState:
+ return ConnectionState.OPEN
+
+ config = UserConfigManager()
+
+ # Create a session
+ session = Session.create(
+ # Any initialization ID will do
+ initialization_id="_any_",
+ session_consumer=NoopSessionConsumer(),
+ # Run in EDIT mode so that console outputs are captured
+ mode=SessionMode.EDIT,
+ app_metadata=AppMetadata(
+ query_params={},
+ filename=file_manager.path,
+ cli_args=cli_args,
+ ),
+ app_file_manager=file_manager,
+ user_config_manager=config,
+ virtual_files_supported=False,
+ )
+
+ # Run the notebook to completion once
+ session.instantiate(InstantiateRequest(object_ids=[], values=[]))
+ await instantiated_event.wait()
+ # Process console messages
+ #
+ # TODO(akshayka): A timing issue with the console output worker
+ # might still exist; the better thing to do would be to flush
+ # the worker, then ask it to quit and join on it. If we have an
+ # issue with some outputs being missed, that's what we should do.
+ session.message_distributor.flush()
+ # Hack: yield to give the session view a chance to process the incoming
+ # console operations.
+ await asyncio.sleep(0.1)
+ # Stop distributor, terminate kernel process, etc -- all information is
+ # captured by the session view.
+ session.close()
+ return session
diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.py
index af10a3692d..1b52409a0b 100644
--- a/marimo/_server/export/exporter.py
+++ b/marimo/_server/export/exporter.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import mimetypes
import os
+from textwrap import dedent
from typing import cast
from marimo import __version__
@@ -15,6 +16,12 @@ from marimo._messaging.mimetypes import KnownMimeType
from marimo._output.utils import build_data_url
from marimo._runtime import dataflow
from marimo._runtime.virtual_file import read_virtual_file
+from marimo._server.export.utils import (
+ get_app_title,
+ get_download_filename,
+ get_filename,
+ get_markdown_from_cell,
+)
from marimo._server.file_manager import AppFileManager
from marimo._server.models.export import ExportAsHTMLRequest
from marimo._server.session.session_view import SessionView
@@ -45,9 +52,7 @@ class Exporter:
index_html_file = os.path.join(root, "index.html")
cell_ids = list(file_manager.app.cell_manager.cell_ids())
- filename = file_manager.filename
- if not filename:
- filename = "notebook.py"
+ filename = get_filename(file_manager)
with open(index_html_file, "r") as f: # noqa: ASYNC101
index_html = f.read()
@@ -95,9 +100,7 @@ class Exporter:
asset_url=request.asset_url,
)
- basename = os.path.basename(filename)
- download_filename = f"{os.path.splitext(basename)[0]}.html"
-
+ download_filename = get_download_filename(file_manager, "html")
return html, download_filename
def export_as_script(
@@ -118,16 +121,47 @@ class Exporter:
graph.cells[cid].code
for cid in dataflow.topological_sort(graph, graph.cells.keys())
]
- filename = file_manager.filename
- if not filename:
- filename = "notebook.script.py"
-
- basename = os.path.basename(filename)
- download_filename = f"{os.path.splitext(basename)[0]}.script.py"
-
code = (
f'\n__generated_with = "{__version__}"\n\n'
+ "\n\n# ---\n\n".join(codes)
)
+ download_filename = get_download_filename(file_manager, ".script.py")
return code, download_filename
+
+ def export_as_md(self, file_manager: AppFileManager) -> tuple[str, str]:
+ # 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(),
+ "",
+ ]
+ previous_was_markdown = False
+ for cell_data in file_manager.app.cell_manager.cell_data():
+ cell = cell_data.cell
+ code = cell_data.code
+ if cell:
+ markdown = get_markdown_from_cell(cell, code)
+ if markdown:
+ previous_was_markdown = True
+ document.append(markdown)
+ else:
+ # Add a blank line between markdown and code
+ if previous_was_markdown:
+ document.append("")
+ previous_was_markdown = False
+ guard = "```"
+ while guard in code:
+ guard += "`"
+ document.extend(
+ [f"""{guard}{{.python.marimo}}""", code, guard, ""]
+ )
+
+ download_filename = get_download_filename(file_manager, ".md")
+ return "\n".join(document).strip(), download_filename
diff --git a/marimo/_server/export/utils.py b/marimo/_server/export/utils.py
index 26df1d05b8..8e53489c37 100644
--- a/marimo/_server/export/utils.py
+++ b/marimo/_server/export/utils.py
@@ -1,122 +1,102 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-import asyncio
-from typing import Callable
-
-from marimo._config.manager import UserConfigManager
-from marimo._messaging.ops import MessageOperation
-from marimo._messaging.types import KernelMessage
-from marimo._runtime.requests import AppMetadata, SerializedCLIArgs
-from marimo._server.export.exporter import Exporter
+import ast
+import os
+import re
+from textwrap import dedent
+from typing import Optional
+
+from marimo._ast.cell import Cell
from marimo._server.file_manager import AppFileManager
-from marimo._server.file_router import AppFileRouter
-from marimo._server.model import ConnectionState, SessionConsumer, SessionMode
-from marimo._server.models.export import ExportAsHTMLRequest
-from marimo._server.models.models import InstantiateRequest
-from marimo._server.sessions import Session
-
-
-def export_as_script(
- filename: str,
-) -> tuple[str, str]:
- file_router = AppFileRouter.from_filename(filename)
- file_key = file_router.get_unique_file_key()
- assert file_key is not None
- file_manager = file_router.get_file_manager(file_key)
-
- return Exporter().export_as_script(file_manager)
-
-
-async def run_app_then_export_as_html(
- filename: str,
- include_code: bool,
- cli_args: SerializedCLIArgs,
-) -> tuple[str, str]:
- # Create a file router and file manager
- file_router = AppFileRouter.from_filename(filename)
- file_key = file_router.get_unique_file_key()
- assert file_key is not None
- file_manager = file_router.get_file_manager(file_key)
-
- config = UserConfigManager()
- session = await run_app_until_completion(file_manager, cli_args)
- # Export the session as HTML
- html, filename = Exporter().export_as_html(
- file_manager=session.app_file_manager,
- session_view=session.session_view,
- display_config=config.get_config()["display"],
- request=ExportAsHTMLRequest(
- include_code=include_code,
- download=False,
- files=[],
- ),
- )
- return html, filename
-
-
-async def run_app_until_completion(
- file_manager: AppFileManager,
- cli_args: SerializedCLIArgs,
-) -> Session:
- instantiated_event = asyncio.Event()
-
- # Create a no-op session consumer
- class NoopSessionConsumer(SessionConsumer):
- def on_start(
- self,
- check_alive: Callable[[], None],
- ) -> Callable[[KernelMessage], None]:
- del check_alive
-
- def listener(message: KernelMessage) -> None:
- if message[0] == "completed-run":
- instantiated_event.set()
-
- return listener
-
- def on_stop(self) -> None:
- pass
-
- async def write_operation(self, op: MessageOperation) -> None:
- pass
-
- def connection_state(self) -> ConnectionState:
- return ConnectionState.OPEN
-
- config = UserConfigManager()
-
- # Create a session
- session = Session.create(
- # Any initialization ID will do
- initialization_id="_any_",
- session_consumer=NoopSessionConsumer(),
- # Run in EDIT mode so that console outputs are captured
- mode=SessionMode.EDIT,
- app_metadata=AppMetadata(
- query_params={},
- filename=file_manager.path,
- cli_args=cli_args,
- ),
- app_file_manager=file_manager,
- user_config_manager=config,
- virtual_files_supported=False,
- )
-
- # Run the notebook to completion once
- session.instantiate(InstantiateRequest(object_ids=[], values=[]))
- await instantiated_event.wait()
- # Process console messages
- #
- # TODO(akshayka): A timing issue with the console output worker
- # might still exist; the better thing to do would be to flush
- # the worker, then ask it to quit and join on it. If we have an
- # issue with some outputs being missed, that's what we should do.
- session.message_distributor.flush()
- # Hack: yield to give the session view a chance to process the incoming
- # console operations.
- await asyncio.sleep(0.1)
- # Stop distributor, terminate kernel process, etc -- all information is
- # captured by the session view.
- session.close()
- return session
+
+
+def format_filename_title(filename: str) -> str:
+ basename = os.path.basename(filename)
+ name, ext = os.path.splitext(basename)
+ title = re.sub("[-_]", " ", name)
+ return title.title()
+
+
+def get_filename(
+ file_manager: AppFileManager, default: str = "notebook.py"
+) -> str:
+ filename = file_manager.filename
+ if not filename:
+ filename = default
+ return filename
+
+
+def get_app_title(file_manager: AppFileManager) -> str:
+ if file_manager.app.config.app_title:
+ return f"{file_manager.app.config.app_title}"
+ filename = get_filename(file_manager)
+ return format_filename_title(filename)
+
+
+def get_download_filename(file_manager: AppFileManager, extension: str) -> str:
+ filename = get_filename(file_manager, f"notebook.{extension}")
+ basename = os.path.basename(filename)
+ return f"{os.path.splitext(basename)[0]}.{extension}"
+
+
+def _const_string(args: list[ast.stmt]) -> str:
+ (inner,) = args
+ if hasattr(inner, "values"):
+ (inner,) = inner.values
+ return f"{inner.value}" # type: ignore[attr-defined]
+
+
+def get_markdown_from_cell(
+ cell: Cell, code: str, native_callout: bool = False
+) -> Optional[str]:
+ """Attempt to extract markdown from a cell, or return None"""
+
+ if not (cell.refs == {"mo"} and not cell.defs):
+ return None
+ markdown_lines = [
+ line for line in code.strip().split("\n") if line.startswith("mo.md(")
+ ]
+ if len(markdown_lines) > 1:
+ return None
+
+ code = code.strip()
+ # Attribute Error handled by the outer try/except block.
+ # Wish there was a more compact to ignore ignore[attr-defined] for all.
+ try:
+ (body,) = ast.parse(code).body
+ callout = None
+ if body.value.func.attr == "md": # type: ignore[attr-defined]
+ value = body.value # type: ignore[attr-defined]
+ elif body.value.func.attr == "callout": # type: ignore[attr-defined]
+ if not native_callout:
+ return None
+ if body.value.args: # type: ignore[attr-defined]
+ callout = _const_string(body.value.args) # type: ignore[attr-defined]
+ else:
+ (keyword,) = body.value.keywords # type: ignore[attr-defined]
+ assert keyword.arg == "kind"
+ callout = _const_string([keyword.value]) # type: ignore
+ value = body.value.func.value # type: ignore[attr-defined]
+ else:
+ return None
+ assert value.func.value.id == "mo"
+ except (AssertionError, AttributeError, ValueError):
+ # No reason to explicitly catch exceptions if we can't parse out
+ # markdown. Just handle it as a code block.
+ return None
+
+ # Dedent behavior is a little different that in marimo js, so handle
+ # accordingly.
+ md_lines = _const_string(value.args).split("\n")
+ md_lines = [line.rstrip() for line in md_lines]
+ md = dedent(md_lines[0]) + "\n" + dedent("\n".join(md_lines[1:]))
+ md = md.strip()
+ if callout:
+ md = dedent(
+ f"""
+ ::: {{.callout-{callout}}}
+ {md}
+ :::"""
+ )
+ return md
diff --git a/pyproject.toml b/pyproject.toml
index 326be21f70..5720f424da 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -88,6 +88,8 @@ dev = [
"pytest~=7.4.0",
"pytest-codecov~=0.5.1",
"pytest-asyncio~=0.23.4",
+ "types-Markdown~=3.6.0.20240316",
+ "types-PyYAML~=6.0.12.20240311",
"mypy~=1.7.0",
"ruff~=0.3.6",
"typos~=1.17.1",
diff --git a/tests/_cli/snapshots/async.txt b/tests/_cli/snapshots/async.txt
new file mode 100644
index 0000000000..34badf80f2
--- /dev/null
+++ b/tests/_cli/snapshots/async.txt
@@ -0,0 +1,9 @@
+---
+title: Notebook
+marimo-version: 0.0.0
+---
+
+```{.python.marimo}
+import asyncio
+await asyncio.sleep(0.1)
+```
diff --git a/tests/_cli/snapshots/broken.txt b/tests/_cli/snapshots/broken.txt
new file mode 100644
index 0000000000..3dc7982a5e
--- /dev/null
+++ b/tests/_cli/snapshots/broken.txt
@@ -0,0 +1,8 @@
+---
+title: Notebook
+marimo-version: 0.0.0
+---
+
+```{.python.marimo}
+valid_statement = 1
+```
diff --git a/tests/_cli/snapshots/dataflow.md.txt b/tests/_cli/snapshots/dataflow.md.txt
new file mode 100644
index 0000000000..036c0b79f1
--- /dev/null
+++ b/tests/_cli/snapshots/dataflow.md.txt
@@ -0,0 +1,438 @@
+---
+title: Dataflow
+marimo-version: 0.0.0
+---
+
+# How marimo notebooks run
+
+Reactive execution is based on a single rule: when a cell is run, all other
+cells that reference any of the global variables it defines run
+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
+cells and edges represent data dependencies. marimo creates this graph by
+analyzing each cell (without running it) to determine its
+
+- references ("refs*), the global variables it reads but doesn't define;
+- definitions ("defs"), the global variables it defines.
+
+There is an edge from one cell to another if the latter cell references any
+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}
+mo.accordion(
+ {
+ "Tip: inspecting refs and defs": f"""
+ Use `mo.refs()` and `mo.defs()` to inspect the refs and defs of any
+ given cell. This can help with debugging complex notebooks.
+
+ For example, here are the refs and defs of this cell:
+
+ {mo.as_html({"refs": mo.refs(), "defs": mo.defs()})}
+ """
+ }
+)
+```
+
+```{.python.marimo}
+mo.md(
+ f"""
+ {mo.as_html(plot_wave(amplitude, period))}
+
+ - `refs: {mo.refs()}`
+ - `defs: {mo.defs()}`
+ """
+)
+```
+
+```{.python.marimo}
+period = 2 * 3.14159
+
+mo.md(
+ f"""
+ - `refs: {mo.refs()}`
+ - `defs: {mo.defs()}`
+ """
+)
+```
+
+```{.python.marimo}
+amplitude = 1
+
+mo.md(
+ f"""
+ - `refs: {mo.refs()}`
+ - `defs: {mo.defs()}`
+ """
+)
+```
+
+```{.python.marimo}
+def plot_wave(amplitude, period):
+ if not numpy_installed:
+ return mo.md(
+ "> Oops! It looks like you don't have `numpy` installed."
+ )
+ if not matplotlib_installed:
+ return mo.md(
+ "> Oops! It looks like you don't have `matplotlib` installed."
+ )
+ x = np.linspace(0, 2 * np.pi, 256)
+ plt.plot(x, amplitude * np.sin(2 * np.pi / period * x))
+ plt.xlim(0, 2 * np.pi)
+ plt.ylim(-2, 2)
+ plt.xticks(
+ [0, np.pi / 2, np.pi, 3 * np.pi / 2, 2 * np.pi],
+ [0, r"$\pi/2$", r"$\pi$", r"$3\pi/2$", r"$2\pi$"],
+ )
+ plt.yticks([-2, -1, 0, 1, 2])
+ plt.gcf().set_size_inches(6.5, 2.4)
+ return plt.gca()
+
+mo.md(
+ f"""
+ - `refs: {mo.refs()}`
+ - `defs: {mo.defs()}`
+ """
+)
+```
+
+🌊 **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.
+
+```
+ +------+ +-----------+
+ +-----------| {mo} |-----------+ | {np, plt} |
+ | +---+--+ | +----+------+
+ | | | |
+ | | | |
+ v v v v
+ +----------+ +-------------+ +--+----------+
+ | {period} | | {amplitude} | | {plot_wave} |
+ +---+------+ +-----+-------+ +------+------+
+ | | |
+ | v |
+ | +----+ |
+ +------------> | {} | <-------------+
+ +----+
+```
+
+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
+constraint, there would be no way for marimo to know which order to
+execute cells in.
+
+If you violate this constraint, marimo provides a helpful
+error message, like below:
+
+```{.python.marimo}
+planet = "Mars"
+planet
+```
+
+```{.python.marimo}
+planet = "Earth"
+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.
+
+**🌊 Try it!** Get rid of the following errors by merging the next two
+cells into a single cell.
+
+```{.python.marimo}
+count = 0
+```
+
+```{.python.marimo}
+count += 1
+```
+
+### Underscore-prefixed variables are local to cells
+
+Global variables prefixed with an underscore are "private" to the cells
+that define them. This means that multiple cells can define the same
+underscore-prefixed name, and one cell's private variables won't be
+made available to other cells.
+
+**Example**.
+
+```{.python.marimo}
+_private_variable, _ = 1, 2
+_private_variable, _
+```
+
+```{.python.marimo}
+_private_variable, _ = 3, 4
+_private_variable, _
+```
+
+```{.python.marimo}
+# `_private_variable` and `_` are not defined in this cell
+_private_variable, _
+```
+
+### Deleting a cell deletes its variables
+
+Deleting a cell deletes its global variables and
+then runs all cells that reference them. This prevents severe bugs that
+can arise when state has been deleted from the editor but not from the
+program memory.
+
+```{.python.marimo}
+to_be_deleted = "variable still exists"
+
+mo.md(
+ """
+ 🌊 **Try it!**
+
+ Delete this cell by clicking the trash bin icon.
+ """
+)
+```
+
+```{.python.marimo}
+to_be_deleted
+```
+
+### Cycles are not allowed
+
+Cycles among cells are not allowed. For example:
+
+```{.python.marimo}
+one = two - 1
+```
+
+```{.python.marimo}
+two = one + 1
+```
+
+### marimo doesn't track attributes
+
+marimo only tracks global variables. Writing object attributes does not
+trigger reactive execution.
+
+**🌊 Example**. Change the value of `state.number` in the next cell, then
+run the cell. Notice how the subsequent cell isn't updated.
+
+```{.python.marimo}
+state.number = 1
+```
+
+```{.python.marimo}
+state.number
+```
+
+```{.python.marimo}
+class namespace:
+ pass
+
+state = namespace()
+state.number = 0
+```
+
+```{.python.marimo}
+mo.accordion(
+ {
+ "Why not track attributes?": """
+ marimo can't reliably trace attributes
+ to cells that define them. For example, attributes are routinely
+ created or modified by library code.
+ """
+ }
+)
+```
+
+### marimo doesn't track mutations
+
+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}
+mo.accordion(
+ {
+ "Tip (advanced): mutable state": (
+ """
+ You can use the fact that marimo does not track attributes or
+ mutations to implement mutable state in marimo. An example of
+ this is shown in the `ui` tutorial.
+ """
+ )
+ }
+)
+```
+
+## Best practices
+
+The constraints marimo puts on your notebooks are all natural consequences
+of the fact that marimo programs are directed acyclic graphs. As long as
+you keep this fact in mind, you'll quickly adapt to the marimo way of
+writing notebooks.
+
+Ultimately, these constraints will enable you to create powerful notebooks
+and apps, and they'll encourage you to write clean, reproducible code.
+
+Follow these tips to stay on the marimo way:
+
+```{.python.marimo}
+mo.accordion(tips)
+```
+
+## What's next?
+
+Check out the tutorial on interactivity for a tour of UI elements:
+
+```
+marimo tutorial ui
+```
+
+```{.python.marimo}
+matplotlib_installed = False
+numpy_installed = False
+
+try:
+ import matplotlib.pyplot as plt
+
+ matplotlib_installed = True
+except ModuleNotFoundError:
+ pass
+
+try:
+ import numpy as np
+
+ numpy_installed = True
+except ModuleNotFoundError:
+ pass
+```
+
+````{.python.marimo}
+tips = {
+ "Use global variables sparingly": (
+ """
+ Keep the number of global variables in your program small to avoid
+ name collisions across cells. Keep the number of global variables
+ defined by any one cell small to make sure that the units of
+ reactive execution are small.
+ """
+ ),
+ "Use descriptive names": (
+ """
+ Use descriptive variable names, especially for global variables.
+ This will help you minimize name clashes, and will also result in
+ better code.
+ """
+ ),
+ "Use functions": (
+ """
+ Encapsulate logic into functions to avoid polluting the global
+ namespace with temporary or intermediate variables.
+ """
+ ),
+ "Minimize mutations": (
+ """
+ We saw earlier that marimo cannot track object mutations. So try
+ to only mutate an object in the cell that creates it, or create
+ new objects instead of mutating existing ones.
+
+ For example, don't do this:
+
+ ```python3
+ # a cell
+ numbers = [1, 2, 3]
+ ```
+
+ ```python3
+ # another cell
+ numbers.append(4)
+ ```
+
+ Instead, prefer
+
+ ```python3
+ # a cell
+ numbers = [1, 2, 3]
+ numbers.append(4)
+ ```
+
+ or
+
+ ```python3
+ # a cell
+ numbers = [1, 2, 3]
+ ```
+
+ ```python3
+ # another cell
+ more_numbers = numbers + [4]
+ ```
+ """
+ ),
+ "Write idempotent cells": (
+ """
+ Write cells whose outputs and behavior are the same when given
+ the same inputs (refs); such cells are called _idempotent_. This will
+ help you avoid bugs, and let you cache expensive intermediate
+ computations (see the next tip).
+ """
+ ),
+ "Cache intermediate computations with `@functools.cache`": (
+ """
+ Use Python's builtin `functools` library to cache expensive
+ intermediate computations. You can do this if you abstract complex
+ logic into idempotent functions, following earlier tips.
+
+ For example:
+
+ ```python3
+ import functools
+
+ @functools.cache
+ def compute_prediction(problem_parameters):
+ ...
+ ```
+
+ Whenever `compute_predictions` is called with a value of
+ `problem_parameters` it has not seen, it will compute the predictions
+ and store them in a cache. The next time it is called with the same
+ parameters, instead of recomputing the predictions, it will just
+ fetch the previously computed ones from the cache.
+ """
+ ),
+}
+````
+
+```{.python.marimo}
+import marimo as mo
+```
\ No newline at end of file
diff --git a/tests/_cli/snapshots/frontmatter-test.py.txt b/tests/_cli/snapshots/frontmatter-test.py.txt
new file mode 100644
index 0000000000..ba78150164
--- /dev/null
+++ b/tests/_cli/snapshots/frontmatter-test.py.txt
@@ -0,0 +1,24 @@
+import marimo
+
+__generated_with = "0.0.0"
+app = marimo.App(app_title="My Title")
+
+
+def __(mo):
+ mo.md(
+ r"""
+ # Notebook
+ """
+ )
+ return
+
+
+def __():
+ print("Hello, World!")
+ return
+
+
+if __name__ == "__main__":
+ app.run()
\ No newline at end of file
diff --git a/tests/_cli/snapshots/marimo_for_jupyter_users.md.txt b/tests/_cli/snapshots/marimo_for_jupyter_users.md.txt
new file mode 100644
index 0000000000..20b46b0b77
--- /dev/null
+++ b/tests/_cli/snapshots/marimo_for_jupyter_users.md.txt
@@ -0,0 +1,160 @@
+---
+title: Marimo For Jupyter Users
+marimo-version: 0.0.0
+---
+
+# marimo for Jupyter users
+
+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*.
+
+Try updating the value of x in the next cell, then run it.
+
+```{.python.marimo}
+x = 0; x
+```
+
+```{.python.marimo}
+y = x + 1; y
+```
+
+marimo 'reacts' to the change in `x` and automatically recalculates `y`!
+
+**Explanation.** marimo reads the code in your cells and understands the
+dependences between them, based on the variables that each cell declares and
+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.
+
+It also ensures that your code and outputs remain in sync:
+
+- You don't have to worry about whether you forgot to re-run a cell.
+- When you delete a cell, its variables are automatically removed from
+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
+synchronized with Python.
+
+```{.python.marimo}
+import marimo as mo
+```
+
+```{.python.marimo}
+slider = mo.ui.slider(start=1, stop=10, label="$x$")
+slider
+```
+
+```{.python.marimo}
+slider.value
+```
+
+**Explanation.** marimo is both a notebook and a library. Import `marimo as
+mo` and use `mo.ui` to get access to powerful UI elements.
+
+UI elements assigned to variables are automatically plugged into marimo's
+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
+
+```marimo run your_notebook.py```
+
+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)
+
+```{.python.marimo}
+z.value
+```
+
+```{.python.marimo}
+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:
+
+```{.python.marimo}
+df = 0
+```
+
+```{.python.marimo}
+df = 1
+```
+
+```{.python.marimo}
+results = df.groupby(["my_column"]).sum()
+```
+
+**Explanation.** `results` depends on `df`, but which value of `df` should it use? Reactivity makes it impossible to answer this question in a sensible way, so marimo disallows variable reassignment.
+
+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.
+
+```{.python.marimo}
+mo.md(
+ f"""
+ The value of {slider} is {slider.value}.
+ """
+)
+```
+
+**Explanation.** By lifting Markdown into Python, marimo lets you construct
+dynamic Markdown parametrized by arbitrary Python elements. marimo knows
+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.
+
+### marimo notebooks are Python scripts
+marimo notebooks are stored as pure Python scripts. This lets you version them with git, execute them with the command line, and re-use logic from one notebook in another.
+
+### marimo notebooks do not store outputs
+marimo does _not_ save your outputs in the file; if you want them saved, make sure to save them to disk with Python, or export to HTML via the notebook menu.
+
+### 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.
+
+We believe that the tools we use shape the way we think — better tools, for better minds. With marimo, we hope to provide the Python community with a better programming environment to do research and communicate it; to experiment with code and share it; to learn computational science and teach it.
+
+The marimo editor and library have many features not discussed here.
+Check out [our docs](https://docs.marimo.io/) to learn more!
+
+_This guide was adapted from [Pluto for Jupyter
+users](https://featured.plutojl.org/basic/pluto%20for%20jupyter%20users).
+We ❤️ Pluto.jl!_
\ No newline at end of file
diff --git a/tests/_cli/snapshots/markdown.txt b/tests/_cli/snapshots/markdown.txt
new file mode 100644
index 0000000000..24ce211de7
--- /dev/null
+++ b/tests/_cli/snapshots/markdown.txt
@@ -0,0 +1,12 @@
+---
+title: Notebook
+marimo-version: 0.0.0
+---
+
+```{.python.marimo}
+import marimo as mo
+```
+
+```{.python.marimo}
+slider = mo.ui.slider(0, 10)
+```
diff --git a/tests/_cli/test_cli_export.py b/tests/_cli/test_cli_export.py
index 68fde5775a..84ef3dd6da 100644
--- a/tests/_cli/test_cli_export.py
+++ b/tests/_cli/test_cli_export.py
@@ -325,3 +325,112 @@ class TestExportScript:
in line
)
break
+
+
+class TestExportMarkdown:
+ @staticmethod
+ def test_export_markdown(temp_marimo_file: str) -> None:
+ p = subprocess.run(
+ ["marimo", "export", "md", temp_marimo_file],
+ capture_output=True,
+ )
+ assert p.returncode == 0, p.stderr.decode()
+ output = p.stdout.decode()
+ output = output.replace(__version__, "0.0.0")
+ snapshot("markdown.txt", output)
+
+ @staticmethod
+ def test_export_script_async(temp_async_marimo_file: str) -> None:
+ p = subprocess.run(
+ ["marimo", "export", "md", temp_async_marimo_file],
+ capture_output=True,
+ )
+ assert p.returncode == 0, p.stderr.decode()
+ output = p.stdout.decode()
+ output = output.replace(__version__, "0.0.0")
+ snapshot("async.txt", output)
+
+ @staticmethod
+ def test_export_broken(temp_unparsable_marimo_file: str) -> None:
+ p = subprocess.run(
+ ["marimo", "export", "md", temp_unparsable_marimo_file],
+ capture_output=True,
+ )
+ assert p.returncode == 0, p.stderr.decode()
+ output = p.stdout.decode()
+ output = output.replace(__version__, "0.0.0")
+ snapshot("broken.txt", output)
+
+ @pytest.mark.skipif(
+ condition=DependencyManager.has_watchdog(),
+ reason="hangs when watchdog is installed",
+ )
+ async def test_export_watch_script(self, temp_marimo_file: str) -> None:
+ temp_out_file = temp_marimo_file.replace(".md", ".script.md")
+ p = subprocess.Popen( # noqa: ASYNC101
+ [
+ "marimo",
+ "export",
+ "md",
+ temp_marimo_file,
+ "--watch",
+ "--output",
+ temp_out_file,
+ ],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ )
+
+ # Wait for the message
+ while True:
+ line = p.stdout.readline().decode()
+ if line:
+ assert f"Watching {temp_marimo_file}" in line
+ break
+
+ assert not path.exists(temp_out_file)
+
+ # Modify file
+ with open(temp_marimo_file, "a") as f: # noqa: ASYNC101
+ f.write("\n# comment\n")
+
+ assert p.poll() is None
+ # Wait for rebuild
+ while True:
+ line = p.stdout.readline().decode()
+ if line:
+ assert "Re-exporting" in line
+ break
+
+ await asyncio.sleep(0.1)
+ assert path.exists(temp_out_file)
+
+ @pytest.mark.skipif(
+ condition=DependencyManager.has_watchdog(),
+ reason="hangs when watchdog is installed",
+ )
+ def test_export_watch_script_no_out_dir(
+ self, temp_marimo_file: str
+ ) -> None:
+ p = subprocess.Popen(
+ [
+ "marimo",
+ "export",
+ "md",
+ temp_marimo_file,
+ "--watch",
+ ],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ )
+
+ # Should return an error
+ while True:
+ line = p.stderr.readline().decode()
+ if line:
+ assert (
+ "Cannot use --watch without providing "
+ + "an output file with --output."
+ in line
+ )
+ break
diff --git a/tests/_cli/test_ipynb_to_marimo.py b/tests/_cli/test_ipynb_to_marimo.py
index fbb96131e9..64f544b2f7 100644
--- a/tests/_cli/test_ipynb_to_marimo.py
+++ b/tests/_cli/test_ipynb_to_marimo.py
@@ -7,7 +7,7 @@ import textwrap
from typing import TYPE_CHECKING
from marimo._ast import codegen
-from marimo._cli.ipynb_to_marimo import convert_from_path
+from marimo._cli.convert.ipynb import convert_from_ipynb_file
if TYPE_CHECKING:
from collections.abc import Sequence
@@ -16,7 +16,7 @@ DIR_PATH = os.path.dirname(os.path.realpath(__file__))
def get_codes(ipynb_name: str) -> tuple[Sequence[str], Sequence[str]]:
- contents = convert_from_path(
+ contents = convert_from_ipynb_file(
DIR_PATH + f"/ipynb_data/{ipynb_name}.ipynb.txt"
)
diff --git a/tests/_cli/test_markdown_conversion.py b/tests/_cli/test_markdown_conversion.py
new file mode 100644
index 0000000000..669d098eb9
--- /dev/null
+++ b/tests/_cli/test_markdown_conversion.py
@@ -0,0 +1,121 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import os
+import sys
+import tempfile
+from textwrap import dedent
+
+import pytest
+
+from marimo import __version__
+from marimo._cli.convert.markdown import convert_from_md
+from marimo._server.export import export_as_md
+
+# Just a handful of scripts to test
+from marimo._tutorials import dataflow, marimo_for_jupyter_users
+from tests.mocks import snapshotter
+
+modules = {
+ "marimo_for_jupyter_users": marimo_for_jupyter_users,
+ "dataflow": dataflow,
+}
+
+DIR_PATH = os.path.dirname(os.path.realpath(__file__))
+
+snapshot = snapshotter(__file__)
+
+
+def sanitized_version(output: str) -> str:
+ return output.replace(__version__, "0.0.0")
+
+
+def convert_from_py(py: str) -> str:
+ # Needs to be a .py for export to be invoked.
+ tempfile_name = ""
+ try:
+ # in windows, can't re-open an open named temporary file, hence
+ # delete=False and manual clean up
+ with tempfile.NamedTemporaryFile(
+ mode="w", suffix=".py", delete=False
+ ) as f:
+ tempfile_name = f.name
+ f.write(py)
+ f.seek(0)
+ output = export_as_md(tempfile_name)[0]
+ finally:
+ os.remove(tempfile_name)
+
+ return sanitized_version(output)
+
+
+# Regarding windows skip: This should be fine, as less complex cases are
+# captured by test_markdown_frontmatter. Here, snapshotting fails in windows
+# due to emojis in the tutorials :(
+ sys.platform == "win32", reason="Failing on Windows CI due to emojis"
+)
+def test_markdown_snapshots() -> None:
+ for name, mod in modules.items():
+ output = sanitized_version(export_as_md(mod.__file__)[0])
+ snapshot(f"{name}.md.txt", output)
+
+
+# Windows does not encode emojis correctly for md -> python
+ sys.platform == "win32", reason="Failing on Windows CI due to emojis"
+)
+def test_idempotent_markdown_to_marimo() -> None:
+ for script in modules.keys():
+ with open(DIR_PATH + f"/snapshots/{script}.md.txt") as f:
+ md = f.read()
+ python_source = sanitized_version(convert_from_md(md))
+ assert convert_from_py(python_source) == md.strip()
+
+
+def test_markdown_frontmatter() -> None:
+ script = dedent(
+ """
+ ---
+ title: "My Title"
+ description: "My Description"
+ tags: ["tag1", "tag2"]
+ filters:
+ - name: "filter1"
+ - name: "filter2"
+ ---
+
+ # Notebook
+
+ ```{.python.marimo}
+ print("Hello, World!")
+ ```
+ """[1:]
+ )
+ print(script)
+ output = sanitized_version(convert_from_md(script))
+ assert 'app_title="My Title"' in output
+ snapshot("frontmatter-test.py.txt", output)
+
+
+def test_markdown_just_frontmatter() -> None:
+ script = dedent(
+ """
+ ---
+ title: "My Title"
+ description: "My Description"
+ tags: ["tag1", "tag2"]
+ filters:
+ - name: "filter1"
+ - name: "filter2"
+ ---
+ """[1:]
+ )
+ output = sanitized_version(convert_from_md(script))
+ assert 'app_title="My Title"' in output
+
+
+def test_markdown_empty() -> None:
+ script = ""
+ with pytest.raises(ValueError):
+ convert_from_md(script)
diff --git a/tests/conftest.py b/tests/conftest.py
index 354d684d51..96ea9e0d63 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -208,6 +208,48 @@ def temp_async_marimo_file() -> Generator[str, None, None]:
tmp_dir.cleanup()
+def temp_unparsable_marimo_file() -> Generator[str, None, None]:
+ tmp_dir = TemporaryDirectory()
+ tmp_file = tmp_dir.name + "/notebook.py"
+ content = inspect.cleandoc(
+ """
+ import marimo
+ app = marimo.App()
+
+ app._unparsable_cell(
+ r\"""
+ return
+ \""",
+ name="__"
+ )
+
+ app._unparsable_cell(
+ r\"""
+ partial_statement =
+ \""",
+ name="__"
+ )
+
+ @app.cell
+ def __():
+ valid_statement = 1
+ return valid_statement,
+
+ if __name__ == "__main__":
+ app.run()
+ """
+ )
+
+ try:
+ with open(tmp_file, "w") as f:
+ f.write(content)
+ f.flush()
+ yield tmp_file
+ finally:
+ tmp_dir.cleanup()
+
+
# Factory to create ExecutionRequests and abstract away cell ID
class ExecReqProvider:
def __init__(self) -> None: