In recent days, I prepared some translated books and documents, found a number of tools, and finally froze 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. ReStructuredText was originally just used to generate Python project documentation in reStructuredText. But as the project has improved, many non-Python projects have adopted Sphinx as a document writing tool, and it’s even possible to write books in Sphinx.

The advantages of generating documents using Sphinx include:

  • Rich output formats: Supports output in HTML (including Windows help documents), LaTeX (you can print PDF versions), manual Pages (man documents), plain text, etc.
  • Complete cross-referencing: semantic tags that automate linking functions, classes, citations, terms, etc.
  • Clear hierarchical structure: Easily define document trees and automatically link to peer/parent/subordinate articles;
  • Beautiful automatic indexing: can automatically generate beautiful module index;
  • Precise syntax highlightingAutomatic syntax highlighting based on Pyacknowledgments;
  • Open extension: support for automatic testing of code blocks, automatic inclusion of Python module documentation, and more.

start

The process includes the following steps:

  • Install the Sphinx
  • First document
  • Hosted online
  • Generating PDF

Install the Sphinx

Sphinx relies on Python and provides a Python package, so a PIP installation can be used. The only package I have installed here is sphinx-doc.

pip install sphinx-doc
Copy the code

At this point, through bash autocomplete (two tabs in a row), you can see that there are several commands that Sphinx recommends using sphinx-Quickstart, which is a setup wizard.

$ sphinx-
sphinx-apidoc      sphinx-autogen     sphinx-build       sphinx-quickstart
Copy the code

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: A book
> Author name(s): qiwihui
>The Project release [] : 0.0.1

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]: 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/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.
Copy the code

Explanation 1, the whole setup process includes:

  1. Whether to separate the source directory from the build directory. By default, no.

  2. The templates directory and the static file directory are prefixed with the default _;

  3. Project name;

  4. Project author;

  5. Project version, empty by default;

  6. The project language, default is EN;

  7. Document extension, default.rst;

  8. Home file name, default index;

  9. The default value for enabled extensions is no:

    • autodoc
    • doctest
    • intersphinx
    • todo
    • coverage
    • imgmath
    • mathjax
    • ifconfig
    • viewcode
    • githubpages
  10. Generate a Makefile, default is;

  11. Generate Windows with command line, default is.

Explanation 2, the project directory file structure is as follows:

Sphinx - Test ├─ Makefile ├─ Build ├─ makeCopy the code

Among them:

  • Makefile: can be thought of as a file containing instructions that can be used to build the document output when using the make command.
  • build: Output directory of the generated file.
  • make.bat: Windows cli.
  • _static: static file directory, such as images, etc.
  • _templates: template directory.
  • conf.py: stores the Sphinx configuration included in thesphinx-quickstartYou can define other values for the selected values.
  • index.rst: document project start file.

Let’s look at what is generated by default:

$ 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.
Copy the code

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

The default alabaster style 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'
Copy the code

First document

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!
Copy the code

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`Copy the code

Recompile, at which point the document has changed.

Hosted online

ReadTheDocs is directly used to host Sphinx-generated web documents. Manage the previous document with Git and push it to Github. Then Import a Project from ReadTheDocs.

Alternatively, you can set custom domain names:

  1. Add the DNS CNAME record to domain name managementreadthedocs.io, such asonebook.qiwihui.com
  2. In the projectAdmin -> DomainsTo set the domain name added in the previous step, enable HTTPS, and save the configuration.

The process is simple.

Generating PDF

Sphinx generates PDFS by converting RST to Tex and then producing PDFS. This process encountered a lot of pits, and finally summarized the process as follows:

First, install the Tex environment. On macs, it is recommended to install MacTex instead of BasicTex, which handles a lot of problems on its own for beginners. When finished, update TexLive with TLMGR.

$ brew cask install mactex
$ sudo tlmgr update --self
Copy the code

You can then set the latex_engine and latex_elements parameters in con.py, 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 "En" \XeTeXlinebreakskip = 0pt plus 1pt \parindent 2em \definecolor{VerbatimColor}{RGB}{VerbatimColor} \setcounter{tocdepth}{3} \renewcommand\familydefault{\ttdefault} \renewcommand\CJKfamilydefault{\CJKrmdefault} '''
}
# Set up document
latex_documents = [
    (master_doc, 'sphinx.tex'.'Your first Sphinx book'.'作者:qiwihui'.'manual'.True),]Copy the code

Finally, compile:

$ make latexpdf
Copy the code

Make latexpdf will convert RST to Tex and generate PDF from Tex, which can be split manually:

$ make latex
$ cd build/latex
$ make
Copy the code

The resulting PDF document can be viewed under Build /latex.

The font

Use fc-list to get the font information and modify the font Settings accordingly.

$ brew install fontconfig
$ fc-list :lang=zh
Copy the code

Problems encountered:

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

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

conclusion

With a quick look at the flow of the documentation, In general Sphinx is excellent for writing project documentation, and reStructuredText has many advantages over Markdown.

GitHub repo: qiwihui/blog

Follow me: @qiwihui

Site: QIWIHUI