基于 Sphinx 以纯文本编写富媒体项目文档的方法介绍

简介

本文介绍一种纯文本书写富媒体项目文档的方式。

使用的工具有 python 文档引擎 Sphinx,文本式 UML 工具 PlantUML,书写文档的格式是 reStructuredText

以 reStructuredText 和 PlantUML 语法书写纯文本文件,然后通过 Sphinx 编译成 html,通过浏览器进行阅读。经过适当配置后也可以编译 pdf, latex 等格式。

Sphinx 原本是 Python 的文档生成工具,但是随着它的发展,已经成为了一个优秀的文档工具。配合 ReadTheDocs 提供的 Read the Docs 主题,可以形成美观清晰的文档。Sphinx 的 cross-referencing t很吸引人,而且有许多扩展

PlantUML 定义了一整套 UML 语法,通过这套语法书写的文本文件经过 PlantUML 的转换后可以生成相应的 UML 图。这对于进行 UML 图的版本管理有比较重要的意义。

reStructuredText 是类似于 markdown 的一种标记式语言。相对于轻量的 markdown,reStructuredText 更加适合写作技术文档,可以参阅 3

环境

  • Python 2.7.15
  • Windows 10

依赖安装

  1. 安装 Sphinx
  2. 安装 PlantUML
  3. 没了。(想不到依赖这么少吧.jpg)

以下是详细

安装 Sphinx

使用 pip 一键安装:

1
pip install sphinx

然后创建文档项目。

1
2
3
4
5
6
7
8
9
10
11
# 在要创建文档的位置运行以下命令
mkdir docs
cd docs

# 运行以下命令,会有一堆问题,除了语言之外能默认的全部默认
# 语言输入:
# zh_CN
# 这样生成简体中文(Simplified Chinese)的项目。
# 参见:http://www.sphinx-doc.org/en/master/usage/configuration.html#confval-language
# 另外,插件部分建议开启 todo, mathjax, ifconfig, viewcode
sphinx-quickstart

按照默认选项,会生成 docs/_build 目录,这是最终编译的的文档所在位置。具体目录如图

现在编译项目,在当前路径下

1
make html

成功时的提示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Running Sphinx v1.8.1
loading translations [zh_CN]... done
making output directory...
building [mo]: targets for 0 po files that are out of date
building [html]: targets for 1 source files that are out of date
updating environment: 1 added, 0 changed, 0 removed
reading sources... [100%] index
looking for now-outdated files... none found
pickling environment... done
checking consistency... done
preparing documents... done
writing output... [100%] index
generating indices... genindex
writing additional pages... search
copying static files... done
copying extra files... done
dumping search index in Chinese (code: zh) ... done
dumping object inventory... done
build succeeded.

The HTML pages are in _build\html.

双击打开 _build/html/index.html,就可以看到生成的文档了。

现在配置主题 Read the Docs Sphinx Theme。有两种方式,一种是通过 pip 安装,一种是下载到本地。

pip 安装:

1
2
3
4
pip install sphinx_rtd_theme

# 然后在 conf.py 文件中修改配置:
html_theme = "sphinx_rtd_theme"

本地形式:

下载项目文件,地址
https://github.com/rtfd/sphinx_rtd_theme

例如 https://github.com/rtfd/sphinx_rtd_theme/archive/0.4.2.zip

在项目下创建 _themes 文件夹,将 zip 解压放入

修改 conf.py 配置:

1
2
3
4
5
html_theme = "sphinx_rtd_theme"
html_theme_path = ["_themes", ]

# 避免编译主题中的文档
exclude_patterns += ['_themes']

再次 make html,现在的效果:

至此安装和主题配置都完成了。

配置文件最终内容:

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
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config

# -- 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 = u'Sample'
copyright = u'2018, Hustlion'
author = u'Hustlion'

# The short X.Y version
version = u''
# The full version, including alpha/beta/rc tags
release = u''


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

# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.todo',
'sphinx.ext.mathjax',
'sphinx.ext.ifconfig',
'sphinx.ext.viewcode',
]

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

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'

# The master toctree document.
master_doc = 'index'

# 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 = u'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 = [u'_build', 'Thumbs.db', '.DS_Store']




# The name of the Pygments (syntax highlighting) style to use.
pygments_style = None


