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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: support iconfify icons in markdown with ::lucide:rocket:: syntax (#2612)
Myles Scolnick043831c8c4f5
diff --git a/docs/api/markdown.md b/docs/api/markdown.mdindex ef451f52d7..dc128213df 100644--- a/docs/api/markdown.md+++ b/docs/api/markdown.md@@ -10,7 +10,11 @@ elements.## Icons-You can render icons from [Iconify](https://icon-sets.iconify.design/) with `mo.icon`.+We support rendering icons from [Iconify](https://icon-sets.iconify.design/).++When is inside markdown, you can render an icon with the syntax `::iconset:icon-name::` for example `::lucide:rocket::` or `::mdi:home::`. This is useful for quickly adding an icon, however, it does not support advanced configuration such as size, color, and rotation.++For other advanced features, use `mo.icon()` such as `mo.icon("lucide:rocket", size=20)` or `mo.icon("mdi:home", color="blue")`.```{eval-rst}.. autofunction:: marimo.icondiff --git a/frontend/src/core/codemirror/language/markdown.ts b/frontend/src/core/codemirror/language/markdown.tsindex 4b269b190d..22a9d10a2c 100644--- a/frontend/src/core/codemirror/language/markdown.ts+++ b/frontend/src/core/codemirror/language/markdown.ts@@ -193,7 +193,7 @@ export class MarkdownLanguageAdapter implements LanguageAdapter {enhancedMarkdownExtension(hotkeys),autocompletion({activateOnTyping: true,- override: [emojiCompletionSource],+ override: [emojiCompletionSource, lucideIconCompletionSource],}),// Markdown autorunmarkdownAutoRunExtension(movementCallbacks),@@ -245,3 +245,58 @@ const getEmojiList = once(async (): Promise<Completion[]> => {type: "emoji",}));});++const lucideIconCompletionSource: CompletionSource = async (context) => {+ // Check if the cursor is at a position where a Lucide icon can be inserted+ if (!context.explicit && !context.matchBefore(/::[\w-]*$/)) {+ return null;+ }++ const iconList = await getLucideIconList();+ const filter = context.matchBefore(/::[\w-]*$/)?.text.slice(2) ?? "";++ return {+ from: context.pos - filter.length - 2,+ options: iconList,+ validFor: /^[\w-:]*$/,+ };+};++// This loads Lucide icons from a CDN+const getLucideIconList = once(async (): Promise<Completion[]> => {+ const iconList = await fetch(+ "https://unpkg.com/[email protected]/tags.json",+ )+ .then((res) => {+ if (!res.ok) {+ throw new Error("Failed to fetch Lucide icon list");+ }+ return res.json() as unknown as Record<string, string[]>;+ })+ .catch(() => {+ // If we can't fetch the icon list, just return an empty list+ return {};+ });++ const asSvg = (iconName: string) => {+ return `https://cdn.jsdelivr.net/npm/[email protected]/icons/${iconName}.svg`;+ };++ return Object.entries(iconList).map(+ ([iconName, aliases]): Completion => ({+ label: `::${iconName}`,+ displayLabel: iconName,+ type: "lucide-icon",+ boost: 10,+ apply: `::lucide:${iconName}::`,+ detail: aliases.join(", "),+ info: () => {+ const img = document.createElement("img");+ img.src = asSvg(iconName);+ img.style.width = "24px";+ img.style.height = "24px";+ return img;+ },+ }),+ );+});diff --git a/marimo/_output/md.py b/marimo/_output/md.pyindex f51fa4b29d..a326b6f599 100644--- a/marimo/_output/md.py+++ b/marimo/_output/md.py@@ -8,6 +8,7 @@ import markdown # type: ignorefrom marimo._output.hypertext import Htmlfrom marimo._output.md_extensions.external_links import ExternalLinksExtension+from marimo._output.md_extensions.iconify import IconifyExtensionfrom marimo._output.rich_help import mddocextension_configs = {@@ -66,6 +67,8 @@ def _md("admonition",# LinksExternalLinksExtension(),+ # Iconify+ IconifyExtension(),],extension_configs=extension_configs, # type: ignore[arg-type]).strip()diff --git a/marimo/_output/md_extensions/iconify.py b/marimo/_output/md_extensions/iconify.pynew file mode 100644index 0000000000..326f527e97--- /dev/null+++ b/marimo/_output/md_extensions/iconify.py@@ -0,0 +1,41 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from typing import TYPE_CHECKING+from xml.etree.ElementTree import Element++from markdown import Extension, Markdown, inlinepatterns++if TYPE_CHECKING:+ import re+++class IconifyPattern(inlinepatterns.InlineProcessor):+ """+ Converts ::icon-set:icon-name:: to an iconify-icon element.+ """++ def __init__(self, pattern: str, md: Markdown) -> None:+ super().__init__(pattern, md)++ def handleMatch( # type: ignore+ self, m: re.Match[str], data: str+ ) -> tuple[Element, int, int]:+ del data+ icon_name = m.group(1)+ return (+ Element("iconify-icon", {"icon": icon_name, "inline": ""}),+ m.start(0),+ m.end(0),+ )+++class IconifyExtension(Extension):+ def extendMarkdown(self, md: Markdown) -> None:+ # Add IconifyPattern with high priority (200) to+ # handle it before other inline patterns+ md.inlinePatterns.register(+ IconifyPattern(r"::([a-zA-Z0-9-]+:[a-zA-Z0-9-]+)::", md),+ "iconify",+ 200,+ )diff --git a/marimo/_smoke_tests/icons.py b/marimo/_smoke_tests/icons.pyindex 7bb1a6737b..9e32a25e72 100644--- a/marimo/_smoke_tests/icons.py+++ b/marimo/_smoke_tests/icons.py@@ -5,33 +5,26 @@# ]# ///# Copyright 2024 Marimo. All rights reserved.+import marimo-__generated_with = "0.1.79"+__generated_with = "0.9.7"app = marimo.App()@app.celldef __():import marimo as mo- return mo,+ return (mo,)@app.celldef __(mo):- mo.hstack(- [- mo.md("Icon sets"),- mo.icon("lucide:leaf", size=20),- mo.icon("material-symbols:rocket-launch", size=20),- mo.icon("ic:twotone-rocket-launch", size=20),- ],- justify="start",- )+ mo.md(r"""::lucide:alarm-clock::""")return[email protected](hide_code=True)def __(mo):mo.hstack([@@ -85,12 +78,11 @@ def __(mo):mo.ui.button(label=f"{mo.icon('material-symbols:rocket-launch')} Launch"),- mo.ui.button(- label=f"Clear {mo.icon('material-symbols:close-rounded')}"- ),+ mo.ui.button(label=f"::material-symbols:rocket-launch:: Launch"),+ mo.ui.button(label=f"Clear ::material-symbols:close-rounded::"),# Left and rightmo.ui.button(- label=f"{mo.icon('material-symbols:download')} Download {mo.icon('material-symbols:csv')}"+ label=f"::material-symbols:download:: Download ::material-symbols:csv::"),],justify="start",diff --git a/tests/_output/test_md.py b/tests/_output/test_md.pyindex 9fe4c1a953..a9071c62fc 100644--- a/tests/_output/test_md.py+++ b/tests/_output/test_md.py@@ -57,3 +57,25 @@ def test_md_footnotes() -> None:assert _md(footnote_input, apply_markdown_class=False).text == (expected_output)+++def test_md_iconify() -> None:+ # Test iconify conversion+ iconify_input = "This is an icon: ::lucide:user::"+ expected_output = '<span class="paragraph">This is an icon: <iconify-icon icon="lucide:user" inline=""></iconify-icon></span>' # noqa: E501+ assert (+ _md(iconify_input, apply_markdown_class=False).text == expected_output+ )++ # Test multiple icons+ multiple_icons_input = "Icons: ::mdi:home:: ::fa:car:: ::lucide:settings::"+ expected_output = '<span class="paragraph">Icons: <iconify-icon icon="mdi:home" inline=""></iconify-icon> <iconify-icon icon="fa:car" inline=""></iconify-icon> <iconify-icon icon="lucide:settings" inline=""></iconify-icon></span>' ## noqa: E501+ assert (+ _md(multiple_icons_input, apply_markdown_class=False).text+ == expected_output+ )++ # Test icon within other markdown elements+ mixed_input = "# Header with ::lucide:star:: icon\n\n**Bold text with ::mdi:alert:: icon**" # noqa: E501+ expected_output = '<h1 id="header-with-icon">Header with <iconify-icon icon="lucide:star" inline=""></iconify-icon> icon</h1>\n<span class="paragraph"><strong>Bold text with <iconify-icon icon="mdi:alert" inline=""></iconify-icon> icon</strong></span>' # noqa: E501+ assert _md(mixed_input, apply_markdown_class=False).text == expected_output