Created
February 11, 2026 19:28
-
-
Save darenr/d05f0117b2abd85998499df28639f563 to your computer and use it in GitHub Desktop.
Add an emoji plugin to Mistune (Markdown parser)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from typing import Any | |
| import emoji | |
| import mistune | |
| def parse_inline_emoji(inline: mistune.InlineParser, m: Any, state: mistune.InlineState) -> int: | |
| """Parses an emoji token from the match.""" | |
| # The 'emoji_code' group is expected in the pattern | |
| code = m.group("emoji_code") | |
| state.append_token({"type": "emoji", "raw": code}) | |
| return m.end() | |
| def render_html_emoji(renderer: mistune.HTMLRenderer, text: str) -> str: | |
| """Renders the emoji code into its Unicode character.""" | |
| return emoji.emojize(f":{text}:", language="alias") | |
| def emojis_plugin(md: mistune.Markdown) -> None: | |
| """ | |
| Mistune plugin to parse and render emoji codes like :smile: or :rocket:. | |
| """ | |
| # Regex to match :emoji_code: | |
| pattern = r":(?P<emoji_code>[A-Za-z0-9+._’()_-]+):" | |
| md.inline.register("emoji", pattern, parse_inline_emoji, before="link") | |
| if md.renderer and md.renderer.NAME == "html": | |
| md.renderer.register("emoji", render_html_emoji) | |
| def main() -> None: | |
| """Main function to demonstrate the emoji plugin.""" | |
| markdown = mistune.create_markdown(plugins=[emojis_plugin]) | |
| text = "Here is a :smile: and a :rocket: example." | |
| html = markdown(text) | |
| print(f"Markdown: {text}") | |
| print(f"HTML: {html}") | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment