【文檔】使用Sphinx + reST編寫文檔

0 前言

寫文檔是開發人員平常工做中的一項重要內容,除了word以外,我更偏心使用標記語言(Markup Language)。使用標記語言,能夠利用簡單、免費的文本編輯器(記事本,vim, emacs...)編寫文檔並設置格式,再生成html或pdf等格式,或者直接把編輯好的文件傳到github或wiki上面 ,經過瀏覽器能夠直接查看帶有格式的文檔。html

目前標記語言主要有兩種,Markdown和reStructuredText(簡稱reST)。該使用哪種是一個見仁見智的選擇,我在這裏就不比較它們(包括其餘標記語言)的優劣了,感興趣的能夠參考:node

對我我的來講,一開始嘗試了一段時間的Markdown,因爲工具很差用以及支持的格式很少的緣由,轉而使用reST,再配合sphinx,感受好極了。python

不少開源項目的文檔就是用sphinx+reST作的,好比最近我正關注的hyperscan:http://01org.github.io/hyperscan/dev-reference/。你們能夠點進去看一下生成的效果,它用的樣式是Alabaster 0.7.6。git

本文如下內容均在Ubuntu 14.04上驗證經過。github

 安裝軟件包

使用sphinx+reST編寫文檔,須要安裝一些軟件包vim

sudo apt-get install python-pip
sudo pip install -U Sphinx

若是要從代碼註釋生成API文檔,須要安裝doxygen和breathe插件,後者可讓sphinx處理doxygen生成的xml:瀏覽器

sudo apt-get install doxygen
sudo pip install breathe

若是要生成pdf文件,須要安裝texlive:bash

sudo apt-get install texlive-full

若是要生成中文pdf,則須要確認安裝了必要的東亞語言和字體包,好比texlive-lang-cjk和texlive-fonts-recommended,能夠參考http://www.tuicool.com/articles/nAJJVb 。  app

2 項目創建

最簡單的方法是創建工做目錄後(這裏是doc),在其中運行sphinx-quickstart。運行此命令後sphinx會問你一些問題,根據狀況回答便可。在這裏我創建了一個名爲foo的Project,版本是1.0,做者名爲zzq,將source與build目錄放開,其餘都選默認:框架

zzq@vmware:~/doc$ sphinx-quickstart 
Welcome to the Sphinx 1.3.3 quickstart utility.

Please enter values for the following settings (just press Enter to
accept a default value, if one is given in brackets).

Enter the root path for documentation.
> Root path for the documentation [.]: 

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]: y

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 [_]: 

The project name will occur in several places in the built documentation.
> Project name: foo
> Author name(s): zzq

Sphinx has the notion of a "version" and a "release" for the
software. Each version can have multiple releases. For example, for
Python the version is something like 2.5 or 3.0, while the release is
something like 2.5.1 or 3.0a1.  If you don't need this dual structure,
just set both to the same value.
> Project version: 1.0
> Project release [1.0]: 

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]: 

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]: 

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]: 

Sphinx can also add configuration for epub output:
> Do you want to use the epub builder (y/n) [n]: 

Please indicate if you want to use one of the following Sphinx extensions:
> autodoc: automatically insert docstrings from modules (y/n) [n]: 
> doctest: automatically test code snippets in doctest blocks (y/n) [n]: 
> intersphinx: link between Sphinx documentation of different projects (y/n) [n]: 
> todo: write "todo" entries that can be shown or hidden on build (y/n) [n]: 
> coverage: checks for documentation coverage (y/n) [n]: 
> pngmath: include math, rendered as PNG images (y/n) [n]: 
> mathjax: include math, rendered in the browser by MathJax (y/n) [n]: 
> ifconfig: conditional inclusion of content based on config values (y/n) [n]: 
> viewcode: include links to the source code of documented Python objects (y/n) [n]: 

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]: 

Creating file ./source/conf.py.
Creating file ./source/index.rst.
Creating file ./Makefile.
Creating file ./make.bat.

Finished: An initial directory structure has been created.

You should now populate your master file ./source/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.

zzq@vmware:~/doc$ 

