2.4. Sphinx重要扩展介绍

2.4.1. Sphinx内置扩展

可以通过以下链接找到 Sphinx的扩展:

  • sphinx extensions doc : 官方文档介绍, 含 Built-in extensionsThird-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. 重要内置扩展介绍 目录树 (toctree)

由于 reST 没有处理多个文档, 或将文档分割成多个输出文件的机制, Sphinx使用一个自定义指令来添加组成整篇文档的单个文件间的关系, 以及目录. 这个指令的核心就是 toctree .


简单包含某个文件, 可以使用 include 指令. 代码与语法着色

更多功能, 参考 Showing code examples

.. code-block:: python
   :lineno-start: 10
   :emphasize-lines: 9
   :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` 引用代码段.


代码 2.4.1 demo_python.py
10import pytool
11import numpy as np
12import matplotlib.pyplot as plt
14# =====================generate Ellipse=====================
15a = 6  # major axis
16b = 2  # minor axis
17x0 = 10  # center x0
18y0 = 10  # center y0
19N = 1000  # number of points
21# angle for rotating ellipse data
22theta = np.pi * 30 / 180
24x, y = pytool.ellipse_surface(a, b, x0, y0, N, 'rand')
26x = x - np.mean(x)
27y = y - np.mean(y)

并可以通过 代码 2.4.1 引用代码段. 公式, 图, 表, 代码段编号及引用

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.

# If True, displayed math equations are numbered across pages when numfig
# is enabled. The numfig_secnum_depth setting is respected. The eq, not
# numref, role must be used to reference equation numbers. Default is
# True.
math_numfig = True

# see http://www.sphinx-doc.org/en/master/usage/configuration.html#confval-numfig
# If true, figures, tables and code-blocks are automatically numbered if they have a caption.
# The numref role is enabled. Obeyed so far only by HTML and LaTeX builders. Default is False.
# The LaTeX builder always assigns numbers whether this option is enabled or not.
numfig = True
numfig_secnum_depth = 2

# A dictionary mapping 'figure', 'table', 'code-block' and 'section' to strings that are used for format of figure numbers.
# As a special character, %s will be replaced to figure number.
# Default is to use 'Fig. %s' for 'figure', 'Table %s' for 'table', 'Listing %s' for 'code-block' and 'Section' for 'section'.
numfig_format = {
    'figure': 'Fig. %s',
    'table': 'Table %s',
    'code-block': 'Listing %s',
    'section': 'Section %s',

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`.


(2.4.1)\[e^{i\pi} + 1 = 0 \]

使用``label``, 公式将被编号, 可以使用 :eq:`euler` (等效于 Eq.2.4.1 ) 来引用公式 Eq.2.4.1.

图像示例, 代码:

.. _fig-DeepLearningPlatforms:

.. figure:: ../_static/figs/mkdocs/demo_reffig.png
   :alt: 深度学习平台
   :align: center

通过 :figure:numref:`fig-DeepLearningPlatforms` 可以引用.



通过 图 2.4.1 可以引用.

表格示例, 代码:

.. table:: Truth table for "not"
   :name: table-Not

   =====  =====
   A      not A
   =====  =====
   False  True
   True   False
   =====  =====

可以通过 :table:numref:`table-Not` 引用.


表 2.4.1 Truth table for “not”


not A





可以通过 表 2.4.1 引用. 其它标记指令

下表 给出了语义标记, 详见 Sphinx Roles.





缩写 abbr

:abbr:`LIFO (last-in, first-out)`


An abbreviation

命令 command



The name of an OS-level command

下载 download

:download:`this example script <../example.py>`

this example script

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

文档 doc

:doc:`Monty Python members </people>`

Monty Python members

Link to the specified document; the document name can be specified in absolute or relative fashion

编号引用 numref

:numref:`Monty Python members </people>`

Monty Python members

Link to the specified figures, tables, code-blocks and sections; the standard reST labels are used.

环境变量 envvar



An environment variable. Index entries are generated. Also generates a link to the matching envvar directive, if it exists.

语法标记 token



The name of a grammar token (used to create links between productionlist directives).

Python中的关键字 keyword



The name of a keyword in Python. This creates a link to a reference label with that name, if it exists.

选项 option



A command-line option to an executable program. This generates a link to a option directive, if it exists.

图形化标签 guilabel



button, menu, title…

按键 kbd

:kbd:`Control-x Control-f`

Control-x Control-f

Mark a sequence of keystrokes

数学 math




公式引用 eq



The name of an OS-level command

邮件头 mailheader



The name of an OS-level command

make变量 makevar



The name of a make variable

首页 manpage



A reference to a Unix manual page including the section

菜单选择 menuselection

:menuselection:`Start --> Programs`

Start ‣ Programs

Menu selection

程序 program



The name of an executable program

正则表达式 regexp



A regular expression. Quotes should not be included.

变量渲染 samp

:samp:`print 1+{variable}`:samp:`print 1+{variable}`

print 1+variable

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 pep


A reference to a Python Enhancement Proposal

命令 rfc



A reference to an Internet Request for Comments.

定义实例 dfn



Mark the defining instance of a term in the text. (No index entries are generated.)

文件或目录 file



The name of a file or directory. Within the contents, you can use curly braces to indicate a “variable” part

新闻组 newsgroup

:newsgroup:`aaa bbb`

aaa bbb

The name of a Usenet newsgroup.

下面给出了新增的一些替换指令, 详见 Sphinx Roles Substitutions.

  • 发布: |release| 被渲染为 0.1

  • 版本: |version| 被渲染为 0.1

  • 日期: |today| 被渲染为 Apr 04, 2022 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.4.2. 第三方扩展 第三方扩展简介及安装

