2.5. Sphinx重要扩展介绍#
2.5.1. Sphinx内置扩展#
可以通过以下链接找到 Sphinx的扩展:
sphinx extensions doc : 官方文档介绍, 含 Built-in extensions 和 Third-party extensions
Awesome Sphinx : A curated list of awesome tools for Sphinx Python Documentation Generator.
sphinx-contrib : a collection of Sphinx extensions maintained by their respective authors. It is not an official part of Sphinx.
Survey of Sphinx extensions : This is list of Sphinx extensions at October, 2014.
重要内置扩展介绍#
sphinx.ext.napoleon: 支持 NumPy 和 Google 风格的 docstrings,方便将代码注释转换为文档。
sphinx.ext.autodoc: 自动从注释中生成文档,特别适用于生成 API 文档。
sphinx.ext.autosummary: 自动生成摘要页面和文档目录,常与 autodoc 一起使用。
sphinx.ext.todo: 支持在文档中添加 TODO 列表和条目,可以选择性地显示或隐藏这些条目。
sphinx.ext.viewcode: 在文档中提供源代码的链接,方便查看代码实现。
sphinx.ext.intersphinx: 允许文档之间的交叉引用,可以引用其他项目的文档。
sphinx.ext.graphviz: 支持 Graphviz 语法,可以在文档中插入和显示图表。
目录树 (toctree)#
由于 reST 没有处理多个文档, 或将文档分割成多个输出文件的机制, Sphinx使用一个自定义指令来添加组成整篇文档的单个文件间的关系, 以及目录. 这个指令的核心就是 toctree
.
小技巧
简单包含某个文件, 可以使用 include 指令.
代码与语法着色#
更多功能, 参考 Showing code examples
.. code-block:: python
:lineno-start: 10
:emphasize-lines: 9
:linenos:
:caption: demo_python.py
:name: code-PythonGenerateEllipse
import pytool
import numpy as np
import matplotlib.pyplot as plt
# =====================generate Ellipse=====================
a = 6 # major axis
b = 2 # minor axis
x0 = 10 # center x0
y0 = 10 # center y0
N = 1000 # number of points
# angle for rotating ellipse data
theta = np.pi * 30 / 180
x, y = pytool.ellipse_surface(a, b, x0, y0, N, 'rand')
x = x - np.mean(x)
y = y - np.mean(y)
并可以通过 :code-block:numref:`code-PythonGenerateEllipse` 引用代码段.
将被渲染成
10import pytool
11import numpy as np
12import matplotlib.pyplot as plt
13
14# =====================generate Ellipse=====================
15a = 6 # major axis
16b = 2 # minor axis
17x0 = 10 # center x0
18y0 = 10 # center y0
19N = 1000 # number of points
20
21# angle for rotating ellipse data
22theta = np.pi * 30 / 180
23
24x, y = pytool.ellipse_surface(a, b, x0, y0, N, 'rand')
25
26x = x - np.mean(x)
27y = y - np.mean(y)
并可以通过 :code-block:numref: code-PythonGenerateEllipse 引用代码段.
公式, 图, 表, 代码段编号及引用#
在 conf.py 文件中配置相关选项, 设置是否启用图表公式编号, 以及编号目录深度即格式, 代码如下:
math_number_all = True # Set this option to True if you want all displayed math to be numbered. The default is False.
math_eqref_format = 'Eq.{number}' # gets rendered as, for example, Eq.10.
math_numfig = True
numfig = True
numfig_secnum_depth = 2
numfig_format = {
'figure': '图 %s',
'table': '表 %s',
'code-block': '代码 %s',
'section': '节 %s',
}
公式示例, 代码
.. math:: e^{i\pi} + 1 = 0
:label: euler
使用``label``, 公式将被编号, 可以使用 ``:eq:`euler``` (等效于 :math:numref:`euler` ) 来引用公式 :eq:`euler`.
图像示例, 代码
.. _fig-DeepLearningPlatforms:
.. figure:: ./logo.png
:alt: 深度学习平台
:align: center
通过 :figure:numref:`fig-DeepLearningPlatforms` 可以引用.

