Sphinx 常见问题

这是一份关于 Sphinx 的常见问题清单。欢迎提出新的条目!

我如何 …

… 不用 LaTeX 就能创建 PDF 文件?

rinohtype 提供了一个 PDF 生成器,可以作为 LaTeX 生成器的直接替代。

… 获得章节编号?

它们在 LaTeX 输出中是自动的;对于 HTML,在你想开始编号的地方给 toctree 指令一个 :numbered: 选项。

… 自定义内置 HTML 文件的外观?

使用主题,参阅 HTML 主题化

… 添加全局替换或包括?

rst_prologrst_epilog 配置值中添加它们。

… 在侧边栏显示整个 TOC 树?

在自定义布局模板中使用 toctree 可调用,可能在 sidebartoc 块中。

… 编写我自己的插件?

参阅 插件教程

… 使用 MoinMoin 标记从我现有的文档转换?

最简单的方法是转换为 xhtml,然后将 xhtml 转换为 reST。你仍然需要标记类和类似的东西,但标题和代码示例会很干净。

更多的插件和其他贡献的东西,请看 sphinx-contrib 仓库。

将 Sphinx 与 …

Read the Docs

Read the Docs 是一个基于 Sphinx 的文档托管服务。他们将托管 sphinx 文档,同时支持其他一些功能,包括版本支持、PDF 生成等等。Getting Started 是一个很好的开始。

Epydoc

有一个第三方扩展提供了一个 api role,它指的是 Epydoc 的 API 文档,用于给定的标识符。

Doxygen

Michael Jones 正在开发一个 reST/Sphinx 与 doxygen 的桥梁,名为 breathe

SCons

Glenn Hutchings 写了一个 SCons 构建脚本来构建 Sphinx 文档;它的被托管在:https://bitbucket.org/zondo/sphinx-scons

PyPI

Jannis Leidel 写了一个 setuptools 命令,可以自动将 Sphinx 文档上传到 PyPI 软件包文档区 https://pythonhosted.org/

GitHub Pages

请将 sphinx.ext.githubpages 添加到你的项目中。它允许你在 GitHub Pages 中发布你的文档。它为 GitHub Pages 自动生成关于构建 HTML 文档的辅助文件。

MediaWiki

See https://bitbucket.org/kevindunn/sphinx-wiki/wiki/Home, a project by Kevin Dunn.

Google Analytics

你可以使用一个自定义的 layout.html 模板,像这样:

{% extends "!layout.html" %}

{%- block extrahead %}
{{ super() }}
<script>
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'XXX account number XXX']);
  _gaq.push(['_trackPageview']);
</script>
{% endblock %}

