CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-sphinx-codeautolink

Automatic links from code examples to reference documentation.

Overview
Eval results
Files

extension-setup.mddocs/

Extension Setup and Configuration

Core extension functionality including the main setup function, configuration values, and extension lifecycle management. This covers everything needed to install, configure, and customize the extension behavior.

Capabilities

Main Setup Function

The primary entry point for the Sphinx extension that registers all components and event handlers.

def setup(app: Sphinx) -> dict[str, Any]:
    """
    Set up extension, directives and events.
    
    This function is called by Sphinx when the extension is loaded. It registers
    configuration values, directives, event handlers, and static resources.
    
    Parameters:
    - app: Sphinx application instance
    
    Returns:
    - dict: Extension metadata containing version, env_version, and parallel_read_safe
    """

Configuration Values

Configuration options that can be set in your Sphinx conf.py file to customize extension behavior.

# Core behavior configuration
codeautolink_autodoc_inject: bool = False
"""Automatically inject autolink-examples directives into autodoc docstrings"""

codeautolink_global_preface: str = ""
"""Global code to prepend to all parsed code blocks"""

codeautolink_custom_blocks: dict = {}
"""Custom block type transformers mapping block names to transformer functions"""

codeautolink_concat_default: bool = False
"""Default concatenation behavior for code blocks"""

codeautolink_search_css_classes: list = []
"""Additional CSS classes to search for code blocks"""

# Inventory and resolution configuration
codeautolink_inventory_map: dict = {}
"""Mapping to transform inventory locations (e.g., redirect old paths to new ones)"""

# Warning configuration
codeautolink_warn_on_missing_inventory: bool = False
"""Warn when inventory entries are missing"""

codeautolink_warn_on_failed_resolve: bool = False
"""Warn when name resolution fails"""

codeautolink_warn_on_no_backreference: bool = False
"""Warn when no backreferences are found"""

codeautolink_warn_on_default_parse_fail: bool = False
"""Warn when parsing fails on default language blocks"""

Extension State Management

The main extension class that manages state and coordinates between Sphinx events.

class SphinxCodeAutoLink:
    """
    Provide functionality and manage state between events.
    
    This class handles the complete lifecycle of code block processing,
    from initial parsing through final link application.
    """
    
    def build_inited(self, app) -> None:
        """
        Handle initial setup when build starts.
        
        Initializes caches, reads configuration, and prepares the extension
        for processing documents.
        """
    
    def autodoc_process_docstring(self, app, what, name, obj, options, lines) -> None:
        """
        Handle autodoc-process-docstring event.
        
        Automatically injects autolink-examples directives into autodoc
        docstrings when codeautolink_autodoc_inject is enabled.
        """
    
    def parse_blocks(self, app, doctree) -> None:
        """
        Parse code blocks for later link substitution.
        
        Analyzes Python code blocks in the document tree, extracts name
        usage patterns, and prepares them for resolution.
        """
    
    def merge_environments(self, app, env, docnames, other) -> None:
        """
        Merge transform information between build environments.
        
        Handles parallel build scenarios by merging cached transform data.
        """
    
    def purge_doc_from_environment(self, app, env, docname) -> None:
        """
        Remove transforms from cache when documents are removed.
        
        Cleans up cached data for documents that are no longer part of the build.
        """
    
    def create_references(self, app, env) -> None:
        """
        Clean source transforms and create code references.
        
        Resolves parsed names to their documentation locations using
        inventory data and creates the final reference mappings.
        """
    
    def generate_backref_tables(self, app, doctree, docname):
        """
        Generate backreference tables.
        
        Creates tables showing where API elements appear in code examples,
        replacing autolink-examples directive nodes.
        """
    
    def apply_links(self, app, exception) -> None:
        """
        Apply links to HTML output and write refs file.
        
        Post-processes generated HTML files to inject clickable links
        into code elements based on resolved references.
        """

Helper Functions

Utility functions for extension operation and debugging.

def print_exceptions(*, append_source: bool = False):
    """
    Print the traceback of uncaught and unexpected exceptions.
    
    Decorator that ensures exceptions in event handlers are properly
    displayed for debugging, as Sphinx masks tracebacks by default.
    
    Parameters:
    - append_source: If True, add document source information to error messages
    
    Returns:
    - Decorator function
    """

def transpose_inventory(inv: dict, relative_to: str, *, use_tuple: bool = False) -> dict[str, str]:
    """
    Transpose Sphinx inventory from {type: {name: (..., location)}} to {name: location}.
    
    Converts Sphinx's nested inventory format to a flat mapping suitable
    for name resolution. Filters to Python domain only.
    
    Parameters:
    - inv: Sphinx inventory dictionary
    - relative_to: Directory to make file paths relative to
    - use_tuple: Force using Sphinx inventory tuple interface
    
    Returns:
    - dict: Flat mapping from object names to their documentation URLs
    """

Usage Examples

Basic Configuration

# conf.py
extensions = [
    'sphinx_codeautolink',
    'sphinx.ext.autodoc',  # Required
]

# Enable warnings for debugging
codeautolink_warn_on_missing_inventory = True
codeautolink_warn_on_failed_resolve = True

Advanced Configuration

# conf.py
extensions = ['sphinx_codeautolink']

# Automatically add examples to autodoc docstrings
codeautolink_autodoc_inject = True

# Global imports for all code blocks
codeautolink_global_preface = """
import numpy as np
import matplotlib.pyplot as plt
"""

# Custom block processors
def process_sage_code(source):
    # Custom transformation for SageMath code
    return source, source.replace('sage:', 'python:')

codeautolink_custom_blocks = {
    'sage': process_sage_code
}

# Redirect old documentation URLs
codeautolink_inventory_map = {
    'old.module.Class': 'new.module.Class',
    'deprecated.function': 'current.function'
}

# Enable all warnings
codeautolink_warn_on_missing_inventory = True
codeautolink_warn_on_failed_resolve = True
codeautolink_warn_on_no_backreference = True
codeautolink_warn_on_default_parse_fail = True

Version Information

__version__: str = "0.17.5"
"""Package version string"""

Install with Tessl CLI

npx tessl i tessl/pypi-sphinx-codeautolink

docs

code-processing.md

extension-setup.md

index.md

name-resolution.md

rst-directives.md

tile.json