reStructuredText 初级入门

reStructuredText 是 Sphinx 默认使用的纯文本标记语言。这个部分简要介绍 reStructuredText(reST) 的概念和语法,目标是给文档创作者足够的知识,提高工作效率。由于 reST 设计目标本来就是简单的标记语言,学起来也不会很费力。

参见

权威的 reStructuredText 用户文档。本文中的“ref”链接也是指向这个 reST 文档的相应部分。

段落

段落(ref)是 reST 文档中最基本的组成部分。段落就是大段的文字,段落之间可以有空行。如同 Python 一样,reST 中缩进也很重要,所以同一段落中的内容,左侧都要使用同样的缩进量。

行内标记

标准的 reST 行内标记非常简单,如下:

  • 一个星号: *文本* 表示强调(斜体),

  • 两个星号: **文本** 表示更加强调(粗体),以及

  • 反单引号: ``text`` 表示代码样例。

如果文本中的星号或者反单引号可能被混淆为行内标记分隔符,添加反斜杠转义即可。

注意,这些标记有些功能限制:

  • 不能嵌套,

  • 标记内不能以空格开始: ``* 文本*``就不行,

  • 行内标记符号外只能是非文字字符。想写空格的话就要转义:thisis\ *one*\ word

这些限制,在将来的 docutils 版本中可能会放宽。

还可以用角色替换或扩展某些内联标记。有关更多信息,请参考 角色

列表、引用及其他区块样式

列表标记(ref)是自然的:只要在段落的开头加上星号并正确地缩进即可。编号列表也是如此;它们也可以使用“#”符号来自动编号:

* This is a bulleted list.
* It has two items, the second
  item uses two lines.

1. This is a numbered list.
2. It has two items too.

#. This is a numbered list.
#. It has two items too.

也可以嵌套列表,但注意它们必须通过空行与父列表项分开:

* this is
* a list

  * with a nested list
  * and some subitems

* and here the parent list continues

定义列表(ref 1)创建如下:

term (up to a line of text)
   Definition of the term, which must be indented

   and can even consist of multiple paragraphs

next term
   Description.

请注意,一个术语可以有很多段,段与段之间用空行分隔,但一段只能有一行文本。

引用的段落(ref)只是通过缩进它们来创建,而不是根据周围的段落创建。

行块(ref)是一种保留换行符的方法:

| These lines are
| broken exactly like in
| the source file.

