or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli-tools.mdconfiguration.mddocument-rendering.mdindex.mdinventory-warnings.mdparsing.mdsphinx-extension.md

sphinx-extension.mddocs/

0

# Sphinx Extension

1

2

Complete Sphinx extension providing MyST markdown support with setup functions, custom directives, roles, reference resolution, and seamless integration with Sphinx's documentation system.

3

4

## Capabilities

5

6

### Extension Setup

7

8

Core setup functions for initializing MyST-Parser as a Sphinx extension, configuring the parsing environment, and integrating with Sphinx's build system.

9

10

```python { .api }

11

def setup(app) -> dict:

12

"""

13

Initialize the Sphinx extension.

14

15

Main entry point called by Sphinx when loading the extension.

16

Sets up MyST parser, configuration, and returns extension metadata.

17

18

Args:

19

app: Sphinx application instance

20

21

Returns:

22

Extension metadata dictionary with version and compatibility info

23

"""

24

25

def setup_sphinx(app, load_parser: bool = False) -> None:

26

"""

27

Initialize all MyST settings and transforms in Sphinx.

28

29

Comprehensive setup function that configures MyST parser integration,

30

registers configuration values, adds transforms, and sets up event handlers.

31

32

Args:

33

app: Sphinx application instance

34

load_parser: Whether to load the MyST parser immediately

35

"""

36

37

def create_myst_config(app) -> MdParserConfig:

38

"""

39

Create MyST config object for Sphinx environment.

40

41

Extracts MyST configuration from Sphinx configuration and creates

42

a MdParserConfig instance with appropriate settings.

43

44

Args:

45

app: Sphinx application instance

46

47

Returns:

48

Configured MdParserConfig instance

49

"""

50

```

51

52

Usage example:

53

54

```python

55

# In Sphinx conf.py

56

extensions = ['myst_parser']

57

58

# MyST configuration options

59

myst_enable_extensions = [

60

"deflist",

61

"tasklist",

62

"substitution",

63

"colon_fence",

64

"linkify",

65

"replacements",

66

"smartquotes"

67

]

68

69

myst_heading_anchors = 3

70

myst_footnote_transition = True

71

myst_dmath_double_inline = True

72

73

# Programmatic setup (for custom extensions)

74

from myst_parser.sphinx_ext.main import setup_sphinx, create_myst_config

75

76

def custom_setup(app):

77

# Initialize MyST extension

78

setup_sphinx(app, load_parser=True)

79

80

# Get MyST configuration

81

myst_config = create_myst_config(app)

82

print(f"MyST extensions: {myst_config.enable_extensions}")

83

84

return {"version": "1.0", "parallel_read_safe": True}

85

```

86

87

### Custom Directives

88

89

MyST-specific Sphinx directives providing enhanced functionality for technical documentation, including figure handling and substitution references.

90

91

```python { .api }

92

class FigureMarkdown(SphinxDirective):

93

"""

94

Figure directive implementation for MyST markdown.

95

96

Provides figure functionality specifically designed for MyST markdown

97

with support for MyST-specific options and formatting.

98

"""

99

100

has_content = True

101

required_arguments = 1

102

optional_arguments = 0

103

final_argument_whitespace = True

104

option_spec = {

105

'alt': str,

106

'height': str,

107

'width': str,

108

'scale': int,

109

'align': lambda x: x, # Validated by align function

110

'target': str,

111

'class': str,

112

'name': str

113

}

114

115

def run(self) -> list: ...

116

117

def align(argument: str) -> str:

118

"""

119

Validate alignment option for figure directives.

120

121

Args:

122

argument: Alignment value to validate

123

124

Returns:

125

Validated alignment value

126

127

Raises:

128

ValueError: When alignment value is invalid

129

"""

130

131

def figwidth_value(argument: str) -> str:

132

"""

133

Validate figure width values.

134

135

Args:

136

argument: Width value to validate

137

138

Returns:

139

Validated width value

140

141

Raises:

142

ValueError: When width value is invalid

143

"""

144

```

145

146

Usage example:

147

148

```python

149

# In MyST markdown document:

150

"""

151

:::{figure} path/to/image.png

152

:alt: Alternative text

153

:width: 80%

154

:align: center

155

:name: my-figure

156

157

Figure caption goes here.

158

:::

159

160

Reference the figure: {numref}`my-figure`

161

"""

162

163

# Programmatic directive usage

164

from myst_parser.sphinx_ext.directives import FigureMarkdown, align, figwidth_value

165

166

# Validate directive options

167

try:

168

alignment = align("center") # Valid: "left", "center", "right"

169

width = figwidth_value("80%") # Valid: percentage or length

170

print(f"Alignment: {alignment}, Width: {width}")

171

except ValueError as e:

172

print(f"Validation error: {e}")

173

```

174

175

### Custom Roles

176

177

MyST-specific Sphinx roles for enhanced text processing and cross-referencing capabilities.

178

179

```python { .api }

180

class SubstitutionReferenceRole(SphinxRole):

181

"""

182

Role for substitution references in MyST markdown.

183

184

Handles substitution reference syntax and provides integration

185

with Sphinx's substitution system.

186

"""

187

188

def run(self) -> tuple[list, list]: ...

189

```

190

191

Usage example:

192

193

