sphinx-github-readthedocs¶
sphinx¶
sphinx
介绍¶
官网:SPHINX
sphinx
是一个文档生成工具,可用于多种语言,有以下特性:
- 输出格式:生成文档可以是
HTML、LaTex、ePub、Textinfo、manual pages、plain text
- 强大的互参考功能:用于函数、类、引文、词汇术语和相似信息的语义标记和自动链接
- 层次结构:文档树的简单定义,自动链接到同级,父类和子类节点
- 自动索引:通用索引以及语言特定的模块索引
- 代码处理:使用
Pygments
高亮器实现自动高亮 - 扩展功能:代码片段的自动测试,包括来自
Python
模块(API
文档)的文档字符串,以及更多 - 贡献扩展:超过
50
个扩展包被用户发布在另一个仓库,其中的大多数可以通过PyPI
安装
默认情况下,sphinx
使用reStructuredText
语言作为标记语言,它也支持markdown
(需要设置)
Sphinx-bug¶
Sphinx工程目前还没有完全支持markdown,尤其是对于数学公式
比如在Markdown中,行内数学符号用$…$,行外数学符号用$$…$$
但是在Sphinx工程中,无法实现行内数学符号效果,行外数学符号也只支持单行
所以如果有涉及数学公式的文章,还是使用其他方法好一点
在github上提了一个bug:Sphinx Markdown MathJax doesn’t work correctly #5957
快速生成文档工程¶
sphinx
提供了工具sphinx-quickstart
用于快速生成一个文档工程
sphinx-quickstart
使用¶
新建空文件夹,该目录下,输入命令sphinx-quickstart
启动一个工程,随后根据需求选择配置
zhujian@zhujian-virtual-machine:~/doc/first$ sphinx-quickstart
Welcome to the Sphinx 1.8.2 quickstart utility.
Please enter values for the following settings (just press Enter to
accept a default value, if one is given in brackets).
Selected root path: .
You have two options for placing the build directory for Sphinx output.
Either, you use a directory "_build" within the root path, or you separate
"source" and "build" directories within the root path.
> Separate source and build directories (y/n) [n]:
默认以当前目录作为根目录,默认将根目录作为源文件路径
可以设置将源文件和输出文件放置在两个不同文件夹内
Inside the root directory, two more directories will be created; "_templates"
for custom HTML templates and "_static" for custom stylesheets and other static
files. You can enter another prefix (such as ".") to replace the underscore.
> Name prefix for templates and static dir [_]:
在源文件目录中会生成两个文件夹:'_templates'
用于保存自定义HTML模板;‘_static’
用于保存自定义样式表和其他静态文件,默认以下划线'_'
来强调文件夹功能
The project name will occur in several places in the built documentation.
> Project name:
> Author name(s):
> Project release []:
输入工程名、作者名、版本号
If the documents are to be written in a language other than English,
you can select a language here by its language code. Sphinx will then
translate text that it generates into that language.
For a list of supported codes, see
http://sphinx-doc.org/config.html#confval-language.
> Project language [en]:
语言定制,默认是英语,中文是zh_CN
The file name suffix for source files. Commonly, this is either ".txt"
or ".rst". Only files with this suffix are considered documents.
> Source file suffix [.rst]:
指定源文件后缀名,默认为'.txt'
或者'.rst'
,仅有指定后缀的文件会被加入文档
One document is special in that it is considered the top node of the
"contents tree", that is, it is the root of the hierarchical structure
of the documents. Normally, this is "index", but if your "index"
document is a custom template, you can also set this to another filename.
> Name of your master document (without suffix) [index]:
指定名为'index'
的文件为内容树的顶部节点,如果名为'index'
的文件已被用于自定义模板,那么可以指定另外一个文件名作为顶部节点
Indicate which of the following Sphinx extensions should be enabled:
> autodoc: automatically insert docstrings from modules (y/n) [n]: y
> doctest: automatically test code snippets in doctest blocks (y/n) [n]: y
> intersphinx: link between Sphinx documentation of different projects (y/n) [n]: y
> todo: write "todo" entries that can be shown or hidden on build (y/n) [n]: y
> coverage: checks for documentation coverage (y/n) [n]: y
> imgmath: include math, rendered as PNG or SVG images (y/n) [n]: y
> mathjax: include math, rendered in the browser by MathJax (y/n) [n]: y
> ifconfig: conditional inclusion of content based on config values (y/n) [n]: y> viewcode: include links to the source code of documented Python objects (y/n) [n]: y
> githubpages: create .nojekyll file to publish the document on GitHub pages (y/n) [n]: y
Note: imgmath and mathjax cannot be enabled at the same time. imgmath has been deselected.
指定下列扩展功能是否使用
autodoc
: 自动从模块中插入文档字符串doctest
: 自动测试文档测试块中的代码片段intersphinx
: 链接不同工程中的sphinx
文档todo
: 是否在构建时显示或隐藏'todo'
条目coverage
: 检查文档覆盖率imgmath
: 将数学公式渲染为PNG
或SVG
图像mathjax
: 在浏览器中用MathJax
渲染数学公式ifconfig
:conditional inclusion of content based on config values
viewcode
: 文档化Python
对象源代码的包含链接githubpages
: 创建一个.nojekyll
文件,以便发布到github
需要注意的是,不能同时配置imgmath
和mathjax
A Makefile and a Windows command file can be generated for you so that you
only have to run e.g. `make html' instead of invoking sphinx-build
directly.
> Create Makefile? (y/n) [y]:
> Create Windows command file? (y/n) [y]:
是否生成一个Makefile
文件和一个Windows
命令文件,这样可以直接生成而不需要使用工具sphinx-build
Creating file ./conf.py.
Creating file ./index.rst.
Creating file ./Makefile.
Creating file ./make.bat.
Finished: An initial directory structure has been created.
You should now populate your master file ./index.rst and create other documentation
source files. Use the Makefile to build the docs, like so:
make builder
where "builder" is one of the supported builders, e.g. html, latex or linkcheck.
配置完成了
工程结构¶
默认源文件和生成文件放在一起
zhujian@zhujian-virtual-machine:~/doc/first$ ls
_build conf.py index.rst make.bat Makefile _static _templates
zhujian@zhujian-virtual-machine:~/doc/first$ tree
.
├── _build
├── conf.py
├── index.rst
├── make.bat
├── Makefile
├── _static
└── _templates
3 directories, 4 files
如果将源文件和生成文件配置成两个文件夹
zhujian@zhujian-virtual-machine:~/doc/sphinx$ ls
build make.bat Makefile source
zhujian@zhujian-virtual-machine:~/doc/sphinx$ tree
.
├── build
├── make.bat
├── Makefile
└── source
├── conf.py
├── index.rst
├── _static
└── _templates
4 directories, 4 files
build
(或_build
)是输出文件路径
Makefile/make.bat
是构建文件
source
是源文件路径(在文件conf.py
中包含了所有的配置选项)
构建¶
如果已经生成了Makefile
文件,那么直接使用make
命令就好了
make builder
builder
指要构建的格式,比如html,latex
等等
zhujian@zhujian-virtual-machine:~/doc/sphinx$ make html
Running Sphinx v1.8.2
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 English (code: en) ... done
dumping object inventory... done
build succeeded.
The HTML pages are in build/html.
然后进入./build/html
,打开index.html
即可
如果源文件和输出文件放置在一起,那么输出会在_build
文件夹内
zhujian@zhujian-virtual-machine:~/doc/first$ make html
Running Sphinx v1.8.2
...
The HTML pages are in _build/html.
也可以使用工具sphinx-build
,操作如下:
sphinx-build -b html sourcedir builddir
sourcedir
指定源文件路径,builddir
指定输出文件路径,-b html
指定输出格式
sphinx
目录树¶
参考:
指令¶
reStructuredtext
包含了多种指令,其格式如下:
.. directive_name::arguments
:option1:
:option2:
content
directive_name
表示指令名
arguments
表示指令参数,直接跟在双冒号之后,由指令觉得是否有参数,有多少个
options
表示指令选项,以字段列表的形式存在
content
表示指令内容,跟在指令和选项之后,间隔一行进行,由指令确定是否允许内容,以及做什么
常见问题:内容应该缩进到与选项相同的级别,比如
.. toctree::
:maxdepth: 2
usage/installation
usage/quickstart
toctree
¶
使用sphinx-quickstart
生成工程后,index.rst
文档如下:
.. sphinx使用 documentation master file, created by
sphinx-quickstart on Sun Dec 16 15:27:21 2018.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to sphinx使用's documentation!
======================================
.. toctree::
:maxdepth: 2
:caption: Contents:
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
其中toctree
表示一个指令,它用于生成目录树(table of content tree
)
添加文档¶
在toctree
指令中可以添加文档,将文档名添加到指令内容即可,比如
.. toctree::
:maxdepth: 2
:caption: Contents:
Sphinx使用 - html主题
zj_rst
其中Sphinx使用 - html主题
和zj_rst
就是文档名
注意1:文档内容要和选项相同级别(同一条竖线下)
注意2:文档中必须要有标题
maxdepth¶
maxdepth
表示目录树显示的标题深度,maxdepth=1
表示显示第一级标记,maxdepth=2
表示显示第一和第二级标题,默认情况下所有级别标题都会列出
:maxdepth: 1
的情况
Contents:
Sphinx使用 - html主题
zj_rst
:maxdepth: 2
的情况
Contents:
Sphinx使用 - html主题
* 内置主题
* 修改
* 自定义
zj_rst
reStructuredtext
语法¶
sphinx
使用reStructuredtext
作为标记语法,下面学习一些相关的内容
- 注释
- 列表
- 类引号块
- 标题
- 源文件引用
- 超链接
列表¶
* This is a bulleted list.
* It has two items, the second
item uses two lines.
1. This is a numbered list.
2. It has two items too.
#. This is a numbered list.
#. It has two items too.
类引号块¶
* this is
* a list
* with a nested list
* and some subitems
* and here the parent list continues
进行嵌套时,必须空一行
标题¶
段标题通过在标题下一行输入等于号('=='
)实现(注意:==
至少和标题一样长)
一级标题
===========
二级标题
**********
三级标题
^^^^^^^^
四级标题
---------
五级标题
>>>>>>>>>
六级标题
:::::::::
源文件引用¶
.. include:: 源文件路径
超链接¶
页内链接
# 引用锚点
锚点_
# 设置锚点
.. _锚点:
外部链接
引用名_
# 输入引用名对应的链接地址
.. _引用名: 链接地址
比如
* hexo.io_
* `hexojs/hexo`_
.. _hexo.io: https://hexo.io/
.. _`hexojs/hexo`: https://github.com/hexojs/hexo/
注意 1:引用名左右需要空格
注意 2:引用名如果带有空格或符号,用反引号括起来
html主题修改¶
内置主题¶
sphinx提供了多种内置主题,当前默认主题是alabaster,还有其他的主题 - builtin-themes
修改¶
修改conf.py中的html_theme
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
我修改成了readthedocs主题风格,它需要先自行安装
pip install sphinx_rtd_theme
自定义¶
sphinx也支持自定义主题,或者对当前主题进行微调 - using-a-theme
markdown
配置¶
sphinx
支持markdown
,使用的是CommonMark语法
配置¶
需要安装recommonmark
pip install recommonmark
然后在配置文件conf.py
中添加Markdown
解析器
source_parsers = {
'.md': 'recommonmark.parser.CommonMarkParser',
}
增加'.md'
作为扩展名
source_suffix = ['.rst', '.md']
MathJax支持¶
参考:
Math support for HTML outputs in Sphinx
Sphinx
教程介绍的是在配置工程时加入mathjax
选项就可以将公式编辑成图片
我用markdown
写文档时,在本地生成的文档中无法正确显示公式,但是在首页(index.rst
)中加入一句
:math:`\sigma_{1}`
就好了。母鸡?
不过在readthedocs
中可以正常显示的
$$ \begin{bmatrix} 1& 2& 3\ 4& 5& 6\ 7& 8& 9 \end{bmatrix}\Rightarrow \begin{bmatrix} 3& 2& 1\ 6& 5& 4\ 9& 8& 7 \end{bmatrix}\Rightarrow \begin{bmatrix} 9& 8& 7\ 6& 5& 4\ 3& 2& 1 \end{bmatrix} $$
MathJax
不支持¶
在sphinx
上使用markdown
编写数学公式时,扩展mathjax
的效果很差
比如行间公式$...$
就无法使用,得用\\(...)\\
另外对于另起一行插入数学公式$$...$$
,如果是单行公式能够支持,但是对于多行公式无法渲染
[pandoc]文档转换工具¶
偶然在网上找到一篇文章 - Markdown+Pandoc+Sphinx+ Git 协作写书式推进团队技术文章,里面提到了一个工具pandoc
,在网上搜索了其他文章 - 文件格式转换神器-pandoc
,发现这是一个通用的文档转换器
Ubuntu
安装¶
下载deb
包pandoc 2.5并安装
sudo dpkg -i pandoc*.deb
sudo apt-get install -f
测试安装
$ pandoc -v
pandoc 1.19.2.1
Compiled with pandoc-types 1.17.0.4, texmath 0.9, skylighting 0.1.1.4
Default user data directory: /home/zj/.pandoc
Copyright (C) 2006-2016 John MacFarlane
Web: http://pandoc.org
This is free software; see the source for copying conditions.
There is no warranty, not even for merchantability or fitness
for a particular purpose.
格式转换¶
pandoc
支持许多标记语言之间的转换,比如markdown
、json
、html
、lua
、reStructuredText
等等
目前比较关心的是markdown
和rst
之间的转换,使用如下命令
pandoc test.md -f markdown -t rst -s -o test1.rst
test.md
是源文件-f
表示源文件格式-t
表示结果文件格式-s
表示生成独立文件-o
表示结果文件名
经过测试发现确实有用,能够部分解决sphinx
中markdown
数学公式和表格的渲染问题
readthedocs¶
ReadtheDocs
介绍¶
Read the Docs
是一个在线文档浏览网站,现在常见的文档管理操作是ReadtheDocs+Github+Sphinx
即用Sphinx
制作文档,用Github
托管文档,用ReadtheDocs
在线浏览文档
在线发布¶
在本地新建sphinx
工程后,将本地文档发送到github
上,然后就可以在readthedocs
上发布在线文档
readthedocs
在github
有一个模板文档工程
生成的在线文档:Welcome to Read the Docs Template’s documentation!
上传文档¶
参考:Importing Your Documentation
上传地址:import
如果使用github
账号登录,那么可以直接在页面上显示你的工程(需要刷新);否则,需要手动导入
注意1:不需要上传build
目录,在readthedocs
导入时会自动编译
注意2:对于已经导入的工程,只要github
上有更新,那么会自动触发readthedocs
更新,不再需要手动操作
编译过程¶
如果你上传的是sphinx
工程,那么readthedocs
首先会在doc或docs文件夹内搜索conf.py
文件,然后是在其他位置,如果没有会自动生成一个
readthedocs完整的编译流程如下:
- 从
github
中check out
代码,如果已经下载,那么更新代码 - 根据你选择的生成格式(比如
sphinx html
)进行编译 - 将编译完成后的文件从构建服务器复制到应用服务器,复制完成后,就开始工作
编译问题¶
参考:
解决UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xe5 in position 108: ordinal not in range(128
Python3异常-AttributeError: module ‘sys’ has no attribute ‘setdefaultencoding’
编译conf.py
文件时,发生中文格式问题
Running Sphinx v1.7.9
WARNING: the config value 'epub_title' is set to a string with non-ASCII characters; this can lead to Unicode errors occurring. Please use Unicode strings, e.g. u'Content'.
WARNING: the config value 'project' is set to a string with non-ASCII characters; this can lead to Unicode errors occurring. Please use Unicode strings, e.g. u'Content'.
loading translations [en]... done
making output directory...
...
...
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128)
Encoding error:
'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128)
The full traceback has been saved in /tmp/sphinx-err-VIWOpI.log, if you want to report the issue to the developers.
有两种解决方法:
第一种是针对python2
,在conf.py
中如下代码,将编码格式改为utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
第二种是修改readthedocs
编译环境,在Admin->Advanced Settings->Python interpreter:
将选项修改成CPython 3.x
编译问题¶
问题一:编译conf.py
文件时,发生中文格式问题¶
参考:
解决UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xe5 in position 108: ordinal not in range(128
Python3异常-AttributeError: module ‘sys’ has no attribute ‘setdefaultencoding’
编译conf.py
文件时,发生中文格式问题
Running Sphinx v1.7.9
WARNING: the config value 'epub_title' is set to a string with non-ASCII characters; this can lead to Unicode errors occurring. Please use Unicode strings, e.g. u'Content'.
WARNING: the config value 'project' is set to a string with non-ASCII characters; this can lead to Unicode errors occurring. Please use Unicode strings, e.g. u'Content'.
loading translations [en]... done
making output directory...
...
...
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128)
Encoding error:
'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128)
The full traceback has been saved in /tmp/sphinx-err-VIWOpI.log, if you want to report the issue to the developers.
有两种解决方法:
第一种是针对python2
,在conf.py
中如下代码,将编码格式改为utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
第二种是修改readthedocs
编译环境,在Admin->Advanced Settings->Python interpreter:
将选项修改成CPython 3.x
问题二:pdflatex
编译出错¶
编译过程中运行pdflatex
时出错:
pdflatex -interaction=nonstopmode /home/docs/checkouts/readthedocs.org/user_builds/zj-computer-foundation/checkouts/latest/docs/source/_build/latex/sphinx.tex
出错提示:
This is pdfTeX, Version 3.14159265-2.6-1.40.16 (TeX Live 2015/Debian) (preloaded format=pdflatex)
restricted \write18 enabled.
entering extended mode
(/home/docs/checkouts/readthedocs.org/user_builds/zj-computer-foundation/checko
uts/latest/docs/source/_build/latex/sphinx.tex
LaTeX2e <2016/02/01>
Babel <3.9q> and hyphenation patterns for 81 language(s) loaded.
...
...
(/usr/share/texlive/texmf-dist/tex/generic/oberdiek/gettitlestring.sty))
(/usr/share/texlive/texmf-dist/tex/latex/psnfss/t1phv.fd)
! Package inputenc Error: Unicode char 计 (U+8BA1)
(inputenc) not set up for use with LaTeX.
See the inputenc package documentation for explanation.
Type H <return> for immediate help.
...
l.74 \sphinxtableofcontents
解决:pdfTex
是用于生成pdf
文件的命令,在Admin->Advanced Settings
中选择取消pdf
生成选项
Create a PDF version of your documentation with each build.