4. Sphinx 配置

简单来说, Sphinx 项目中的 conf.py 文件就是该项目的配置文件,而例如 .readthedocs.yamlrequirement.txt 文件是在部署在 Read The Docs 网站上是的项目运行环境配置文件。

配置文件:

  • .readthedocs.yaml : Sphinx 项目的运行环境的宏观配置

  • requirement.txt : Sphinx 项目的 python 依赖包 的运行环境配置。当然这类依赖导入文件的命名是无所谓的,只要是 .txt 并在 .readthedocs.yaml 中引用即可。

  • conf.py : Sphinx 项目的内部配置

4.1. .readthedocs.yaml

Sphinx 项目的运行环境的宏观配置,包括指向Sphinx 项目的 python 依赖包 的运行环境配置文件。这是推荐的设置项目的方法。在使用此配置文件时, Read The Docs 项目的 管理 --> 高级设置 --> Default settings 列出的设置将被忽略。

Read The Docs 支持使用 YAML 文件配置文档构建。 该配置文件必须在你的项目的根目录下 ,并命名 .readthedocs.yaml

代码块 4.1.1 YAML 文件配置示例
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# .readthedocs.yaml
# Read the Docs configuration file
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details

# Required
version: 2

# Set the version of Python and other tools you might need
build:
  os: ubuntu-20.04
  tools:
    python: "3.9"
    # You can also specify other tool versions:
    # nodejs: "16"
    # rust: "1.55"
    # golang: "1.17"

# Build documentation in the docs/ directory with Sphinx
sphinx:
   configuration: docs/conf.py

# If using Sphinx, optionally build your docs in additional formats such as PDF
# formats:
#    - pdf

# Optionally declare the Python requirements required to build your docs
python:
   install:
   - requirements: docs/requirements.txt

如果想要了解更多关于 YAML 文件配置, 点击前往

需要注意文件的路径问题。在官方的文档中,Sphinx 项目是在项目文件夹下名为 docs 文件夹下新建的,所以在项目最外层与 README.md 同级的情况下, requirement.txt 放在项目最外层,那么它的路径为 docs/requirement.txt

4.2. requirement.txt

Sphinx 项目的 python 依赖包 的运行环境配置。当然这类依赖导入文件的命名是无所谓的,只要是 .txt 并在 .readthedocs.yaml 中引用即可。

因为我们在推送到 Read The Docs 平台时,它是不知道我们项目所需要的 Python 依赖模块的,所以需要我们添加 pip 要求文件 来构建文档; 点击查看pip 要求文件样式要求

代码块 4.2.1 requirement.txt 文件配置示例
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
###### Requirements without Version Specifiers ######
pytest
pytest-cov
beautifulsoup4

###### Requirements with Version Specifiers ######
#   See https://www.python.org/dev/peps/pep-0440/#version-specifiers
docopt == 0.6.1             # Version Matching. Must be version 0.6.1
keyring >= 4.1.1            # Minimum version 4.1.1
coverage != 3.5             # Version Exclusion. Anything except version 3.5
Mopidy-Dirble ~= 1.1        # Compatible release. Same as >= 1.1, == 1.*

###### Refer to other requirements files ######
-r other-requirements.txt

###### A particular file ######
./downloads/numpy-1.9.2-cp34-none-win32.whl
http://wxpython.org/Phoenix/snapshot-builds/wxPython_Phoenix-3.0.3.dev1820+49a8884-cp34-none-win_amd64.whl

###### Additional Requirements without Version Specifiers ######
#   Same as 1st section, just here to show that you can put things in any order.
rejected
green

4.3. conf.py

以下文本项目的实际配置文件。

重要

更多详细内容请学习官方文档的 配置篇

代码块 4.3.1 项目的实际 conf.py
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html

# -- Path setup --------------------------------------------------------------

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))


# -- Project information -----------------------------------------------------
# 项目名
project = 'A Sphinx Book Template'
# 版权,著作权
copyright = '2022, Eugene Forest'
# 作者
author = 'Eugene Forest'

# The short X.Y version. 主要项目版本,用作 |version| .
version = 'alpha'
# The full version, including alpha/beta/rc tags. 完整的项目版本,用作 |release|
release = 'alpha'

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
today_fmt = "%Y-%m-%d, %H:%M:%S"

# The encoding of source files.
# 建议的编码和默认值是 'utf-8-sig' .
source_encoding = 'utf-8-sig'