# -- 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 = 'alabaster'
html_theme = "sphinx_rtd_theme"
html_theme_path = ["_themes", ]
exclude_patterns += ['_themes']

# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}

# 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".
html_static_path = ['_static']

# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# The default sidebars (for documents that don't match any pattern) are
# defined by theme itself. Builtin themes are using these templates by
# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',
# 'searchbox.html']``.
#
# html_sidebars = {}


# -- Options for HTMLHelp output ---------------------------------------------

# Output file base name for HTML help builder.
htmlhelp_basename = 'Sampledoc'


# -- Options for LaTeX output ------------------------------------------------

latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',

# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',

# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',

# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'Sample.tex', u'Sample Documentation',
u'Hustlion', 'manual'),
]


# -- Options for manual page output ------------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'sample', u'Sample Documentation',
[author], 1)
]


# -- Options for Texinfo output ----------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'Sample', u'Sample Documentation',
author, 'Sample', 'One line description of project.',
'Miscellaneous'),
]


# -- Options for Epub output -------------------------------------------------

# Bibliographic Dublin Core info.
epub_title = project

# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#
# epub_identifier = ''

# A unique identification for the text.
#
# epub_uid = ''

# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']


# -- Extension configuration -------------------------------------------------

# -- Options for todo extension ----------------------------------------------

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True

安装 PlantUML

在官网下载,页面:http://plantuml.com/download

例如:http://sourceforge.net/projects/plantuml/files/plantuml.1.2018.11.jar/download

然后在项目下新建 _utils 文件夹,将其放入:

接下来配置编译脚本,使得 sphinx 编译时也将 uml 图进行转换。

在项目根目录下新建 plantuml.cfg 文件,写入以下内容:

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
skinparam backgroundColor white

skinparam note {
BackgroundColor #F1FFFF
BorderColor #2980B9
}

skinparam activity {
BackgroundColor #BDE3FF
ArrowColor #2980B9
BorderColor #2980B9
StartColor #227BC6
EndColor #227BC6
BarColor #227BC6
}

skinparam sequence {
ArrowColor #2980B9
DividerBackgroundColor #BDE3FF
GroupBackgroundColor #BDE3FF
LifeLineBackgroundColor white
LifeLineBorderColor #2980B9
ParticipantBackgroundColor #BDE3FF
ParticipantBorderColor #2980B9
BoxLineColor #2980B9
BoxBackgroundColor #DDDDDD
}

skinparam actorBackgroundColor #FEFECE
skinparam actorBorderColor #A80036

skinparam usecaseArrowColor #A80036
skinparam usecaseBackgroundColor #FEFECE
skinparam usecaseBorderColor #A80036

skinparam classArrowColor #A80036
skinparam classBackgroundColor #FEFECE
skinparam classBorderColor #A80036

skinparam objectArrowColor #A80036
skinparam objectBackgroundColor #FEFECE
skinparam objectBorderColor #A80036

skinparam packageBackgroundColor #FEFECE
skinparam packageBorderColor #A80036

skinparam stereotypeCBackgroundColor #ADD1B2
skinparam stereotypeABackgroundColor #A9DCDF
skinparam stereotypeIBackgroundColor #B4A7E5
skinparam stereotypeEBackgroundColor #EB937F

skinparam componentArrowColor #A80036
skinparam componentBackgroundColor #FEFECE
skinparam componentBorderColor #A80036
skinparam componentInterfaceBackgroundColor #FEFECE
skinparam componentInterfaceBorderColor #A80036

skinparam stateBackgroundColor #BDE3FF
skinparam stateBorderColor #2980B9
skinparam stateArrowColor #2980B9
skinparam stateStartColor black
skinparam stateEndColor black

修改 make.bat (如果是 Linux 下,参照修改 Makefile)为:

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
@ECHO OFF

pushd %~dp0

REM Command file for Sphinx documentation

if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=.
set BUILDDIR=_build

if "%1" == "" goto help

%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)