如下扩展可以通过类似 pip install extensions_name 的命令安装, 在 conf.py 文件中的 extensions 中加入该扩展, 以下不在赘述. 推荐使用的第三方扩展 sphinxcontrib-proof

sphinxcontrib-proof 提供定理, 定义, 证明等支持. 在 conf.py 文件中的 extensions 中加入该扩展 ( sphinxcontrib.proof ) .

然后在 _static 目录下新建 proof.cssproof.js 两个文件, 加入如下内容, 你可以自己定义其它的样式.


.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: " ▲";


$(document).ready(function() {
    $(".proof-type-proof > *").hide();
    $(".proof-type-proof .proof-title").show();
    $(".proof-type-proof .proof-title").click(function() {


.. _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>`).


Definition 2.4.1 (Right triangle)

A right triangle is a triangle in which one angle is a right angle.

Theorem 2.4.2 (Pythagorean theorem)

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.4.2). You can also reference proofs (see the proof of the Pythagorean theorem). 图表编号

借用 jterrace 的论文模版 sphinxtr 中的 numfig 可以实现. 从 这里 下载源码, 将其中的 sphinxtr 放到你的文档源码根目录下, 然后 conf.py 添加

代码 2.4.2 Code Blocks can have captions.
 1 sys.path.insert(0, os.path.join(os.path.abspath(os.path.dirname(__file__)), 'extensions'))
 3 extensions = [
 4   'sphinx.ext.autodoc',
 5   'sphinx.ext.doctest',
 6   'sphinx.ext.intersphinx',
 7   'sphinx.ext.todo',
 8   'sphinx.ext.coverage',
 9   # 'sphinx.ext.imgmath',
10   # 'sphinx.ext.mathjax',
11   'sphinxcontrib.katex',
12   'sphinxcontrib.proof',  # https://framagit.org/spalax/sphinxcontrib-proof/
13   'sphinxcontrib.bibtex',  # https://sphinxcontrib-bibtex.readthedocs.io/en/latest/
14   'sphinxcontrib.seqdiag',  # http://blockdiag.com/en/
15   'sphinx.ext.ifconfig',
16   # 'sphinx.ext.viewcode',
17   # 'sphinx.ext.githubpages',
18   # 'rst2pdf.pdfbuilder',
19   # 'sphinx.ext.napoleon',
20   'numequ',  # https://github.com/jterrace/sphinxtr/tree/master/extensions
21   'numfig',  # https://github.com/jterrace/sphinxtr/tree/master/extensions
22   'subfig',  # https://github.com/jterrace/sphinxtr/tree/master/extensions
23 ]
25 math_numfig = True
26 number_figures = True
27 figure_caption_prefix = 'Figure'

比如, 这里通过如下代码插入图片:

.. _fig-testFigureNumber:

.. figure:: ../_static/figs/logo.*
    :alt: Test Figure Number
    :width: 30%
    :align: center

    Test Figure Number


Test Figure Number

图 2.4.2 Test Figure Number

在其它地方可以通过 :num:`fig-testFigureNumber` 引用, fig-testFigureNumber .


新的Sphinx已经支持对数学公式, 图, 表, 代码段进行编号及引用, 建议使用. sphinxcontrib-bibtex

在 Sphinx中可以使用 BibTex , 通过 pip install sphinxcontrib-bibtex 安装扩展, 并在 conf.py 中添加该扩展 sphinxcontrib.bibtex , 官方文档在 这里 .

然后, 新建 reference.rst , 加入如下代码:

代码 2.4.3 reference.rst.
1.. bibliography:: ./refs.bib
2    :list: enumerated
3    :start: 1

假如 refs.bib 文件中的内容如下:

  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},
  pages={40-44 vol.1},

   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,2003JChPh.118.6720W` 得到 [] .


如果你想自定义参考文献引用格式, 可以通过 pip install pybtex 安装 pybtex , 然后参考 这里 或者下面的讲述配置使用.


pybtex 提示: 安装好 pybtex 后, 若想在你的文档工程中使用, 需要在 conf.py 文件中添加该扩展, 即 extensions = ['pybtex'] , 然后你就可以使用了, 在 .. bibliography:: ./refs.bib 里添加 :style: unsrt 即可以更改文献引用格式.

代码 2.4.4 reference.rst.
1.. bibliography:: ./refs.bib
2   :style: unsrt

注意, 如果添加 liststart 等域, 不能正常渲染, 不能跳转! sphinxcontrib-xxxdiag

xxxdiag 包含以下几种类型:

通过 pip install sphinxcontrib-xxxdiag 安装扩展, 并在 conf.py 中添加该扩展 sphinxcontrib.xxxdiag , 官方文档在 这里 .

举例: 如


.. blockdiag::

 blockdiag {
   blockdiag -> generates -> "block-diagrams";
   blockdiag -> is -> "very easy!";

   blockdiag [color = "greenyellow"];
   "block-diagrams" [color = "pink"];
   "very easy!" [color = "orange"];



.. seqdiag::

 seqdiag {
   seqdiag -> "sequence-diagrams" [label = "generates"];
   seqdiag --> "is very easy!";



.. actdiag::

   actdiag {
     write -> convert -> image

     lane user {
        label = "User"
        write [label = "Writing reST"];
        image [label = "Get diagram IMAGE"];
     lane actdiag {
        convert [label = "Convert reST to Image"];



.. nwdiag::

   nwdiag {
     network dmz {
         address = "210.x.x.x/24"

         web01 [address = "210.x.x.1"];
         web02 [address = "210.x.x.2"];
     network internal {
         address = "172.x.x.x/24";

         web01 [address = "172.x.x.1"];