or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

edit-page.mdhtml-translation.mdindex.mdlink-processing.mdlogo-management.mdsyntax-highlighting.mdtemplate-management.mdtheme-setup.mdtoc-processing.mdutilities.md

utilities.mddocs/

0

# Utilities and Configuration Helpers

1

2

Helper functions for theme configuration management, template processing, sidebar customization, and Sphinx integration utilities.

3

4

## Capabilities

5

6

### Configuration Management

7

8

Functions for accessing and validating theme configuration options.

9

10

```python { .api }

11

def get_theme_options_dict(app: Sphinx) -> Dict[str, Any]:

12

"""

13

Return theme options for the application with a fallback if they don't exist.

14

15

Checks both app.builder.theme_options (the preferred location created by Sphinx

16

as a copy of app.config.html_theme_options) and app.config.html_theme_options

17

(the user configuration from conf.py) with appropriate fallbacks.

18

19

Parameters:

20

- app (Sphinx): Sphinx application instance

21

22

Returns:

23

Dict[str, Any]: Theme options dictionary or empty dict if none exist

24

"""

25

26

def config_provided_by_user(app: Sphinx, key: str) -> bool:

27

"""

28

Check if the user has manually provided the config.

29

30

Determines whether a configuration key was explicitly set by the user

31

in their conf.py file rather than using default values.

32

33

Parameters:

34

- app (Sphinx): Sphinx application instance

35

- key (str): Configuration key to check

36

37

Returns:

38

bool: True if user provided the config, False if using defaults

39

"""

40

```

41

42

### Node Processing Utilities

43

44

Helper functions for processing document nodes and handling docutils compatibility.

45

46

```python { .api }

47

def traverse_or_findall(

48

node: Node, condition: Union[Callable, type], **kwargs

49

) -> Iterable[Node]:

50

"""

51

Triage node.traverse (docutils <0.18.1) vs node.findall.

52

53

Provides compatibility between different docutils versions by using

54

the appropriate method for traversing document nodes.

55

56

Parameters:

57

- node (Node): Document node to traverse

58

- condition (Union[Callable, type]): Condition or type to match

59

- **kwargs: Additional arguments passed to traverse/findall

60

61

Returns:

62

Iterable[Node]: Iterator of matching nodes

63

"""

64

65

def escape_ansi(string: str) -> str:

66

"""

67

Helper function to remove ansi coloring from sphinx warnings.

68

69

Strips ANSI escape sequences from strings, useful for cleaning

70

up log messages and warnings.

71

72

Parameters:

73

- string (str): String potentially containing ANSI codes

74

75

Returns:

76

str: String with ANSI codes removed

77

"""

78

```

79

80

### Logging Utilities

81

82

Warning and logging management for theme messages.

83

84

```python { .api }

85

def maybe_warn(app: Sphinx, msg, *args, **kwargs):

86

"""

87

Wraps the Sphinx logger to allow warning suppression.

88

89

Provides configurable warning behavior based on theme options.

90

When surface_warnings is True, messages are logged as warnings.

91

Otherwise, they are logged as info messages.

92

93

Parameters:

94

- app (Sphinx): Sphinx application instance

95

- msg: Warning message to log

96

- *args: Additional arguments for logging

97

- **kwargs: Additional keyword arguments for logging

98

"""

99

```

100

101

### Sidebar Management

102

103

Functions for managing secondary sidebar content and template processing.

104

105

