PyMdown Extensions
repository·main·Indexed 22 days ago
https://github.com/facelessuser/pymdown-extensionsA suite of specialized extensions for the Python Markdown library, version 8.1.2, designed to provide advanced Markdown features and enhanced processing capabilities, including the Arithmatex extension for LaTeX math equations.
What's inside pymdown-extensions
- PyMdown Extensions is a collection of extensions designed for use with Python Markdown. It provides additional functionality and features to enhance the standard Markdown processing capabilities of the Python Markdown library.
Overview of MagicLink features
mainMagicLink is an extension designed to enhance link handling in Markdown. Its primary capabilities include:
- Auto-Linking: Automatically detects and converts raw HTTP, FTP, and email addresses into clickable links.
- Repository Link Shortening: Converts full repository URLs (GitHub, GitLab, and Bitbucket) into a concise shorthand format.
- Shorthand Link Support: Allows for the use of shorthand formats which can also be configured to auto-link.
- Conflict Resolution: If auto-linking conflicts with your text, you can use the explicit angle bracket format:
#!md <https://www.link.com>. If enabled, repository link shortening will still apply to these bracketed links.
What is the SmartSymbols extension?
mainThe
smartsymbolsextension provides syntax for automatically replacing common text patterns with special characters like trademarks, arrows, fractions, and ordinal numbers. It is designed to be used alongside Python Markdown'ssmartyextension rather than replacing it.Supported replacements include:
- Legal symbols:
(tm),(c),(r) - Arrows:
-->,<--,<--> - Math/Logic:
+/-,=/= - Fractions:
1/4, etc. - Ordinals:
1st,2nd, etc. - Other:
c/o
| Markdown | Result | | :--- | :--- | | `(tm)` | (tm) | | `(c)` | (c) | | `(r)` | (r) | | `c/o` | c/o | | `+/-` | +/- | | `-->` | --> | | `<--` | <-- | | `<-->` | <--> | | `=/=` | =/= | | `1/4` | 1/4 | | `1st` | 1st |- Legal symbols:
How the Keys syntax works
mainThe Keys extension uses the
+symbol to denote key combinations. A sequence of key presses is wrapped in double plus signs (++), and individual keys within the sequence are separated by a single plus sign (+).Example syntax:
++ctrl+alt+delete++++ctrl+alt+delete++Supported ordered list formats in FancyLists
mainFancyLists supports several ordered list marker styles. Using a different list type (e.g., switching from dots to parentheses) will start a new list.
Supported Styles:
- Decimal:
1.or1) - Lowercase Alphabetical:
a.ora) - Uppercase Alphabetical:
A.orA) - Lowercase Roman Numeral:
i.ori) - Uppercase Roman Numeral:
I.orI) - Generic Ordered Markers:
#.or#). These markers inherit the type of the current list as long as they use the same convention (.or)). If used to start a new list, decimal format is assumed. Note: Requirespymdownx.saneheadersto be enabled.
Example Syntax:
1) Item 1 2) Item 2 i. Item 1 ii. Item 2 a. Item a b. Item b #. Item 1 #. Item 2- Decimal:
How FancyLists handles ordered list transitions
mainFancyLists automatically creates a new list or restarts a list when the list type changes. A new list is triggered by:
- Switching between unordered and ordered lists (e.g., moving from
-to1.). - Changing the marker syntax (e.g., switching from
1.to1)). - Changing case (e.g., switching from
a.toA.). - Changing the ordered type (e.g., switching between numerical, roman numeral, alphabetical, or generic styles).
Generic list items (using the
#.syntax) inherit the type from the current list. If they start a new list, they default to the decimal type. As long as the marker is consistent with the current list type, they will append to the existing list rather than creating a new one.Note on Uppercase Alphabetical Lists: To avoid false positives with names starting with an initial (e.g.,
B. Russell), use two spaces after the marker instead of the standard one.B. Russell was an English philosopher. A. This is a list.- Switching between unordered and ordered lists (e.g., moving from
Use URL Snippets
mainIf
url_downloadis enabled, you can use URLs instead of local file paths.Important Constraints:
- Nested Snippets: If a snippet is loaded via URL, all nested snippets within it must also be URLs. Local file references are not allowed inside URL-sourced snippets.
- Security: Enabling this allows the renderer to make outbound HTTP requests. Use with caution in untrusted environments.
Configuration Options:
url_download: Enables/disables URL snippets.url_max_size: Maximum size of the downloaded content (default applies unless set to 0 to ignore).url_timeout: Timeout for the request (default applies unless set to 0 to ignore).url_request_headers: A dictionary of HTTP headers to include in every request.max_retries: Maximum retry attempts for 429 (Too Many Requests) status codes (default: 3).backoff_factor: Factor for linear backoff (default: 2).
How Snippets work
mainSnippets is a preprocessor extension that allows you to insert Markdown or HTML content from external files into your current document. This is useful for maintaining single sources of truth for content (like hyperlinks or code examples) used across multiple files.
Key Behaviors:
- Recursive Inclusion: Supports recursive file inclusion with built-in protection against infinite loops.
- Missing Files: If a specified file cannot be found, the markup is removed from the output.
- Indentation: If the snippet declaration is indented, the inserted content will be indented to that same level.
- Security Warning: Snippets is intended for static content workflows. Do not use it to render untrusted/user-supplied content (e.g., public comments or wikis). Enabling
url_downloadcan expose the renderer to SSRF-style risks.
Handle Exceptions in Custom Fences
mainSuperFences handles most exceptions in validators and formatters gracefully by ignoring the failing component.
- In Validators: If an exception occurs, SuperFences tries the next validator in the list.
- In Formatters: If an exception occurs, the fenced content is abandoned (it will not fall back to a different formatter).
To prevent silent failures and halt Markdown parsing, raise a
SuperFencesException. This will bubble up and display both theSuperFencesExceptionand the original cause.from pymdownx.superfences import SuperFencesException def custom_validator_except(language, inputs, options, attrs, md): try: # ... logic that might raise KeyError ... if inputs['opt'] != "A": return False except KeyError as e: raise SuperFencesException from e return Truedef custom_validator_except(language, inputs, options, attrs, md): """Custom validator.""" okay = True try: for k in inputs.keys(): if k != 'opt': okay = False break if okay: if inputs['opt'] != "A": okay = False else: options['opt'] = inputs['opt'] except KeyError as e: raise SuperFencesException from e return okayHow SaneHeaders changes header syntax
mainBy default, Python Markdown recognizes headers even if there is no space after the hashes (e.g.,
##Header).SaneHeadersmodifies this behavior to follow a stricter rule: a line is only treated as a header if there is at least one space following the#characters. This allows other syntaxes that use#at the start of a line—such as issue links (#998), tags (#tag), orFancyListsordered list markers (#.)—to coexist with standard Markdown headers without being incorrectly parsed as headers.## Header (Recognized as header) ##Not a Header (Not recognized as header)How the Mermaid custom loader works
mainThe Mermaid integration relies on a custom JavaScript loader (often named
extra-loader.js) that performs the following steps:- Defines a Custom Element: It creates a
<diagram-div>custom element using the Shadow DOM to encapsulate Mermaid content and prevent ID collisions. - Initializes Mermaid: It checks for a global
window.mermaidConfig. If not found, it uses adefaultConfig. It then callsmermaid.initialize(config). - Scans and Renders: It searches the document for elements with the class provided by SuperFences (e.g.,
pre.mermaid) or<diagram-div>elements. - Shadow DOM Encapsulation: For each found block, it renders the Mermaid SVG into a temporary element, then moves the resulting SVG into a
<diagram-div>shadow root, replacing the original text source to keep the UI clean.
- Defines a Custom Element: It creates a
How ProgressBar level classes work
mainWhen
level_classis enabled (default isTrue), the extension adds a class to the outer.progresscontainer based on theprogress_incrementsetting.For example, if
progress_incrementis set to20, the extension will generate classes like.progress-20plus,.progress-40plus, etc., depending on the progress value. This allows you to change the color of the progress bar at specific thresholds using CSS:.progress-100plus .progress-bar { background-color: #00e676; } .progress-80plus .progress-bar { background-color: #fbc02d; }