还有几个特殊的块可用:

  • 字段列表( ref ,在 字段列表 中有注释)

  • 选项列表(ref

  • 引用文字块( ref

  • doctest块(ref

文字块

文字代码块(ref)是通过在段落结束时使用特殊标记“::”来引入的。文字块必须缩进(和所有段落一样,用空行隔开周围的段落):

This is a normal text paragraph. The next paragraph is a code sample::

   It is not processed in any way, except
   that the indentation is removed.

   It can span multiple lines.

This is a normal text paragraph again.

“::”标记的处理很灵活:

  • 如果它作为一个单独的段落出现,那么该段落将完全从文档中删除。

  • 如果前面有空格,则删除该标记。

  • 如果前面有非空格,则该标记将被单个冒号替换。

这样,上面示例的第一段的第二句话将被呈现为“下一段是代码示例:”。

代码高亮显示可以在文档范围内使用 highlight 指令为这些文字块启用,在项目范围内使用 highlight_language 配置选项启用。指令的 code-block 可以用于在一个块一个块的基础上设置高亮显示。稍后将讨论这些指令。

doctest块

Doctest块(ref)是将交互式的Python会话剪切粘贴到文档字符串中。它们不需要 literal blocks 语法。doctest 块必须以空行结束,并且 以未使用的提示符结束:

>>> 1 + 1
2

表格

对于 网格式表格ref),你必须自己“绘制”单元格网格。它们是这样的:

+------------------------+------------+----------+----------+
| Header row, column 1   | Header 2   | Header 3 | Header 4 |
| (header rows optional) |            |          |          |
+========================+============+==========+==========+
| body row 1, column 1   | column 2   | column 3 | column 4 |
+------------------------+------------+----------+----------+
| body row 2             | ...        | ...      |          |
+------------------------+------------+----------+----------+

简单表格ref)更容易撰写,但有限制:它们必须包含不止一行,第一列单元格不能包含多行。如:

=====  =====  =======
A      B      A and B
=====  =====  =======
False  False  False
True   False  False
False  True   False
True   True   True
=====  =====  =======

另外还支持两种语法: CSV表列表 。它们使用显式标记块。参考 表格 获取更多信息。

章节

在章节标题的下一行添加英文标点符号做装饰,这样就创建了章节头 (ref) 。也可以同时在章节标题的上一行添加标点符号来创建,只是无论哪种方式,标点字符串的长度至少要和标题一样长:

=================
This is a heading
=================

Normally, there are no heading levels assigned to certain characters as the structure is determined from the succession of headings. However, this convention is used in Python Developer’s Guide for documenting which you may follow:

  • “#” 用于“部分” (part)

  • “*”,用于章 (chapter)

  • = for sections

  • - for subsections

  • ^ for subsubsections

  • " for paragraphs

当然,您可以自由使用自己的标记字符(请参阅reST文档),并使用更深层次的嵌套级别,但请记住,大多数目标格式(HTML,LaTeX)具有有限的支持嵌套深度。

字段列表

字段列表(ref)是这样标记的字段序列:

:fieldname: Field content

它们通常在Python文档中使用:

def my_function(my_arg, my_other_arg):
    """A function just for me.

    :param my_arg: The first of my arguments.
    :param my_other_arg: The second of my arguments.

    :returns: A message (just for me, of course).
    """

Sphinx扩展了标准的docutils行为,并截取文档开头指定的字段列表。请参考 字段列表 以获得更多信息。

角色

A role or “custom interpreted text role” (ref) is an inline piece of explicit markup. It signifies that the enclosed text should be interpreted in a specific way. Sphinx uses this to provide semantic markup and cross-referencing of identifiers, as described in the appropriate section. The general syntax is :rolename:`content`.

Docutils支持以下角色:

有关 Sphinx 中添加的角色,可参考 角色

显式标记

“显式标记”(ref)在reST中用于大多数需要特殊处理的构造,例如脚注,特别突出显示的段落,注释和泛型指令。

显式标记块以一行开头,以”..”开头,后跟空格,并在相同的缩进级别由下一段终止。 (显式标记和普通段落之间需要有一个空行。这可能听起来有点复杂,但是当你写它时它足够直观。)

指令

指令(ref)是显式标记的通用块。除了角色之外,它也是reST的扩展机制之一,并且Sphinx大量使用了它。

Docutils支持以下指令:

  • 警告: 注意, 警示, 危险, 错误, 暗示, 重要, 注释, 技巧, 警告(warning) 以及泛型 警告(admonitions)。 (大多数主题仅限于 “注释” 和 “警告(warning)” 。)

  • 图片:

  • 附加构成元素:

    • 内容 (本地,即仅当前文件,目录)

    • 容器  (一个带有自定义类的容器,用于在HTML中生成外部“<div>” )

    • 标题 (与文档切片无关的标题)

    • 主题, 侧边栏 (突出显示的构成元素)

    • 文字解析 (支持行内标记的文字块)

    • 引用 (带有可选归因线的块引用)

    • 高亮, 重要引文 (带有自己的类属性的块引号)

    • 复合段  (复合段)

  • 特殊表格:

  • 特别指令:

    • 原始 (包括原始目标格式标记)

    • 包含 (包含另外文件的 reStructuredText ) – 在Sphinx中,当给定一个绝对包含文件路径时,该指令将其作为相对于源目录的路径

    • class (assign a class attribute to the next element)

      备注

      When the default domain contains a class directive, this directive will be shadowed. Therefore, Sphinx re-exports it as rst-class.

  • HTML细节:

    • (生成HTML <meta> 标签,另见下方的:ref:html-meta )

    • 文档标题 (覆盖文档标题)

  • 影响标记:

    由于这些只是每个文件,因此最好使用Sphinx的工具来设置:confval:默认角色

警告

不要 使用指令 sectnumheaderfooter

Sphinx 添加的指令见 指令

基本上,指令由名称、参数、选项和内容组成。(记住这个术语,它将在下一章描述自定义指令中使用。)看看这个例子,:

.. function:: foo(x)
              foo(y, z)
   :module: some.module.name

   Return a line of text input from the user.

“function”是指令名称。这里给出了两个参数,第一行的其余部分和第二行,以及一个选项“模块”(如你所见,选项在紧跟在参数后面的行中给出并由冒号表示)。选项必须缩进到与指令内容相同的级别。

The directive content follows after a blank line and is indented relative to the directive start or if options are present, by the same amount as the options.

Be careful as the indent is not a fixed number of whitespace, e.g. three, but any number whitespace. This can be surprising when a fixed indent is used throughout the document and can make a difference for directives which are sensitive to whitespace. Compare:

.. code-block::
   :caption: A cool example

       The output of this line starts with four spaces.

.. code-block::

       The output of this line has no spaces at the beginning.

In the first code block, the indent for the content was fixated by the option line to three spaces, consequently the content starts with four spaces. In the latter the indent was fixed by the content itself to seven spaces, thus it does not start with a space.

图片

reST支持一个image指令(ref),像这样使用:

.. image:: gnu.png
   (options)

在Sphinx中使用时,给定的文件名(此处为“gnu.png”)必须相对于源文件,或者绝对意味着它们相对于顶级源目录。例如,文件“sketch/spam.rst”可以将图像 “images/spam.png”写为“../images/spam.png”或 “/images/spam.png”。

Sphinx会自动将图像文件复制到构建的输出目录的子目录中(例如,用于HTML输出的“_static”目录。)

图像大小选项(“width”和“height”)的解释如下:如果大小没有单位或单位是像素,则只有支持像素的输出通道才会考虑给定大小。其他单位(如点的“pt”)将用于HTML和LaTeX输出(后者用“bp”替换“pt”,因为这是TeX单元,“72bp=1in”)。

Sphinx通过允许扩展名的星号来扩展标准的docutils行为:

.. image:: gnu.*

然后,Sphinx搜索与提供的模式匹配的所有图像并确定其类型。然后,每个生成器从这些候选者中选择最佳图像。例如,如果给出了文件名“gnu.*”并且源树中存在两个文件 gnu.pdf`和:file:`gnu.png,则LaTeX生成器将选择前者,而HTML生成器更喜欢后者。支持的图像类型和选择优先级定义在:doc:/usage/builders/index

请注意,图像文件名不应包含空格。

在 0.4 版本发生变更: 添加了对以星号结尾的文件名的支持。

在 0.6 版本发生变更: 图像路径现在可以是绝对的。

在 1.5 版本发生变更: latex目标支持像素(默认为 96px=1in)。

脚注

对于脚注(ref),使用 ``[#name]``_ 标记脚注位置,并在“脚注”标题后添加脚注主体在文档底部,像这样:

Lorem ipsum [#f1]_ dolor sit amet ... [#f2]_

.. rubric:: Footnotes

.. [#f1] Text of the first footnote.
.. [#f2] Text of the second footnote.

您还可以明确编号脚注( [1]_ )或使用不带名字的自动编号脚注( [#]_ )。

引文

支持标准reST引用(ref),其附加功能是 “global” ,即所有引用都可以从所有文件引用。像这样使用它们:

Lorem ipsum [Ref]_ dolor sit amet.

.. [Ref] Book or article reference, URL or whatever.

引用用法类似于脚注用法,但标签不是数字或以“#”开头。

替代品

reST支持 “substitutions”(ref),它们是文本中按“|name|”引用的文本和/或标记。它们被定义为带有显式标记块的脚注,如下:

.. |name| replace:: replacement *text*

或者:

.. |caution| image:: warning.png
             :alt: Warning!

有关详细信息,请参阅:duref:reST 参考替换 <substitution-definitions>

If you want to use some substitutions for all documents, put them into rst_prolog or rst_epilog or put them into a separate file and include it into all documents you want to use them in, using the include directive. (Be sure to give the include file a file name extension differing from that of other source files, to avoid Sphinx finding it as a standalone document.)

Sphinx定义了一些默认替换,请参阅:ref:默认替换

注释

每个显式标记块都不是有效的标记结构(如上面的脚注),它被视为注释(ref)。例如:

.. This is a comment.

您可以在评论开始后缩进文本以形成多行注释:

..
   This whole indented block
   is a comment.

   Still in the comment.

HTML 元数据

The meta directive allows specifying the HTML metadata element of a Sphinx documentation page. For example, the directive:

.. meta::
   :description: The Sphinx documentation builder
   :keywords: Sphinx, documentation, builder

会产生以下HTML输出:

<meta name="description" content="The Sphinx documentation builder">
<meta name="keywords" content="Sphinx, documentation, builder">

此外,Sphinx将按照元指令中指定的关键字添加到搜索索引中。因此,元元素的”lang“属性被考虑在内。例如,指令:

.. meta::
   :keywords: backup
   :keywords lang=en: pleasefindthiskey pleasefindthiskeytoo
   :keywords lang=de: bittediesenkeyfinden

将下列单词添加到具有不同语言配置的构建的搜索索引中:

  • “pleasefindthiskey”,“pleasefindthiskeytoo”到*英语*构建;

  • “bittediesenkeyfinden”到 *德语*构建;

  • “备份”,以构建在所有语言。

源编码

由于在reST中包含特殊字符(例如em破折号或版权符号)的最简单方法是将它们直接写为Unicode字符,因此必须指定编码。 Sphinx默认假设源文件以UTF-8编码;你可以用:confval:源编码 配置值来改变它。

陷阱

在编写reST文档时,通常会遇到一些问题:

  • 行内标记的分离:如上所述,行内标记跨度必须通过非单词字符与周围文本分开,您必须使用反斜杠转义空格来绕过它。有关详细信息,请参阅 :duref:` 参考<substitution-definitions>` 。

  • 没有嵌套的行内标记:像 see :func:`foo` 这样的东西是不可能的。