In the past few days, I have been preparing to arrange some translated books and documents, looking for a number of tools, and finally fixed them on Sphinx, and distributed and shared them based on the SaaS service provided by ReadTheDocs. This blog is a record and summary of the whole process.

Project code: Qiwihui/Sphinx-doc-starter

Know the Sphinx

Sphinx is a Python-based document generation project. At first it was just to generate Python project documents, using the formality of reStructuredText. But as the project has evolved, many non-Python projects have adopted Sphinx as a documentation tool, and books have even been written in Sphinx.

The advantages of using Sphinx to generate documentation include:

  • Rich output formats: Support for output in HTML (including Windows help document), LaTeX (you can print PDF version), Manual Pages (man document), plain text and many other formats;
  • Complete cross-references: Semantic tags that automatically link functions, classes, citations, terms, etc.
  • Clear layered structure: Easily define document trees and automatically link peer/parent/subordinate articles;
  • Beautifully automated indexing: Can automatically generate beautiful module index;
  • Accurate syntax highlighting: Automatically generate syntax highlighting based on Pygments;
  • Open extension: Support for automatic testing of code blocks, automatic inclusion of Python module readme documents, etc.


This process includes the following steps:

  • Install the Sphinx
  • The first document
  • Hosted online
  • Generating PDF

Install the Sphinx

Sphinx relies on Python and comes with a Python package, so you can install it using PIP. Here I only have the package Sphinx-doc installed.

pip install sphinx-doc

At this point, you can see a few commands by bash auto-completion (tabs twice in a row), and Sphinx recommends using Sphinx-QuickStart, which is a setup wizard.

$ sphinx-
sphinx-apidoc      sphinx-autogen     sphinx-build       sphinx-quickstart

Set the Sphinx

Run Sphinx-QuickStart with the following main Settings: project name, author name, and language (zh_CN), other defaults.

$Sphinx - QuickStart Welcome to the Sphinx 1.8.4 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]: 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: > Author name(s): qiwihui > 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 > 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]: 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]: Indicate which of the following Sphinx extensions should be enabled: > 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]: > imgmath: include math, rendered as PNG or SVG 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]: > githubpages: create .nojekyll file to publish the document on GitHub pages (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/ 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.

Explanation 1. The entire setup process includes:

  1. Whether to separate the source file directorysourceAnd the generated file directorybuild, default is no;
  2. The template directorytemplatesAnd static file directoriesstaticPrefix, default to_;
  3. Project name;
  4. Project author;
  5. Project version, default is empty;
  6. Project language, default toen;
  7. The document extension, default to.rst;
  8. Home page filename, default isindex;
  9. Open extensions, default to no:

    • autodoc
    • doctest
    • intersphinx
    • todo
    • coverage
    • imgmath
    • mathjax
    • ifconfig
    • viewcode
    • githubpages
  10. The Makefile is generated by default.
  11. Build Windows with the command line, default is.

Explanation 2. The project directory file structure is as follows:

Sphinx-Test Heavy Metal Exercises ── Makefile Heavy Metal Exercises ─ Makefile Heavy Metal Exercises ─ Makefile Heavy Metal Exercises ─ Makefile Heavy Metal Exercises ─ make.bat ├─ source Heavy Metal Exercises ─ _static Heavy Metal Exercises ─ _templates Heavy Metal Exercises ─ Heavy Metal Exercises ─ index.rst

Among them:

  • Makefile: can be thought of as a file containing directives that you can use to build the document output when using the make command.
  • build: The output directory of the generated files.
  • make.bat: Windows uses the command line.
  • _static: Directory of static files, such as pictures, etc.
  • _templates: Template directory.
  • Stores Sphinx configurations included insphinx-quickstartWhen the values are selected, you can define other values.
  • index.rst: Document project start file.

Let’s look at the default generation:

$Make HTML Running Sphinx v1.8.4 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.

Then open the build/ HTML /index.html file directly in the browser.

The default style is alabaster, which can be changed to ReadTheDocs style: Sphinx_rtd_theme.

# -- 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 = 'sphinx_rtd_theme'

The first document

Let’s take the following document as an example:

This is a Title
That has a paragraph about a main subject and is set when the '='
is at least the same length of the title itself.

Subject Subtitle
Subtitles are set with '-' and are required to have the same length
of the subtitle itself, just like titles.

Lists can be unnumbered like:

 * Item Foo
 * Item Bar

Or automatically numbered:

 #. Item 1
 #. Item 2

Inline Markup
Words can have *emphasis in italics* or be **bold** and you can define
code samples with back quotes, like when you talk about a command: ``sudo``
gives you super user powers!

Write it to example.rst and change index.rst to:

Welcome to a book's documentation! = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =). Toctree :: : MaxDepth: 2: Caption: example Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search`

Recompile when the document has changed.

Hosted online

ReadTheDocs can be used directly to host Sphinx generated web documents. Manage the previous document with Git, push it to GitHub, and Import a Project in ReadTheDocs.

Alternatively, you can set a custom field name:

  1. Add the DNS CNAME record to the domain name, such
  2. In the projectAdmin -> DomainsSet the domain name you added in the previous step in, turn on HTTPS, and save.

The process is simple.

Generating PDF

Sphinx’s PDF generation process first converts RST to TeX and then produces the PDF. This process encountered many pits, and the final summary of the process is as follows:

First, install the TeX environment. On a Mac, it is recommended to install MacTeX instead of BasicTeX, which requires you to handle a lot of problems yourself for beginners. When you’re done, update Texlive with TLMGR.

$ brew cask install mactex
$ sudo tlmgr update --self

Then, in, set the latex_engine and latex_elements parameters, and you can also set the latex_documents parameter to set the document.

latex_engine = 'xelatex' latex_elements = { 'papersize': 'a4paper', 'pointsize': '11pt', 'preamble': r''' \usepackage{xeCJK} \setCJKmainfont[BoldFont=STZhongsong, ItalicFont=STKaiti]{STSong} \setCJKsansfont[BoldFont=STHeiti]{STXihei} \setCJKmonofont{STFangsong} \XeTeXlinebreaklocale "Zh" \ XetexLineBreakSkip = 0pt plus 1pt \parindent 2em \definecolor{verbatimColor}{RGB}{0.95,0.95,0.95} \setcounter{tocdepth}{3} \renewcommand\familydefault{\ttdefault} \renewcommand\CJKfamilydefault{\CJKrmdefault} ''' } # Set latex_documents = [(master_doc, 'sphinx. Tex ', 'your first Sphinx book ',' author: qiwihui', 'manual', True),]

Finally, compile:

$ make latexpdf

Make Latexpdf converts RST to TeX and generates PDF from TeX, which can be separated manually:

$ make latex
$ cd build/latex
$ make

The generated PDF document can be viewed under Build/LaTeX.

The font

Use the FC-List to get the font information and change the corresponding font Settings.

$ brew install fontconfig
$ fc-list :lang=zh

Problems encountered:

  1. encounter! "" LaTeX Error: File '*.sty' not found."Class of problems:

Solution: Use sudo TLMGR install to install the corresponding package.


Having skimmed through the flow of documents, Sphinx is, in general, very well suited for writing project documents, and reStructuredText has too many advantages over Markdown to recommend it.

GitHub repo:

Follow me: @qiwihui