基於 Sphinx 以純文字編寫富媒體專案文件的方法介紹
文章目錄
簡介
本文介紹一種純文字書寫富媒體專案文件的方式。
使用的工具有 python 文件引擎 Sphinx,文字式 UML 工具
以 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
依賴安裝
- 安裝 Sphinx
- 安裝 PlantUML
- 沒了。(想不到依賴這麼少吧.jpg)
以下是詳細
安裝 Sphinx
使用 pip 一鍵安裝:
pip install sphinx
然後建立文件專案。
# 在要建立文件的位置執行以下命令
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
目錄,這是最終編譯的的文件所在位置。具體目錄如圖
現在編譯專案,在當前路徑下
make html
成功時的提示:
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 安裝:
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
配置:
html_theme = "sphinx_rtd_theme"
html_theme_path = ["_themes", ]
# 避免編譯主題中的文件
exclude_patterns += ['_themes']
再次 make html
,現在的效果:
至此安裝和主題配置都完成了。
配置檔案最終內容:
# -*- 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
檔案,寫入以下內容:
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
)為:
@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
:
@startuml
Alice -> Bob: Hello world!
Bob -> Alice: Hello world again!
@enduml
修改 index.rst
為:
.. 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
,輸出為:
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
內容:
.. toctree::
:maxdepth: 2
:caption: 目錄:
001-CS流程說明
001-CS流程說明.rst
內容(注意標題下的等號要比標題自己長,否則報錯):
我是示例標題
==============
效果
程式碼
以 .. code-block:: lua
開頭,然後空一行,程式碼區要相對縮排兩個空格。可以接受一些選項,比如 :linenos:
顯示行號。
簡單程式碼片:
.. code-block:: lua
SampleID = 5,
更復雜一點的程式碼片:開啟的功能有高亮程式碼行,顯示行數,提供程式碼片標題,提供永久連結名
.. code-block:: lua
:emphasize-lines: 3
:linenos:
:caption: UI_GlobalLogic.lua
:name: bind-id
self.mTableNotification = {
-- ... 其他原有訊息號
CLIENT_NOTIFI_ID.SampleID,
};
function test ()
end
行內程式碼
``code``
標題級別
推薦的做法是與 Python’s Style Guide 採用的一致:
#
with overline, for parts*
with overline, for chapters=
, for sections-
, for subsections^
, for subsubsections"
, for paragraphs
圖片
.. image:: uml_generated/test.png
:align: center
引用程式碼檔案
.. literalinclude:: ./conf.py
變數替換
可以減少一些長字串的重複書寫。
參照:http://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html#substitutions
定義:
.. |target| replace:: ``Logic/UI/Global/UI_GlobalLogic.lua``
引用:
|target|
公式
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