#Use typst SVG to replace markdown in marimo python notebook cells

1 messages · Page 1 of 1 (latest)

signal prairie
#

Marimo is an open-source reactive notebook for Python. It is possible to replace markdown cells with typst SVG.
https://github.com/marimo-team/marimo/discussions/2441
I posted it in marimo's GitHub discussions a few days ago, and it looks like this is the best solution by far.

By the way for Jupyter notebook: https://github.com/xingjian-zhang/typst2img/

Explore data and build apps seamlessly with marimo, a next-generation Python notebook.

GitHub

Typst is a simple markup. typst(r""" #let ee = math.upright("e") $ 1/sqrt(2pi) ee^(-x^2 / 2). $ """) from functools import cache from subprocess import Call...

GitHub

A fast script to render your Typst formulas to svg and png. Integrate formulas to your slides in seconds! - xingjian-zhang/typst2img

bitter widget
#
import typst
import marimo as mo

# Keep a handle to the original in case you want to restore it.
_original_md = mo.md

# Your Typst wrapper template (you can tweak margin, etc.)
_TYPST_PREFIX = b"""#set page(width: auto, height: auto, margin: 10pt)
#set text(size:20pt)
"""
_TYPST_SUFFIX = b"\n"

def _patched_md(*args, **kwargs):
    """
    Monkeypatched mo.md:
      - If given a single str/bytes argument, treat it as Typst markup,
        wrap with #set page(...), compile to SVG, and display via mo.Html.
      - Opt out via _typst=False to call the original mo.md.
    """
    use_typst = kwargs.pop("_typst", True)

    # Allow opting out: mo.md("...", _typst=False)
    if not use_typst:
        return _original_md(*args, **kwargs)

    # Only handle the common case: mo.md("...") or mo.md(r"...")
    if len(args) != 1 or not isinstance(args[0], (str, bytes, bytearray)):
        return _original_md(*args, **kwargs)

    body = args[0]
    if isinstance(body, str):
        body_bytes = body.encode("utf-8")
    else:
        body_bytes = bytes(body)

    source = _TYPST_PREFIX + body_bytes + _TYPST_SUFFIX

    try:
        svg = typst.compile(source, format="svg").decode("utf-8")
        return mo.Html(svg)
    except Exception:
        # If Typst compilation fails, fall back to normal markdown rendering
        # so your app doesn't break completely.
        return _original_md(*args, **kwargs)

# Apply the monkeypatch
mo.md = _patched_md