基于 Sphinx 以纯文本编写富媒体项目文档的方法介绍
文章目錄
- 簡介
- 環境
- 依賴安裝
- 安裝 Sphinx
- 安裝 PlantUML
- Sphinx 關鍵知識總結
- 使用方式
- Sphinx 中的 reStructedText 常用語法
- index.rst 中引用其他頁面
- 代碼
- 標題級別
- 圖片
- 引用代碼文件
- 變量替換
- 公式
- 示例項目下載
- 參考
簡介
本文介紹一種純文本書寫富媒體項目文檔的方式。
使用的工具有 python 文檔引擎 Sphinx,文本式 UML 工具 PlantUML,書寫文檔的格式是 reStructuredText。
以 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
使用 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 whiteskinparam note {BackgroundColor #F1FFFFBorderColor #2980B9 }skinparam activity {BackgroundColor #BDE3FFArrowColor #2980B9BorderColor #2980B9StartColor #227BC6EndColor #227BC6BarColor #227BC6 }skinparam sequence {ArrowColor #2980B9DividerBackgroundColor #BDE3FFGroupBackgroundColor #BDE3FFLifeLineBackgroundColor whiteLifeLineBorderColor #2980B9ParticipantBackgroundColor #BDE3FFParticipantBorderColor #2980B9BoxLineColor #2980B9BoxBackgroundColor #DDDDDD }skinparam actorBackgroundColor #FEFECE skinparam actorBorderColor #A80036skinparam usecaseArrowColor #A80036 skinparam usecaseBackgroundColor #FEFECE skinparam usecaseBorderColor #A80036skinparam classArrowColor #A80036 skinparam classBackgroundColor #FEFECE skinparam classBorderColor #A80036skinparam objectArrowColor #A80036 skinparam objectBackgroundColor #FEFECE skinparam objectBorderColor #A80036skinparam packageBackgroundColor #FEFECE skinparam packageBorderColor #A80036skinparam stereotypeCBackgroundColor #ADD1B2 skinparam stereotypeABackgroundColor #A9DCDF skinparam stereotypeIBackgroundColor #B4A7E5 skinparam stereotypeEBackgroundColor #EB937Fskinparam componentArrowColor #A80036 skinparam componentBackgroundColor #FEFECE skinparam componentBorderColor #A80036 skinparam componentInterfaceBackgroundColor #FEFECE skinparam componentInterfaceBorderColor #A80036skinparam stateBackgroundColor #BDE3FF skinparam stateBorderColor #2980B9 skinparam stateArrowColor #2980B9 skinparam stateStartColor black skinparam stateEndColor black修改 make.bat (如果是 Linux 下,參照修改 Makefile)為:
@ECHO OFFpushd %~dp0REM Command file for Sphinx documentationif "%SPHINXBUILD%" == "" (set SPHINXBUILD=sphinx-build ) set SOURCEDIR=. set BUILDDIR=_buildif "%1" == "" goto help%SPHINXBUILD% >NUL 2>NUL if errorlevel 9009 (echo.echo.The 'sphinx-build' command was not found. Make sure you have Sphinxecho.installed, then set the SPHINXBUILD environment variable to pointecho.to the full path of the 'sphinx-build' executable. Alternatively youecho.may add the Sphinx directory to PATH.echo.echo.If you don't have Sphinx installed, grab it fromecho.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:
@startumlAlice -> Bob: Hello world! Bob -> Alice: Hello world again!@enduml修改 index.rst 為:
.. Sample documentation master file, created bysphinx-quickstart on Fri Oct 12 17:22:09 2018.You can adapt this file completely to your liking, but it should at leastcontain 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:: luaSampleID = 5,更復雜一點的代碼片:打開的功能有高亮代碼行,顯示行數,提供代碼片標題,提供永久鏈接名
.. code-block:: lua:emphasize-lines: 3:linenos::caption: UI_GlobalLogic.lua:name: bind-idself.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|公式
https://build-me-the-docs-please.readthedocs.io/en/latest/Using_Sphinx/UsingMathEquationsInSphinx.html
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示例項目下載
- https://gitee.com/hustlion-dev/sphinx-sample
參考
總結
以上是生活随笔為你收集整理的基于 Sphinx 以纯文本编写富媒体项目文档的方法介绍的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 怎样截屏计算机桌面,如何快速截图? 电脑
- 下一篇: 超好用的卸载软件 —— Geek