執行完以上命令上doc目錄中有如下內容(根據執行sphinx-quickstart命令時對各問題的回答不一樣,下文的文件內容和文件名可能有所不一樣):

build  make.bat  Makefile  source

其中source和build分別是源文件和編譯生成文件的存放目錄,Makefile和make.bat分別是Linux和Windows下的makefile。

source目錄下有如下內容:

conf.py  index.rst  _static  _templates

其中conf.py是配置文件,index.rst是主框架文件,_static是靜態文件存放目錄,好比能夠放一些圖片什麼的,_templates是模板存放目錄。

咱們先建立2個文件intro.rst和sample.rst,在裏面只寫標題。這兩個文件的內容分別是
intro.rst:

intro
=====

sample.rst:

sample
======

 

而後編輯index.rst,在toctree指導語句(directive)中加入剛纔兩個文件的文件名,後綴省略,路徑是相對於源目錄source的:

Welcome to foo's documentation!                                    
===============================                                    
                                                                   
Contents:                                                          
                                                                   
.. toctree::                                                       
   :maxdepth: 2                                                    
                                                                   
   intro                                                           
   sample                                                          
               

此時,能夠回到source的上一級目錄(有Makefile的目錄),運行make html,便可在build目錄中生成HTML文件:

zzq@vmware:~/doc/source$ cd ..
zzq@vmware:~/doc$ make html
sphinx-build -b html -d build/doctrees   source build/html
Running Sphinx v1.3.3
loading pickled environment... done
building [mo]: targets for 0 po files that are out of date
building [html]: targets for 2 source files that are out of date
updating environment: 0 added, 2 changed, 0 removed
reading sources... [100%] sample                                                                                      
looking for now-outdated files... none found
pickling environment... done
checking consistency... done
preparing documents... done
writing output... [100%] sample                                                                                       
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.

Build finished. The HTML pages are in build/html.

編譯成功後使用瀏覽器打開build/html目錄下的index.html,是這樣的:

到此,一次典型的環境配置與html生成步驟就完成了。

若是以爲生成的html主題風格本身不喜歡,能夠個性source/conf.py,找到

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.                                     
html_theme = 'alabaster'

把alabaster改爲其餘主題名就行了 。內置的主題有很多,見:http://sphinx-doc.org/theming.html#builtin-themes

3 conf.py配置

3.1 主題樣式

設置alabaster主題只需在html_theme中設置名字便可:

html_theme = 'alabaster' 

而要設置更美觀的sphinx_rtd_theme主題,須要在文件頭部加上:

import sphinx_rtd_theme 

再設置html_theme:

html_theme = 'sphinx_rtd_theme'

3.2 LOGO

在html_logo中設置圖片文件路徑:

html_logo = './logo.png'

3.3 不顯示源文件連接

默認會在生成的html頁中顯示rst源文件連接,作以下設置後不顯示:

html_show_sourcelink = False

4 Index頁配置

主要是設置目錄樹:

.. toctree::
    :maxdepth: 3
    :numbered:

    foo
    bar

maxdepth把index.html頁中目錄的標題顯示深度限制設爲3,numbered爲編號。以後空一行,在下面列出各子文檔,能夠不加文件後綴。

注意:這裏一樣要注意代碼對齊。

5 生成API文檔

能夠配合使用sphinx+reST+breathe+doxygen來給代碼生成API文檔並沒有縫添加到已有的文檔結構中。

5.1 Step1

運行:

doxygen -g 

生成doxygen配置文件(默認文件名是Doxyfile),而後修改此文件:

  • 項目名稱 PROJECT_NAME = 「MyProject」
  • 對C項目優化 OPTIMIZE_OUTPUT_FOR_C = YES
  • 源文件路徑 INPUT = /home/tom/project/include
  • 源文件編碼 INPUT_ENCODEING = UTF-8
  • 生成XML GENERATE_XML = YES 由於要使用breathe擴展,因此必須生成xml
  • XML輸出目錄 XML_OUTPUT = my_xml
  • 不須要生成html GENERATE_HTML = NO
  • 不須要生成latex GENERATE_LATEX = NO
  • 不顯示包含文件 SHOW_INCLUDE_FILES = NO