java -jar _utils/plantuml.1.2018.11.jar -charset UTF-8 -config plantuml.cfg -psvg -o ../uml_generated/ ./uml/*.uml
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%

goto end

:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%

:end
popd

主要加入了这一句:java -jar _utils/plantuml.1.2018.11.jar -charset UTF-8 -config plantuml.cfg -psvg -o ../uml_generated/ ./uml/*.uml

这一句的功能是,按照 plantuml.cfg 里面的配置,把 uml 文件夹下的 uml 文件编译成图片,放到同级别目录下的 uml_generated 文件夹中,并且支持中文。

接下来创建 uml 文件夹,在其中创建一个测试 uml 文件为 test.uml

1
2
3
4
5
6
@startuml

Alice -> Bob: Hello world!
Bob -> Alice: Hello world again!

@enduml

修改 index.rst 为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
.. Sample documentation master file, created by
sphinx-quickstart on Fri Oct 12 17:22:09 2018.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.

Welcome to Sample's documentation!
==================================

.. image:: uml_generated/test.png
:align: center

.. toctree::
:maxdepth: 2
:caption: Contents:



Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

运行 make html,输出为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Running Sphinx v1.8.1
loading translations [zh_CN]... done
loading pickled environment... done
building [mo]: targets for 0 po files that are out of date
building [html]: targets for 1 source files that are out of date
updating environment: [] 0 added, 1 changed, 0 removed
reading sources... [100%] index
looking for now-outdated files... none found
pickling environment... done
checking consistency... done
preparing documents... done
writing output... [100%] index
generating indices... genindex
writing additional pages... search
copying images... [100%] uml_generated/test.png
copying static files... done
copying extra files... done
dumping search index in Chinese (code: zh) ... done
dumping object inventory... done
build succeeded.

The HTML pages are in _build\html.

打开文档,可以看到 UML 正常显示:

Sphinx 关键知识总结

  • 默认编译在 _build 目录下,文档阅读入口 _build/html/index.html
  • 配置文件是 conf.py
  • 默认入口文件 index.rst
  • make html 编译 html 版本的文档

使用方式

在按上述步骤配置好之后。使用 reStructedText 语法写作正文,使用 PlantUML 画 UML 再用 image 引用即可。

Sphinx 中的 reStructedText 常用语法

详细语法查阅:2

index.rst 中引用其他页面

要求其他页面至少有一个 header,这个 header 会作为标题内容显示出来。例如现在有一个 001-CS流程说明.rst 文件,则在 index.rst 中写 001-CS流程说明 即可引用。

index.rst 内容:

1
2
3
4
5
.. toctree::
:maxdepth: 2
:caption: 目录:

001-CS流程说明

001-CS流程说明.rst 内容(注意标题下的等号要比标题自己长,否则报错):

1
2
我是示例标题
==============

效果

代码

.. code-block:: lua 开头,然后空一行,代码区要相对缩进两个空格。可以接受一些选项,比如 :linenos: 显示行号。

简单代码片:

1
2
3
.. code-block:: lua

SampleID = 5,

更复杂一点的代码片:打开的功能有高亮代码行,显示行数,提供代码片标题,提供永久链接名

1
2
3
4
5
6
7
8
9
10
11
12
13
.. code-block:: lua
:emphasize-lines: 3
:linenos:
:caption: UI_GlobalLogic.lua
:name: bind-id


self.mTableNotification = {
-- ... 其他原有消息号
CLIENT_NOTIFI_ID.SampleID,
};
function test ()
end

行内代码

1
``code``

标题级别

推荐的做法是与 Python’s Style Guide 采用的一致:

  • # with overline, for parts
  • * with overline, for chapters
  • =, for sections
  • -, for subsections
  • ^, for subsubsections
  • ", for paragraphs

图片

1
2
.. image:: uml_generated/test.png
:align: center

引用代码文件

1
.. literalinclude:: ./conf.py

变量替换

可以减少一些长字符串的重复书写。

参照:http://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html#substitutions

1
2
3
4
5
6
定义:

.. |target| replace:: ``Logic/UI/Global/UI_GlobalLogic.lua``

引用:
|target|

公式

https://build-me-the-docs-please.readthedocs.io/en/latest/Using_Sphinx/UsingMathEquationsInSphinx.html

1
2
3
4
5
6
7
If :math:`\sigma_{1}` equals :math:`\sigma_{2}` then etc, etc.

.. math::

(a + b)^2 = a^2 + 2ab + b^2

(a - b)^2 = a^2 - 2ab + b^2

示例项目下载

参考

  1. Sphinx documentation
  2. RestructuredText primer
  3. An introduction to Sphinx and Read the Docs for technical writers
  4. Skinparam command