or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

code-processing.mdextension-setup.mdindex.mdname-resolution.mdrst-directives.md

extension-setup.mddocs/

0

# Extension Setup and Configuration

1

2

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.

3

4

## Capabilities

5

6

### Main Setup Function

7

8

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

9

10

```python { .api }

11

def setup(app: Sphinx) -> dict[str, Any]:

12

"""

13

Set up extension, directives and events.

14

15

This function is called by Sphinx when the extension is loaded. It registers

16

configuration values, directives, event handlers, and static resources.

17

18

Parameters:

19

- app: Sphinx application instance

20

21

Returns:

22

- dict: Extension metadata containing version, env_version, and parallel_read_safe

23

"""

24

```

25

26

### Configuration Values

27

28

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

29

30

```python { .api }

31

# Core behavior configuration

32

codeautolink_autodoc_inject: bool = False

33

"""Automatically inject autolink-examples directives into autodoc docstrings"""

34

35

codeautolink_global_preface: str = ""

36

"""Global code to prepend to all parsed code blocks"""

37

38

codeautolink_custom_blocks: dict = {}

39

"""Custom block type transformers mapping block names to transformer functions"""

40

41

codeautolink_concat_default: bool = False

42

"""Default concatenation behavior for code blocks"""

43

44

codeautolink_search_css_classes: list = []

45

"""Additional CSS classes to search for code blocks"""

46

47

# Inventory and resolution configuration

48

codeautolink_inventory_map: dict = {}

49

"""Mapping to transform inventory locations (e.g., redirect old paths to new ones)"""

50

51

# Warning configuration

52

codeautolink_warn_on_missing_inventory: bool = False

53

"""Warn when inventory entries are missing"""

54

55

codeautolink_warn_on_failed_resolve: bool = False

56

"""Warn when name resolution fails"""

57

58

codeautolink_warn_on_no_backreference: bool = False

59

"""Warn when no backreferences are found"""

60

61

codeautolink_warn_on_default_parse_fail: bool = False

62

"""Warn when parsing fails on default language blocks"""

63

```

64

65

### Extension State Management

66

67

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

68

69

```python { .api }

70

class SphinxCodeAutoLink:

71

"""

72

Provide functionality and manage state between events.

73

74

This class handles the complete lifecycle of code block processing,

75

from initial parsing through final link application.

76

"""

77

78

def build_inited(self, app) -> None:

79

"""

80

Handle initial setup when build starts.

81

82

Initializes caches, reads configuration, and prepares the extension

83

for processing documents.

84

"""

85

86

def autodoc_process_docstring(self, app, what, name, obj, options, lines) -> None:

87

"""

88

Handle autodoc-process-docstring event.

89

90

Automatically injects autolink-examples directives into autodoc

91

docstrings when codeautolink_autodoc_inject is enabled.

92

"""

93

94

def parse_blocks(self, app, doctree) -> None:

95

"""

96

Parse code blocks for later link substitution.

97

98

Analyzes Python code blocks in the document tree, extracts name

99

usage patterns, and prepares them for resolution.

100

"""

101

102

def merge_environments(self, app, env, docnames, other) -> None:

103

"""

104

Merge transform information between build environments.

105

106

Handles parallel build scenarios by merging cached transform data.

107

"""

108

109

def purge_doc_from_environment(self, app, env, docname) -> None:

110

"""

111

Remove transforms from cache when documents are removed.

112

113

Cleans up cached data for documents that are no longer part of the build.

114

"""

115

116

def create_references(self, app, env) -> None:

117

"""

118

Clean source transforms and create code references.

119

120

Resolves parsed names to their documentation locations using

121

inventory data and creates the final reference mappings.

122

"""

123

124

def generate_backref_tables(self, app, doctree, docname):

125

"""

126

Generate backreference tables.

127

128

Creates tables showing where API elements appear in code examples,

129

replacing autolink-examples directive nodes.

130

"""

131

132

def apply_links(self, app, exception) -> None:

133

"""

134

Apply links to HTML output and write refs file.

135

136

Post-processes generated HTML files to inject clickable links

137

into code elements based on resolved references.

138

"""

139

```

140

141

### Helper Functions

142

143

Utility functions for extension operation and debugging.

144

145

```python { .api }

146

def print_exceptions(*, append_source: bool = False):

147

"""

148

Print the traceback of uncaught and unexpected exceptions.

149

150

Decorator that ensures exceptions in event handlers are properly

151

displayed for debugging, as Sphinx masks tracebacks by default.

152

153

Parameters:

154

- append_source: If True, add document source information to error messages

155

156

Returns:

157

- Decorator function

158

"""

159

160

def transpose_inventory(inv: dict, relative_to: str, *, use_tuple: bool = False) -> dict[str, str]:

161

"""

162

Transpose Sphinx inventory from {type: {name: (..., location)}} to {name: location}.

163

164

Converts Sphinx's nested inventory format to a flat mapping suitable

165

for name resolution. Filters to Python domain only.

166

167

Parameters:

168

- inv: Sphinx inventory dictionary

169

- relative_to: Directory to make file paths relative to

170

- use_tuple: Force using Sphinx inventory tuple interface

171

172

Returns:

173

- dict: Flat mapping from object names to their documentation URLs

174

"""

175

```

176

177

## Usage Examples

178

179

### Basic Configuration

180

181

```python

182

# conf.py

183

extensions = [

184

'sphinx_codeautolink',

185

'sphinx.ext.autodoc', # Required

186

]

187

188

# Enable warnings for debugging

189

codeautolink_warn_on_missing_inventory = True

190

codeautolink_warn_on_failed_resolve = True

191

```

192

193

### Advanced Configuration

194

195

```python

196

# conf.py

197

extensions = ['sphinx_codeautolink']

198

199

# Automatically add examples to autodoc docstrings

200

codeautolink_autodoc_inject = True

201

202

# Global imports for all code blocks

203

codeautolink_global_preface = """

204

import numpy as np

205

import matplotlib.pyplot as plt

206

"""

207

208

# Custom block processors

209

def process_sage_code(source):

210

# Custom transformation for SageMath code

211

return source, source.replace('sage:', 'python:')

212

213

codeautolink_custom_blocks = {

214

'sage': process_sage_code

215

}

216

217

# Redirect old documentation URLs

218

codeautolink_inventory_map = {

219

'old.module.Class': 'new.module.Class',

220

'deprecated.function': 'current.function'

221

}

222

223

# Enable all warnings

224

codeautolink_warn_on_missing_inventory = True

225

codeautolink_warn_on_failed_resolve = True

226

codeautolink_warn_on_no_backreference = True

227

codeautolink_warn_on_default_parse_fail = True

228

```

229

230

### Version Information

231

232

```python { .api }

233

__version__: str = "0.17.5"

234

"""Package version string"""

235

```