# The master toctree document.
# “主控”文档的文档名称,即包含根目录的文档 toctree 指令。
# 在 2.0 版更改: 默认值更改为 'index' 从 'contents' .
master_doc = 'index'

# -- General configuration ---------------------------------------------------

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
# 在这里以字符串的形式添加任何Sphinx扩展模块名。
extensions = [
    "sphinx.ext.todo",
    "sphinx.ext.intersphinx",
    "sphinx.ext.autosectionlabel",
    "myst_parser",
    "sphinx_design",
    "sphinx_copybutton",
    "sphinx_togglebutton",
]
# "sphinx.ext.todo" : 对TODO项的支持
# "sphinx.ext.intersphinx" :链接到其他项目的文档
# "sphinx.ext.autosectionlabel" : label 标签自动选中确保唯一性,并允许引用节使用其标题,同时自动为标题创建label
# 'myst_parser' : myst 解析器, 默认情况下,myst_parser 会解析 markdown(.md) ,而 .rst 文件会被 Sphinx 原生解析器 restructureText 解析。
# "sphinx_design" : 用于设计美观、视图大小的响应式 Web 组件。
# "sphinx_copybutton": 代码块复制按钮扩展

# Make sure the target is unique (sphinx.ext.autosectionlabel 插件的配置)
autosectionlabel_prefix_document = True

# MyST Markdown 扩展语法
myst_enable_extensions = [
    "colon_fence",
    "deflist",
    "tasklist",
    "smartquotes", "replacements",
    "linkify",
    "html_image",
    "substitution",
    "dollarmath", "amsmath",
]
# 如果为false,只有包含方案(例如http)的链接才会被识别为外部链接
myst_linkify_fuzzy_links = False
# substitution 的扩展的全局替换,作用于 .md
myst_substitutions = {}
# default is ['{', '}'],替换指令分隔符,不建议更改
# myst_sub_delimiters = ["|", "|"]

# 数学公式语法 $ (dollar math) 设置
myst_dmath_allow_labels = True
myst_dmath_double_inline = True
# myst_dmath_allow_space = False, will cause inline math to only be parsed if there are no initial / final spaces, e.g. $a$ but not $ a$ or $a $.
# myst_dmath_allow_digits = False, will cause inline math to only be parsed if there are no initial / final digits, e.g. $a$ but not 1$a$ or $a$2.

# -- global replace order configuration are as follows---
# 全局字符串替换指令
# 需要注意的是,全局加入替换的功能要谨慎使用,要酌情使用;因为在这里添加后会影响到项目所有的 rst 文件(在所有 rst 文件中添加定义的替换指令)
# 一串 reStructuredText,它将包含在每个读取的源文件的末尾。 这是一个可以添加应该在每个文件中可用的替换的地方
rst_prolog = """
.. |15| raw:: html
      
      <hr width='15%'>

.. |30| raw:: html
      
      <hr width='30%'>
      
.. |50| raw:: html
      
      <hr width='50%'>

.. |75| raw:: html
      
      <hr width='75%'>

"""

# 图片编号功能
# -- numfig configuration are as follows---
# 表格和代码块如果有标题则会自动编号
numfig = True
# -- numfig_secnum_depth configuration are as follows---
# 如果设置为“0”,则数字,表格和代码块从“1”开始连续编号。
# 如果“1”(默认),数字将是“x.1”。“x.2”,… 与“x”的节号(顶级切片;没有“x”如果没有部分)。只有当通过 toctree 指令的“:numbered:”选项激活了段号时,这才自然适用。
# 如果“2”,表示数字将是“x.y.1”,“x.y.2”,…如果位于子区域(但仍然是 x.1 ,x.2 ,… 如果直接位于一个部分和 1 ,2 , … 如果不在任何顶级部分。)
numfig_secnum_depth = 2
# -- numfig_format configuration are as follows---
# 一个字典将“‘figure’”,“‘table’”,“‘code-block’”和“‘section’”映射到用于图号格式的字符串。作为一个特殊字符,“%s”将被替换为图号。
# 默认是使用“‘Fig.%s’”为“‘figure’”, “‘Table%s’”为“‘table’”,“‘Listing%s’”为“‘code-block’”和“‘Section’”为 “‘section’”。
numfig_format = {'code-block': '代码块 %s', }
# -- html_codeblock_linenos_style configuration are as follows---
# 代码块的行号样式
html_codeblock_linenos_style = 'table'
# html_codeblock_linenos_style = 'inline'

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = 'zh_CN'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = []


