### Upgrade Guide: Plugins and Directives Source: https://mistune.lepture.com/en/latest/upgrade Information regarding Mistune plugins and directives during the v2 to v3 upgrade. ```APIDOC ## Upgrade Guide: Plugins and Directives ### Description Guidance on Mistune plugins and directives for the v2 to v3 upgrade. For plugins, refer to the advanced guide and built-in source code. For directives, v3 introduces a new fenced style. ### Method N/A (Documentation of changes, not an API endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response #### Success Response (N/A) N/A #### Response Example N/A ``` -------------------------------- ### Upgrade Guide: AstRenderer Changes Source: https://mistune.lepture.com/en/latest/upgrade Explains the removal of `AstRenderer` in Mistune v3 and how to achieve AST rendering. ```APIDOC ## Upgrade Guide: AstRenderer Changes ### Description In Mistune v3, the explicit `AstRenderer` class has been removed. AST rendering can now be achieved by passing `None` or `'ast'` to the `create_markdown` function. ### Method N/A (Documentation of changes, not an API endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example ```python import mistune # To render AST in v3 md = mistune.create_markdown(renderer='ast') # or renderer=None markdown_text = '...markdown text...' markdown_output = md(markdown_text) ``` ### Response #### Success Response (N/A) N/A #### Response Example N/A ``` -------------------------------- ### Enable Math Plugin in Mistune Source: https://mistune.lepture.com/en/latest/plugins Illustrates how to enable the 'math' plugin for handling block and inline math syntax using
and tags respectively. The plugin is off by default. Examples show enabling it via create_markdown and a custom Markdown setup. ```python markdown = mistune.create_markdown(plugins=['math']) ``` ```python from mistune.plugins.math import math renderer = mistune.HTMLRenderer() markdown = mistune.Markdown(renderer, plugins=[math]) ``` -------------------------------- ### Upgrade Guide: Plugin Parameter Changes Source: https://mistune.lepture.com/en/latest/upgrade Details the parameter changes in specific Mistune plugins when upgrading from v2 to v3. ```APIDOC ## Upgrade Guide: Plugin Parameter Changes ### Description This section outlines the parameter signature changes for specific Mistune plugins when upgrading from v2 to v3. ### Method N/A (Documentation of changes, not an API endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response #### Success Response (N/A) N/A #### Response Example ```diff - abbr(self, key, definition) + abbr(self, text: str, title: str) - task_list_item(self, text: str, level: int, checked: bool) + task_list_item(self, text: str, checked: bool) ``` ``` -------------------------------- ### Upgrade Guide: HTMLRenderer Changes Source: https://mistune.lepture.com/en/latest/upgrade Details the parameter changes in `HTMLRenderer` methods when upgrading from Mistune v2 to v3. ```APIDOC ## Upgrade Guide: HTMLRenderer Changes ### Description This section details the modifications to the `HTMLRenderer` methods between Mistune v2 and v3, focusing on parameter changes. ### Method N/A (Documentation of changes, not an API endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response #### Success Response (N/A) N/A #### Response Example ```diff - link(self, link, text=None, title=None) + link(self, text, url, title=None) - image(self, src, alt="", title=None) + image(self, text, url, title=None) - heading(self, text, level) + heading(self, text, level, **attrs) - list(self, text, ordered, level, start=None) + list(self, text, ordered, **attrs) - list_item(self, text, level) + list_item(self, text) - table_cell(self, text, align=None, is_head=False) + table_cell(self, text, align=None, head=False) ``` ``` -------------------------------- ### Parsing Setext-Style Headings in Python Source: https://mistune.lepture.com/en/latest/api This example illustrates the Markdown syntax for setext-style headings. It shows how a first-level heading (H1) is created by placing text on one line, followed by a line of multiple equals signs (`=`). ```python H1 title ======== ``` -------------------------------- ### Parsing Fenced Code Blocks in Python Source: https://mistune.lepture.com/en/latest/api This example showcases the syntax for fenced code blocks, which are delimited by three or more backticks (`) or tildes (~). It includes an example of a Python code block within the fenced delimiters. ```python ```python def markdown(text): return mistune.html(text) ``` ``` -------------------------------- ### Define HTML Renderers for Mistune Plugins (Python) Source: https://mistune.lepture.com/en/latest/advanced This Python code provides examples of renderer functions for Mistune plugins, specifically for horizontal rules ('hr') and math expressions ('block_math', 'inline_math'). These functions are used to convert parsed Markdown tokens into HTML, demonstrating how to handle tokens with different structures (type only, type and raw/text, type and attrs). ```python def render_hr(renderer): # token with only type, like: # {'type': 'hr'} return '
' def render_math(renderer, text): # token with type and (text or raw), e.g.: # {'type': 'block_math', 'raw': 'a^b'} return '
$$' + text + '$$
' def render_link(renderer, text, **attrs): # token with type, text or raw, and attrs href = attrs['href'] return f'{text}' ``` -------------------------------- ### AstRenderer Creation (Python) Source: https://mistune.lepture.com/en/latest/upgrade Demonstrates how to create a Markdown instance with an AST renderer in Mistune v3. In v3, AstRenderer is no longer a distinct class; instead, `None` or `'ast'` can be passed to `create_markdown`. ```python import mistune md = mistune.create_markdown(renderer='ast') # or render=None md('...markdown text...') ``` -------------------------------- ### Enable Insert Plugin in Mistune Source: https://mistune.lepture.com/en/latest/plugins Shows how to enable the 'insert' plugin for adding tags. The plugin is not active by default. Code examples include using create_markdown with plugins and setting up a custom Markdown instance with the insert plugin. ```python markdown = mistune.create_markdown(plugins=['insert']) ``` ```python from mistune.plugins.formatting import insert renderer = mistune.HTMLRenderer() markdown = mistune.Markdown(renderer, plugins=[insert]) ``` -------------------------------- ### Enable Footnotes Plugin in Mistune Source: https://mistune.lepture.com/en/latest/plugins Illustrates how to enable the footnotes plugin in Mistune, which is included by default in `mistune.html()`. Provides two Python code examples for creating a Markdown instance with this plugin. ```python markdown = mistune.create_markdown(plugins=['footnotes']) ``` ```python from mistune.plugins.footnotes import footnotes renderer = mistune.HTMLRenderer() markdown = mistune.Markdown(renderer, plugins=[footnotes]) ``` -------------------------------- ### Enable Superscript Plugin in Mistune Source: https://mistune.lepture.com/en/latest/plugins Explains how to enable the 'superscript' plugin to generate tags. This plugin is not enabled by default. Examples cover using create_markdown and manually configuring a Markdown instance with the superscript plugin. ```python markdown = mistune.create_markdown(plugins=['superscript']) ``` ```python from mistune.plugins.formatting import superscript renderer = mistune.HTMLRenderer() markdown = mistune.Markdown(renderer, plugins=[superscript]) ``` -------------------------------- ### Storing Reference Link Data in Python Source: https://mistune.lepture.com/en/latest/api This example shows how the `parse_ref_link` method stores parsed reference link information within the `state.env` dictionary. It details the structure of the stored data, including the URL and optional title for a given reference name. ```python state.env['ref_links']['example'] = { 'url': 'https://example.com', 'title': "Optional title", } ``` -------------------------------- ### Parsing Block Quotes in Python Source: https://mistune.lepture.com/en/latest/api This code illustrates the expected syntax for a block quote in Markdown. It shows how text intended as a block quote should be formatted, typically starting each line with a right arrow (`>`). ```python > a block quote starts > with right arrows ``` -------------------------------- ### Enable Admonitions Directive in Python Source: https://mistune.lepture.com/en/latest/directives This Python code demonstrates how to enable the Admonition directive within Mistune. It shows the setup for both reStructuredText (RST) style and fenced style directives, allowing for different visual cues like 'warning' boxes in the rendered output. Proper initialization of the directive within `create_markdown` is crucial for its functionality. ```python import mistune from mistune.directives import Admonition, RSTDirective, FencedDirective markdown = mistune.create_markdown( plugins=[ ... RSTDirective([Admonition()]), # FencedDirective([Admonition()]), ] ) ``` -------------------------------- ### HTMLRenderer Method Signature Changes (Python) Source: https://mistune.lepture.com/en/latest/upgrade This snippet highlights the parameter changes in several methods of Mistune's HTMLRenderer when upgrading from v2 to v3. These changes are crucial for custom renderer implementations. ```python - link(self, link, text=None, title=None) + link(self, text, url, title=None) - image(self, src, alt="", title=None) + image(self, text, url, title=None) - heading(self, text, level) + heading(self, text, level, **attrs) - list(self, text, ordered, level, start=None) + list(self, text, ordered, **attrs) - list_item(self, text, level) + list_item(self, text) - table_cell(self, text, align=None, is_head=False) + table_cell(self, text, align=None, head=False) ``` -------------------------------- ### Plugin Signature Changes (Python) Source: https://mistune.lepture.com/en/latest/upgrade This section details the updated method signatures for Mistune plugins when upgrading from v2 to v3. Developers need to adjust their custom plugin code to match these new signatures. ```python - abbr(self, key, definition) + abbr(self, text: str, title: str) - task_list_item(self, text: str, level: int, checked: bool) + task_list_item(self, text: str, checked: bool) ``` -------------------------------- ### Register Block and Inline Math Plugins in Mistune (Python) Source: https://mistune.lepture.com/en/latest/advanced This Python code snippet demonstrates how to register custom block-level and inline-level math plugins with a Mistune Markdown instance. It includes registering patterns and parsing functions, and conditionally registering HTML renderers if the instance uses an HTML renderer. ```python def math(md): md.block.register('block_math', BLOCK_MATH_PATTERN, parse_block_math, before='list') md.inline.register('inline_math', INLINE_MATH_PATTERN, parse_inline_math, before='link') if md.renderer and md.renderer.NAME == 'html': md.renderer.register('block_math', render_block_math) md.renderer.register('inline_math', render_inline_math) ``` -------------------------------- ### Enable Task Lists Plugin in Mistune Source: https://mistune.lepture.com/en/latest/plugins Details how to enable the task_lists plugin in Mistune for GitHub-style to-do items. This plugin is not enabled by default in `mistune.html()`. Two Python examples demonstrate its integration. ```python markdown = mistune.create_markdown(plugins=['task_lists']) ``` ```python from mistune.plugins.task_lists import task_lists renderer = mistune.HTMLRenderer() markdown = mistune.Markdown(renderer, plugins=[task_lists]) ``` -------------------------------- ### Define Inline-Level Math Pattern for Mistune (Python) Source: https://mistune.lepture.com/en/latest/advanced This Python code defines a regular expression pattern for identifying inline math syntax in Markdown using Mistune. The pattern looks for text enclosed in single dollar signs ('$'), ensuring the content is not whitespace and capturing it within a named group. ```python INLINE_MATH_PATTERN = r'\$(?!\s)(?P.+?)(?!\s)\$' # regex represents: INLINE_MATH_PATTERN = ( r'\$' r'(?!\s)' r'(?P.+?)' r'(?!\s)' r'\$' ) ``` -------------------------------- ### Parse Inline-Level Math Token in Mistune (Python) Source: https://mistune.lepture.com/en/latest/advanced This Python function parses an inline-level math match captured by a regular expression in Mistune. It extracts the math text and appends a token of type 'inline_math' to the state, including the raw math content. It returns the end position of the parsed text. ```python def parse_inline_math(inline, m, state): text = m.group('math_text') # use ``state.append_token`` to save parsed inline math token state.append_token({'type': 'inline_math', 'raw': text}) # return the end position of parsed text return m.end() ``` -------------------------------- ### Define Block-Level Math Pattern for Mistune (Python) Source: https://mistune.lepture.com/en/latest/advanced This Python code defines a regular expression pattern for identifying block-level math syntax in Markdown using Mistune. The pattern specifically looks for lines enclosed in double dollar signs ('$$'), allowing for optional leading spaces and capturing the math content within a named group. ```python BLOCK_MATH_PATTERN = r'^ {0,3}\$\$[ \t]*\n(?P.+?)\n\$\$[ \t]*$' # regex represents: BLOCK_MATH_PATTERN = ( r'^ {0,3}' # line can startswith 0~3 spaces just like other block elements defined in commonmark r'\$\$' # followed by $$ r'[ \t]*\n' # this line can contain extra spaces and tabs r'(?P.+?)' # this is the math content, MUST use named group r'\n\$\$[ \t]*$') # endswith $$ + extra spaces and tabs # if you want to make the math pattern more strictly, it could be like: BLOCK_MATH_PATTERN = r'^\$\$\n(?P.+?)\n\$\$$' ``` -------------------------------- ### Parse Block-Level Math Token in Mistune (Python) Source: https://mistune.lepture.com/en/latest/advanced This Python function is designed to parse a block-level math match captured by a regular expression in Mistune. It extracts the math text from the match object and appends a token of type 'block_math' to the state, including the raw math content. It returns the end position of the parsed text. ```python def parse_block_math(block, m, state): text = m.group('math_text') # use ``state.append_token`` to save parsed block math token state.append_token({'type': 'block_math', 'raw': text}) # return the end position of parsed text # since python doesn't count ``$``, we have to +1 # if the pattern is not ended with ``, we can't +1 return m.end() + 1 ``` -------------------------------- ### Create a basic Mistune Markdown instance Source: https://mistune.lepture.com/en/latest/guide Creates a default Markdown instance using `mistune.create_markdown()`. This instance escapes HTML by default and has no plugins enabled. ```python import mistune markdown = mistune.create_markdown() ``` -------------------------------- ### Customizing HTMLRenderer Source: https://mistune.lepture.com/en/latest/renderers Demonstrates how to create a custom HTML renderer by subclassing `mistune.HTMLRenderer` to add support for custom syntax, such as inline math. ```APIDOC ## Customize HTMLRenderer ### Description Extend `mistune.HTMLRenderer` to add custom syntax support. This example shows how to add inline math rendering. ### Method ```python from mistune import HTMLRenderer from mistune.escape import escape class MyRenderer(HTMLRenderer): def codespan(self, text): if text.startswith('$') and text.endswith('$'): return '' + escape(text) + '' return '' + escape(text) + '' # Usage: markdown = mistune.create_markdown(renderer=MyRenderer()) print(markdown('hi `$a^2=4$`')) ``` ### Available Methods for HTMLRenderer This lists the methods available on `HTMLRenderer` and its plugins: * **Inline Level:** `text`, `link`, `image`, `emphasis`, `strong`, `codespan`, `linebreak`, `softbreak`, `inline_html` * **Block Level:** `paragraph`, `heading`, `blank_line`, `thematic_break`, `block_text`, `block_code`, `block_quote`, `block_html`, `block_error`, `list`, `list_item` * **Plugin Provided:** `strikethrough`, `mark`, `insert`, `subscript`, `abbr`, `ruby`, `task_list_item`, `table`, `table_head`, `table_body`, `table_row`, `table_cell`, `footnote_ref`, `footnotes`, `footnote_item`, `def_list`, `def_list_head`, `def_list_item`, `block_math`, `inline_math` ``` -------------------------------- ### Mistune CLI Help Source: https://mistune.lepture.com/en/latest/cli Displays the help message for the Mistune command-line tool, outlining available options and their purposes. This includes options for specifying input message or file, plugins, escape, hardwrap, output file, and renderer. ```bash $ python -m mistune -h ``` -------------------------------- ### Parsing Reference-Style Links in Python Source: https://mistune.lepture.com/en/latest/api This snippet demonstrates the Markdown syntax for reference-style links. It shows how to define a link text and its corresponding reference, followed by the definition of the reference with its URL and an optional title. ```python a [link][example] [example]: https://example.com "Optional title" ``` -------------------------------- ### Generate Abstract Syntax Tree (AST) with Mistune Source: https://mistune.lepture.com/en/latest/guide Creates a Markdown instance configured to generate an Abstract Syntax Tree (AST) instead of HTML. This is achieved by setting `renderer=None` or `renderer='ast'`. ```python import mistune markdown = mistune.create_markdown(renderer=None) text = 'hello **world**' print(markdown(text)) ``` ```python import mistune markdown = mistune.create_markdown(renderer='ast') ``` -------------------------------- ### Definition Lists Plugin Source: https://mistune.lepture.com/en/latest/plugins The def_list plugin enables the creation of HTML definition lists using the `term : definition` syntax. This plugin is NOT enabled by default in `mistune.html()`. ```APIDOC ## Definition Lists Plugin ### Description Enables HTML definition lists. ### Usage **NOT ENABLED** by default in `mistune.html()`. To enable the def_list plugin with your own markdown instance: ```python import mistune # Using create_markdown markdown = mistune.create_markdown(plugins=['def_list']) # Using Markdown constructor with explicit plugin from mistune.plugins.def_list import def_list renderer = mistune.HTMLRenderer() markdown = mistune.Markdown(renderer, plugins=[def_list]) ``` ``` -------------------------------- ### Enable Definition Lists Plugin in Mistune Source: https://mistune.lepture.com/en/latest/plugins Describes how to enable the def_list plugin in Mistune for creating HTML definition lists. This functionality is not enabled by default in `mistune.html()`. Two Python code snippets show how to set it up. ```python markdown = mistune.create_markdown(plugins=['def_list']) ``` ```python from mistune.plugins.def_list import def_list renderer = mistune.HTMLRenderer() markdown = mistune.Markdown(renderer, plugins=[def_list]) ``` -------------------------------- ### Unix PIPE Markdown Conversion Source: https://mistune.lepture.com/en/latest/cli Demonstrates using the Mistune command-line tool with Unix pipes. Standard input from 'echo' is piped to mistune for conversion to HTML. ```bash echo "foo **bar**" | python -m mistune ``` -------------------------------- ### Enable Table Plugin in Mistune Source: https://mistune.lepture.com/en/latest/plugins Shows how to enable the table plugin in Mistune, which is active by default in `mistune.html()`. Includes two Python snippets for initializing a Markdown object with table support. ```python markdown = mistune.create_markdown(plugins=['table']) ``` ```python from mistune.plugins.table import table renderer = mistune.HTMLRenderer() markdown = mistune.Markdown(renderer, plugins=[table]) ``` -------------------------------- ### Customize Mistune renderer for syntax highlighting Source: https://mistune.lepture.com/en/latest/guide Implements a custom renderer `HighlightRenderer` that extends `mistune.HTMLRenderer`. It overrides the `block_code` method to use Pygments for syntax highlighting of code blocks. ```python import mistune from pygments import highlight from pygments.lexers import get_lexer_by_name from pygments.formatters import html class HighlightRenderer(mistune.HTMLRenderer): def block_code(self, code, info=None): if info: lexer = get_lexer_by_name(info, stripall=True) formatter = html.HtmlFormatter() return highlight(code, lexer, formatter) return '
' + mistune.escape(code) + '
' markdown = mistune.create_markdown(renderer=HighlightRenderer()) print(markdown('```python\nassert 1 == 1\n```')) ``` -------------------------------- ### Markdown Renderer Source: https://mistune.lepture.com/en/latest/renderers Explains how to use the `MarkdownRenderer` to reformat Markdown text and how to customize it for plugins. ```APIDOC ## Markdown Renderer ### Description The `MarkdownRenderer` is used to reformat Markdown text. The basic `MarkdownRenderer` only supports standard Markdown syntax. For plugins, you need to customize it. ### Basic Usage ```python from mistune.renderers.markdown import MarkdownRenderer format_markdown = mistune.create_markdown(renderer=MarkdownRenderer()) print(format_markdown('your_markdown_text')) ``` ### Customizing with Plugins To add support for plugins like strikethrough, subclass `MarkdownRenderer` and implement the corresponding methods. ```python from mistune.renderers.markdown import MarkdownRenderer class MyRenderer(MarkdownRenderer): def strikethrough(self, token, state): return '~~' + self.render_children(token, state) + '~~ # Usage with strikethrough plugin format_markdown = mistune.create_markdown(renderer=MyRenderer(), plugins=['strikethrough']) print(format_markdown('~~This is strikethrough~~')) ``` ### Default Methods for MarkdownRenderer * **Inline Level:** `text`, `link`, `image`, `emphasis`, `strong`, `codespan`, `linebreak`, `softbreak`, `inline_html` * **Block Level:** `paragraph`, `heading`, `blank_line`, `thematic_break`, `block_text`, `block_code`, `block_quote`, `block_html`, `block_error`, `list` ``` -------------------------------- ### Enable Mark Plugin in Mistune Source: https://mistune.lepture.com/en/latest/plugins Demonstrates how to enable the 'mark' plugin for inserting tags. This plugin is not enabled by default. Two methods are shown: using create_markdown with a plugin list, and creating a custom Markdown instance with an HTMLRenderer and the mark plugin. ```python markdown = mistune.create_markdown(plugins=['mark']) ``` ```python from mistune.plugins.formatting import mark renderer = mistune.HTMLRenderer() markdown = mistune.Markdown(renderer, plugins=[mark]) ``` -------------------------------- ### Convert Markdown to HTML via File Source: https://mistune.lepture.com/en/latest/cli Converts a markdown file (e.g., README.md) to HTML using the Mistune command-line tool. This is the default conversion behavior. ```bash $ python -m mistune -f README.md ``` -------------------------------- ### Add strikethrough plugin to Mistune Source: https://mistune.lepture.com/en/latest/guide Creates a Markdown instance with the 'strikethrough' plugin enabled. This allows the use of `~~text~~` for strikethrough formatting. ```python import mistune markdown = mistune.create_markdown(plugins=['strikethrough']) markdown('~~s~~') ``` -------------------------------- ### Mistune Math Plugin Source: https://mistune.lepture.com/en/latest/api Provides support for mathematical notation using LaTeX-like syntax, with block math delimited by `$$` and inline math by `$`. This plugin requires a Markdown instance. Variants exist for use within quotes and lists. ```python import mistune markdown = mistune.create_markdown(plugins=['math']) text = "Block math is surrounded by $$:\n\n$$ f(a)=f(b) $$ \n\nInline math is surrounded by `$`, such as $f(a)=f(b)$" html = markdown(text) print(html) ``` -------------------------------- ### Customize HTMLRenderer for Inline Math in Mistune Source: https://mistune.lepture.com/en/latest/renderers Demonstrates how to create a custom HTMLRenderer in Mistune to handle inline math syntax, extending the default behavior for specific patterns like '$a^2=4$'. It shows subclassing HTMLRenderer and overriding the 'codespan' method. ```python from mistune import HTMLRenderer import mistune from mistune.util import escape class MyRenderer(HTMLRenderer): def codespan(self, text): if text.startswith('$') and text.endswith('$'): return '' + escape(text) + '' return '' + escape(text) + '' # use customized renderer markdown = mistune.create_markdown(renderer=MyRenderer()) print(markdown('hi `$a^2=4$`')) ``` -------------------------------- ### Table Plugin Source: https://mistune.lepture.com/en/latest/plugins The table plugin enables the creation of markdown tables using pipe-delimited syntax. It is enabled by default in `mistune.html()`. ```APIDOC ## Table Plugin ### Description Enables markdown table syntax. ### Usage Enabled by default in `mistune.html()`. To create a markdown instance with the table plugin: ```python import mistune # Using create_markdown markdown = mistune.create_markdown(plugins=['table']) # Using Markdown constructor with explicit plugin from mistune.plugins.table import table renderer = mistune.HTMLRenderer() markdown = mistune.Markdown(renderer, plugins=[table]) ``` ``` -------------------------------- ### Enable Strikethrough Plugin in Mistune Source: https://mistune.lepture.com/en/latest/plugins Demonstrates how to enable the strikethrough plugin in Mistune, which is enabled by default in `mistune.html()`. Shows two methods for creating a custom Markdown instance with the plugin. ```python markdown = mistune.create_markdown(plugins=['strikethrough']) ``` ```python from mistune.plugins.formatting import strikethrough renderer = mistune.HTMLRenderer() markdown = mistune.Markdown(renderer, plugins=[strikethrough]) ``` -------------------------------- ### Enable Spoiler Plugin with create_markdown Source: https://mistune.lepture.com/en/latest/plugins Shows how to enable the spoiler plugin when creating a markdown instance using the `mistune.create_markdown` function by passing 'spoiler' in the plugins list. ```python markdown = mistune.create_markdown(plugins=['spoiler']) ``` -------------------------------- ### Enable Spoiler Plugin with HTMLRenderer Source: https://mistune.lepture.com/en/latest/plugins Demonstrates an alternative method to enable the spoiler plugin by explicitly importing the plugin and passing it to the `mistune.Markdown` constructor along with an `HTMLRenderer`. ```python from mistune.plugins.spoiler import spoiler renderer = mistune.HTMLRenderer() markdown = mistune.Markdown(renderer, plugins=[spoiler]) ``` -------------------------------- ### Block Spoiler Syntax and Conversion Source: https://mistune.lepture.com/en/latest/plugins Demonstrates the syntax for a block-level spoiler using the '>!' marker and its corresponding HTML conversion into a `
` element. ```markdown >! here is the spoiler content >! >! it will be hidden ``` ```html

