写文档是开发人员平常工做中的一项重要内容,除了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
最简单的方法是创建工做目录后(这里是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
设置alabaster主题只需在html_theme中设置名字便可:
html_theme = 'alabaster'
而要设置更美观的sphinx_rtd_theme主题,须要在文件头部加上:
import sphinx_rtd_theme
再设置html_theme:
html_theme = 'sphinx_rtd_theme'
在html_logo中设置图片文件路径:
html_logo = './logo.png'
默认会在生成的html页中显示rst源文件连接,作以下设置后不显示:
html_show_sourcelink = False
主要是设置目录树:
.. toctree:: :maxdepth: 3 :numbered: foo bar
maxdepth把index.html页中目录的标题显示深度限制设为3,numbered为编号。以后空一行,在下面列出各子文档,能够不加文件后缀。
注意:这里一样要注意代码对齐。
能够配合使用sphinx+reST+breathe+doxygen来给代码生成API文档并没有缝添加到已有的文档结构中。
运行:
doxygen -g
生成doxygen配置文件(默认文件名是Doxyfile),而后修改此文件:
运行:
doxygen [Doxyfile]
输出注释,主要是xml。
配置conf.py,以支持breathe扩展。前提是这一扩展已经安装。
加入扩展:
extensions = ['breathe']
配置breathe:
breathe_projects = { "myproject": "./my_xml" } breathe_default_project = "myproject" breathe_domain_by_extension = {"h" : "c"}
按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."
生成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
便可。
reStructuredText标记语言比Makedown强大不少,支持多种排版样式。不过这里只介绍开发人员主要会用到的一些样式。reST文档的详细介绍见http://docutils.sourceforge.net/rst.html
在文本下一行(或上一行)添加至少与文本长度同宽的符号,便可以使文本成为标题。但并无规定某一个级别的标题必须用什么字符,能够参考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左边导航变为以下这样:
段落是构成reST文档的基本单位。经过一个或一个以上的空行隔开的文本区块就是一个段落。正如在python里同样,reST中的缩进很是重要。同一段落的多个文本行必须有同样的缩进。
注意在段落内换行并不会在html中生成换行符,要想保持在文本编辑器中的换行符,须要在这些行前面加上|和空格:
| aaaaaaaa | bbbbbbbbb | cccccccccccc
行内标记经常使用的有:
示例:
aaaa **加粗** aaaaa aaaa *倾斜* aaaaa aaaaa ``引用`` aaaaaa
效果:
注意这些符号在先后不能有非空白字符,不然没法生效。
示例:
* item * item * item 1. item1 2. item2 3. item3 #. item4 #. item5 #. item6 FOO this is very interesting. BAR this is interesting, too.
效果:
在文档中列出代码是开发人员常常用到的一个功能。在reST文档中列出代码有三种方式:
示例:
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); }
效果:
主要有两种方式:
记住连接URL要加http://前缀,不要直接从网址开始写。
示例:
visit `baidu <http://www.baidu.com>`_ visit `baidu URL`_ .. _baidu URL: http://www.baidu.com
效果:
使用image指导语句。
示例:
baidu logo: .. image:: ./images/bdlog.png :width: 200px
效果:
// TODO: figure
使用文本字符绘制的表格。简单表格用的字符较少,但功能有限,如不能表格行不能换行;复杂不及格使用的字符较多。
示例:
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. | +------------------------+------------+---------------------+
效果:
示例:
It is methioned by [Ref]_ that C++ is good. .. [Ref] 《zzq's talk》
效果:
与引用语法相似,只是它在正文中显示的不是文本,而是编号。
示例:
orem ipsum [#f1]_ dolor sit amet ... [#f2]_
Footnotes
.. [#f1] Text of the first footnote.
.. [#f2] Text of the second footnote.
效果:
替换相似脚注,在正文中使用|text|这样标签,而后能够设定使用其余文本或者图片来代替text这个占位符。
示例:
I like eat |apple| very much.
.. |apple| replace:: 苹果
效果:
I like eat 苹果 very much.