```python { .api }

106

def set_secondary_sidebar_items(

107

app: Sphinx, pagename: str, templatename: str, context, doctree

108

) -> None:

109

"""

110

Set the secondary sidebar items to render for the given pagename.

111

112

Processes theme_secondary_sidebar_items configuration to determine

113

which sidebar templates should be displayed on each page, supporting

114

both global and page-specific sidebar configurations.

115

116

Parameters:

117

- app (Sphinx): Sphinx application instance

118

- pagename (str): Name of current page

119

- templatename (str): Template being used

120

- context: Page context dictionary

121

- doctree: Document tree for the page

122

"""

123

124

def _update_and_remove_templates(

125

app: Sphinx,

126

context: Dict[str, Any],

127

templates: Union[List, str],

128

section: str,

129

templates_skip_empty_check: Optional[List[str]] = None,

130

) -> List[str]:

131

"""

132

Update templates to include html suffix if needed; remove templates which render empty.

133

134

Processes template lists to:

135

- Add .html suffix to templates without extensions

136

- Remove templates that render to empty strings (performance optimization)

137

- Skip empty checks for specified templates that are slow to render

138

139

Parameters:

140

- app (Sphinx): Sphinx application instance

141

- context (Dict[str, Any]): Page context for template rendering

142

- templates (Union[List, str]): Template names or comma-separated string

143

- section (str): Template section name (e.g., 'theme_navbar_start')

144

- templates_skip_empty_check (Optional[List[str]]): Templates to skip empty check

145

146

Returns:

147

List[str]: Filtered list of template names with .html suffixes

148

"""

149

150

def _get_matching_sidebar_items(

151

pagename: str, sidebars: Dict[str, List[str]]

152

) -> List[str]:

153

"""

154

Get the matching sidebar templates to render for the given pagename.

155

156

Matches page names against sidebar configuration patterns, supporting

157

glob patterns and wildcard matching. Emits warnings for ambiguous matches.

158

159

Parameters:

160

- pagename (str): Name of the current page

161

- sidebars (Dict[str, List[str]]): Mapping of patterns to sidebar templates

162

163

Returns:

164

List[str]: List of sidebar template names for the page

165

"""

166

167

def _has_wildcard(pattern: str) -> bool:

168

"""

169

Check whether the pattern contains a wildcard.

170

171

Detects glob-style wildcards in patterns used for sidebar matching.

172

173

Parameters:

174

- pattern (str): Pattern string to check

175

176

Returns:

177

bool: True if pattern contains wildcards (*, ?, [])

178

"""

179

```

180

181

## Usage Examples

182

183

### Configuration Access

184

185

```python

186

# Check if user provided custom configuration

187

if config_provided_by_user(app, 'html_permalinks_icon'):

188

# User set custom permalink icon

189

pass

190

else:

191

# Use theme default

192

app.config.html_permalinks_icon = "#"

193

194

# Get theme options with fallback

195

theme_options = get_theme_options_dict(app)

196

logo_config = theme_options.get("logo", {})

197

```

198

199

### Sidebar Configuration

200

201

```python

202

# conf.py - Global sidebar configuration

203

html_theme_options = {

204

"secondary_sidebar_items": ["page-toc", "edit-this-page"]

205

}

206

207

# Page-specific sidebar configuration

208

html_theme_options = {

209

"secondary_sidebar_items": {

210

# Specific pages

211

"index": ["search-field"],

212

"contact": ["search-field", "edit-this-page"],

213

214

# Pattern matching

215

"user-guide/**": ["page-toc", "edit-this-page"],

216

"api/**": ["page-toc", "sourcelink"],

217

"tutorials/*": ["page-toc", "edit-this-page", "download-page"],

218

219

# Wildcards

220

"**/examples": ["page-toc", "download-page"],

221

"reference/*/methods": ["page-toc", "edit-this-page"]

222

}

223

}

224

```

225

226

### Custom Template Processing

227

228

```python

229

# Templates can be specified as lists or comma-separated strings

230

navbar_templates = ["navbar-logo", "navbar-nav", "search-field"]

231

# or

232

navbar_templates = "navbar-logo, navbar-nav, search-field"

233

234

# Templates are automatically processed to:

235

# 1. Add .html extension if missing

236

# 2. Remove templates that render empty (unless skipped)

237

# 3. Handle slow-rendering templates efficiently

238

```

239

240

### Warning Configuration

241

242

```python

243

# conf.py - Control warning visibility

244

html_theme_options = {

245

"surface_warnings": True, # Show warnings prominently

246

# or

247

"surface_warnings": False, # Log warnings as info messages

248

}

249

```

250

251

### Node Processing

252

253

```python

254

# Docutils compatibility for node traversal

255

from pydata_sphinx_theme.utils import traverse_or_findall

256

from docutils import nodes

257

258

# Works with both old and new docutils versions

259

for ref_node in traverse_or_findall(document, nodes.reference):

260

# Process reference nodes

261

pass

262

```

263

264

## Template Section Names

265

266

Valid section names for `_update_and_remove_templates`:

267

268

- `theme_navbar_start`, `theme_navbar_center`, `theme_navbar_persistent`, `theme_navbar_end`

269

- `theme_article_header_start`, `theme_article_header_end`

270

- `theme_article_footer_items`, `theme_content_footer_items`

271

- `theme_footer_start`, `theme_footer_center`, `theme_footer_end`

272

- `theme_primary_sidebar_end`, `theme_secondary_sidebar_items`

273

- `sidebars`

274

275

## Constants

276

277

```python { .api }

278

SPHINX_LOGGER = logging.getLogger(__name__)

279

```

280

281

The module-level logger instance used for theme-related log messages.