Docutils标记API¶
本节介绍用于添加REST标记元素(角色和指令)的API。
角色¶
指令¶
指令由派生自 docutils.parsers.rst.Directive
. 它们必须通过使用 Sphinx.add_directive()
或 Sphinx.add_directive_to_domain()
.
- class docutils.parsers.rst.Directive[源代码]¶
新指令的标记语法由以下五个类属性确定:
- required_arguments = 0¶
必需的指令参数数。
- optional_arguments = 0¶
所需参数之后的可选参数数。
- final_argument_whitespace = False¶
最后一个论点可以包含空格吗?
- option_spec = None¶
将选项名映射到验证程序函数。
选项验证器函数采用单个参数,即选项参数(或
None
如果没有给出),则应该验证它或将其转换为正确的形式。他们提高ValueError
或TypeError
表示失败。在
docutils.parsers.rst.directives
模块。
- has_content = False¶
指令可以有内容吗?
新指令必须实现
run()
方法:始终在指令上设置的实例属性是:
- name¶
指令名(在多个名称下注册同一个指令类时很有用)。
- arguments¶
作为列表提供给指令的参数。
- options¶
指定给指令的选项,作为字典将选项名称映射到已验证/转换的值。
- content¶
指令内容(如果给定),作为
ViewList
。
- lineno¶
指令出现的绝对行号。这并不总是一个有用的值;使用
srcline
相反。
- content_offset¶
指令内容的内部偏移量。呼叫时使用
nested_parse
(见下文)。
- block_text¶
包含整个指令的字符串。
ViewLists¶
docutils表示类中的文档源行 docutils.statemachine.ViewList
. 这是一个具有扩展功能的列表——首先,切片创建原始列表的视图,列表还包含有关源行号的信息。
这个 Directive.content
属性是视图列表。如果生成要作为REST分析的内容,则必须自己创建一个视图列表。以下几点对于内容生成很重要:
构造函数接受字符串(行)和源(文档)名称的列表。
这个
.append()
方法也接受行和源名称。
将指令内容解析为REST¶
许多指令将包含更多必须分析的标记。要执行此操作,请使用 Directive.run()
方法:
self.state.nested_parse
sphinx.util.nodes.nested_parse_with_titles()
--这允许解析内容中的标题。
两个API都将内容解析到一个给定的节点中。它们的用法如下:
node = docutils.nodes.paragraph()
# either
nested_parse_with_titles(self.state, self.result, node)
# or
self.state.nested_parse(self.result, 0, node)
备注
sphinx.util.docutils.switch_source_input()
允许在嵌套分析期间更改目标文件。混合内容很有用。例如, sphinx. ext.autodoc
使用它来分析docstrings::
from sphinx.util.docutils import switch_source_input
# Switch source_input between parsing content.
# Inside this context, all parsing errors and warnings are reported as
# happened in new source_input (in this case, ``self.result``).
with switch_source_input(self.state, self.result):
node = docutils.nodes.paragraph()
self.state.nested_parse(self.result, 0, node)
自 1.7 版本弃用: 在Sphinx1.6之前, sphinx.ext.autodoc.AutodocReporter
就是为了这个目的。它被替换为 switch_source_input()
。
如果不需要包装节点,可以使用任何具体的节点类型并返回 node.children
来自指令。
参见
Creating directives 如何使用docutils文档