通过 fig-DeepLearningPlatforms
可以引用.
表格示例, 代码
其它标记指令#
下表给出了语义标记, 详见 Sphinx Roles .
标记名 |
示例代码 |
渲染结果 |
说明 |
缩写 |
|
|
An abbreviation |
命令 |
|
|
The name of an OS-level command |
下载 |
|
|
This role lets you link to files within your source tree that are not reST documents that can be viewed, but files that can be downloaded |
文档 |
|
|
Link to the specified document; the document name can be specified in absolute or relative fashion |
编号引用 |
|
|
Link to the specified figures, tables, code-blocks and sections; the standard reST labels are used. |
环境变量 |
|
|
An environment variable. Index entries are generated. Also generates a link to the matching envvar directive, if it exists. |
语法标记 |
|
|
The name of a grammar token (used to create links between productionlist directives). |
Python中的关键字 |
|
|
The name of a keyword in Python. This creates a link to a reference label with that name, if it exists. |
选项 |
|
|
A command-line option to an executable program. This generates a link to a option directive, if it exists. |
图形化标签 |
|
|
button, menu, title… |
按键 |
|
|
Mark a sequence of keystrokes |
数学 |
|
|
数学表达式 |
公式引用 |
|
|
The name of an OS-level command |
邮件头 |
|
|
The name of an OS-level command |
make变量 |
|
|
The name of a make variable |
首页 |
|
|
A reference to a Unix manual page including the section |
菜单选择 |
|
|
Menu selection |
程序 |
|
|
The name of an executable program |
正则表达式 |
|
|
A regular expression. Quotes should not be included. |
变量渲染 |
|
|
A piece of literal text, such as code. Within the contents, you can use curly braces to indicate a “variable” part, as in file. |
PythonPEP |
|
--- |
A reference to a Python Enhancement Proposal |
命令 |
|
|
A reference to an Internet Request for Comments. |
定义实例 |
|
|
Mark the defining instance of a term in the text. (No index entries are generated.) |
文件或目录 |
|
|
The name of a file or directory. Within the contents, you can use curly braces to indicate a “variable” part |
新闻组 |
|
|
The name of a Usenet newsgroup. |
下面给出了新增的一些替换指令, 详见 Sphinx Roles Substitutions.
发布:
|release|
被渲染为 0.1版本:
|version|
被渲染为 0.1日期:
|today|
被渲染为 2025 年 04 月 29 日
More domains#
The sphinx-contrib repository contains more domains available as extensions; currently Ada, CoffeeScript, Erlang, HTTP, Lasso, MATLAB, PHP, and Ruby domains. Also available are domains for Chapel, Common Lisp, dqn, Go, Jinja, Operation, and Scala. Refer to Sphinx More domains.
2.5.2. 第三方扩展#
sphinxext.rediraffe: 支持 URL 重定向,适用于重构文档结构时保持旧链接可用。
sphinx_design: 提供设计组件和样式,可以更好地美化和布局文档内容。
sphinx_copybutton: 在代码块旁边添加一个复制按钮,方便用户复制代码。
autoapi.extension: 自动从代码中生成 API 文档,类似于 autodoc,但提供更多的配置选项和支持。
_extension.gallery_directive: 自定义扩展,通常用于展示图库或图像集合。
_extension.component_directive: 自定义扩展,通常用于定义和展示组件。
myst_parser: 支持 Markdown 语法,可以在 Sphinx 项目中使用 Markdown 编写文档。
ablog: 为 Sphinx 添加博客功能,可以在文档站点中发布博客文章。
jupyter_sphinx: 支持在文档中嵌入和运行 Jupyter Notebook 内容。
sphinxcontrib.youtube: 支持在文档中嵌入 YouTube 视频。
nbsphinx: 支持将 Jupyter Notebooks 转换为 Sphinx 文档。
numpydoc: 专门支持 NumPy 风格的 docstrings,有助于标准化文档格式。
sphinx_togglebutton: 提供可折叠内容块,用户可以展开和折叠内容。
jupyterlite_sphinx: 支持在文档中嵌入 JupyterLite 内容,使得文档中可以包含交互式 Jupyter 环境。
sphinx_favicon: 支持在文档中设置自定义 favicon 图标。这些插件帮助增强和扩展 Sphinx 的功能,使得文档生成更为便捷和多样化。
如下扩展可以通过类似 pip install extensions_name
的命令安装,
在 conf.py 文件中的 extensions
中加入该扩展, 以下不在赘述.
2.5.3. 推荐使用的第三方扩展#
sphinxcontrib-proof#
sphinxcontrib-proof 提供定理, 定义, 证明等支持.
在 conf.py 文件中的 extensions
中加入该扩展 ( sphinxcontrib.proof
) .
然后在 _static 目录下新建 proof.css 和 proof.js 两个文件, 加入如下内容, 你可以自己定义其它的样式.
proof.css
.proof {
margin-top: 1em;
margin-bottom: 1em;
}
/* Titles */
.proof .proof-title {
background-color: #0000EE;
border: 1px solid #86989b;
color: white;
font-size: 120%;
}
/* Content */
.proof-content {
border: 1px solid #9fb1b4;
background-color: #F0F8FF;
padding: 0.5em 1em;
}
/* Toggle proof */
.proof-type-proof > .proof-title {
display: block;
clear: both;
}
.proof-type-proof > .proof-title:after {
content: " ▼";
}
.proof-type-proof > .proof-title.open:after {
content: " ▲";
}
proof.js
$(document).ready(function() {
$(".proof-type-proof > *").hide();
$(".proof-type-proof .proof-title").show();
$(".proof-type-proof .proof-title").click(function() {
$(this).parent().children().not(".proof-title").toggle(400);
$(this).parent().children(".proof-title").toggleClass("open");
})
});
使用举例
.. _righttriangle:
.. proof:definition:: Right triangle
A *right triangle* is a triangle in which one angle is a right angle.
.. _pythagorean:
.. proof:theorem:: Pythagorean theorem
In a :ref:`righttriangle`, the square of the hypotenuse is equal to the sum of the squares of the other two sides.
.. _proof:
.. proof:proof::
The proof is left to the reader.
You can label and reference definition and theorems (e.g. :numref:`theorem {number} <pythagorean>`). You can also reference proofs (see the :ref:`proof of the Pythagorean theorem <proof>`).
代码将被渲染为
A right triangle is a triangle in which one angle is a right angle.
In a Right triangle, the square of the hypotenuse is equal to the sum of the squares of the other two sides.
The proof is left to the reader.
You can label and reference definition and theorems (e.g. theorem 2.5.2). You can also reference proofs (see the proof of the Pythagorean theorem).
sphinxcontrib-bibtex#
在 Sphinx中可以使用 BibTex , 通过 pip install sphinxcontrib-bibtex
安装扩展,
并在 conf.py 中添加该扩展 sphinxcontrib.bibtex
,
官方文档在 https://sphinxcontrib-bibtex.readthedocs.io/en/latest/usage.html 。
然后, 新建 reference.rst
, 加入如下代码:
.. code-block:: rst
:caption: reference.rst.
:linenos:
:emphasize-lines: 3,5
.. bibliography:: ./refs.bib
:list: enumerated
:start: 1
假如 refs.bib
文件中的内容如下:
@Proceedings{1993:PatiOMP,
author={Y. C. {Pati} and R. {Rezaiifar} and P. S. {Krishnaprasad}},
booktitle={Proceedings of 27th Asilomar Conference on Signals, Systems and Computers},
title={Orthogonal matching pursuit: recursive function approximation with applications to wavelet decomposition},
year={1993},
volume={},
number={},
pages={40-44 vol.1},
doi={10.1109/ACSSC.1993.342465},
ISSN={1058-6393},
month={Nov},
}
@article{2003JChPh.118.6720W,
author = {{Wu}, Y. and {Batista}, V.~S.},
title = "{Matching-pursuit for simulations of quantum processes}",
journal = {\jcp},
keywords = {Tunneling traversal time quantum Zeno dynamics, Foundations of quantum mechanics, measurement theory, Fourier analysis, Integral transforms},
year = 2003,
month = apr,
volume = 118,
pages = {6720-6724},
doi = {10.1063/1.1560636},
adsurl = {http://adsabs.harvard.edu/abs/2003JChPh.118.6720W},
adsnote = {Provided by the SAO/NASA Astrophysics Data System}
}
可以通过 ``:cite:`1993:PatiOMP` , :cite:`2003JChPh.118.6720W``` 来引用, 即 :cite:`1993:PatiOMP` , :cite:`2003JChPh.118.6720W` . 如果一次性引用多个文献, 可以用逗号分开, 但不要有空格, 比如这样 ``:cite:`1993:PatiOMP,2003JChPh.118.6720W``` 得到 :cite:`1993:PatiOMP,2003JChPh.118.6720W` .
提示
如果你想自定义参考文献引用格式,
可以通过 pip install pybtex
安装 pybtex ,
然后参考 https://sphinxcontrib-bibtex.readthedocs.io/en/latest/usage.html#custom-formatting-sorting-and-labelling ,
或者下面的讲述配置使用.
备注
pybtex
提示: 安装好 pybtex 后, 若想在你的文档工程中使用, 需要在 conf.py 文件中添加该扩展, 即 extensions = ['pybtex']
, 然后你就可以使用了, 在 .. bibliography:: ./refs.bib
里添加 :style: unsrt
即可以更改文献引用格式.
1.. bibliography:: ./refs.bib
2 :style: unsrt
注意, 如果添加 list
或 start
等域, 不能正常渲染, 不能跳转!
sphinxcontrib-xxxdiag#
xxxdiag
包含以下几种类型:
通过 pip install sphinxcontrib-xxxdiag
安装扩展,
并在 conf.py
中添加该扩展 sphinxcontrib.xxxdiag
,
官方文档在 这里 。