0
# Sphinx CodeAutoLink
1
2
A Sphinx extension that automatically creates clickable links from individual code elements in documentation examples to their corresponding reference documentation. It operates by parsing Python code blocks in documentation, analyzing the syntax tree to identify functions, classes, and other code elements, then automatically generating hyperlinks to the appropriate sections of the API documentation.
3
4
## Package Information
5
6
- **Package Name**: sphinx-codeautolink
7
- **Language**: Python
8
- **Installation**: `pip install sphinx-codeautolink`
9
- **Python Requirements**: >=3.10
10
- **Dependencies**: `sphinx>=3.2.0`, `beautifulsoup4>=4.8.1`
11
- **Optional Dependencies**: `ipython!=8.7.0` (for IPython support)
12
13
## Core Imports
14
15
```python
16
import sphinx_codeautolink
17
```
18
19
For extension setup (in conf.py):
20
21
```python
22
extensions = [
23
'sphinx_codeautolink',
24
# other extensions...
25
]
26
```
27
28
## Basic Usage
29
30
### Extension Setup
31
32
Add to your Sphinx `conf.py`:
33
34
```python
35
# Enable the extension
36
extensions = [
37
'sphinx_codeautolink',
38
'sphinx.ext.autodoc', # Required dependency
39
]
40
41
# Optional configuration
42
codeautolink_autodoc_inject = True
43
codeautolink_warn_on_missing_inventory = True
44
codeautolink_warn_on_failed_resolve = True
45
```
46
47
### Using Directives in RST Documents
48
49
```rst
50
.. autolink-examples:: MyClass
51
:collapse:
52
53
.. autolink-preface::
54
import numpy as np
55
import matplotlib.pyplot as plt
56
57
.. code-block:: python
58
59
# This code block will automatically get links
60
data = np.array([1, 2, 3, 4, 5])
61
plt.plot(data)
62
plt.show()
63
64
.. autolink-skip::
65
66
.. code-block:: python
67
68
# This code block will not get automatic links
69
print("No links here")
70
```
71
72
## Architecture
73
74
The extension follows Sphinx's event-driven architecture and operates through several key phases:
75
76
- **Initialization**: Extension registers configuration values, directives, and event handlers
77
- **Parse Phase**: Code blocks are analyzed using AST parsing to identify name access patterns and imports
78
- **Reference Creation**: Names are resolved to their documentation locations using inventory data
79
- **Link Application**: HTML output is post-processed to inject clickable links into code elements
80
- **Backreference Generation**: Optional tables showing where API elements are used in examples
81
82
Core components include the AST-based parser for Python code analysis, the inventory resolver for mapping names to documentation URLs, and the HTML post-processor for link injection.
83
84
## Capabilities
85
86
### Extension Setup and Configuration
87
88
Core extension functionality including the main setup function, configuration values, and extension lifecycle management.
89
90
```python { .api }
91
def setup(app: Sphinx) -> dict[str, Any]:
92
"""Set up extension, directives and events."""
93
94
# Configuration values for conf.py
95
# codeautolink_autodoc_inject: bool = False
96
# codeautolink_global_preface: str = ""
97
# codeautolink_custom_blocks: dict = {}
98
# codeautolink_concat_default: bool = False
99
# codeautolink_search_css_classes: list = []
100
# codeautolink_inventory_map: dict = {}
101
# codeautolink_warn_on_missing_inventory: bool = False
102
# codeautolink_warn_on_failed_resolve: bool = False
103
# codeautolink_warn_on_no_backreference: bool = False
104
# codeautolink_warn_on_default_parse_fail: bool = False
105
```
106
107
[Extension Setup](./extension-setup.md)
108
109
### RST Directives
110
111
Custom Sphinx directives for controlling link generation behavior, including example display, code concatenation, prefacing, and selective skipping.
112
113
```python { .api }
114
# Available directives:
115
# .. autolink-examples:: <object_name>
116
# .. autolink-concat:: [on|off|section]
117
# .. autolink-preface:: [level]
118
# .. autolink-skip:: [next|section|file|off]
119
```
120
121
[RST Directives](./rst-directives.md)
122
123
### Code Block Processing
124
125
Code block analysis and transformation system that parses Python code, identifies name usage patterns, and prepares them for link generation.
126
127
```python { .api }
128
def parse_names(source: str, doctree_node) -> list[Name]:
129
"""Parse names from Python source code."""
130
131
def clean_pycon(source: str) -> tuple[str, str]:
132
"""Clean up Python console syntax to pure Python."""
133
134
def clean_ipython(source: str) -> tuple[str, str]:
135
"""Clean up IPython magics and console syntax to pure Python."""
136
```
137
138
[Code Block Processing](./code-processing.md)
139
140
### Name Resolution
141
142
System for resolving code names and imports to their documentation locations using Sphinx inventory data and intersphinx references.
143
144
```python { .api }
145
def resolve_location(chain: Name, inventory) -> str:
146
"""Resolve a name chain to its final documented location."""
147
148
class CouldNotResolve(Exception):
149
"""Exception raised when name resolution fails."""
150
```
151
152
[Name Resolution](./name-resolution.md)
153
154
## Types
155
156
### Name and Access Types
157
158
```python { .api }
159
class Name:
160
"""A name accessed in source traced back to an import."""
161
import_components: list[str]
162
code_str: str
163
lineno: int
164
end_lineno: int
165
context: LinkContext | None = None
166
resolved_location: str | None = None
167
168
class Component:
169
"""Name access component."""
170
name: str
171
lineno: int
172
end_lineno: int
173
context: str
174
175
class Access:
176
"""Accessed import whose tail is about to be recorded as a Name."""
177
context: LinkContext
178
prior_components: list[Component]
179
components: list[Component]
180
```
181
182
### Enums
183
184
```python { .api }
185
class LinkContext(str, Enum):
186
"""Context in which a link appears to help HTML matching."""
187
none = "none"
188
after_call = "after_call"
189
import_from = "import_from"
190
import_target = "import_target"
191
192
class NameBreak(str, Enum):
193
"""Elements that break name access chains."""
194
call = "()"
195
namedexpr = ":="
196
import_from = ">"
197
```
198
199
### Extension Classes
200
201
```python { .api }
202
class SphinxCodeAutoLink:
203
"""Provide functionality and manage state between events."""
204
205
def build_inited(self, app) -> None: ...
206
def autodoc_process_docstring(self, app, what, name, obj, options, lines) -> None: ...
207
def parse_blocks(self, app, doctree) -> None: ...
208
def create_references(self, app, env) -> None: ...
209
def generate_backref_tables(self, app, doctree, docname): ...
210
def apply_links(self, app, exception) -> None: ...
211
```