CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pymdown-extensions

Extension pack for Python Markdown that provides 20+ specialized extensions for enhanced text processing.

Pending
Overview
Eval results
Files

code-and-math.mddocs/

Code and Math Extensions

Extensions for advanced code syntax highlighting, mathematical expressions, inline code highlighting, enhanced fenced code blocks with custom formatters, and multimedia content processing.

Capabilities

Highlight (Code Syntax Highlighting)

Advanced syntax highlighting for code blocks using Pygments, providing comprehensive language support and customizable formatting options.

def makeExtension(**kwargs):
    """
    Create Highlight extension for code syntax highlighting.
    
    Configuration:
    - use_pygments: bool - Use Pygments for highlighting (True)
    - css_class: str - CSS class for highlighted code ('highlight')
    - pygments_style: str - Pygments style name ('default')
    - noclasses: bool - Inline styles instead of CSS classes (False)
    - linenums: bool - Enable line numbers (None)
    - linenums_style: str - Line number style ('table')
    - extend_pygments_lang: list - Additional language mappings
    
    Returns:
    HighlightExtension instance
    """

class HighlightExtension(Extension):
    """Advanced code highlighting extension."""

class Highlight:
    """Core highlighting class with Pygments integration."""

class HighlightTreeprocessor(Treeprocessor):
    """Processes code blocks for highlighting."""

class InlineHtmlFormatter:
    """Inline code formatter (requires Pygments)."""

class BlockHtmlFormatter:
    """Block code formatter (requires Pygments)."""

Usage Example:

import markdown

# Basic usage with Pygments
md = markdown.Markdown(extensions=['pymdownx.highlight'])

# With custom configuration
md = markdown.Markdown(extensions=[
    'pymdownx.highlight'
], extension_configs={
    'pymdownx.highlight': {
        'pygments_style': 'github',
        'linenums': True,
        'linenums_style': 'pymdownx-inline'
    }
})

text = '''
```python
def hello_world():
    print("Hello, World!")

''' html = md.convert(text)

### Inline Hilite (Inline Code Highlighting)

Syntax highlighting for inline code snippets, enabling language-specific highlighting within regular text.

```python { .api }
def makeExtension(**kwargs):
    """
    Create InlineHilite extension for inline code highlighting.
    
    Configuration:
    - css_class: str - CSS class for highlighted inline code ('highlight')
    - style_plain_text: bool - Style plain text inline code (True)
    - use_pygments: bool - Use Pygments for highlighting (True)
    
    Returns:
    InlineHiliteExtension instance
    """

class InlineHiliteExtension(Extension):
    """Inline code highlighting extension."""

class InlineHilitePattern(InlineProcessor):
    """Inline code pattern processor."""

class InlineHiliteException(Exception):
    """Custom exception for inline highlighting errors."""

Usage Example:

import markdown

md = markdown.Markdown(extensions=['pymdownx.inlinehilite'])

# Inline code with language: `#!python print("Hello")`
text = "Use `#!python print('Hello World')` for output."
html = md.convert(text)

SuperFences (Enhanced Fenced Code Blocks)

Advanced fenced code blocks with support for custom formatters, nested fences, and enhanced code block processing capabilities.

def makeExtension(**kwargs):
    """
    Create SuperFences extension for enhanced code blocks.
    
    Configuration:
    - css_class: str - CSS class for code blocks ('highlight')
    - custom_fences: list - Custom fence configurations
    - disable_indented_code_blocks: bool - Disable indented code (False)
    - preserve_tabs: bool - Preserve tab characters (False)
    - relaxed_headers: bool - Relaxed fenced code headers (False)
    
    Returns:
    SuperFencesExtension instance
    """

class SuperFencesExtension(Extension):
    """Enhanced fenced code blocks extension."""

class SuperFencesPreprocessor(Preprocessor):
    """Superfences preprocessor."""

class SuperFencesTreeprocessor(Treeprocessor):
    """Superfences tree processor."""

def fence_code_format(source, language, css_class, options, md, **kwargs):
    """
    Default code formatter for fenced blocks.
    
    Parameters:
    - source: str - Source code content
    - language: str - Programming language
    - css_class: str - CSS class name
    - options: dict - Formatter options
    - md: Markdown - Markdown instance
    
    Returns:
    str - Formatted HTML
    """

Usage Example:

import markdown

# Custom formatter example
def my_formatter(source, language, css_class, options, md, **kwargs):
    return f'<div class="custom-code">{source}</div>'

md = markdown.Markdown(extensions=[
    'pymdownx.superfences'
], extension_configs={
    'pymdownx.superfences': {
        'custom_fences': [
            {
                'name': 'custom',
                'class': 'custom-fence',
                'format': my_formatter
            }
        ]
    }
})

