Created
July 17, 2026 16:52
-
-
Save 0bx/038f206dfd054d2958bebe3731026f59 to your computer and use it in GitHub Desktop.
Rich theme
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 rich.markdown import Markdown, TextElement, MarkdownContext | |
| from rich.console import Console, ConsoleOptions, RenderResult | |
| from rich.theme import Theme | |
| from rich.text import Text | |
| from markdown_it.token import Token | |
| # See: https://rich.readthedocs.io/en/stable/appendix/colors.html | |
| custom_theme = Theme({ | |
| "markdown.h1": "bold underline", | |
| "markdown.h2": "bold", | |
| "markdown.h3": "underline", | |
| "markdown.block_quote": "yellow", | |
| "markdown.hr": "bright_black", | |
| "markdown.link": "cyan", | |
| "markdown.link_url": "green" | |
| }) | |
| class CustomHeading(TextElement): | |
| """A heading.""" | |
| @classmethod | |
| def create(cls, markdown: Markdown, token: Token): | |
| return cls(token.tag) | |
| def on_enter(self, context: MarkdownContext) -> None: | |
| self.text = Text() | |
| context.enter_style(self.style_name) | |
| def __init__(self, tag: str) -> None: | |
| self.tag = tag | |
| self.style_name = f"markdown.{tag}" | |
| super().__init__() | |
| def __rich_console__( | |
| self, console: Console, options: ConsoleOptions | |
| ) -> RenderResult: | |
| text = self.text | |
| text.justify = "left" | |
| yield text | |
| def test_print(): | |
| console = Console(theme=custom_theme) | |
| MD = """ | |
| # Test 1 | |
| * Li 1 | |
| * Li 2 | |
| ## Test 2 | |
| - Item 1 | |
| - Item 2 | |
| ### Heading 3 | |
| Some paragraph | |
| #### Heading 4 | |
| | Column 1 | Column 2 | | |
| | -------- | -------- | | |
| | Text | Text | | |
| ##### Heading 5 | |
| This is a [link](http://example.com) to example! | |
| ###### Heading 6 | |
| And here we put **bold**, *italic*, and ~strikethrough~ | |
| --- | |
| > Block quote | |
| ```bash | |
| # Comment | |
| sh | |
| ``` | |
| """ | |
| md = Markdown(MD) | |
| md.elements["heading_open"] = CustomHeading | |
| console.print(md) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment