sphinx-github-readthedocs

sphinx

sphinx介绍

官网:SPHINX

sphinx是一个文档生成工具,可用于多种语言,有以下特性:

  1. 输出格式:生成文档可以是HTML、LaTex、ePub、Textinfo、manual pages、plain text
  2. 强大的互参考功能:用于函数、类、引文、词汇术语和相似信息的语义标记和自动链接
  3. 层次结构:文档树的简单定义,自动链接到同级,父类和子类节点
  4. 自动索引:通用索引以及语言特定的模块索引
  5. 代码处理:使用Pygments高亮器实现自动高亮
  6. 扩展功能:代码片段的自动测试,包括来自Python模块(API文档)的文档字符串,以及更多
  7. 贡献扩展:超过50个扩展包被用户发布在另一个仓库,其中的大多数可以通过PyPI安装

默认情况下,sphinx使用reStructuredText语言作为标记语言,它也支持markdown(需要设置)


安装

参考:Installing Sphinx

sphinx提供了多种安装方式,常用Python安装方式:

pip install -U Sphinx

升级sphinx同样使用此命令

Sphinx-bug

Sphinx工程目前还没有完全支持markdown,尤其是对于数学公式

比如在Markdown中,行内数学符号用$…$,行外数学符号用$$…$$

但是在Sphinx工程中,无法实现行内数学符号效果,行外数学符号也只支持单行

所以如果有涉及数学公式的文章,还是使用其他方法好一点

在github上提了一个bug:Sphinx Markdown MathJax doesn’t work correctly #5957

快速生成文档工程

参考:Getting Started

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.

指定下列扩展功能是否使用

  1. autodoc: 自动从模块中插入文档字符串
  2. doctest: 自动测试文档测试块中的代码片段
  3. intersphinx: 链接不同工程中的sphinx文档
  4. todo: 是否在构建时显示或隐藏'todo'条目
  5. coverage: 检查文档覆盖率
  6. imgmath: 将数学公式渲染为PNGSVG图像
  7. mathjax: 在浏览器中用MathJax渲染数学公式
  8. ifconfig: conditional inclusion of content based on config values
  9. viewcode: 文档化Python对象源代码的包含链接
  10. githubpages: 创建一个.nojekyll文件,以便发布到github

需要注意的是,不能同时配置imgmathmathjax

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即可

_images/new_project.png

如果源文件和输出文件放置在一起,那么输出会在_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目录树

参考:

Directives

Defining document structure

目录树


指令

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
caption

caption用于生成目录树标题,当前是Content,比如,修改成“目录树”

目录树:

Sphinx使用 - html主题
zj_rst

reStructuredtext语法

sphinx使用reStructuredtext作为标记语法,下面学习一些相关的内容

  • 注释
  • 列表
  • 类引号块
  • 标题
  • 源文件引用
  • 超链接

注释

使用..表示注释

.. 注释内容



.. 注释1
    注释2
    注释3

列表

* 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

进行嵌套时,必须空一行

标题

段标题通过在标题下一行输入等于号('==')实现(注意:==至少和标题一样长

一级标题
===========

二级标题
**********

三级标题
^^^^^^^^

四级标题
---------

五级标题
>>>>>>>>>

六级标题
:::::::::

_images/titles.png

源文件引用

.. include:: 源文件路径

超链接

页内链接

# 引用锚点
锚点_
# 设置锚点
.. _锚点:

外部链接

引用名_
# 输入引用名对应的链接地址
.. _引用名: 链接地址

比如

* hexo.io_
* `hexojs/hexo`_

.. _hexo.io: https://hexo.io/

.. _`hexojs/hexo`: https://github.com/hexojs/hexo/ 

_images/out-ref.png

注意 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

_images/rtd_theme.png

自定义

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

Creating equations 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安装

下载debpandoc 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支持许多标记语言之间的转换,比如markdownjsonhtmlluareStructuredText等等

_images/diagram.jpg

目前比较关心的是markdownrst之间的转换,使用如下命令

pandoc test.md -f markdown -t rst -s -o test1.rst
  • test.md是源文件
  • -f表示源文件格式
  • -t表示结果文件格式
  • -s表示生成独立文件
  • -o表示结果文件名

经过测试发现确实有用,能够部分解决sphinxmarkdown数学公式和表格的渲染问题

readthedocs

ReadtheDocs介绍

官网:Read the Docs

Read the Docs是一个在线文档浏览网站,现在常见的文档管理操作是ReadtheDocs+Github+Sphinx

即用Sphinx制作文档,用Github托管文档,用ReadtheDocs在线浏览文档


登录

首先需要注册一个ReadtheDocs账号

Sign Up

推荐直接用githb账号登录

在线发布

在本地新建sphinx工程后,将本地文档发送到github上,然后就可以在readthedocs上发布在线文档

readthedocsgithub有一个模板文档工程

rtfd/template

生成的在线文档:Welcome to Read the Docs Template’s documentation!

上传文档

参考:Importing Your Documentation

上传地址:import

如果使用github账号登录,那么可以直接在页面上显示你的工程(需要刷新);否则,需要手动导入

注意1:不需要上传build目录,在readthedocs导入时会自动编译

注意2:对于已经导入的工程,只要github上有更新,那么会自动触发readthedocs更新,不再需要手动操作

编译过程

参考:Build Process

如果你上传的是sphinx工程,那么readthedocs首先会在doc或docs文件夹内搜索conf.py文件,然后是在其他位置,如果没有会自动生成一个

readthedocs完整的编译流程如下:

  • githubcheck 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.

ReadtheDocs - 添加徽章

参考:Badges

ReadtheDocs网站上新建工程后,可以添加状态徽章(status badges)

其位置在工程主页->概述(Overview)子页中

_images/badge.png

点击Badge选项下的Get this badge按钮,就会跳出相应使用链接

_images/get-badge.png