应用程序API¶
每个Sphinx扩展都是一个Python模块,至少有一个 setup()
函数. 在初始化时使用一个参数调用此函数,该应用程序对象表示Sphinx进程.
扩展设置¶
这些方法通常在扩展名的 setup()
函数中调用.
使用Sphinx扩展API的示例可以在 sphinx.ext
包中看到.
-
Sphinx.
setup_extension
(name)[源代码]¶ 导入并设置Sphinx扩展模块.
加载模块 name 给出的扩展名.如果您的分机需要其他分机提供的功能,请使用此功能.如果被叫两次,则为无操作.
-
Sphinx.
require_sphinx
(version)[源代码]¶ 如果需要,请检查Sphinx版本.
将 version (必须是
major.minor
版本字符串,例如'1.1'
)与正在运行的Sphinx的版本进行比较,并在它太旧时中止构建.1.0 新版功能.
-
Sphinx.
connect
(event, callback)[源代码]¶ 注册 callback*在发出 *event 时被调用.
有关可用核心事件和回调函数参数的详细信息,请参阅 sphinx 核心事件 .
该方法返回一个 “listener ID” ,可用作以下参数
disconnect()
.
-
Sphinx.
add_config_value
(name, default, rebuild)[源代码]¶ 注册配置值.
这对于Sphinx识别新值并相应地设置默认值是必要的.*name* 应以扩展名为前缀,以避免冲突. default 值可以是任何 Python 对象. 字符串值 rebuild 必须是其中一个值:
'env'
如果设置中的更改仅在解析文档时生效 - 这意味着必须重建整个环境.'html'
如果设置更改需要完全重建HTML文档.''
如果设置的更改不需要任何特殊重建.
在 0.6 版更改: 将 rebuild 从简单的布尔值(相当于
''
或'env'
)更改为字符串. 但是,布尔仍然被内部接受和转换.在 0.4 版更改: 如果 default 值是可调用的,则将使用config对象作为其参数调用它以获取默认值. 这可用于实现默认值取决于其他值的配置值.
-
Sphinx.
set_translator
(name, translator_class)[源代码]¶ 注册或覆盖Docutils翻译课程.
这用于注册自定义输出转换器或替换内置转换器. 这允许扩展使用自定义转换器并为转换器定义自定义节点(请参阅
add_node()
).1.3 新版功能.
在 1.8 版更改: 添加 override 关键字.
-
Sphinx.
add_node
(node, **kwds)[源代码]¶ 注册Docutils节点类.
这对Docutils内部是必要的. 它还可以在将来用于验证解析文档中的节点.
Sphinx HTML,LaTeX,文本和联机帮助页面编写器的节点访问者函数可以作为关键字参数给出: 关键字应该是
'html'
,'latex'
,'text'
,'man'
,'texinfo'
或其他任何一个或多个支持翻译,价值是一个2元组的(visit, depart)
方法.如果visit
函数引发,depart
可以是None
docutils.nodes.SkipNode
. 例:class math(docutils.nodes.Element): pass def visit_math_html(self, node): self.body.append(self.starttag(node, 'math')) def depart_math_html(self, node): self.body.append('</math>') app.add_node(math, html=(visit_math_html, depart_math_html))
显然,当您在要翻译的文档中遇到时,您没有指定访问者方法的翻译器会阻塞节点.
在 0.5 版更改: 添加了对提供访问功能的关键字参数的支持.
-
Sphinx.
add_enumerable_node
(node, figtype, title_getter=None, **kwds)[源代码]¶ 将Docutils节点类注册为numfig目标.
Sphinx自动为节点编号.然后用户可以使用
numref
来引用它.figtype is a type of enumerable nodes. Each figtypes have individual numbering sequences. As a system figtypes,
figure
,table
andcode-block
are defined. It is able to add custom nodes to these default figtypes. It is also able to define new custom figtype if new figtype is given.title_getter 是获取节点标题的getter函数. 它需要一个可枚举节点的实例,并且必须将其标题作为字符串返回. 标题用于默认的引用标题
ref
. 默认情况下,Sphinx从节点中搜索docutils.nodes.caption
或docutils.nodes.title
作为标题.其他关键字参数用于节点访问者功能.有关详细信息,请参阅
Sphinx.add_node()
.1.4 新版功能.
-
Sphinx.
add_directive
(name, directiveclass)[源代码] 注册Docutils指令.
name must be the prospective directive name. There are two possible ways to write a directive:
In the docutils 0.4 style, obj is the directive function. content, arguments and options are set as attributes on the function and determine whether the directive has content, arguments and options, respectively. This style is deprecated.
In the docutils 0.5 style, obj is the directive class. It must already have attributes named has_content, required_arguments, optional_arguments, final_argument_whitespace and option_spec that correspond to the options for the function way. See the Docutils docs for details.
The directive class must inherit from the class
docutils.parsers.rst.Directive
.例如,(已存在的)
literalinclude
指令将添加如下:from docutils.parsers.rst import Directive, directives class LiteralIncludeDirective(Directive): has_content = True required_arguments = 1 optional_arguments = 0 final_argument_whitespace = True option_spec = { 'class': directives.class_option, 'name': directives.unchanged, } def run(self): ... add_directive('literalinclude', LiteralIncludeDirective)
在 0.6 版更改: 现在支持Docutils 0.5样式的指令类.
1.8 版后已移除: 不推荐使用Docutils 0.4-style(基于功能)指令支持.
在 1.8 版更改: 添加 override 关键字.
-
Sphinx.
add_role
(name, role)[源代码]¶ 注册Docutils角色.
name must be the role name that occurs in the source, role the role function. Refer to the Docutils documentation for more information.
在 1.8 版更改: 添加 override 关键字.
-
Sphinx.
add_generic_role
(name, nodeclass)[源代码]¶ 注册一般的Docutils角色.
注册一个Docutils角色,它只会将其内容包装在 nodeclass 给出的节点中.
0.6 新版功能.
在 1.8 版更改: 添加 override 关键字.
-
Sphinx.
add_domain
(domain)[源代码]¶ 注册域.
使得Sphinx知道给定的 domain (必须是类;更确切地说,是
Domain
的子类).1.0 新版功能.
在 1.8 版更改: 添加 override 关键字.
-
Sphinx.
add_directive_to_domain
(domain, name, directiveclass)[源代码] 在域中注册Docutils指令.
例如
add_directive()
, 但该指令被添加到名为 domain 的域中.1.0 新版功能.
在 1.8 版更改: 添加 override 关键字.
-
Sphinx.
add_role_to_domain
(domain, name, role)[源代码]¶ 在域中注册Docutils角色.
例如
add_role()
,但角色被添加到名为 domain 的域中.1.0 新版功能.
在 1.8 版更改: 添加 override 关键字.
-
Sphinx.
add_index_to_domain
(domain, index)[源代码]¶ 注册域的自定义索引.
将自定义*索引*类添加到名为 domain 的域中. * index *必须是
Index
的子类.1.0 新版功能.
在 1.8 版更改: 添加 override 关键字.
-
Sphinx.
add_object_type
(directivename, rolename, indextemplate='', parse_node=None, ref_nodeclass=None, objname='', doc_field_types=[])[源代码]¶ 注册新的对象类型.
这个方法是一种非常方便的方法来添加一个新的 object 类型,可以交叉引用.它会这样做:
Create a new directive (called directivename) for documenting an object. It will automatically add index entries if indextemplate is nonempty; if given, it must contain exactly one instance of
%s
. See the example below for how the template will be interpreted.Create a new role (called rolename) to cross-reference to these object descriptions.
If you provide parse_node, it must be a function that takes a string and a docutils node, and it must populate the node with children parsed from the string. It must then return the name of the item to be used in cross-referencing and index entries. See the
conf.py
file in the source for this documentation for an example.The objname (if not given, will default to directivename) names the type of object. It is used when listing objects, e.g. in search results.
例如,如果您在自定义Sphinx扩展中进行此调用:
app.add_object_type('directive', 'dir', 'pair: %s; directive')
您可以在文档中使用此标记:
.. rst:directive:: function Document a function. <...> See also the :rst:dir:`function` directive.
For the directive, an index entry will be generated as if you had prepended
.. index:: pair: function; directive
The reference node will be of class
literal
(so it will be rendered in a proportional font, as appropriate for code) unless you give the ref_nodeclass argument, which must be a docutils node class. Most useful aredocutils.nodes.emphasis
ordocutils.nodes.strong
– you can also usedocutils.nodes.generated
if you want no further text decoration. If the text should be treated as literal (e.g. no smart quote replacement), but not have typewriter styling, usesphinx.addnodes.literal_emphasis
orsphinx.addnodes.literal_strong
.For the role content, you have the same syntactical possibilities as for standard Sphinx roles (see 交叉引用语法).
在 1.8 版更改: 添加 override 关键字.
-
Sphinx.
add_crossref_type
(directivename, rolename, indextemplate='', ref_nodeclass=None, objname='')[源代码]¶ 注册一个新的crossref对象类型.
This method is very similar to
add_object_type()
except that the directive it generates must be empty, and will produce no output.That means that you can add semantic targets to your sources, and refer to them using custom roles instead of generic ones (like
ref
). Example call:app.add_crossref_type('topic', 'topic', 'single: %s', docutils.nodes.emphasis)
用法示例:
.. topic:: application API The application API ------------------- Some random text here. See also :topic:`this section <application API>`.
(Of course, the element following the
topic
directive needn’t be a section.)在 1.8 版更改: 添加 override 关键字.
-
Sphinx.
add_transform
(transform)[源代码]¶ 注册解析后要应用的Docutils变换.
Add the standard docutils
Transform
subclass transform to the list of transforms that are applied after Sphinx parses a reST document.¶ 优先
sphinx 的主要目的
0-99
通过docutils修复无效节点.翻译doctree.
100-299
制备
300-399
早
400-699
主要
700-799
后期处理.修改文本和引用的截止日期.
800-899
收集引用和引用的节点.域名处理.
900-999
完成并清理.
-
Sphinx.
add_post_transform
(transform)[源代码]¶ 在写入之前注册要应用的Docutils变换.
Add the standard docutils
Transform
subclass transform to the list of transforms that are applied before Sphinx writes a document.
-
Sphinx.
add_js_file
(filename, **kwargs)[源代码]¶ 注册一个JavaScript文件以包含在HTML输出中.
Add filename to the list of JavaScript files that the default HTML template will include. The filename must be relative to the HTML static path , or a full URI with scheme. The keyword arguments are also accepted for attributes of
<script>
tag.例:
app.add_js_file('example.js') # => <script src="_static/example.js"></script> app.add_js_file('example.js', async="async") # => <script src="_static/example.js" async="async"></script>
0.5 新版功能.
在 1.8 版更改: Renamed from
app.add_javascript()
. And it allows keyword arguments as attributes of script tag.
-
Sphinx.
add_css_file
(filename, **kwargs)[源代码]¶ 注册一个样式表以包含在HTML输出中.
Add filename to the list of CSS files that the default HTML template will include. The filename must be relative to the HTML static path, or a full URI with scheme. The keyword arguments are also accepted for attributes of
<link>
tag.例:
app.add_css_file('custom.css') # => <link rel="stylesheet" href="_static/custom.css" type="text/css" /> app.add_css_file('print.css', media='print') # => <link rel="stylesheet" href="_static/print.css" # type="text/css" media="print" /> app.add_css_file('fancy.css', rel='alternate stylesheet', title='fancy') # => <link rel="alternate stylesheet" href="_static/fancy.css" # type="text/css" title="fancy" />
1.0 新版功能.
在 1.6 版更改: Optional
alternate
and/ortitle
attributes can be supplied with the alternate (of boolean type) and title (a string) arguments. The default is no title and alternate =False
. For more information, refer to the documentation.在 1.8 版更改: Renamed from
app.add_stylesheet()
. And it allows keyword arguments as attributes of link tag.
-
Sphinx.
add_latex_package
(packagename, options=None)[源代码]¶ 注册一个包以包含在LaTeX源代码中.
Add packagename to the list of packages that LaTeX source code will include. If you provide options, it will be taken to usepackage declaration.
app.add_latex_package('mypackage') # => \usepackage{mypackage} app.add_latex_package('mypackage', 'foo,bar') # => \usepackage[foo,bar]{mypackage}
1.3 新版功能.
-
Sphinx.
add_lexer
(alias, lexer)[源代码]¶ 为源代码注册一个新词法分析器.
Use lexer, which must be an instance of a Pygments lexer class, to highlight code blocks with the given language alias.
0.6 新版功能.
-
Sphinx.
add_autodocumenter
(cls)[源代码]¶ 注册autodoc扩展的新文档类.
Add cls as a new documenter class for the
sphinx.ext.autodoc
extension. It must be a subclass ofsphinx.ext.autodoc.Documenter
. This allows to auto-document new types of objects. See the source of the autodoc module for examples on how to subclassDocumenter
.待处理
为Documenter和子类化添加真正的文档
0.6 新版功能.
-
Sphinx.
add_autodoc_attrgetter
(type, getter)[源代码]¶ 为autodoc扩展注册一个新的``getattr``函数.
Add getter, which must be a function with an interface compatible to the
getattr()
builtin, as the autodoc attribute getter for objects that are instances of typ. All cases where autodoc needs to get an attribute of a type are then handled by this function instead ofgetattr()
.0.6 新版功能.
-
Sphinx.
add_search_language
(cls)[源代码]¶ 为HTML搜索索引注册新语言.
Add cls, which must be a subclass of
sphinx.search.SearchLanguage
, as a support language for building the HTML full-text search index. The class must have a lang attribute that indicates the language it should be used for. Seehtml_search_language
.1.1 新版功能.
-
Sphinx.
add_source_suffix
(suffix, filetype)[源代码]¶ 注册源文件的后缀.
Same as
source_suffix
. The users can override this using the setting.1.8 新版功能.
-
Sphinx.
add_source_parser
(parser)[源代码]¶ 注册解析器类.
1.4 新版功能.
在 1.8 版更改: suffix argument is deprecated. It only accepts parser argument. Use
add_source_suffix()
API to register suffix instead.在 1.8 版更改: 添加 override 关键字.
-
Sphinx.
add_html_theme
(name, theme_path)[源代码]¶ 注册HTML主题.
The name is a name of theme, and path is a full path to the theme (refs: 将您的主题分发为Python包).
1.6 新版功能.
-
Sphinx.
add_html_math_renderer
(name, inline_renderers, block_renderers)[源代码]¶ 注册HTML的数学渲染器.
The name is a name of math renderer. Both inline_renderers and block_renderers are used as visitor functions for the HTML writer: the former for inline math node (
nodes.math
), the latter for block math node (nodes.math_block
). Regarding visitor functions, seeadd_node()
for details.1.8 新版功能.
-
Sphinx.
add_message_catalog
(catalog, locale_dir)[源代码]¶ 注册消息目录.
The catalog is a name of catalog, and locale_dir is a base path of message catalog. For more details, see
sphinx.locale.get_translation()
.1.8 新版功能.
-
exception
sphinx.application.
ExtensionError
¶ 如果扩展API出现问题,所有这些方法都会引发此异常。
发出事件¶
Sphinx运行时信息¶
应用程序对象还提供运行时信息作为属性.
-
Sphinx.
srcdir
¶ 源目录.
-
Sphinx.
confdir
¶ 包含
conf.py
的目录.
-
Sphinx.
doctreedir
¶ 存储酸洗doctree的目录.
-
Sphinx.
outdir
¶ 用于存储构建文档的目录.
sphinx 核心事件¶
These events are known to the core. The arguments shown are given to the
registered event handlers. Use Sphinx.connect()
in an extension’s setup
function (note that conf.py
can also have a setup
function) to connect
handlers to the events. Example:
def source_read_handler(app, docname, source):
print('do something here...')
def setup(app):
app.connect('source-read', source_read_handler)
-
builder-inited
(app)¶ 创建构建器对象时发出。 它可以作为
app.builder
.
-
config-inited
(app, config)¶ 初始化配置对象时发出.
1.8 新版功能.
-
env-get-outdated
(app, env, added, changed, removed)¶ 当环境确定哪些源文件已更改并应重新读取时发出。 added, changed 和 removed 是环境已确定的文档名集。除了这些之外,您还可以返回要重新阅读的文档名列表。
1.1 新版功能.
-
env-purge-doc
(app, env, docname)¶ Emitted when all traces of a source file should be cleaned from the environment, that is, if the source file is removed or before it is freshly read. This is for extensions that keep their own caches in attributes of the environment.
For example, there is a cache of all modules on the environment. When a source file has been changed, the cache’s entries for the file are cleared, since the module declarations could have been removed from the file.
0.5 新版功能.
-
env-before-read-docs
(app, env, docnames)¶ Emitted after the environment has determined the list of all added and changed files and just before it reads them. It allows extension authors to reorder the list of docnames (inplace) before processing, or add more docnames that Sphinx did not consider changed (but never add any docnames that are not in
env.found_docs
).You can also remove document names; do this with caution since it will make Sphinx treat changed files as unchanged.
1.3 新版功能.
-
source-read
(app, docname, source)¶ Emitted when a source file has been read. The source argument is a list whose single element is the contents of the source file. You can process the contents and replace this item to implement source-level transformations.
For example, if you want to use
$
signs to delimit inline math, like in LaTeX, you can use a regular expression to replace$...$
by:math:`...`
.0.5 新版功能.
-
doctree-read
(app, doctree)¶ Emitted when a doctree has been parsed and read by the environment, and is about to be pickled. The doctree can be modified in-place.
-
missing-reference
(app, env, node, contnode)¶ Emitted when a cross-reference to a Python module or object cannot be resolved. If the event handler can resolve the reference, it should return a new docutils node to be inserted in the document tree in place of the node node. Usually this node is a
reference
node containing contnode as a child.- 参数
env – The build environment (
app.builder.env
).node – The
pending_xref
node to be resolved. Its attributesreftype
,reftarget
,modname
andclassname
attributes determine the type and target of the reference.contnode – The node that carries the text and formatting inside the future reference and should be a child of the returned reference node.
0.5 新版功能.
-
doctree-resolved
(app, doctree, docname)¶ Emitted when a doctree has been “resolved” by the environment, that is, all references have been resolved and TOCs have been inserted. The doctree can be modified in place.
Here is the place to replace custom nodes that don’t have visitor methods in the writers, so that they don’t cause errors when the writers encounter them.
-
env-merge-info
(app, env, docnames, other)¶ This event is only emitted when parallel reading of documents is enabled. It is emitted once for every subprocess that has read some documents.
You must handle this event in an extension that stores data in the environment in a custom location. Otherwise the environment in the main process will not be aware of the information stored in the subprocess.
other is the environment object from the subprocess, env is the environment from the main process. docnames is a set of document names that have been read in the subprocess.
For a sample of how to deal with this event, look at the standard
sphinx.ext.todo
extension. The implementation is often similar to that ofenv-purge-doc
, only that information is not removed, but added to the main environment from the other environment.1.3 新版功能.
-
env-updated
(app, env)¶ Emitted when the
update()
method of the build environment has completed, that is, the environment and all doctrees are now up-to-date.You can return an iterable of docnames from the handler. These documents will then be considered updated, and will be (re-)written during the writing phase.
0.5 新版功能.
在 1.3 版更改: The handlers’ return value is now used.
-
env-check-consistency
(app, env)¶ Emitted when Consistency checks phase. You can check consistency of metadata for whole of documents.
1.6 新版功能: 作为**实验**事件
-
html-collect-pages
(app)¶ Emitted when the HTML builder is starting to write non-document pages. You can add pages to write by returning an iterable from this event consisting of
(pagename, context, templatename)
.1.0 新版功能.
-
html-page-context
(app, pagename, templatename, context, doctree)¶ Emitted when the HTML builder has created a context dictionary to render a template with – this can be used to add custom elements to the context.
The pagename argument is the canonical name of the page being rendered, that is, without
.html
suffix and using slashes as path separators. The templatename is the name of the template to render, this will be'page.html'
for all pages from reST documents.The context argument is a dictionary of values that are given to the template engine to render the page and can be modified to include custom values. Keys must be strings.
The doctree argument will be a doctree when the page is created from a reST documents; it will be
None
when the page is created from an HTML template alone.You can return a string from the handler, it will then replace
'page.html'
as the HTML template for this page.0.4 新版功能.
在 1.3 版更改: 返回值现在可以指定模板名称.
-
build-finished
(app, exception)¶ Emitted when a build has finished, before Sphinx exits, usually used for cleanup. This event is emitted even when the build process raised an exception, given as the exception argument. The exception is reraised in the application after the event handlers have run. If the build process raised no exception, exception will be
None
. This allows to customize cleanup actions depending on the exception status.0.5 新版功能.
检查Sphinx版本¶
使用此选项可以使您的扩展适应Sphinx中的API更改.
-
sphinx.
version_info
= (2, 1, 0, 'beta', 0)¶ 版本信息,以便更好地使用程序.
A tuple of five elements; for Sphinx version 1.2.1 beta 3 this would be
(1, 2, 1, 'beta', 3)
. The fourth element can be one of:alpha
,beta
,rc
,final
.final
always has 0 as the last element.1.2 新版功能: 在1.2版之前,检查字符串``sphinx .__ version__``.
Config对象¶
-
class
sphinx.config.
Config
(*args)[源代码]¶ 配置文件抽象.
The config object makes the values of all config values available as attributes.
It is exposed via the
sphinx.application.Application.config
andsphinx.environment.Environment.config
attributes. For example, to get the value oflanguage
, use eitherapp.config.language
orenv.config.language
.
模板桥¶
-
class
sphinx.application.
TemplateBridge
[源代码]¶ This class defines the interface for a “template bridge”, that is, a class that renders templates given a template name and a context.
-
init
(builder, theme=None, dirs=None)[源代码]¶ 由构建器调用以初始化模板系统.
builder is the builder object; you’ll probably want to look at the value of
builder.config.templates_path
.theme is a
sphinx.theming.Theme
object or None; in the latter case, dirs can be list of fixed directories to look for templates.
-
newest_template_mtime
()[源代码]¶ Called by the builder to determine if output files are outdated because of template changes. Return the mtime of the newest template file that was changed. The default implementation returns
0
.
-
例外¶
-
exception
sphinx.errors.
SphinxError
[源代码]¶ Sphinx错误的基类.
This is the base class for “nice” exceptions. When such an exception is raised, Sphinx will abort the build and present the exception category and message to the user.
Extensions are encouraged to derive from this exception for their custom errors.
Exceptions not derived from
SphinxError
are treated as unexpected and shown to the user with a part of the traceback (and the full traceback saved in a temporary file).-
category
¶ Description of the exception “category”, used in converting the exception to a string (“category: message”). Should be set accordingly in subclasses.
-