# 应用程序API¶

class sphinx.application.Sphinx[源代码]

## 扩展设置¶

Sphinx.setup_extension(name)[源代码]

Sphinx.require_sphinx(version)[源代码]

version (必须是 major.minor 版本字符串,例如 '1.1')与正在运行的Sphinx的版本进行比较,并在它太旧时中止构建.

1.0 新版功能.

Sphinx.connect(event, callback)[源代码]

Sphinx.disconnect(listener_id)[源代码]

Sphinx.add_builder(builder)[源代码]

builder 必须是一个继承自 Builder 的类.

Sphinx.add_config_value(name, default, rebuild)[源代码]

• 'env' 如果设置中的更改仅在解析文档时生效 - 这意味着必须重建整个环境.

• 'html' 如果设置更改需要完全重建HTML文档.

• '' 如果设置的更改不需要任何特殊重建.

Sphinx.add_event(name)[源代码]

Sphinx.set_translator(name, translator_class)[源代码]

1.3 新版功能.

Sphinx.add_node(node, **kwds)[源代码]

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('[/itex]')



Sphinx.add_enumerable_node(node, figtype, title_getter=None, **kwds)[源代码]

Sphinx自动为节点编号.然后用户可以使用 numref 来引用它.

figtype is a type of enumerable nodes. Each figtypes have individual numbering sequences. As a system figtypes, figure, table and code-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.captiondocutils.nodes.title 作为标题.

1.4 新版功能.

Sphinx.add_directive(name, func, content, arguments, **options)[源代码]
Sphinx.add_directive(name, directiveclass)[源代码]

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.

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):
...



1.8 版后已移除: 不推荐使用Docutils 0.4-style(基于功能)指令支持.

Sphinx.add_role(name, role)[源代码]

name must be the role name that occurs in the source, role the role function. Refer to the Docutils documentation for more information.

Sphinx.add_generic_role(name, nodeclass)[源代码]

0.6 新版功能.

Sphinx.add_domain(domain)[源代码]

1.0 新版功能.

Sphinx.override_domain(domain)[源代码]

Override a registered domain.

Make the given domain class known to Sphinx, assuming that there is already a domain with its .name. The new domain must be a subclass of the existing one.

1.0 新版功能.

1.8 版后已移除: Integrated to add_domain().

Sphinx.add_directive_to_domain(domain, name, func, content, arguments, **options)[源代码]
Sphinx.add_directive_to_domain(domain, name, directiveclass)[源代码]

1.0 新版功能.

Sphinx.add_role_to_domain(domain, name, role)[源代码]

1.0 新版功能.

Sphinx.add_index_to_domain(domain, index)[源代码]

1.0 新版功能.

Sphinx.add_object_type(directivename, rolename, indextemplate='', parse_node=None, ref_nodeclass=None, objname='', doc_field_types=[])[源代码]

• 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.

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 are docutils.nodes.emphasis or docutils.nodes.strong – you can also use docutils.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, use sphinx.addnodes.literal_emphasis or sphinx.addnodes.literal_strong.

For the role content, you have the same syntactical possibilities as for standard Sphinx roles (see 交叉引用语法).

Sphinx.add_crossref_type(directivename, rolename, indextemplate='', ref_nodeclass=None, objname='')[源代码]

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.)

Sphinx.add_transform(transform)[源代码]

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)[源代码]

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)[源代码]

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>

# => <script src="_static/example.js" async="async"></script>


0.5 新版功能.

Sphinx.add_css_file(filename, **kwargs)[源代码]

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" />

#          type="text/css" media="print" />

# => <link rel="alternate stylesheet" href="_static/fancy.css"
#          type="text/css" title="fancy" />


1.0 新版功能.

Sphinx.add_latex_package(packagename, options=None)[源代码]

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}
# => \usepackage[foo,bar]{mypackage}


1.3 新版功能.

Sphinx.add_lexer(alias, lexer)[源代码]

Use lexer to highlight code blocks with the given language alias.

0.6 新版功能.

Sphinx.add_autodocumenter(cls)[源代码]

Add cls as a new documenter class for the sphinx.ext.autodoc extension. It must be a subclass of sphinx.ext.autodoc.Documenter. This allows to auto-document new types of objects. See the source of the autodoc module for examples on how to subclass Documenter.

0.6 新版功能.

Sphinx.add_autodoc_attrgetter(type, getter)[源代码]

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 of getattr().

0.6 新版功能.

Sphinx.add_search_language(cls)[源代码]

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. See html_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 新版功能.

Sphinx.add_env_collector(collector)[源代码]

1.6 新版功能.

Sphinx.add_html_theme(name, theme_path)[源代码]

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)[源代码]

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, see add_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 新版功能.

Sphinx.is_parallel_allowed(typ)[源代码]

typ is a type of processing; 'read' or 'write'.

exception sphinx.application.ExtensionError

## 发出事件¶

class sphinx.application.Sphinx[源代码]
emit(event, *arguments)[源代码]

Emit event 并将 arguments 传递给回调函数.

emit_firstresult(event, *arguments)[源代码]

Emit event 并将 arguments 传递给回调函数.

0.5 新版功能.

## Sphinx运行时信息¶

Sphinx.project

Sphinx.srcdir

Sphinx.confdir

Sphinx.doctreedir

Sphinx.outdir

## sphinx 核心事件¶

These events are known to the core. The arguments shown are given to the registered event handlers. Use 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):

builder-inited(app)

config-inited(app, config)

1.8 新版功能.

env-get-outdated(app, env, 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.

Parameters
• env – The build environment (app.builder.env).

• node – The pending_xref node to be resolved. Its attributes reftype, reftarget, modname and classname 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 of env-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 新版功能.

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 新版功能.

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.version_info = (2, 2, 0, 'final', 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 and sphinx.environment.Environment.config attributes. For example, to get the value of language, use either app.config.language or env.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.

render(template, context)[源代码]

Called by the builder to render a template given as a filename with a specified context (a Python dictionary).

render_string(template, context)[源代码]

Called by the builder to render a template given as a string with a specified context (a Python dictionary).

## 例外¶

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.

exception sphinx.errors.ConfigError[源代码]

exception sphinx.errors.ExtensionError(message, orig_exc=None)[源代码]

exception sphinx.errors.ThemeError[源代码]

exception sphinx.errors.VersionRequirementError[源代码]