here is the spoiler content

it will be hidden

``` -------------------------------- ### Customize MarkdownRenderer with Plugins in Mistune Source: https://mistune.lepture.com/en/latest/renderers Explains how to extend Mistune's MarkdownRenderer to support additional Markdown features, such as strikethrough, by creating a subclass and overriding specific renderer methods. It also shows how to enable plugins during markdown creation. ```python from mistune.renderers.markdown import MarkdownRenderer import mistune class MyRenderer(MarkdownRenderer): def strikethrough(self, token, state): return '~~' + self.render_children(token, state) + '~~' format_markdown = mistune.create_markdown(renderer=MarkdownRenderer(), plugins=['strikethrough']) format_markdown('your_markdown_text') ``` -------------------------------- ### Markdown Conversion with HTMLRenderer in Python Source: https://mistune.lepture.com/en/latest/api This snippet demonstrates how to instantiate the Markdown class with an HTMLRenderer to convert Markdown text into HTML. The HTMLRenderer is configured with `escape=False` to prevent HTML escaping. The method takes Markdown text as input and returns its HTML representation. ```python from mistune import HTMLRenderer md = Markdown(renderer=HTMLRenderer(escape=False)) md('hello **world**') ``` -------------------------------- ### Mistune Definition Lists Plugin Source: https://mistune.lepture.com/en/latest/api Adds support for definition lists in markdown, similar to HTML's `
`, `
`, and `
` tags. It parses terms and their corresponding definitions. This plugin requires a Markdown instance. ```python import mistune markdown = mistune.create_markdown(plugins=['def_list']) text = "Apple\n: Pomaceous fruit of plants of the genus Malus in\n the family Rosaceae.\n\nOrange\n: The fruit of an evergreen tree of the genus Citrus." html = markdown(text) print(html) ``` -------------------------------- ### Footnotes Plugin Source: https://mistune.lepture.com/en/latest/plugins The footnotes plugin allows for the creation of footnotes using `[^1]` and `[^1]: explanation` syntax. It is enabled by default in `mistune.html()`. ```APIDOC ## Footnotes Plugin ### Description Enables footnote syntax `[^1]` and `[^1]: explanation`. ### Usage Enabled by default in `mistune.html()`. To create a markdown instance with the footnotes plugin: ```python import mistune # Using create_markdown markdown = mistune.create_markdown(plugins=['footnotes']) # Using Markdown constructor with explicit plugin from mistune.plugins.footnotes import footnotes renderer = mistune.HTMLRenderer() markdown = mistune.Markdown(renderer, plugins=[footnotes]) ``` ``` -------------------------------- ### Abbreviations Plugin Source: https://mistune.lepture.com/en/latest/plugins The abbr plugin enables the creation of abbreviations using `*[ABBR]: Full Text` syntax. This plugin is NOT enabled by default in `mistune.html()`. ```APIDOC ## Abbreviations Plugin ### Description Enables abbreviation syntax `*[ABBR]: Full Text`. ### Usage **NOT ENABLED** by default in `mistune.html()`. To enable the abbr plugin with your own markdown instance: ```python import mistune # Using create_markdown markdown = mistune.create_markdown(plugins=['abbr']) # Using Markdown constructor with explicit plugin from mistune.plugins.abbr import abbr renderer = mistune.HTMLRenderer() markdown = mistune.Markdown(renderer, plugins=[abbr]) ``` ``` -------------------------------- ### Enable URL Plugin in Mistune Source: https://mistune.lepture.com/en/latest/plugins Explains how to activate the URL plugin in Mistune for creating links from raw URLs. This plugin is not enabled by default in `mistune.html()`. Two Python methods are provided for custom Markdown instances. ```python markdown = mistune.create_markdown(plugins=['url']) ``` ```python from mistune.plugins.url import url renderer = mistune.HTMLRenderer() markdown = mistune.Markdown(renderer, plugins=[url]) ``` -------------------------------- ### Task Lists Plugin Source: https://mistune.lepture.com/en/latest/plugins The task_lists plugin enables the creation of GitHub-style to-do items using `- [ ]` and `- [x]` syntax. This plugin is NOT enabled by default in `mistune.html()`. ```APIDOC ## Task Lists Plugin ### Description Enables GitHub-style to-do items (`- [ ]` and `- [x]`). ### Usage **NOT ENABLED** by default in `mistune.html()`. To enable the task_lists plugin with your own markdown instance: ```python import mistune # Using create_markdown markdown = mistune.create_markdown(plugins=['task_lists']) # Using Markdown constructor with explicit plugin from mistune.plugins.task_lists import task_lists renderer = mistune.HTMLRenderer() markdown = mistune.Markdown(renderer, plugins=[task_lists]) ``` ``` -------------------------------- ### Convert Markdown String to HTML Source: https://mistune.lepture.com/en/latest/cli Converts a markdown string directly to HTML using the `-m` option of the Mistune command-line tool. ```bash $ python -m mistune -m "Hi **Markdown**" ``` -------------------------------- ### Enable Subscript Plugin in Mistune Source: https://mistune.lepture.com/en/latest/plugins Details how to enable the 'subscript' plugin for creating tags. The plugin is disabled by default. Two methods are presented: using create_markdown and initializing a Markdown instance with the subscript plugin. ```python markdown = mistune.create_markdown(plugins=['subscript']) ``` ```python from mistune.plugins.formatting import subscript renderer = mistune.HTMLRenderer() markdown = mistune.Markdown(renderer, plugins=[subscript]) ``` -------------------------------- ### Strikethrough Plugin Source: https://mistune.lepture.com/en/latest/plugins The strikethrough plugin enables the `~~text~~` markdown syntax for strikethrough text. It is enabled by default in `mistune.html()`. ```APIDOC ## Strikethrough Plugin ### Description Enables `~~text~~` markdown for strikethrough. ### Usage Enabled by default in `mistune.html()`. To create a markdown instance with the strikethrough plugin: ```python import mistune # Using create_markdown markdown = mistune.create_markdown(plugins=['strikethrough']) # Using Markdown constructor with explicit plugin from mistune.plugins.formatting import strikethrough renderer = mistune.HTMLRenderer() markdown = mistune.Markdown(renderer, plugins=[strikethrough]) ``` ``` -------------------------------- ### Enable Abbreviations Plugin in Mistune Source: https://mistune.lepture.com/en/latest/plugins Illustrates how to activate the abbr plugin in Mistune for creating abbreviations. This plugin is not enabled by default in `mistune.html()`. Two Python methods are provided for creating a custom Markdown instance. ```python markdown = mistune.create_markdown(plugins=['abbr']) ``` ```python from mistune.plugins.abbr import abbr renderer = mistune.HTMLRenderer() markdown = mistune.Markdown(renderer, plugins=[abbr]) ``` -------------------------------- ### Reformat Markdown File Source: https://mistune.lepture.com/en/latest/cli Reformats a markdown file using a markdown renderer and writes the output back to the same file. This is useful for standardizing markdown formatting. ```bash $ python -m mistune -f README.md -r markdown -o README.md ``` -------------------------------- ### Registering a New Parsing Rule in Python Source: https://mistune.lepture.com/en/latest/api This method signature shows how to register a new parsing rule for the mistune parser. It involves providing a name for the rule, a regular expression pattern, a parsing function, and an optional rule to insert before. ```python register(_name : str_, _pattern : str | None_, _func : Callable[[Self, Match[str], ST], int | None]_, _before : str | None = None_) → None ``` -------------------------------- ### Mistune Abbreviations Plugin Source: https://mistune.lepture.com/en/latest/api Supports abbreviations in markdown, allowing for shorthand definitions that are expanded in the HTML output using the `` tag. This plugin requires a Markdown instance. ```python import mistune markdown = mistune.create_markdown(plugins=['abbr']) text = "The HTML specification\nis maintained by the W3C.\n\n*[HTML]: Hyper Text Markup Language\n*[W3C]: World Wide Web Consortium" html = markdown(text) print(html) ``` -------------------------------- ### Inline Spoiler Syntax and Conversion Source: https://mistune.lepture.com/en/latest/plugins Illustrates the syntax for an inline spoiler using the '>!' and '!<' markers and its conversion into a `` element within a paragraph. ```markdown this is the >! hidden text !< ``` ```html