Arithmatex (Math Rendering)

LaTeX mathematical expression rendering with support for inline and block math, compatible with MathJax, KaTeX, and other math rendering engines.

def makeExtension(**kwargs):
    """
    Create Arithmatex extension for math rendering.
    
    Configuration:
    - inline_syntax: list - Inline math syntax patterns
    - block_syntax: list - Block math syntax patterns  
    - generic: bool - Use generic output format (True)
    - tex_inline_wrap: list - Inline math wrapper
    - tex_block_wrap: list - Block math wrapper
    - preview: bool - Enable math preview (True)
    
    Returns:
    ArithmatexExtension instance
    """

class ArithmatexExtension(Extension):
    """Mathematical expression rendering extension."""

class InlineArithmatexPattern(InlineProcessor):
    """Inline math pattern processor."""

class BlockArithmatexProcessor(BlockProcessor):
    """Block math pattern processor."""

def arithmatex_inline_format(**kwargs):
    """
    Configurable inline math formatter.
    
    Returns:
    Callable formatter function
    """

def arithmatex_fenced_format(**kwargs):
    """
    Configurable fenced math formatter.
    
    Returns:
    Callable formatter function
    """

Usage Example:

import markdown

# Basic math support
md = markdown.Markdown(extensions=['pymdownx.arithmatex'])

# Inline math: $E = mc^2$  
# Block math: $$\sum_{i=1}^n x_i$$
text = """
Einstein's equation: $E = mc^2$

$$
\\sum_{i=1}^{n} x_i = \\frac{n(n+1)}{2}
$$
"""
html = md.convert(text)

# Custom formatter for MathJax
def mathjax_inline_format(math):
    return f'\\({math}\\)'

def mathjax_block_format(math):
    return f'\\[{math}\\]'

md = markdown.Markdown(extensions=[
    'pymdownx.arithmatex'
], extension_configs={
    'pymdownx.arithmatex': {
        'inline_syntax': ['dollar'],
        'block_syntax': ['dollar']
    }
})

Base64 (Image Embedding)

Converts external images to inline base64 data URIs, enabling self-contained HTML documents without external dependencies.

def makeExtension(**kwargs):
    """
    Create B64 extension for base64 image embedding.
    
    Configuration:
    - base_path: str - Base path for resolving relative image paths
    -
    
    Returns:
    B64Extension instance
    """

class B64Extension(Extension):
    """Base64 image embedding extension."""

class B64Postprocessor(Postprocessor):
    """Image processing for base64 embedding."""

Usage Example:

import markdown

md = markdown.Markdown(extensions=['pymdownx.b64'])

# Images will be converted to base64 data URIs
text = "![Alt text](./image.png)"
html = md.convert(text)  # Results in <img src="data:image/png;base64,..." />

Advanced Code Configuration

Custom Syntax Highlighting

# Language alias configuration
extension_configs = {
    'pymdownx.highlight': {
        'extend_pygments_lang': [
            {'name': 'mylang', 'lang': 'python', 'options': {}}
        ]
    }
}

SuperFences Custom Formatters

def diagram_formatter(source, language, css_class, options, md, **kwargs):
    """Custom formatter for diagram generation."""
    if language == 'diagram':
        # Process diagram markup
        return f'<div class="diagram">{process_diagram(source)}</div>'
    return source

extension_configs = {
    'pymdownx.superfences': {
        'custom_fences': [
            {
                'name': 'diagram',
                'class': 'diagram',
                'format': diagram_formatter
            }
        ]
    }
}

Math Rendering Integration

# MathJax configuration
extension_configs = {
    'pymdownx.arithmatex': {
        'generic': True,
        'tex_inline_wrap': ['\\(', '\\)'],
        'tex_block_wrap': ['\\[', '\\]']
    }
}

# KaTeX configuration  
extension_configs = {
    'pymdownx.arithmatex': {
        'generic': False,
        'tex_inline_wrap': ['$', '$'],
        'tex_block_wrap': ['$$', '$$']
    }
}

Types

from typing import Callable, Dict, List, Optional, Any
from markdown import Extension, Preprocessor, InlineProcessor, BlockProcessor, Treeprocessor, Postprocessor

# Formatter function types
CodeFormatter = Callable[[str, str, str, Dict, Any], str]
MathFormatter = Callable[[str], str]

# Configuration types
FenceConfig = Dict[str, Any]  # Custom fence configuration
PygmentsConfig = Dict[str, Any]  # Pygments configuration options
MathSyntax = List[str]  # Math syntax pattern list

Install with Tessl CLI

npx tessl i tessl/pypi-pymdown-extensions

docs

advanced-blocks.md

code-and-math.md

content-structure.md

index.md

linking-and-media.md

text-enhancement.md

utilities-specialized.md

tile.json