{% block footer %}
{{ super() }}
<div class="footer">This page uses <a href="https://analytics.google.com/">
Google Analytics</a> to collect statistics. You can disable it by blocking
the JavaScript coming from www.google-analytics.com.
<script>
  (function() {
    var ga = document.createElement('script');
    ga.src = ('https:' == document.location.protocol ?
              'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    ga.setAttribute('async', 'true');
    document.documentElement.firstChild.appendChild(ga);
  })();
</script>
</div>
{% endblock %}
Google Search

用谷歌搜索替换 Sphinx 的内置搜索功能,步骤如下:

  1. https://cse.google.com/cse/all,创建谷歌搜索的代码片段。

  2. 复制代码片段并将其粘贴到你的 Sphinx 项目中的 _templates/searchbox.html 中:

    <div>
       <h3>{{ _('Quick search') }}</h3>
       <script>
          (function() {
             var cx = '......';
             var gcse = document.createElement('script');
             gcse.async = true;
             gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
             var s = document.getElementsByTagName('script')[0];
             s.parentNode.insertBefore(gcse, s);
          })();
       </script>
      <gcse:search></gcse:search>
    </div>
    
  3. html_sidebars 配置值中添加 searchbox.html

Sphinx vs. Docutils

tl;dr: docutils 将 reStructuredText 转换为多种输出格式。Sphinx 建立在 docutils 的基础上,允许构建交叉引用和索引的文档体。

docutils 是一个文本处理系统,用于将纯文本文档转换为其他更丰富的格式。正如 docutils 文档 中所指出的,docutils 使用 读取器 来读取文档,解析器 将纯文本格式解析为由不同类型的 节点 组成的内部树状表示,写入器 以各种文档格式输出该树状表示。docutils 为一种纯文本格式提供了解析器 —— reStructuredText —— 尽管其他 out-of-tree 解析器已经被实现,包括 Sphinx 的 Markdown 解析器。另一方面,它为许多不同的格式提供了写入器,包括 HTML、LaTeX、man pages、Open Document Format 和 XML。

docutils 通过各种 前端工具 暴露其所有功能,如 rst2htmlrst2odtrst2xml。但重要的是,所有这些工具,以及 docutils 本身,都与单个文档有关。它们不支持交叉引用、文档索引或构建文档层次结构(通常表现为目录)等概念”

Sphinx 以 docutils 为基础,利用 docutils 的阅读器和解析器,并提供自己的 构建器。因此,Sphinx 包装了一些由 docutils 提供的 writers。这使得 Sphinx 可以提供许多用 docutils 根本不可能实现的功能,比如上面提到的那些。

Epub 信息

以下列表给出了创建 epub 文件的一些提示:

  • 将文本分成几个文件。单个 HTML 文件越长,电子书阅读器渲染它们所需的时间就越长。在极端情况下,渲染时间可能长达一分钟。

  • 尽量减少标记。这也是对渲染时间的回报。

  • For some readers you can use embedded or external fonts using the CSS @font-face directive. This is extremely useful for code listings which are often cut at the right margin. The default Courier font (or variant) is quite wide and you can only display up to 60 characters on a line. If you replace it with a narrower font, you can get more characters on a line. You may even use FontForge and create narrow variants of some free font. In my case I get up to 70 characters on a line.

    You may have to experiment a little until you get reasonable results.

  • Test the created epubs. You can use several alternatives. The ones I am aware of are Epubcheck, Calibre, FBreader (although it does not render the CSS), and Bookworm. For Bookworm, you can download the source from https://code.google.com/archive/p/threepress and run your own local server.

  • Large floating divs are not displayed properly. If they cover more than one page, the div is only shown on the first page. In that case you can copy the epub.css from the sphinx/themes/epub/static/ directory to your local _static/ directory and remove the float settings.

  • Files that are inserted outside of the toctree directive must be manually included. This sometimes applies to appendixes, e.g. the glossary or the indices. You can add them with the epub_post_files option.

  • The handling of the epub cover page differs from the reStructuredText procedure which automatically resolves image paths and puts the images into the _images directory. For the epub cover page put the image in the html_static_path directory and reference it with its full path in the epub_cover config option.

  • kindlegen command can convert from epub3 resulting file to .mobi file for Kindle. You can get yourdoc.mobi under _build/epub after the following command:

    $ make epub
    $ kindlegen _build/epub/yourdoc.epub
    

    The kindlegen command doesn’t accept documents that have section titles surrounding toctree directive:

    Section Title
    =============
    
    .. toctree::
    
       subdocument
    
    Section After Toc Tree
    ======================
    

    kindlegen assumes all documents order in line, but the resulting document has complicated order for kindlegen:

    ``parent.xhtml`` -> ``child.xhtml`` -> ``parent.xhtml``
    

    If you get the following error, fix your document structure:

    Error(prcgen):E24011: TOC section scope is not included in the parent chapter:(title)
    Error(prcgen):E24001: The table of content could not be built.
    

Texinfo info

There are two main programs for reading Info files, info and GNU Emacs. The info program has less features but is available in most Unix environments and can be quickly accessed from the terminal. Emacs provides better font and color display and supports extensive customization (of course).

Notes

The following notes may be helpful if you want to create Texinfo files:

  • Each section corresponds to a different node in the Info file.

  • Colons (:) cannot be properly escaped in menu entries and xrefs. They will be replaced with semicolons (;).

  • Links to external Info files can be created using the somewhat official URI scheme info. For example:

    info:Texinfo#makeinfo_options
    
  • Inline markup

    The standard formatting for *strong* and _emphasis_ can result in ambiguous output when used to markup parameter names and other values. Since this is a fairly common practice, the default formatting has been changed so that emphasis and strong are now displayed like `literal's.

    The standard formatting can be re-enabled by adding the following to your conf.py:

    texinfo_elements = {'preamble': """
    @definfoenclose strong,*,*
    @definfoenclose emph,_,_
    """}