Extension pack for Python Markdown that provides 20+ specialized extensions for enhanced text processing.
—
Extensions using the generic blocks framework for creating structured content including admonitions, captions, definitions, tabbed interfaces, HTML blocks, and other advanced block-level elements.
Generic block processing framework that provides the foundation for all block-based extensions with consistent syntax and extensible architecture.
def makeExtension(**kwargs):
"""
Create base Blocks extension for generic block processing.
Returns:
BlocksExtension instance
"""
class BlocksExtension(Extension):
"""Base blocks framework extension."""
class BlocksMgrExtension(Extension):
"""Blocks manager extension for coordinating block processing."""
class BlocksProcessor(BlockProcessor):
"""Generic block processor."""
class BlocksTreeprocessor(Treeprocessor):
"""Blocks tree processor for post-processing."""
class BlockEntry:
"""Block entry tracking class."""
def get_frontmatter(text):
"""
Parse YAML frontmatter from text.
Parameters:
- text: str - Input text with potential frontmatter
Returns:
tuple - (frontmatter_dict, remaining_text)
"""
def reindent(text, indent_level=0):
"""
Reindent text to specified level.
Parameters:
- text: str - Text to reindent
- indent_level: int - Target indentation level
Returns:
str - Reindented text
"""
def unescape_markdown(text):
"""
Unescape markdown placeholders.
Parameters:
- text: str - Text with escaped markdown
Returns:
str - Unescaped text
"""Abstract base class for all block implementations providing consistent interface and type validation.
class Block:
"""
Abstract base class for all block implementations.
Provides standard interface and validation utilities.
"""
def __init__(self, **kwargs):
"""Initialize block with configuration."""
def run(self, content, **kwargs):
"""Process block content and return HTML."""
# Type validation functions
def type_multi(*validators):
"""Validate against multiple type validators."""
def type_any():
"""Accept any type."""
def type_none():
"""Accept None/null values."""
def type_bool():
"""Validate boolean type."""
def type_string():
"""Validate string type."""
def type_integer():
"""Validate integer type."""
def type_float():
"""Validate float type."""
def type_list():
"""Validate list type."""
def type_dict():
"""Validate dictionary type."""Create callout boxes and admonitions with various styles for notes, warnings, tips, and other highlighted content.
class Admonition(Block):
"""
Admonition block for creating styled callout boxes.
Supports various admonition types: note, warning, tip, danger, info, etc.
"""
def run(self, content, type="note", title=None, **kwargs):
"""
Process admonition block content.
Parameters:
- content: str - Block content
- type: str - Admonition type ('note', 'warning', 'tip', etc.)
- title: str - Optional custom title
Returns:
str - Rendered admonition HTML
"""Usage Example:
import markdown
md = markdown.Markdown(extensions=['pymdownx.blocks.admonition'])
text = '''
!!! note "Important Information"
This is a note admonition with a custom title.
!!! warning
This is a warning without a custom title.
!!! tip "Pro Tip"
This is a helpful tip for users.
'''
html = md.convert(text)Advanced collapsible content blocks with more features than the basic details extension.
class Details(Block):
"""
Advanced details block for collapsible content.
Provides enhanced functionality over basic details extension.
"""
def run(self, content, summary="Details", open=False, **kwargs):
"""
Process details block content.
Parameters:
- content: str - Block content
- summary: str - Summary text for the details element
- open: bool - Whether details should start expanded
Returns:
str - Rendered details HTML
"""Advanced tabbed interfaces with enhanced functionality and styling options.
class Tab(Block):
"""
Tab block for creating tabbed interfaces.
Provides advanced tabbed content functionality.
"""
def run(self, content, title, **kwargs):
"""
Process tab block content.
Parameters:
- content: str - Tab content
- title: str - Tab title
Returns:
str - Rendered tab HTML
"""
class TabbedTreeprocessor(Treeprocessor):
"""Tabbed content tree processor for tab group coordination."""Usage Example:
import markdown
md = markdown.Markdown(extensions=['pymdownx.blocks.tab'])
text = '''
/// tab | Python
```python
print("Hello from Python!")///
/// tab | JavaScript
console.log("Hello from JavaScript!");///
/// tab | Bash
echo "Hello from Bash!"/// ''' html = md.convert(text)
### Caption Blocks
Add captions to figures, tables, and other content elements with proper semantic markup.
```python { .api }
class Caption(Block):
"""
Caption block for adding captions to content elements.
Provides semantic caption markup for figures and tables.
"""
def run(self, content, type="figure", **kwargs):
"""
Process caption block content.
Parameters:
- content: str - Caption content
- type: str - Caption type ('figure', 'table', etc.)
Returns:
str - Rendered caption HTML
"""Create definition lists and glossary entries with enhanced formatting.
class Definition(Block):
"""
Definition block for creating definition lists and glossaries.
Provides enhanced definition list functionality.
"""
def run(self, content, term, **kwargs):
"""
Process definition block content.
Parameters:
- content: str - Definition content
- term: str - Term being defined
Returns:
str - Rendered definition HTML
"""Raw HTML content blocks with safety features and validation.
class HTML(Block):
"""
HTML block for raw HTML content.
Provides controlled HTML content insertion with safety features.
"""
def run(self, content, validate=True, **kwargs):
"""
Process HTML block content.
Parameters:
- content: str - Raw HTML content
- validate: bool - Whether to validate HTML
Returns:
str - Processed HTML content
"""All blocks follow a consistent syntax pattern:
/// block-type | title
Block content goes here
///
/// block-type
attribute: value
another: value
Block content with YAML frontmatter
///!!! note "Optional Title"
Admonition content
!!! warning
Warning content without custom title
!!! danger "Critical Alert"
Danger admonition with custom title/// tab | Tab 1 Title
Content for first tab
///
/// tab | Tab 2 Title
Content for second tab
////// details | Summary Text
open: true
Collapsible content that starts expanded
///
/// details | Click to Expand
Content that starts collapsed
///from pymdownx.blocks import block
# Register custom block
@block.register('custom')
class CustomBlock(Block):
def run(self, content, **kwargs):
return f'<div class="custom">{content}</div>'text = '''
/// admonition
type: warning
title: "Custom Warning"
This admonition uses YAML frontmatter for configuration.
///
'''text = '''
/// details | Outer Details
/// tab | Inner Tab 1
Content in nested tab
///
/// tab | Inner Tab 2
More nested content
///
///
'''from pymdownx.blocks.block import type_string, type_bool, type_integer
class CustomBlock(Block):
config = {
'title': type_string(),
'enabled': type_bool(),
'count': type_integer()
}from pymdownx.blocks.block import type_multi, type_string, type_none
class FlexibleBlock(Block):
config = {
'optional_title': type_multi(type_string(), type_none())
}md = markdown.Markdown(extensions=[
'pymdownx.blocks.admonition',
'pymdownx.blocks.tab',
'pymdownx.superfences',
'pymdownx.highlight'
])Blocks can contain other markdown extensions:
text = '''
!!! note "Code Example"
```python
def hello():
print("Hello from inside an admonition!")
```
This code block is processed by SuperFences within the admonition.
'''from typing import Any, Callable, Dict, List, Optional, Union
from markdown import Extension, BlockProcessor, Treeprocessor
# Block-related types
BlockConfig = Dict[str, Any] # Block configuration dictionary
BlockValidator = Callable[[Any], bool] # Type validator function
BlockContent = str # Block content string
BlockAttributes = Dict[str, Any] # Block attribute dictionary
# YAML frontmatter types
Frontmatter = Dict[str, Any] # Parsed YAML frontmatter
FrontmatterTuple = tuple[Frontmatter, str] # (frontmatter, content) tuple
# Block processing types
BlockResult = str # Processed block HTML result
IndentLevel = int # Text indentation levelInstall with Tessl CLI
npx tessl i tessl/pypi-pymdown-extensions