0
# nbsphinx
1
2
nbsphinx is a Sphinx extension that provides a source parser for `*.ipynb` files. It enables seamless integration of Jupyter notebooks into Sphinx-generated documentation websites with custom Sphinx directives for displaying notebook code cells and their results in both HTML and LaTeX output formats.
3
4
## Package Information
5
6
- **Package Name**: nbsphinx
7
- **Language**: Python
8
- **Installation**: `pip install nbsphinx`
9
10
## Core Imports
11
12
```python
13
import nbsphinx
14
```
15
16
For use as Sphinx extension, add to `conf.py`:
17
18
```python
19
extensions = [
20
'nbsphinx',
21
]
22
```
23
24
## Basic Usage
25
26
The primary usage is as a Sphinx extension. Once configured, it automatically processes `.ipynb` files during the Sphinx build.
27
28
```python
29
# In conf.py - minimal configuration
30
extensions = ['nbsphinx']
31
32
# Optional configuration
33
nbsphinx_execute = 'auto' # 'auto', 'always', 'never'
34
nbsphinx_allow_errors = False
35
nbsphinx_timeout = None
36
```
37
38
Basic notebook integration:
39
40
```rst
41
# In index.rst, add notebooks to toctree
42
.. toctree::
43
:maxdepth: 2
44
45
my-notebook
46
another-notebook
47
```
48
49
## Architecture
50
51
nbsphinx operates as a Sphinx extension with several key components:
52
53
- **NotebookParser**: Parses `.ipynb` files and converts them to Sphinx documents
54
- **Exporter**: Converts notebooks to reStructuredText using nbconvert with custom templates
55
- **Custom Directives**: Provides notebook-specific RST directives (nbinput, nboutput, etc.)
56
- **Document Transforms**: Processes notebook content for cross-references, galleries, and links
57
- **Event Handlers**: Integrates with Sphinx build lifecycle for execution and asset management
58
59
## Capabilities
60
61
### Sphinx Extension Setup
62
63
Core functionality for registering nbsphinx as a Sphinx extension, including configuration values, directives, parsers, and event handlers.
64
65
```python { .api }
66
def setup(app):
67
"""
68
Initialize Sphinx extension.
69
70
Parameters:
71
- app: Sphinx application object
72
73
Returns:
74
dict: Extension metadata with version, parallel_read_safe, parallel_write_safe, env_version
75
"""
76
```
77
78
[Extension Setup](./sphinx-extension.md)
79
80
### Notebook Processing
81
82
Converts Jupyter notebooks to reStructuredText with support for execution, custom templates, and resource management.
83
84
```python { .api }
85
class Exporter(nbconvert.RSTExporter):
86
"""Convert Jupyter notebooks to reStructuredText."""
87
def __init__(self, execute='auto', kernel_name='', execute_arguments=[],
88
allow_errors=False, timeout=None, codecell_lexer='none'): ...
89
def from_notebook_node(self, nb, resources=None, **kw): ...
90
91
class NotebookParser(rst.Parser):
92
"""Sphinx source parser for Jupyter notebooks."""
93
def parse(self, inputstring, document): ...
94
```
95
96
[Notebook Processing](./notebook-processing.md)
97
98
### Custom Directives
99
100
Specialized reStructuredText directives for displaying notebook content including input cells, output cells, galleries, and admonitions.
101
102
```python { .api }
103
class NbInput(rst.Directive):
104
"""A notebook input cell with prompt and code area."""
105
106
class NbOutput(rst.Directive):
107
"""A notebook output cell with optional prompt."""
108
109
class NbGallery(sphinx.directives.other.TocTree):
110
"""A thumbnail gallery for notebooks."""
111
112
class NbInfo(_NbAdmonition):
113
"""An information box."""
114
115
class NbWarning(_NbAdmonition):
116
"""A warning box."""
117
```
118
119
[Custom Directives](./custom-directives.md)
120
121
### Text Processing
122
123
Utilities for converting between formats, handling Markdown/RST conversion, and processing notebook content.
124
125
```python { .api }
126
def markdown2rst(text):
127
"""Convert Markdown string to reST via pandoc with LaTeX math support."""
128
129
def convert_pandoc(text, from_format, to_format):
130
"""Simple wrapper for markdown2rst conversion via pandoc."""
131
132
def pandoc(source, fmt, to, filter_func=None):
133
"""Convert string between formats via pandoc with optional filter function."""
134
```
135
136
[Text Processing](./text-processing.md)
137
138
### Configuration Options
139
140
Comprehensive configuration system for controlling notebook execution, display formatting, widget support, and build behavior.
141
142
Configuration values include execution control (`nbsphinx_execute`, `nbsphinx_allow_errors`), display formatting (`nbsphinx_prompt_width`, `nbsphinx_codecell_lexer`), and widget support (`nbsphinx_widgets_path`).
143
144
[Configuration](./configuration.md)
145
146
## Types
147
148
```python { .api }
149
class NotebookError(sphinx.errors.SphinxError):
150
"""Error during notebook parsing."""
151
category = 'Notebook error'
152
153
# Document Node Types
154
class CodeAreaNode(docutils.nodes.Element):
155
"""Input area or plain-text output area of a Jupyter notebook code cell."""
156
157
class FancyOutputNode(docutils.nodes.Element):
158
"""A custom node for non-plain-text output of code cells."""
159
160
class AdmonitionNode(docutils.nodes.Element):
161
"""A custom node for info and warning boxes."""
162
163
class GalleryNode(docutils.nodes.Element):
164
"""A custom node for thumbnail galleries."""
165
166
class DummyTocTree(docutils.nodes.Element):
167
"""A dummy node to replace and disable sphinx.addnodes.toctree."""
168
169
# Transform Classes
170
class RewriteLocalLinks(docutils.transforms.Transform):
171
"""Turn links to source files into :doc:/:ref: links."""
172
173
class CreateNotebookSectionAnchors(docutils.transforms.Transform):
174
"""Create section anchors for Jupyter notebooks."""
175
176
class CreateSectionLabels(docutils.transforms.Transform):
177
"""Make labels for each document and each section thereof."""
178
179
class CreateDomainObjectLabels(docutils.transforms.Transform):
180
"""Create labels for domain-specific object signatures."""
181
182
class ReplaceAlertDivs(docutils.transforms.Transform):
183
"""Replace certain <div> elements with AdmonitionNode containers."""
184
185
class CopyLinkedFiles(docutils.transforms.Transform):
186
"""Mark linked local files to be copied to HTML output."""
187
188
class ForceEquations(docutils.transforms.Transform):
189
"""Unconditionally enable equations on notebooks."""
190
191
class GetSizeFromImages(sphinx.transforms.post_transforms.images.BaseImageConverter):
192
"""Get size from images and store as node attributes for LaTeX."""
193
```