PyMdown Extensions

repository·main·Indexed 22 days ago

https://github.com/facelessuser/pymdown-extensions

A 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.

Tokens
53.7K
Snippets
189
Records
250
Agent score
77%

What's inside pymdown-extensions

  1. Overview of MagicLink features

    main

    MagicLink 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.
  2. What is the SmartSymbols extension?

    main

    The smartsymbols extension 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's smarty extension 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 |
  3. Supported ordered list formats in FancyLists

    main

    FancyLists 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. or 1)
    • Lowercase Alphabetical: a. or a)
    • Uppercase Alphabetical: A. or A)
    • Lowercase Roman Numeral: i. or i)
    • Uppercase Roman Numeral: I. or I)
    • 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: Requires pymdownx.saneheaders to 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
  4. How FancyLists handles ordered list transitions

    main

    FancyLists automatically creates a new list or restarts a list when the list type changes. A new list is triggered by:

    1. Switching between unordered and ordered lists (e.g., moving from - to 1.).
    2. Changing the marker syntax (e.g., switching from 1. to 1)).
    3. Changing case (e.g., switching from a. to A.).
    4. 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.
  5. Use URL Snippets

    main

    If url_download is 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).
  6. How Snippets work

    main

    Snippets 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_download can expose the renderer to SSRF-style risks.
  7. Handle Exceptions in Custom Fences

    main

    SuperFences 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 the SuperFencesException and 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 True
    def 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 okay
  8. How SaneHeaders changes header syntax

    main

    By default, Python Markdown recognizes headers even if there is no space after the hashes (e.g., ##Header).

    SaneHeaders modifies 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), or FancyLists ordered 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)
  9. How the Mermaid custom loader works

    main

    The Mermaid integration relies on a custom JavaScript loader (often named extra-loader.js) that performs the following steps:

    1. Defines a Custom Element: It creates a <diagram-div> custom element using the Shadow DOM to encapsulate Mermaid content and prevent ID collisions.
    2. Initializes Mermaid: It checks for a global window.mermaidConfig. If not found, it uses a defaultConfig. It then calls mermaid.initialize(config).
    3. Scans and Renders: It searches the document for elements with the class provided by SuperFences (e.g., pre.mermaid) or <diagram-div> elements.
    4. 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.
  10. How ProgressBar level classes work

    main

    When level_class is enabled (default is True), the extension adds a class to the outer .progress container based on the progress_increment setting.

    For example, if progress_increment is set to 20, 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; }