# -- Options for HTML output -------------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
# 主题配置
html_theme = "sphinx_book_theme"
# 以下为 sphinx_book_theme 的主题配置/定制(sphinx_book_theme)
html_theme_options = {

    # ----------------主题内容中导航栏的功能按钮配置--------
    # 添加存储库链接
    "repository_url": "https://github.com/Eugene-Forest/NoteBook",
    # 添加按钮以链接到存储库
    "use_repository_button": True,
    # 要添加按钮以打开有关当前页面的问题
    "use_issues_button": True,
    # 添加一个按钮来建议编辑
    "use_edit_page_button": True,
    # 在导航栏添加一个按钮来切换全屏的模式。
    "use_fullscreen_button": True,  # 默认 `True`
    # 默认情况下,编辑按钮将指向master分支,但如果您想更改此设置,请使用以下配置
    "repository_branch": "main",
    # 默认情况下,编辑按钮将指向存储库的根目录;而我们 sphinx项目的 doc文件其实是在 source 文件夹下的,包括 conf.py 和 index(.rst) 主目录
    "path_to_docs": "source",
    # 您可以添加 use_download_button 按钮,允许用户以多种格式下载当前查看的页面
    "use_download_button": True,

    # --------------------------右侧辅助栏配置---------
    # 重命名右侧边栏页内目录名,标题的默认值为Contents。
    "toc_title": "导航",
    # -- 在导航栏中显示子目录,向下到这里列出的深度。 ----
    "show_toc_level": 2,

    # --------------------------左侧边栏配置--------------
    # -- 只显示标识,不显示 `html_title`,如果它存在的话。-----
    "logo_only": True,
    # 控制左侧边栏列表的深度展开,默认值为1,它仅显示文档的顶级部分
    "show_navbar_depth": 1,
    # 自定义侧边栏页脚,默认为 Theme by the Executable Book Project
    # "extra_navbar": "<p>Your HTML</p>",
    "home_page_in_toc": False,  # 是否将主页放在导航栏(顶部)

    # ------------------------- 单页模式 -----------------
    # 如果您的文档只有一个页面,并且您不需要左侧导航栏,那么您可以 使用以下配置将其配置sphinx-book-theme 为以单页模式运行
    # "single_page": True,

    # -- 在每个页面的页脚添加额外的 HTML。---
    # "extra_footer": '',
}

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".

# 添加你自己的 CSS 规则
html_static_path = ['_static']
html_css_files = ["custom.css"]


# 自定义徽标、和网站图标
html_logo = "./_static/template.svg"
html_favicon = "./_static/template.svg"
# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
#html_title = None




###########################################################################
#          auto-created readthedocs.org specific configuration            #
###########################################################################


#
# The following code was added during an automated build on readthedocs.org
# It is auto created and injected for every build. The result is based on the
# conf.py.tmpl file found in the readthedocs.org codebase:
# https://github.com/rtfd/readthedocs.org/blob/main/readthedocs/doc_builder/templates/doc_builder/conf.py.tmpl
#
# Note: this file shouldn't rely on extra dependencies.

import importlib
import sys
import os.path

# Borrowed from six.
PY3 = sys.version_info[0] == 3
string_types = str if PY3 else basestring

from sphinx import version_info

# Get suffix for proper linking to GitHub
# This is deprecated in Sphinx 1.3+,
# as each page can have its own suffix
if globals().get('source_suffix', False):
    if isinstance(source_suffix, string_types):
        SUFFIX = source_suffix
    elif isinstance(source_suffix, (list, tuple)):
        # Sphinx >= 1.3 supports list/tuple to define multiple suffixes
        SUFFIX = source_suffix[0]
    elif isinstance(source_suffix, dict):
        # Sphinx >= 1.8 supports a mapping dictionary for multiple suffixes
        SUFFIX = list(source_suffix.keys())[0]  # make a ``list()`` for py2/py3 compatibility
    else:
        # default to .rst
        SUFFIX = '.rst'
else:
    SUFFIX = '.rst'

# Add RTD Static Path. Add to the end because it overwrites previous files.
if not 'html_static_path' in globals():
    html_static_path = []
if os.path.exists('_static'):
    html_static_path.append('_static')

# Add RTD Theme only if they aren't overriding it already
using_rtd_theme = (
    (
        'html_theme' in globals() and
        html_theme in ['default'] and
        # Allow people to bail with a hack of having an html_style
        'html_style' not in globals()
    ) or 'html_theme' not in globals()
)
if using_rtd_theme:
    theme = importlib.import_module('sphinx_rtd_theme')
    html_theme = 'sphinx_rtd_theme'
    html_style = None
    html_theme_options = {}
    if 'html_theme_path' in globals():
        html_theme_path.append(theme.get_html_theme_path())
    else:
        html_theme_path = [theme.get_html_theme_path()]