this is the hidden text

``` -------------------------------- ### Mistune Task Lists Plugin Source: https://mistune.lepture.com/en/latest/api Enables task list support in markdown, following GitHub Flavored Markdown specifications. It allows for creating lists with checkboxes for 'to-do' items. This plugin requires a Markdown instance. ```python import mistune markdown = mistune.create_markdown(plugins=['task_lists']) text = "- [ ] unchecked task\n- [x] checked task" html = markdown(text) print(html) ``` -------------------------------- ### Create a non-escaped Mistune Markdown instance Source: https://mistune.lepture.com/en/latest/guide Creates a Markdown instance with HTML escaping disabled by setting `escape=False`. This allows raw HTML tags to be rendered directly. ```python import mistune markdown = mistune.create_markdown(escape=False) markdown('
hello
') ``` -------------------------------- ### Enable Ruby Plugin in Mistune Source: https://mistune.lepture.com/en/latest/plugins Explains how to enable the 'ruby' plugin for generating tags, which is used for East Asian typography. The plugin is not enabled by default. Code snippets demonstrate enabling it using create_markdown and a custom Markdown renderer. ```python markdown = mistune.create_markdown(plugins=['ruby']) ``` ```python from mistune.plugins.ruby import ruby renderer = mistune.HTMLRenderer() markdown = mistune.Markdown(renderer, plugins=[ruby]) ``` -------------------------------- ### Mistune Mark Plugin Source: https://mistune.lepture.com/en/latest/api Introduces a 'mark' feature using double equals signs (`==text==`), which renders as the HTML `` tag. This plugin requires a Markdown instance. ```python import mistune markdown = mistune.create_markdown(plugins=['mark']) text = "==mark me== ==mark \\=\\= equal==" html = markdown(text) print(html) ``` -------------------------------- ### Configure Markdown with Fenced or RST Directives in Python Source: https://mistune.lepture.com/en/latest/directives This snippet shows how to create a Mistune markdown instance with either FencedDirective or RSTDirective plugins. It demonstrates how to include specific directive types like Admonition and TableOfContents within these directive plugins. These plugins extend Mistune's parsing capabilities to handle custom directive syntaxes. ```python import mistune from mistune.directives import FencedDirective, RSTDirective from mistune.directives import Admonition, TableOfContents markdown = mistune.create_markdown(plugins=[ 'math', 'footnotes', # ... FencedDirective([ Admonition(), TableOfContents(), ]), ]) markdown = mistune.create_markdown(plugins=[ 'math', 'footnotes', # ... RSTDirective([ Admonition(), TableOfContents(), ]), ]) ``` -------------------------------- ### Mistune Strikethrough Plugin Source: https://mistune.lepture.com/en/latest/api Implements strikethrough formatting using double tildes (`~~text~~`), converting it to the HTML `` tag. This plugin requires a Markdown instance. ```python import mistune markdown = mistune.create_markdown(plugins=['strikethrough']) text = "~~This was mistaken text~~" html = markdown(text) print(html) ``` -------------------------------- ### URL Plugin Source: https://mistune.lepture.com/en/latest/plugins The URL plugin automatically converts raw URLs into clickable links. This plugin is NOT enabled by default in `mistune.html()`. ```APIDOC ## URL Plugin ### Description Converts raw URLs into clickable links. ### Usage **NOT ENABLED** by default in `mistune.html()`. To enable the URL plugin with your own markdown instance: ```python import mistune # Using create_markdown markdown = mistune.create_markdown(plugins=['url']) # Using Markdown constructor with explicit plugin from mistune.plugins.url import url renderer = mistune.HTMLRenderer() markdown = mistune.Markdown(renderer, plugins=[url]) ``` ``` -------------------------------- ### Mistune Insert Plugin Source: https://mistune.lepture.com/en/latest/api Adds support for the 'insert' tag, using double carets (`^^text^^`) to denote text that should be rendered with the HTML `` tag. This plugin requires a Markdown instance. ```python import mistune markdown = mistune.create_markdown(plugins=['insert']) text = "^^insert me^^" html = markdown(text) print(html) ``` -------------------------------- ### RestructuredText Renderer Source: https://mistune.lepture.com/en/latest/renderers Shows how to use the `RSTRenderer` to convert Markdown text into RestructuredText format. ```APIDOC ## RestructuredText Renderer ### Description Use `mistune.renderers.rst.RSTRenderer` to convert Markdown to RestructuredText. ### Method ```python from mistune.renderers.rst import RSTRenderer convert_rst = mistune.create_markdown(renderer=RSTRenderer()) print(convert_rst('your_markdown_text')) ``` ``` -------------------------------- ### Mistune Subscript Plugin Source: https://mistune.lepture.com/en/latest/api Supports subscript formatting using the tilde symbol (`~text~`), which is rendered as the HTML `` tag. This plugin requires a Markdown instance. ```python import mistune markdown = mistune.create_markdown(plugins=['subscript']) text = "H~2~O is a liquid." html = markdown(text) print(html) ``` -------------------------------- ### Mistune Renderers Overview Source: https://mistune.lepture.com/en/latest/renderers Mistune provides several built-in renderers for converting Markdown to different formats. You can also create custom renderers to extend its functionality. ```APIDOC ## Mistune Renderers Mistune includes several built-in renderers: * `mistune.renderers.html.HTMLRenderer` * `mistune.renderers.markdown.MarkdownRenderer` * `mistune.renderers.rst.RSTRenderer` Custom renderers can be created by subclassing `mistune.HTMLRenderer` or `mistune.renderers.markdown.MarkdownRenderer`. ``` -------------------------------- ### Convert Markdown to RestructuredText Source: https://mistune.lepture.com/en/latest/cli Converts a markdown file to RestructuredText (RST) format by specifying the 'rst' renderer with the `-r` option in the Mistune command-line tool. ```bash $ python -m mistune -f README.md -r rst ``` -------------------------------- ### Convert Markdown to HTML with Mistune Source: https://mistune.lepture.com/en/latest/guide Basic usage of Mistune to convert Markdown text to HTML. The `.html()` method enables all features by default, including strikethrough, table, and footnote plugins, without escaping HTML tags. ```python import mistune mistune.html(YOUR_MARKDOWN_TEXT) ``` -------------------------------- ### Convert Markdown to RestructuredText using Mistune Source: https://mistune.lepture.com/en/latest/renderers Shows how to use Mistune with the RSTRenderer to convert Markdown text into RestructuredText format. This is useful for documentation generation or cross-format content conversion. ```python from mistune.renderers.rst import RSTRenderer import mistune convert_rst = mistune.create_markdown(renderer=RSTRenderer()) convert_rst('your_markdown_text') ``` -------------------------------- ### Mistune Superscript Plugin Source: https://mistune.lepture.com/en/latest/api Enables superscript formatting using the caret symbol (`^text^`), which is converted to the HTML `` tag. This plugin requires a Markdown instance. ```python import mistune markdown = mistune.create_markdown(plugins=['superscript']) text = "2^10^ is 1024." html = markdown(text) print(html) ``` -------------------------------- ### Mistune Ruby Plugin Source: https://mistune.lepture.com/en/latest/api Adds support for ruby markup, enabling the display of pronunciation or annotations alongside East Asian characters using the `` tag. This plugin requires a Markdown instance. ```python import mistune markdown = mistune.create_markdown(plugins=['ruby']) text = "[漢字(ㄏㄢˋㄗˋ)]\n[漢(ㄏㄢˋ)字(ㄗˋ)]" html = markdown(text) print(html) ``` -------------------------------- ### Mistune Table Plugin Source: https://mistune.lepture.com/en/latest/api Enables table parsing in markdown, allowing for structured data presentation using pipe-delimited syntax. This plugin requires a Markdown instance. It also has variants for use within quotes and lists. ```python import mistune markdown = mistune.create_markdown(plugins=['table']) text = "First Header | Second Header\n------------- | ------------- \nContent Cell | Content Cell\nContent Cell | Content Cell" html = markdown(text) print(html) ``` -------------------------------- ### Reformat Markdown using Mistune's MarkdownRenderer Source: https://mistune.lepture.com/en/latest/renderers Illustrates the use of Mistune's MarkdownRenderer to reformat existing Markdown text. This can be employed for standardizing Markdown syntax or preparing content for specific Markdown parsers. ```python from mistune.renderers.markdown import MarkdownRenderer import mistune format_markdown = mistune.create_markdown(renderer=MarkdownRenderer()) format_markdown('your_markdown_text') ``` -------------------------------- ### Create Markdown Instance - Mistune Source: https://mistune.lepture.com/en/latest/api Creates a reusable Markdown instance with configurable options for HTML escaping, hard line breaks, renderer, and plugins. This allows for consistent markdown processing throughout an application. The function returns a Markdown instance that can be called with markdown text. ```python import mistune markdown = mistune.create_markdown( escape=False, hard_wrap=True, plugins=['table'] ) # Now use the created markdown instance markdown_text = 'This is a **test**.\nThis should be a line break.' html_result = markdown(markdown_text) # html_result will contain
tags for newlines if hard_wrap is True ``` -------------------------------- ### Generate Unique Key - Mistune Utility Source: https://mistune.lepture.com/en/latest/api Generates a unique key, typically used for internal linking mechanisms such as references in links or for footnote identifiers. This utility ensures that these keys are consistent and unique within the parsed document. ```python import mistune link_text = 'My Link' unique_key = mistune.unikey(link_text) # unique_key will be a generated identifier for the link ``` -------------------------------- ### Customize FencedDirective Markers Source: https://mistune.lepture.com/en/latest/api Demonstrates customizing the fence markers for the FencedDirective plugin in mistune. This allows using different characters, such as colons, for the directive fences, which can be useful for nesting directives with varying fence lengths. ```python from mistune.directives import FencedDirective, Admonition directive = FencedDirective([Admonition()], ':') # Example usage with custom markers: # :::: {note} Nesting directives # ... # :::: ``` -------------------------------- ### Mistune Footnotes Plugin Source: https://mistune.lepture.com/en/latest/api Adds support for footnotes in markdown. It parses footnote references and definitions, converting them into HTML with appropriate links and sections. This plugin requires a Markdown instance. ```python import mistune markdown = mistune.create_markdown(plugins=['footnotes']) text = "That's some text with a footnote.[^1]\n\n[^1]: And that's the footnote." html = markdown(text) print(html) ``` -------------------------------- ### Render TOC as UL HTML Source: https://mistune.lepture.com/en/latest/api Renders a list of table of contents items into an HTML unordered list (
    ). The input 'toc' should be an iterable of tuples, where each tuple contains the heading level, ID, and text. ```python toc_items = [ (1, 'toc-intro', 'Introduction'), (2, 'toc-install', 'Install'), (2, 'toc-upgrade', 'Upgrade'), (1, 'toc-license', 'License'), ] toc_html = mistune.toc.render_toc_ul(toc_items) ``` -------------------------------- ### Enable Table of Contents Directive in Python Source: https://mistune.lepture.com/en/latest/directives This code snippet illustrates how to activate the Table of Contents (TOC) plugin in Mistune using the RSTDirective. It configures Mistune to parse the `.. toc::` directive, allowing for automatic generation of a table of contents based on the document's headings. This is useful for navigating longer documents. ```python import mistune from mistune.directives import RSTDirective, TableOfContents markdown = mistune.create_markdown( plugins=[ # ... RSTDirective([TableOfContents()]), ] ) ``` -------------------------------- ### Use FencedDirective Plugin with Mistune Source: https://mistune.lepture.com/en/latest/api Adds the FencedDirective plugin to a mistune Markdown instance for supporting directive syntax similar to fenced code blocks. Developers can customize the fence markers. It accepts a list of directive plugins and an optional markers string. ```python import mistune from mistune.directives import FencedDirective, Admonition md = mistune.create_markdown(plugins=[ FencedDirective([Admonition()]) ]) ```