Box of handy tools for Sphinx providing comprehensive extensions and enhancements for documentation generation.
Configuration value documentation, cross-referencing roles, and specialized formatting features. These extensions provide tools for documenting configuration options and creating rich cross-references within documentation.
Specialized directive and role for documenting configuration values with proper formatting and cross-referencing.
class ConfigurationValue(SphinxDirective):
"""Directive for documenting configuration values."""
has_content = True
required_arguments = 1 # configuration value name
optional_arguments = 0
final_argument_whitespace = False
option_spec = {
'type': directives.unchanged,
'default': directives.unchanged,
'required': directives.flag,
'versionadded': directives.unchanged,
'versionchanged': directives.unchanged,
'deprecated': directives.unchanged,
}
def run(self) -> List[Node]:
"""Create configuration value documentation."""
def register_confval(app: Sphinx, name: str, type_: type, default: Any = None) -> None:
"""
Register configuration value with Sphinx.
Args:
app: Sphinx application instance
name: Configuration value name
type_: Expected type for the value
default: Default value if not specified
"""
def confval_role(name: str, rawtext: str, text: str, lineno: int,
inliner: Inliner, options: Dict[str, Any] = {},
content: List[str] = []) -> Tuple[List[Node], List[system_message]]:
"""
Role for cross-referencing configuration values.
Args:
name: Role name ('confval')
rawtext: Raw role text
text: Configuration value name to reference
lineno: Line number in document
inliner: Sphinx inliner
options: Role options
content: Role content
Returns:
Tuple of confval reference nodes and any error messages
"""Usage:
.. confval:: my_config_option
:type: str
:default: "default_value"
:versionadded: 1.2.0
This configuration option controls the behavior of...
Valid values are:
* ``"auto"`` - Automatic detection
* ``"manual"`` - Manual configuration
* ``"disabled"`` - Disable feature
Configuration can be referenced with :confval:`my_config_option`.Roles for linking to various types of assets and files with enhanced handling.
def asset_role(name: str, rawtext: str, text: str, lineno: int,
inliner: Inliner, options: Dict[str, Any] = {},
content: List[str] = []) -> Tuple[List[Node], List[system_message]]:
"""
Role for linking to assets that open in browser instead of downloading.
Args:
name: Role name ('asset')
rawtext: Raw role text
text: Asset path or URL
lineno: Line number in document
inliner: Sphinx inliner
options: Role options
content: Role content
Returns:
Tuple of asset link nodes and any error messages
"""
def source_role(name: str, rawtext: str, text: str, lineno: int,
inliner: Inliner, options: Dict[str, Any] = {},
content: List[str] = []) -> Tuple[List[Node], List[system_message]]:
"""
Role for linking to source files on GitHub or in documentation.
Args:
name: Role name ('source')
rawtext: Raw role text
text: File path
lineno: Line number in document
inliner: Sphinx inliner
options: Role options
content: Role content
Returns:
Tuple of source link nodes and any error messages
"""Usage:
:asset:`documents/manual.pdf`
:asset:`https://example.com/image.png`
:source:`src/module/__init__.py`
:source:`sphinx_toolbox/utils.py`Role for creating links to Wikipedia articles with language support.
def make_wikipedia_link(title: str, lang: str = "en",
display_text: Optional[str] = None) -> str:
"""
Create Wikipedia link URL.
Args:
title: Wikipedia article title
lang: Language code (default: "en")
display_text: Optional display text override
Returns:
Wikipedia article URL
"""
def wikipedia_role(name: str, rawtext: str, text: str, lineno: int,
inliner: Inliner, options: Dict[str, Any] = {},
content: List[str] = []) -> Tuple[List[Node], List[system_message]]:
"""
Role for linking to Wikipedia articles.
Args:
name: Role name ('wikipedia')
rawtext: Raw role text
text: Article title, optionally with lang prefix
lineno: Line number in document
inliner: Sphinx inliner
options: Role options
content: Role content
Returns:
Tuple of Wikipedia link nodes and any error messages
"""Configuration:
# Wikipedia language setting
wikipedia_lang = "en" # Default language for Wikipedia linksUsage:
:wikipedia:`Python (programming language)`
:wikipedia:`fr:Python (programming language)` (French Wikipedia)
:wikipedia:`Machine learning`Enhanced cross-referencing for Python decorators.
class PyDecoXRefRole(XRefRole):
"""Cross-reference role for Python decorators."""
def process_link(self, env: BuildEnvironment, refnode: Element,
has_explicit_title: bool, title: str,
target: str) -> Tuple[str, str]:
"""
Process decorator cross-reference link.
Args:
env: Build environment
refnode: Reference node
has_explicit_title: Whether explicit title was provided
title: Link title
target: Link target
Returns:
Tuple of processed title and target
"""
def setup_decorator_xref(app: Sphinx) -> None:
"""Set up decorator cross-reference support."""Usage:
:deco:`property`
:deco:`classmethod`
:deco:`staticmethod`
:deco:`my_custom_decorator`Special directive for documenting Flake8 error codes and warnings.
class Flake8CodesDirective(SphinxDirective):
"""Directive for documenting Flake8 error codes."""
has_content = True
required_arguments = 0
optional_arguments = 1 # optional codes file path
option_spec = {
'codes': directives.unchanged,
'format': directives.unchanged,
}
def run(self) -> List[Node]:
"""Generate Flake8 codes documentation."""
def parse_flake8_codes(codes_content: str) -> List[Dict[str, str]]:
"""
Parse Flake8 codes from content.
Args:
codes_content: Content containing Flake8 codes
Returns:
List of parsed code dictionaries
"""Usage:
.. flake8-codes::
:codes: flake8_codes.txt
:format: table
.. flake8-codes::
E101: Indentation contains mixed spaces and tabs
E111: Indentation is not a multiple of four
W291: Trailing whitespaceUtilities for documenting and integrating with pre-commit hooks.
def setup_precommit_integration(app: Sphinx) -> None:
"""Set up pre-commit hook integration."""
class PreCommitDirective(SphinxDirective):
"""Directive for documenting pre-commit hooks."""
has_content = True
def run(self) -> List[Node]:
"""Document pre-commit hook configuration."""Enhanced support for documenting version changes and deprecations.
class VersionChange(SphinxDirective):
"""Enhanced version change documentation."""
option_spec = {
'version': directives.unchanged,
'reason': directives.unchanged,
}
def run(self) -> List[Node]:
"""Create version change documentation."""Usage:
.. versionchange:: 2.0.0
:reason: API redesign
The ``old_function`` was replaced with ``new_function``.
.. deprecated:: 1.5.0
:reason: Security concerns
Use ``secure_function`` instead.Testing support for Sphinx extensions and documentation.
def run_setup(app: Sphinx) -> None:
"""Run extension setup for testing."""
def check_html_regression(test_output: str, expected_output: str) -> None:
"""
Check HTML output against expected results.
Args:
test_output: Generated HTML output
expected_output: Expected HTML output
Raises:
AssertionError: If outputs don't match
"""
def make_test_app(**kwargs) -> Sphinx:
"""Create Sphinx application for testing."""
class SphinxTestCase:
"""Base class for Sphinx extension testing."""
def setup_app(self, **kwargs) -> Sphinx:
"""Set up test Sphinx application."""
def build_docs(self, builder: str = 'html') -> None:
"""Build documentation for testing."""
def get_output(self, filename: str) -> str:
"""Get built output content."""Comprehensive configuration value definitions and validation.
# Configuration values added by various extensions
CONFIGURATION_VALUES = {
# GitHub integration
'github_username': (None, 'env', [str, type(None)]),
'github_repository': (None, 'env', [str, type(None)]),
# Asset handling
'assets_dir': ('_assets', 'html', [str]),
# Wikipedia
'wikipedia_lang': ('en', 'env', [str]),
# Source links
'source_link_target': ('github', 'env', [str]),
# Enhanced autodoc
'all_typevars': (False, 'env', [bool]),
'no_unbound_typevars': (False, 'env', [bool]),
# And many more...
}
def validate_all_config(app: Sphinx, config: Config) -> None:
"""Validate all sphinx-toolbox configuration values."""Centralized role registration for all sphinx-toolbox roles.
def register_all_roles(app: Sphinx) -> None:
"""Register all sphinx-toolbox roles with Sphinx."""
ROLE_REGISTRY = {
'asset': asset_role,
'source': source_role,
'wikipedia': wikipedia_role,
'confval': confval_role,
'deco': PyDecoXRefRole,
# Additional roles from other extensions
'issue': 'sphinx_toolbox.issues.issue_role',
'pull': 'sphinx_toolbox.issues.pull_role',
}Comprehensive error handling for configuration and role processing.
class ConfigurationError(SphinxError):
"""Base exception for configuration errors."""
class RoleProcessingError(SphinxError):
"""Raised when role processing fails."""
class CrossReferenceError(SphinxError):
"""Raised when cross-reference resolution fails."""Install with Tessl CLI
npx tessl i tessl/pypi-sphinx-toolbox