if globals().get('websupport2_base_url', False):
    websupport2_base_url = 'https://readthedocs.org/websupport'
    websupport2_static_url = 'https://assets.readthedocs.org/static/'


#Add project information to the template context.
context = {
    'using_theme': using_rtd_theme,
    'html_theme': html_theme,
    'current_version': "latest",
    'version_slug': "latest",
    'MEDIA_URL': "https://media.readthedocs.org/",
    'STATIC_URL': "https://assets.readthedocs.org/static/",
    'PRODUCTION_DOMAIN': "readthedocs.org",
    'proxied_static_path': "/_/static/",
    'versions': [
    ("latest", "/zh/latest/"),
    ],
    'downloads': [ 
    ("html", "//a-sphinx-book-template.readthedocs.io/_/downloads/zh/latest/htmlzip/"),
    ],
    'subprojects': [ 
    ],
    'slug': 'a-sphinx-book-template',
    'name': u'A-Sphinx-Book-Template',
    'rtd_language': u'zh',
    'programming_language': u'',
    'canonical_url': 'https://a-sphinx-book-template.readthedocs.io/zh/latest/',
    'analytics_code': 'None',
    'single_version': False,
    'conf_py_path': '/source/',
    'api_host': 'https://readthedocs.org',
    'github_user': 'Eugene-Forest',
    'proxied_api_host': '/_',
    'github_repo': 'A-Sphinx-Book-Template',
    'github_version': 'main',
    'display_github': True,
    'bitbucket_user': 'None',
    'bitbucket_repo': 'None',
    'bitbucket_version': 'main',
    'display_bitbucket': False,
    'gitlab_user': 'None',
    'gitlab_repo': 'None',
    'gitlab_version': 'main',
    'display_gitlab': False,
    'READTHEDOCS': True,
    'using_theme': (html_theme == "default"),
    'new_theme': (html_theme == "sphinx_rtd_theme"),
    'source_suffix': SUFFIX,
    'ad_free': False,
    'docsearch_disabled': False,
    'user_analytics_code': '',
    'global_analytics_code': 'UA-17997319-1',
    'commit': 'aa581b1b',
}

# For sphinx >=1.8 we can use html_baseurl to set the canonical URL.
# https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-html_baseurl
if version_info >= (1, 8):
    if not globals().get('html_baseurl'):
        html_baseurl = context['canonical_url']
    context['canonical_url'] = None





if 'html_context' in globals():
    
    html_context.update(context)
    
else:
    html_context = context

# Add custom RTD extension
if 'extensions' in globals():
    # Insert at the beginning because it can interfere
    # with other extensions.
    # See https://github.com/rtfd/readthedocs.org/pull/4054
    extensions.insert(0, "readthedocs_ext.readthedocs")
else:
    extensions = ["readthedocs_ext.readthedocs"]

# Add External version warning banner to the external version documentation
if 'branch' == 'external':
    extensions.insert(1, "readthedocs_ext.external_version_warning")
    readthedocs_vcs_url = 'None'
    readthedocs_build_url = 'https://readthedocs.org/projects/a-sphinx-book-template/builds/18056305/'

project_language = 'zh'

# User's Sphinx configurations
language_user = globals().get('language', None)
latex_engine_user = globals().get('latex_engine', None)
latex_elements_user = globals().get('latex_elements', None)

# Remove this once xindy gets installed in Docker image and XINDYOPS
# env variable is supported
# https://github.com/rtfd/readthedocs-docker-images/pull/98
latex_use_xindy = False

chinese = any([
    language_user in ('zh_CN', 'zh_TW'),
    project_language in ('zh_CN', 'zh_TW'),
])

japanese = any([
    language_user == 'ja',
    project_language == 'ja',
])

if chinese:
    latex_engine = latex_engine_user or 'xelatex'

    latex_elements_rtd = {
        'preamble': '\\usepackage[UTF8]{ctex}\n',
    }
    latex_elements = latex_elements_user or latex_elements_rtd
elif japanese:
    latex_engine = latex_engine_user or 'platex'

# Make sure our build directory is always excluded
exclude_patterns = globals().get('exclude_patterns', [])
exclude_patterns.extend(['_build'])