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.

improvement: guess pycon for codehighlighting (#5101)

Myles Scolnick612284faaa8a
diff --git a/marimo/_output/md.py b/marimo/_output/md.py
index 7316e950c0..4eb382e753 100644
--- a/marimo/_output/md.py
+++ b/marimo/_output/md.py
@@ -1,6 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import re
from functools import cache
from importlib.util import find_spec
from inspect import cleandoc
@@ -9,6 +10,7 @@ from typing import Any, Literal, Optional, Union
from urllib.request import urlopen
import markdown # type: ignore
+import markdown.preprocessors # type: ignore
import pymdownx.emoji # type: ignore
from marimo._output.hypertext import Html
@@ -17,32 +19,125 @@ from marimo._output.md_extensions.iconify import IconifyExtension
from marimo._output.rich_help import mddoc
from marimo._utils.url import is_url
-extension_configs: dict[str, dict[str, Any]] = {
- "pymdownx.arithmatex": {
- # Use "generic" mode, no preview, since we don't use MathJax
- "preview": False,
- "generic": True,
- # The default "\\(" causes problems when passing
- # html-escaped `md` output back into `md`
- "tex_inline_wrap": ["||(", "||)"],
- "tex_block_wrap": ["||[", "||]"],
- # Wrap latex in a custom element
- "block_tag": "marimo-tex",
- "inline_tag": "marimo-tex",
- },
- "pymdownx.superfences": {
- "disable_indented_code_blocks": True,
- "css_class": "codehilite",
- },
- "pymdownx.emoji": {
- # This uses native emoji characters,
- # instead of loading from a CDN
- "emoji_generator": pymdownx.emoji.to_alt,
- },
- "footnotes": {
- "UNIQUE_IDS": True,
- },
-}
+
+class PyconDetectorExtension(markdown.Extension):
+ """Markdown extension to detect Python console sessions and mark them as pycon."""
+
+ def extendMarkdown(self, md: markdown.Markdown) -> None:
+ """Add the preprocessor to the markdown instance."""
+ processor = PyconDetectorPreprocessor(md)
+ md.preprocessors.register(processor, "pycon_detector", 30)
+
+
+class PyconDetectorPreprocessor(markdown.preprocessors.Preprocessor):
+ """Preprocessor that detects Python console sessions in fenced code blocks.
+
+ For example, the following code:
+
+ ```
+ >>> print("Hello, world!")
+ ... print("Hello, world!")
+ ```
+
+ will be detected as a Python console session and marked as `pycon`.
+ """
+
+ def __init__(self, md: markdown.Markdown) -> None:
+ super().__init__(md)
+ # Pattern to match fenced code blocks
+ self.fence_pattern = re.compile(
+ r"^(\s*)```(\w*)\s*\n(.*?)^(\s*)```\s*$", re.MULTILINE | re.DOTALL
+ )
+
+ def run(self, lines: list[str]) -> list[str]:
+ """Process the lines and detect pycon patterns."""
+ text = "\n".join(lines)
+
+ def replace_fence(match: re.Match[str]) -> str:
+ indent = match.group(1)
+ language = match.group(2) or ""
+ code = match.group(3)
+
+ # Only process if no language is specified
+ if not language:
+ if self._detect_pycon(code):
+ # Replace with pycon language
+ return f"{indent}```pycon\n{code}{indent}```"
+
+ # Return original
+ return match.group(0)
+
+ modified_text = self.fence_pattern.sub(replace_fence, text)
+ return modified_text.split("\n")
+
+ def _detect_pycon(self, code: str) -> bool:
+ """
+ Detect if code contains Python console session patterns.
+
+ Returns True if the code appears to be a Python console session
+ (contains >>> or ... prompts).
+ """
+ lines = code.strip().split("\n")
+
+ # Look for Python console prompts
+ console_prompt_pattern = re.compile(r"^\s*>>>")
+ continuation_prompt_pattern = re.compile(r"^\s*\.\.\.")
+
+ # Count lines that look like console prompts
+ prompt_lines = 0
+ for line in lines:
+ if console_prompt_pattern.match(
+ line
+ ) or continuation_prompt_pattern.match(line):
+ prompt_lines += 1
+
+ # If more than 30% of non-empty lines are prompts, likely a console session
+ non_empty_lines = [line for line in lines if line.strip()]
+ if len(non_empty_lines) == 0:
+ return False
+
+ return prompt_lines / len(non_empty_lines) > 0.3
+
+
+@cache
+def _get_extension_configs() -> dict[str, dict[str, Any]]:
+ extension_configs: dict[str, dict[str, Any]] = {
+ "pymdownx.arithmatex": {
+ # Use "generic" mode, no preview, since we don't use MathJax
+ "preview": False,
+ "generic": True,
+ # The default "\\(" causes problems when passing
+ # html-escaped `md` output back into `md`
+ "tex_inline_wrap": ["||(", "||)"],
+ "tex_block_wrap": ["||[", "||]"],
+ # Wrap latex in a custom element
+ "block_tag": "marimo-tex",
+ "inline_tag": "marimo-tex",
+ },
+ "pymdownx.highlight": {
+ "use_pygments": True,
+ # Try to guess the language of the code block
+ "guess_lang": "block",
+ # Show the language in the classname, helps with debugging and
+ # customizing the styles
+ "pygments_lang_class": True,
+ },
+ "pymdownx.superfences": {
+ "disable_indented_code_blocks": True,
+ "css_class": "codehilite",
+ },
+ "pymdownx.emoji": {
+ # This uses native emoji characters,
+ # instead of loading from a CDN
+ "emoji_generator": pymdownx.emoji.to_alt,
+ },
+ "footnotes": {
+ "UNIQUE_IDS": True,
+ },
+ }
+
+ return extension_configs
+
MarkdownSize = Literal["sm", "base", "lg", "xl", "2xl"]
@@ -55,10 +150,11 @@ def _has_module(module_name: str) -> bool:
@cache
-def get_extensions() -> list[Union[str, markdown.Extension]]:
+def _get_extensions() -> list[Union[str, markdown.Extension]]:
return [
# Syntax highlighting
- "codehilite",
+ PyconDetectorExtension(), # Python console detection (run before highlight)
+ "pymdownx.highlight",
# Markdown tables
"tables",
# LaTeX
@@ -131,8 +227,8 @@ class _md(Html):
# markdown.markdown appends a newline, hence strip
html_text = markdown.markdown(
text,
- extensions=get_extensions(),
- extension_configs=extension_configs, # type: ignore[arg-type]
+ extensions=_get_extensions(),
+ extension_configs=_get_extension_configs(),
).strip()
# replace <p> tags with <span> as HTML doesn't allow nested <div>s in <p>s
html_text = html_text.replace(
diff --git a/marimo/_smoke_tests/markdown/highlight.py b/marimo/_smoke_tests/markdown/highlight.py
new file mode 100644
index 0000000000..c9739b5528
--- /dev/null
+++ b/marimo/_smoke_tests/markdown/highlight.py
@@ -0,0 +1,66 @@
+import marimo
+
+__generated_with = "0.13.12"
+app = marimo.App(width="medium")
+
+
+def _(mo):
+ mo.md(
+ """
+ ```
+ >>> # pycon (omitted)
+ >>> def foo():
+ >>> pass
+ ```
+
+ ```
+ # python (omitted)
+ def foo():
+ return range(1, 100)
+ return x + y
+ ```
+
+ ```pycon
+ >>> def foo():
+ >>> pass
+ ```
+
+ ```python
+ # python
+ def foo():
+ pass
+ x + y
+ ```
+ """
+ )
+ return
+
+
+def _(mo):
+ mo.md(
+ r"""
+ ```js
+ // js
+ const myVar = "";
+ ```
+
+ ```
+ import { foo } from "bar";
+ // js omitted
+ var myVar = "";
+ ```
+ """
+ )
+ return
+
+
+def _():
+ import marimo as mo
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_islands/snapshots/markdown.txt b/tests/_islands/snapshots/markdown.txt
index 4e64d414ca..5896df0346 100644
--- a/tests/_islands/snapshots/markdown.txt
+++ b/tests/_islands/snapshots/markdown.txt
@@ -6,7 +6,7 @@
<marimo-cell-output>
<span class="markdown prose dark:prose-invert"><h1 id="hello-markdown">Hello, Markdown!</h1>
<span class="paragraph">This is a paragsraph.</span>
-<div class="codehilite"><pre><span></span><code><span class="n">mo</span><span class="o">.</span><span class="n">md</span><span class="p">(</span>
+<div class="language-python3 codehilite"><pre><span></span><code><span class="n">mo</span><span class="o">.</span><span class="n">md</span><span class="p">(</span>
<span class="w"> </span><span class="sd">&#39;&#39;&#39;</span>
<span class="sd"> # Hello, Markdown!</span>
<span class="sd"> This is a paragraph.</span>
diff --git a/tests/_output/test_md.py b/tests/_output/test_md.py
index a0a7e6aabb..21e9dcd7f9 100644
--- a/tests/_output/test_md.py
+++ b/tests/_output/test_md.py
@@ -32,7 +32,7 @@ def test_md() -> None:
def test_md_code_blocks() -> None:
# Test code block conversion
code_input = "```python\nprint('Hello, world!')\n```"
- expected_output = '<div class="codehilite"><pre><span></span><code><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Hello, world!&#39;</span><span class="p">)</span>\n</code></pre></div>' # noqa: E501
+ expected_output = '<div class="language-python codehilite"><pre><span></span><code><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Hello, world!&#39;</span><span class="p">)</span>\n</code></pre></div>' # noqa: E501
assert _md(code_input, apply_markdown_class=False).text == expected_output
@@ -115,6 +115,142 @@ def test_md_sane_lists() -> None:
assert _md(input_text, apply_markdown_class=False).text == expected_output
+def test_md_pycon_detection() -> None:
+ # Test basic pycon detection with >>> prompts
+ pycon_input = """```
+>>> print("Hello, world!")
+Hello, world!
+>>> x = 42
+>>> print(x)
+42
+```"""
+ result = _md(pycon_input, apply_markdown_class=False).text
+ assert "language-pycon" in result
+ assert "&gt;&gt;&gt;" in result # HTML-encoded >>>
+
+ # Test pycon detection with continuation prompts
+ pycon_continuation = """```
+>>> def hello():
+... print("Hello")
+... return True
+>>> hello()
+Hello
+True
+```"""
+ result = _md(pycon_continuation, apply_markdown_class=False).text
+ assert "language-pycon" in result
+ assert "&gt;&gt;&gt;" in result # HTML-encoded >>>
+
+ # Test mixed prompts
+ mixed_prompts = """```
+>>> import os
+>>> for i in range(2):
+... print(i)
+0
+1
+>>> print("done")
+done
+```"""
+ result = _md(mixed_prompts, apply_markdown_class=False).text
+ assert "language-pycon" in result
+
+ # Test that regular python code is not converted
+ regular_python = """```python
+def hello():
+ print("Hello")
+ return True
+
+hello()
+```"""
+ result = _md(regular_python, apply_markdown_class=False).text
+ assert "language-python" in result
+ assert "language-pycon" not in result
+
+ # Test that code without language is converted if it has pycon patterns
+ no_language_pycon = """```
+>>> 1 + 1
+2
+>>> "hello".upper()
+'HELLO'
+```"""
+ result = _md(no_language_pycon, apply_markdown_class=False).text
+ assert "language-pycon" in result
+
+ # Test that code without prompts is not converted
+ no_prompts = """```
+print("Hello")
+x = 42
+print(x)
+```"""
+ result = _md(no_prompts, apply_markdown_class=False).text
+ assert "language-pycon" not in result
+
+ # Test edge case: low ratio of prompts (should not convert)
+ low_ratio = """```
+>>> print("one line with prompt")
+line without prompt
+another line without prompt
+yet another line without prompt
+and another line without prompt
+```"""
+ result = _md(low_ratio, apply_markdown_class=False).text
+ # Should not be converted because prompt ratio is too low (1/5 = 20% < 30%)
+ assert "language-pycon" not in result
+
+ # Test edge case: high ratio of prompts (should convert)
+ high_ratio = """```
+>>> print("first")
+first
+>>> print("second")
+second
+>>> print("third")
+third
+some output
+```"""
+ result = _md(high_ratio, apply_markdown_class=False).text
+ # Should be converted because prompt ratio is high (3/7 = ~43% > 30%)
+ assert "language-pycon" in result
+
+ # Test empty code block
+ empty_block = """```
+```"""
+ result = _md(empty_block, apply_markdown_class=False).text
+ assert "language-pycon" not in result
+
+ # Test with specified language other than python (should not convert)
+ other_language = """```javascript
+>>> this is not python
+console.log("hello");
+```"""
+ result = _md(other_language, apply_markdown_class=False).text
+ assert "language-javascript" in result
+ assert "language-pycon" not in result
+
+ # Test with whitespace around prompts
+ whitespace_prompts = """```
+ >>> print("with spaces")
+ with spaces
+ >>> x = 1
+```"""
+ result = _md(whitespace_prompts, apply_markdown_class=False).text
+ assert "language-pycon" in result
+
+ # Test single line with prompt (should convert)
+ single_line = """```
+>>> print("single")
+```"""
+ result = _md(single_line, apply_markdown_class=False).text
+ assert "language-pycon" in result
+
+ # Test only continuation prompts (should convert)
+ only_continuation = """```
+... print("continuation")
+... print("more")
+```"""
+ result = _md(only_continuation, apply_markdown_class=False).text
+ assert "language-pycon" in result
+
+
def test_md_repr_markdown():
input_text = "This is **bold** and this is _italic_."
md = _md(input_text)
diff --git a/tests/_runtime/snapshots/docstrings_class.txt b/tests/_runtime/snapshots/docstrings_class.txt
index b3138a86aa..082b0f87bc 100644
--- a/tests/_runtime/snapshots/docstrings_class.txt
+++ b/tests/_runtime/snapshots/docstrings_class.txt
@@ -1,4 +1,4 @@
-<div class="codehilite"><pre><span></span><code><span class="k">class</span><span class="w"> </span><span class="nc">MyClass</span><span class="p">()</span>
+<div class="language-python3 codehilite"><pre><span></span><code><span class="k">class</span><span class="w"> </span><span class="nc">MyClass</span><span class="p">()</span>
</code></pre></div>
<span class="paragraph">Some docstring for the class.</span>
diff --git a/tests/_runtime/snapshots/docstrings_function.txt b/tests/_runtime/snapshots/docstrings_function.txt
index f7d462a2e8..ffa1b46725 100644
--- a/tests/_runtime/snapshots/docstrings_function.txt
+++ b/tests/_runtime/snapshots/docstrings_function.txt
@@ -1,4 +1,4 @@
-<div class="codehilite"><pre><span></span><code><span class="k">def</span><span class="w"> </span><span class="nf">my_func</span><span class="p">(</span><span class="n">arg1</span><span class="p">,</span> <span class="n">arg2</span><span class="p">)</span>
+<div class="language-python3 codehilite"><pre><span></span><code><span class="k">def</span><span class="w"> </span><span class="nf">my_func</span><span class="p">(</span><span class="n">arg1</span><span class="p">,</span> <span class="n">arg2</span><span class="p">)</span>
</code></pre></div>
<span class="paragraph">This is a simple docstring for a function.</span>
\ No newline at end of file
diff --git a/tests/_runtime/snapshots/docstrings_function_google.txt b/tests/_runtime/snapshots/docstrings_function_google.txt
index bde9313829..efc915a4c8 100644
--- a/tests/_runtime/snapshots/docstrings_function_google.txt
+++ b/tests/_runtime/snapshots/docstrings_function_google.txt
@@ -1,4 +1,4 @@
-<div class="codehilite"><pre><span></span><code><span class="k">def</span><span class="w"> </span><span class="nf">my_func</span><span class="p">(</span><span class="n">arg1</span><span class="p">,</span> <span class="n">arg2</span><span class="p">)</span>
+<div class="language-python3 codehilite"><pre><span></span><code><span class="k">def</span><span class="w"> </span><span class="nf">my_func</span><span class="p">(</span><span class="n">arg1</span><span class="p">,</span> <span class="n">arg2</span><span class="p">)</span>
</code></pre></div>
<h1 id="arguments">Arguments</h1>
diff --git a/tests/_runtime/test_complete.py b/tests/_runtime/test_complete.py
index e3ba55087a..f57eb39570 100644
--- a/tests/_runtime/test_complete.py
+++ b/tests/_runtime/test_complete.py
@@ -26,7 +26,7 @@ def test_build_docstring_function_no_init():
)
assert "my_func" in result
assert "This is a simple docstring for a function." in result
- assert '<div class="codehilite">' in result
+ assert '<div class="language-python3 codehilite">' in result
if DependencyManager.docstring_to_markdown.has():
snapshot("docstrings_function.txt", result)