5.2 Step2

運行:

doxygen [Doxyfile] 

輸出註釋,主要是xml。

5.3 Step3

配置conf.py,以支持breathe擴展。前提是這一擴展已經安裝。

加入擴展:

extensions = ['breathe'] 

配置breathe:

breathe_projects = { "myproject": "./my_xml" }
breathe_default_project = "myproject"
breathe_domain_by_extension = {"h" : "c"}

5.4 Step4

按breathe擴展語法編寫rst文件,好比:

My API
==========

sp.h
----

.. doxygenfile:: sp.h

上面的語句爲項目中的sp.h接口文件生成了html文檔。

最後,運行 make html 生成html便可。

在這些步驟中,須要先調用doxygen生成xml,再調用sphinx-build(make html時自動調用)生成最終文檔,若是想一步完成,能夠在Makefile中加入doxygen調用:

html:
    doxygen Doxyfile
    $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
    @echo
    @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."

 

6 生成PDF

生成PDF的前提是安裝了texlive,若是要生成中文PDF,還須要確認安裝了東亞語言包和字體包(texlive-lang-cjk, texlive-fonts-recommands之類)。

而後配置conf.py,在latex_elements中加入:

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': '''
\\hypersetup{unicode=true}
\\usepackage{CJKutf8}
\\AtBeginDocument{\\begin{CJK}{UTF8}{gbsn}}
\\AtEndDocument{\\end{CJK}}
''',

最後運行 make latexpdf 便可。

7 reST語法介紹

reStructuredText標記語言比Makedown強大不少,支持多種排版樣式。不過這裏只介紹開發人員主要會用到的一些樣式。reST文檔的詳細介紹見http://docutils.sourceforge.net/rst.html

7.1 章節標題

在文本下一行(或上一行)添加至少與文本長度同寬的符號,便可以使文本成爲標題。但並無規定某一個級別的標題必須用什麼字符,能夠參考python文檔的一些約定:

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

咱們把intro.rst改爲下面這樣:

                                                                                                                     
intro                                                              
=====                                                              
                                                                   
aaa                                                                
---                                                                
aaaaaaaaaaaa                                                       
                                                                   
bbbb                                                               
----                                                               
bbbbbbbbbbb

其中,intro是一級標題,aaa和bbbb是二級標題。

回到上一級目錄從新make html,生成的intro.html效果以下:

生成的html標籤分別是<h1>和<h2>。此時首頁index.html效果以下:

在右邊的Contents中,sphinx已經給咱們生成了各文件的標題連接,深度爲2,深度能夠在index.rst中的maxdepth中設置。然而index.html左邊的導航裏並無各文件的連接,像intro.html裏那樣,這個能夠經過修改conf.py實現,找到html_sidebars,改成:

html_sidebars = { '**': ['globaltoc.html', 'sourcelink.html', 'searchbox.html']}

修改後保存,從新make html,index.html左邊導航變爲以下這樣:

7.2 段落

段落是構成reST文檔的基本單位。經過一個或一個以上的空行隔開的文本區塊就是一個段落。正如在python裏同樣,reST中的縮進很是重要。同一段落的多個文本行必須有同樣的縮進。

注意在段落內換行並不會在html中生成換行符,要想保持在文本編輯器中的換行符,須要在這些行前面加上|和空格:

| aaaaaaaa                                                      
| bbbbbbbbb                                                     
| cccccccccccc 

7.3 行內標記

行內標記經常使用的有:

  • 字體加粗 兩個星號
  • 字體傾斜 一個星號
  • 代碼或內容引用 兩個反引號(`)

示例:

aaaa **加粗** aaaaa                                                
                                                                   
aaaa *傾斜* aaaaa                                                  
                                                                   
aaaaa ``引用`` aaaaaa  

效果:

注意這些符號在先後不能有非空白字符,不然沒法生效。

7.4 列表

  • 符號列表 *號後空格
  • 編號列表 數字加點加空格,或者#號加點加空格
  • 定義列表 術語(只能一行)的下一行縮進,下一行爲定義內容

示例:

* item                                                          
* item                                                          
* item                                                          
                                                                
1. item1                                                        
2. item2                                                        
3. item3                                                        
                                                                
#. item4                                                        
#. item5                                                        
#. item6                                                        
                                                                
FOO                                                             
    this is very interesting.                                   
                                                                
BAR                                                             
    this is interesting, too. 

效果:

7.5 代碼

在文檔中列出代碼是開發人員常常用到的一個功能。在reST文檔中列出代碼有三種方式:

  • 行內代碼 用``code``
  • 簡單代碼塊 在代碼塊的上一個段落後面加2個冒號,空一行後開始代碼塊,代碼塊要縮進
  • 複雜代碼塊 使用code-block指導語句,還能夠選擇列出行號和高亮重點行等

示例:

source code below ::                                             
                                                                
    void foo()                                                  
    {                                                           
        int i;                                                  
                                                                
        for(i=0; i<10; i++)                                     
            printf("i: %d\n", a);                               
    }                                                           
                                                                
source code again                                               
                                                                
.. code-block:: c                                               
    :linenos:                                                   
    :emphasize-lines: 3,6                                       
                                                                
    void foo()                                                  
    {                                                                                            
        int i;                                                  
                                                                
        for(i=0; i<10; i++)                                     
            printf("i: %d\n", a);                               
    }                                                           
                                     

效果:

7.6 超連接

主要有兩種方式:

  • 行內超連接 語法`連接文字 <URL>`_
  • 分開的超連接 用到連接的地方`連接文字`_, 定義連接的地方 .. _連接文字: URL

記住連接URL要加http://前綴,不要直接從網址開始寫。

示例:

visit `baidu <http://www.baidu.com>`_                           
                                                                
visit `baidu URL`_                                              
                                                                
.. _baidu URL: http://www.baidu.com   

效果:

7.7 圖片

使用image指導語句。

示例:

baidu logo:                                                     
                                                                
.. image:: ./images/bdlog.png                                   
    :width: 200px 

效果:

// TODO: figure

7.8 表格

使用文本字符繪製的表格。簡單表格用的字符較少,但功能有限,如不能表格行不能換行;複雜不及格使用的字符較多。

示例:

simple table:                                                   
                                                                
=====  =====  ======                                            
   Inputs     Output                                            
------------  ------                                            
A      B      A or B                                            
=====  =====  ======                                            
False  False  False                                             
True   False  True                                                                               
False  True   True                                              
True   True   True                                              
=====  =====  ======                                            
                                                                
grid table: 
                                                               
+------------------------+------------+----------+----------+   
| Header row, column 1   | Header 2   | Header 3 | Header 4 |   
| (header rows optional) |            |          |          |   
+========================+============+==========+==========+   
| body row 1, column 1   | column 2   | column 3 | column 4 |   
+------------------------+------------+----------+----------+   
| body row 2             | Cells may span columns.          |   
+------------------------+------------+---------------------+   
| body row 3             | Cells may  | - Table cells       |   
+------------------------+ span rows. | - contain           |   
| body row 4             |            | - body elements.    |   
+------------------------+------------+---------------------+ 

效果:

7.9 引用

示例:

It is methioned by [Ref]_ that C++ is good.                     
                                                                
.. [Ref] 《zzq's talk》

效果:

7.10 腳註

與引用語法相似,只是它在正文中顯示的不是文本,而是編號。

示例:

orem ipsum [#f1]_ dolor sit amet ... [#f2]_                    
                                                                
Footnotes                                                       
                                                                
.. [#f1] Text of the first footnote.                            
.. [#f2] Text of the second footnote.   

效果:

7.11 替換

替換相似腳註,在正文中使用|text|這樣標籤,而後能夠設定使用其餘文本或者圖片來代替text這個佔位符。

示例:

I like eat |apple| very much.                                   
                                                                
.. |apple| replace:: 蘋果  

效果:

I like eat 蘋果 very much.

參考

  1. sphinx-doc官網
  2. reStructuredText標記語言規範
相關文章
相關標籤/搜索