```python

194

# In MyST markdown with substitutions:

195

"""

196

---

197

myst:

198

substitutions:

199

project_name: "MyST-Parser"

200

version: "4.0.1"

201

---

202

203

# {sub-ref}`project_name` Documentation

204

205

Version: {sub-ref}`version`

206

"""

207

208

# In conf.py for global substitutions:

209

myst_substitutions = {

210

"project_name": "MyST-Parser",

211

"version": "4.0.1",

212

"author": "Chris Sewell"

213

}

214

```

215

216

### Reference Resolution

217

218

Advanced reference resolution system for MyST cross-references, providing integration with Sphinx's reference system and support for MyST-specific reference formats.

219

220

```python { .api }

221

class MystReferenceResolver:

222

"""

223

Resolver for MyST reference syntax.

224

225

Handles resolution of MyST-style references including:

226

- Cross-references to sections, figures, tables

227

- External references and inventory links

228

- Custom domain references

229

"""

230

231

def __init__(self, document): ...

232

233

def resolve_reference(

234

self,

235

ref_node,

236

has_explicit_title: bool,

237

title: str,

238

target: str

239

) -> tuple[str, str] | None: ...

240

241

def resolve_any_xref(

242

self,

243

ref_node,

244

has_explicit_title: bool,

245

title: str,

246

target: str

247

) -> list[tuple[str, str]]: ...

248

```

249

250

Usage example:

251

252

```python

253

# MyST reference syntax examples:

254

"""

255

# Section Header {#my-section}

256

257

See {ref}`my-section` for details.

258

259

Cross-document reference: {doc}`other-document`

260

261

External reference: {external+sphinx:doc}`configuration`

262

263

Custom domain: {py:class}`MyClass`

264

"""

265

266

# Programmatic reference resolution

267

from myst_parser.sphinx_ext.myst_refs import MystReferenceResolver

268

from docutils import nodes

269

270

# Create resolver

271

resolver = MystReferenceResolver(document)

272

273

# Create reference node

274

ref_node = nodes.reference('', '', refuri='#my-section')

275

276

# Resolve reference

277

result = resolver.resolve_reference(

278

ref_node,

279

has_explicit_title=False,

280

title="Section Header",

281

target="my-section"

282

)

283

284

if result:

285

resolved_title, resolved_uri = result

286

print(f"Resolved: {resolved_title} -> {resolved_uri}")

287

```

288

289

### Math Configuration

290

291

MyST-Parser provides built-in support for mathematical expressions through markdown-it-py plugins and standard Sphinx math extensions. Configuration is handled through MyST settings.

292

293

Usage example:

294

295

```python

296

# MyST math syntax:

297

"""

298

Inline math: $x^2 + y^2 = z^2$

299

300

Display math:

301

$$

302

\\int_{-\\infty}^{\\infty} e^{-x^2} dx = \\sqrt{\\pi}

303

$$

304

305

Math directive:

306

```{math}

307

:label: euler-formula

308

309

e^{i\\pi} + 1 = 0

310

```

311

312

Reference equation: {eq}`euler-formula`

313

"""

314

315

# Configuration in conf.py:

316

myst_dmath_allow_labels = True

317

myst_dmath_allow_space = True

318

myst_dmath_allow_digits = True

319

myst_dmath_double_inline = True

320

```

321

322

## Configuration Options

323

324

MyST-specific Sphinx configuration options:

325

326

```python

327

# In conf.py - Core MyST options

328

myst_enable_extensions = [

329

"amsmath", # LaTeX math environments

330

"colon_fence", # ::: fence syntax

331

"deflist", # Definition lists

332

"dollarmath", # $ and $$ math

333

"fieldlist", # Field lists

334

"html_admonition", # HTML admonitions

335

"html_image", # HTML images

336

"linkify", # Auto-link URLs

337

"replacements", # Text replacements

338

"smartquotes", # Smart quotes

339

"strikethrough", # ~~text~~

340

"substitution", # Text substitutions

341

"tasklist", # - [ ] task lists

342

]

343

344

# Heading configuration

345

myst_heading_anchors = 3

346

myst_heading_slug_func = None

347

348

# Link configuration

349

myst_all_links_external = False

350

myst_url_schemes = ("http", "https", "mailto", "ftp")

351

352

# Reference configuration

353

myst_ref_domains = None

354

355

# Math configuration

356

myst_dmath_allow_labels = True

357

myst_dmath_allow_space = True

358

myst_dmath_allow_digits = True

359

myst_dmath_double_inline = False

360

361

# HTML configuration

362

myst_html_meta = {}

363

364

# Footnote configuration

365

myst_footnote_transition = True

366

myst_footnote_sort = False

367

368

# Substitution configuration

369

myst_substitutions = {}

370

371

# Title configuration

372

myst_title_to_header = False

373

374

# Fence configuration

375

myst_fence_as_directive = []

376

myst_number_code_blocks = []

377

```

378

379

## Types

380

381

Sphinx extension related type definitions:

382

383

```python { .api }

384

class FigureMarkdown(SphinxDirective):

385

"""MyST figure directive implementation."""

386

387

class SubstitutionReferenceRole(SphinxRole):

388

"""MyST substitution reference role implementation."""

389

390

class MystReferenceResolver:

391

"""MyST reference resolution system."""

392

```