アプリケーションAPI

それぞれのSphinx拡張は、最低でも setup() 関数を一つ持っている、Pythonモジュールです。この関数は初期化時に一つの引数を伴って呼び出されます。この引数はapplicationオブジェクトで、Sphinxのプロセスに関する情報を持っています。

class sphinx.application.Sphinx[ソース]

Sphinxオブジェクトは以下のようなAPIを持っています

拡張のセットアップ

以下のメソッドは通常、拡張機能のsetup()関数の中で呼ばれます。

Sphinx拡張APIの使用法に関するサンプルは、Sphinx標準の sphinx.ext のパッケージの中を見てください。

Sphinx.setup_extension(extname: str) None[ソース]

Import and setup a Sphinx extension module.

Load the extension given by the module name. Use this if your extension needs the features provided by another extension. No-op if called twice.

static Sphinx.require_sphinx(version: tuple[int, int] | str) None[ソース]

Check the Sphinx version if requested.

Compare version with the version of the running Sphinx, and abort the build when it is too old.

パラメータ:

version -- The required version in the form of major.minor or (major, minor).

バージョン 1.0 で追加.

バージョン 7.1 で変更: Type of version now allows (major, minor) form.

Sphinx.connect(event: str, callback: Callable, priority: int = 500) int[ソース]

Register callback to be called when event is emitted.

For details on available core events and the arguments of callback functions, please see Sphinxコアイベント.

パラメータ:
  • event -- The name of target event

  • callback -- Callback function for the event

  • priority -- The priority of the callback. The callbacks will be invoked in order of priority (ascending).

戻り値:

A listener ID. It can be used for disconnect().

バージョン 3.0 で変更: Support priority

Sphinx.disconnect(listener_id: int) None[ソース]

Unregister callback by listener_id.

パラメータ:

listener_id -- A listener_id that connect() returns

Sphinx.add_builder(builder: type[Builder], override: bool = False) None[ソース]

Register a new builder.

パラメータ:
  • builder -- A builder class

  • override -- If true, install the builder forcedly even if another builder is already installed as the same name

バージョン 1.8 で変更: Add override keyword.

Sphinx.add_config_value(name: str, default: Any, rebuild: Literal['', 'env', 'epub', 'gettext', 'html', 'applehelp', 'devhelp'], types: type | Collection[type] | ENUM = ()) None[ソース]

Register a configuration value.

This is necessary for Sphinx to recognize new values and set default values accordingly.

パラメータ:
  • name -- The name of the configuration value. It is recommended to be prefixed with the extension name (ex. html_logo, epub_title)

  • default -- The default value of the configuration.

  • rebuild --

    The condition of rebuild. It must be one of those values:

    • 'env' 設定を変更してからビルドをかけると、環境全体が再ビルドされます。

    • 'html' この設定を変更してからビルドをかけた場合、出力がHTMLの時にフル再ビルドされます。

    • '' 設定を変更してもなにも再ビルドに関しては影響を与えません。

  • types -- The type of configuration value. A list of types can be specified. For example, [str] is used to describe a configuration that takes string value.

バージョン 0.4 で変更: If the default value is a callable, it will be called with the config object as its argument in order to get the default value. This can be used to implement config values whose default depends on other values.

バージョン 0.6 で変更: rebuild が単純なブーリアン型('', 'env' に相当)から文字列に変更されました。後方互換性のために、ブーリアン型も受け取ることが可能で、その場合には内部で変換されます。

Sphinx.add_event(name: str) None[ソース]

Register an event called name.

This is needed to be able to emit it.

パラメータ:

name -- The name of the event

Sphinx.set_translator(name: str, translator_class: type[nodes.NodeVisitor], override: bool = False) None[ソース]

Register or override a Docutils translator class.

This is used to register a custom output translator or to replace a builtin translator. This allows extensions to use a custom translator and define custom nodes for the translator (see add_node()).

パラメータ:
  • name -- The name of the builder for the translator

  • translator_class -- A translator class

  • override -- If true, install the translator forcedly even if another translator is already installed as the same name

バージョン 1.3 で追加.

バージョン 1.8 で変更: Add override keyword.

Sphinx.add_node(node: type[Element], override: bool = False, **kwargs: tuple[Callable, Callable | None]) None[ソース]

Register a Docutils node class.

This is necessary for Docutils internals. It may also be used in the future to validate nodes in the parsed documents.

パラメータ:
  • node -- A node class

  • kwargs -- Visitor functions for each builder (see below)

  • override -- If true, install the node forcedly even if another node is already installed as the same name

Node visitor functions for the Sphinx HTML, LaTeX, text and manpage writers can be given as keyword arguments: the keyword should be one or more of 'html', 'latex', 'text', 'man', 'texinfo' or any other supported translators, the value a 2-tuple of (visit, depart) methods. depart can be None if the visit function raises docutils.nodes.SkipNode. Example:

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: type[Element], figtype: str, title_getter: TitleGetter | None = None, override: bool = False, **kwargs: tuple[Callable, Callable]) None[ソース]

Register a Docutils node class as a numfig target.

Sphinx numbers the node automatically. And then the users can refer it using numref.

パラメータ:
  • node -- A node class

  • figtype -- The type of enumerable nodes. Each figtype has individual numbering sequences. As system figtypes, figure, table and code-block are defined. It is possible to add custom nodes to these default figtypes. It is also possible to define new custom figtype if a new figtype is given.

  • title_getter -- A getter function to obtain the title of node. It takes an instance of the enumerable node, and it must return its title as string. The title is used to the default title of references for ref. By default, Sphinx searches docutils.nodes.caption or docutils.nodes.title from the node as a title.

  • kwargs -- Visitor functions for each builder (same as add_node())

  • override -- If true, install the node forcedly even if another node is already installed as the same name

バージョン 1.4 で追加.

Sphinx.add_directive(name: str, cls: type[Directive], override: bool = False) None[ソース]

Register a Docutils directive.

パラメータ:
  • name -- The name of the directive

  • cls -- A directive class

  • override -- If false, do not install it if another directive is already installed as the same name If true, unconditionally install the directive.

For example, a custom directive named my-directive would be added like this:

from docutils.parsers.rst import Directive, directives

class MyDirective(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):
        ...

def setup(app):
    app.add_directive('my-directive', MyDirective)

For more details, see the Docutils docs .

バージョン 0.6 で変更: Docutils 0.5 スタイルのディレクティブクラスをサポートしました。

バージョン 1.8 で非推奨: Docutils 0.4-style (function based) directives support is deprecated.

バージョン 1.8 で変更: Add override keyword.

Sphinx.add_role(name: str, role: Any, override: bool = False) None[ソース]

Register a Docutils role.

パラメータ:
  • name -- The name of role

  • role -- A role function

  • override -- If false, do not install it if another role is already installed as the same name If true, unconditionally install the role.

For more details about role functions, see the Docutils docs .

バージョン 1.8 で変更: Add override keyword.

Sphinx.add_generic_role(name: str, nodeclass: Any, override: bool = False) None[ソース]

Register a generic Docutils role.

Docutilsのロールを登録します。このロールは特に何もしませんが、与えられた nodeclass を使ってラップされるようになります。

パラメータ:

override -- If false, do not install it if another role is already installed as the same name If true, unconditionally install the role.

バージョン 0.6 で追加.

バージョン 1.8 で変更: Add override keyword.

Sphinx.add_domain(domain: type[Domain], override: bool = False) None[ソース]

Register a domain.

パラメータ:
  • domain -- A domain class

  • override -- If false, do not install it if another domain is already installed as the same name If true, unconditionally install the domain.

バージョン 1.0 で追加.

バージョン 1.8 で変更: Add override keyword.

Sphinx.add_directive_to_domain(domain: str, name: str, cls: type[Directive], override: bool = False) None[ソース]

Register a Docutils directive in a domain.

add_directive() と似ていますが、ディレクティブを、 domain で指定されたドメインにのみ追加します。

パラメータ:
  • domain -- The name of target domain

  • name -- A name of directive

  • cls -- A directive class

  • override -- If false, do not install it if another directive is already installed as the same name If true, unconditionally install the directive.

バージョン 1.0 で追加.

バージョン 1.8 で変更: Add override keyword.

Sphinx.add_role_to_domain(domain: str, name: str, role: RoleFunction | XRefRole, override: bool = False) None[ソース]

Register a Docutils role in a domain.

add_role() に似ていますが、 domain で指定されたドメインに、新しいロールを追加します。

パラメータ:
  • domain -- The name of the target domain

  • name -- The name of the role

  • role -- The role function

  • override -- If false, do not install it if another role is already installed as the same name If true, unconditionally install the role.

バージョン 1.0 で追加.

バージョン 1.8 で変更: Add override keyword.

Sphinx.add_index_to_domain(domain: str, index: type[Index], override: bool = False) None[ソース]

Register a custom index for a domain.

Add a custom index class to the domain named domain.

パラメータ:
  • domain -- The name of the target domain

  • index -- The index class

  • override -- If false, do not install it if another index is already installed as the same name If true, unconditionally install the index.

バージョン 1.0 で追加.

バージョン 1.8 で変更: Add override keyword.

Sphinx.add_object_type(directivename: str, rolename: str, indextemplate: str = '', parse_node: Callable | None = None, ref_nodeclass: type[TextElement] | None = None, objname: str = '', doc_field_types: Sequence = (), override: bool = False) None[ソース]

Register a new object type.

このメソッドは、クロスリファレンスを作成できる、新しい 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.

  • rolename で指定された名前を持つ、新しいロールが作成されます。これを使用すると、これらのオブジェクトの説明に対して、クロスリファレンスを張ることができるようになります。

  • parse_node を指定する場合には、文字列と、docutilsのノードを受け取る関数を指定しなければなりません。ノードは、その文字列をパースして得られた子供のノードを受け取ります。この関数はクロスリファレンスと索引のエントリーで使用される名前を返さなければなりません。ここの説明のサンプルを見たい場合には、Sphinxのソースコードの conf.py を参照してください。

  • objname (もし与えられなければ、デフォルトでは directivename と同値になります)は、オブジェクトのタイプ名の名前を付けます。これは、検索結果など、オブジェクトを一覧表示する場合に使用されます。

以下のような関数呼び出しが、カスタムのSphinx拡張の中で行われたとすると:

app.add_object_type('directive', 'dir', 'pair: %s; directive')

ドキュメント内で次のようなマークアップが使用できるようになります:

.. rst:directive:: function

   Document a function.

<...>

See also the :rst:dir:`function` directive.

また、このディレクティブを使用すると、以下のようにindexディレクティブを書いたのと同じ索引が作成されます:

.. index:: pair: function; directive

リファレンスノードのクラスは、 ref_nodeclass を指定しない場合には literal (コードの記述に適したプロポーショナルフォントでレンダリングされる)になります。クラスは、docutilsのノードクラスを設定する必要があります。docutilsのクラスの中で頻繁に使用されるのは docutils.nodes.emphasis あるいは docutils.nodes.strong です。もしも装飾が不要であれば、 docutils.nodes.generated も使用できます。もしテキストをリテラルとして処理したいなら(例えばスマートクォート置換が扶養であれば)、そしてタイプライタースタイルで表示したくないなら、 sphinx.addnodes.literal_emphasissphinx.addnodes.literal_strong を使用してください。

ロールの中身に関しては、標準のSphinxのロールと同じ構文を使用できます(クロスリファレンス文法 参照)。

If override is True, the given object_type is forcedly installed even if an object_type having the same name is already installed.

バージョン 1.8 で変更: Add override keyword.

Sphinx.add_crossref_type(directivename: str, rolename: str, indextemplate: str = '', ref_nodeclass: type[TextElement] | None = None, objname: str = '', override: bool = False) None[ソース]

Register a new crossref object type.

This method is very similar to add_object_type() except that the directive it generates must be empty, and will produce no output.

これは、セマンティックのターゲットをソースに追加して、カスタムのロールを使用して参照することができるということを意味しています。ただし、 ref のような一般的なものは使用することができません。サンプル:

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

もちろん、 topic ディレクティブに続く要素はセクションでなくてもかまいません。

パラメータ:

override -- If false, do not install it if another cross-reference type is already installed as the same name If true, unconditionally install the cross-reference type.

バージョン 1.8 で変更: Add override keyword.

Sphinx.add_transform(transform: type[Transform]) None[ソース]

Register a Docutils transform to be applied after parsing.

Add the standard docutils Transform subclass transform to the list of transforms that are applied after Sphinx parses a reST document.

パラメータ:

transform -- A transform class

priority range categories for Sphinx transforms

Priority

Main purpose in Sphinx

0-99

Fix invalid nodes by docutils. Translate a doctree.

100-299

Preparation

300-399

early

400-699

main

700-799

Post processing. Deadline to modify text and referencing.

800-899

Collect referencing and referenced nodes. Domain processing.

900-999

Finalize and clean up.

refs: Transform Priority Range Categories

Sphinx.add_post_transform(transform: type[Transform]) None[ソース]

Register a Docutils transform to be applied before writing.

Add the standard docutils Transform subclass transform to the list of transforms that are applied before Sphinx writes a document.

パラメータ:

transform -- A transform class

Sphinx.add_js_file(filename: str | None, priority: int = 500, loading_method: str | None = None, **kwargs: Any) None[ソース]

Register a JavaScript file to include in the HTML output.

パラメータ:
  • filename -- The name of a JavaScript file that the default HTML template will include. It must be relative to the HTML static path, or a full URI with scheme, or None . The None value is used to create an inline <script> tag. See the description of kwargs below.

  • priority -- Files are included in ascending order of priority. If multiple JavaScript files have the same priority, those files will be included in order of registration. See list of "priority range for JavaScript files" below.

  • loading_method -- The loading method for the JavaScript file. Either 'async' or 'defer' are allowed.

  • kwargs -- Extra keyword arguments are included as attributes of the <script> tag. If the special keyword argument body is given, its value will be added as the content of the <script> tag.

サンプル:

app.add_js_file('example.js')
# => <script src="_static/example.js"></script>

app.add_js_file('example.js', loading_method="async")
# => <script src="_static/example.js" async="async"></script>

app.add_js_file(None, body="var myVariable = 'foo';")
# => <script>var myVariable = 'foo';</script>
priority range for JavaScript files

Priority

Main purpose in Sphinx

200

default priority for built-in JavaScript files

500

default priority for extensions

800

default priority for html_js_files

A JavaScript file can be added to the specific HTML page when an extension calls this method on html-page-context event.

バージョン 0.5 で追加.

バージョン 1.8 で変更: Renamed from app.add_javascript(). And it allows keyword arguments as attributes of script tag.

バージョン 3.5 で変更: Take priority argument. Allow to add a JavaScript file to the specific page.

バージョン 4.4 で変更: Take loading_method argument. Allow to change the loading method of the JavaScript file.

Sphinx.add_css_file(filename: str, priority: int = 500, **kwargs: Any) None[ソース]

Register a stylesheet to include in the HTML output.

パラメータ:
  • filename -- The name of a CSS file that the default HTML template will include. It must be relative to the HTML static path, or a full URI with scheme.

  • priority -- Files are included in ascending order of priority. If multiple CSS files have the same priority, those files will be included in order of registration. See list of "priority range for CSS files" below.

  • kwargs -- Extra keyword arguments are included as attributes of the <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" />
priority range for CSS files

Priority

Main purpose in Sphinx

200

default priority for built-in CSS files

500

default priority for extensions

800

default priority for html_css_files

A CSS file can be added to the specific HTML page when an extension calls this method on html-page-context event.

バージョン 1.0 で追加.

バージョン 1.6 で変更: Optional alternate and/or title attributes can be supplied with the arguments alternate (a Boolean) and title (a string). 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.

バージョン 3.5 で変更: Take priority argument. Allow to add a CSS file to the specific page.

Sphinx.add_latex_package(packagename: str, options: str | None = None, after_hyperref: bool = False) None[ソース]

Register a package to include in the LaTeX source code.

Add packagename to the list of packages that LaTeX source code will include. If you provide options, it will be taken to the usepackage declaration. If you set after_hyperref truthy, the package will be loaded after hyperref package.

app.add_latex_package('mypackage')
# => \usepackage{mypackage}
app.add_latex_package('mypackage', 'foo,bar')
# => \usepackage[foo,bar]{mypackage}

バージョン 1.3 で追加.

バージョン 3.1 で追加: after_hyperref option.

Sphinx.add_lexer(alias: str, lexer: type[Lexer]) None[ソース]

Register a new lexer for source code.

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

バージョン 0.6 で追加.

バージョン 2.1 で変更: Take a lexer class as an argument.

バージョン 4.0 で変更: Removed support for lexer instances as an argument.

Sphinx.add_autodocumenter(cls: Any, override: bool = False) None[ソース]

Register a new documenter class for the autodoc extension.

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 auto-documenting new types of objects. See the source of the autodoc module for examples on how to subclass Documenter.

If override is True, the given cls is forcedly installed even if a documenter having the same name is already installed.

See Developing autodoc extension for IntEnum.

バージョン 0.6 で追加.

バージョン 2.2 で変更: Add override keyword.

Sphinx.add_autodoc_attrgetter(typ: type, getter: Callable[[Any, str, Any], Any]) None[ソース]

Register a new getattr-like function for the autodoc extension.

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: Any) None[ソース]

Register a new language for the HTML search index.

言語ごとに、HTMLの全文検索インデックスを構築する、 sphinx.search.SearchLanguage クラスのサブクラスである cls を追加します。このクラスにはどの言語から使われるのかを表す、 lang 属性を持たせる必要があります。詳しくは、 html_search_language を参照してください。

バージョン 1.1 で追加.

Sphinx.add_source_suffix(suffix: str, filetype: str, override: bool = False) None[ソース]

Register a suffix of source files.

Same as source_suffix. The users can override this using the config setting.

パラメータ:

override -- If false, do not install it the same suffix is already installed. If true, unconditionally install the suffix.

バージョン 1.8 で追加.

Sphinx.add_source_parser(parser: type[Parser], override: bool = False) None[ソース]

Register a parser class.

パラメータ:

override -- If false, do not install it if another parser is already installed for the same suffix. If true, unconditionally install the 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 で変更: Add override keyword.

Sphinx.add_env_collector(collector: type[EnvironmentCollector]) None[ソース]

Register an environment collector class.

Refer to Environment Collector API.

バージョン 1.6 で追加.

Sphinx.add_html_theme(name: str, theme_path: str) None[ソース]

Register a HTML Theme.

The name is a name of theme, and theme_path is a full path to the theme (refs: Distribute your theme as a Python package).

バージョン 1.6 で追加.

Sphinx.add_html_math_renderer(name: str, inline_renderers: tuple[Callable, Callable | None] | None = None, block_renderers: tuple[Callable, Callable | None] | None = None) None[ソース]

Register a math renderer for 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, see add_node() for details.

バージョン 1.8 で追加.

Sphinx.add_message_catalog(catalog: str, locale_dir: str) None[ソース]

Register a message catalog.

パラメータ:
  • catalog -- The name of the catalog

  • locale_dir -- The base path of the message catalog

For more details, see sphinx.locale.get_translation().

バージョン 1.8 で追加.

Sphinx.is_parallel_allowed(typ: str) bool[ソース]

Check whether parallel processing is allowed or not.

パラメータ:

typ -- A type of processing; 'read' or 'write'.

exception sphinx.application.ExtensionError

ここで説明したすべてのメソッドは、もし拡張APIの中で何か想定外のことが発生した時には、この例外を投げます。

イベントの発行

class sphinx.application.Sphinx[ソース]
emit(event: str, *args: Any, allowed_exceptions: tuple[type[Exception], ...] = ()) list[ソース]

Emit event and pass arguments to the callback functions.

Return the return values of all callbacks as a list. Do not emit core Sphinx events in extensions!

パラメータ:
  • event -- The name of event that will be emitted

  • args -- The arguments for the event

  • allowed_exceptions -- The list of exceptions that are allowed in the callbacks

バージョン 3.1 で変更: Added allowed_exceptions to specify path-through exceptions

emit_firstresult(event: str, *args: Any, allowed_exceptions: tuple[type[Exception], ...] = ()) Any[ソース]

Emit event and pass arguments to the callback functions.

Return the result of the first callback that doesn't return None.

パラメータ:
  • event -- The name of event that will be emitted

  • args -- The arguments for the event

  • allowed_exceptions -- The list of exceptions that are allowed in the callbacks

バージョン 0.5 で追加.

バージョン 3.1 で変更: Added allowed_exceptions to specify path-through exceptions

Sphinx runtime information

The application object also provides runtime information as attributes.

Sphinx.project

ターゲットプロジェクト。 Project を参照してください。

Sphinx.srcdir

ソースディレクトリ。

Sphinx.confdir

Directory containing conf.py.

Sphinx.doctreedir

pickle化された doctree を格納するディレクトリ

Sphinx.outdir

Directory for storing built document.

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)

Below is an overview of each event that happens during a build. In the list below, we include the event name, its callback parameters, and the input and output type for that event:

1. event.config-inited(app,config)
2. event.builder-inited(app)
3. event.env-get-outdated(app, env, added, changed, removed)
4. event.env-before-read-docs(app, env, docnames)

for docname in docnames:
   5. event.env-purge-doc(app, env, docname)

   if doc changed and not removed:
      6. source-read(app, docname, source)
      7. run source parsers: text -> docutils.document
         - parsers can be added with the app.add_source_parser() API
      8. apply transforms based on priority: docutils.document -> docutils.document
         - event.doctree-read(app, doctree) is called in the middle of transforms,
           transforms come before/after this event depending on their priority.

9. event.env-merge-info(app, env, docnames, other)
   - if running in parallel mode, this event will be emitted for each process

10. event.env-updated(app, env)
11. event.env-get-updated(app, env)
12. event.env-check-consistency(app, env)

# The updated-docs list can be builder dependent, but generally includes all new/changed documents,
# plus any output from `env-get-updated`, and then all "parent" documents in the ToC tree
# For builders that output a single page, they are first joined into a single doctree before post-transforms
# or the doctree-resolved event is emitted
for docname in updated-docs:
   13. apply post-transforms (by priority): docutils.document -> docutils.document
   14. event.doctree-resolved(app, doctree, docname)
       - In the event that any reference nodes fail to resolve, the following may emit:
       - event.missing-reference(env, node, contnode)
       - event.warn-missing-reference(domain, node)

15. Generate output files
16. event.build-finished(app, exception)

Here is a more detailed list of these events.

builder-inited(app)

ビルダーオブジェクトが作成された時に発行されます。ビルダーオブジェクトは app.builder とすることで参照できます。

config-inited(app, config)

Emitted when the config object has been initialized.

バージョン 1.8 で追加.

env-get-outdated(app, env, added, changed, removed)

ソースファイルが変更されたりして、再読み込みする必要がある場合に発行されます。 added, changed, removed には、ドキュメント名のセットです。さらに追加で読み込み直すべきドキュメントのリストを返すことができます。

バージョン 1.1 で追加.

env-purge-doc(app, env, docname)

ソースファイルが削除されたり、新たに読み込まる場合など、環境の中に含まれるソースファイルの関連情報をクリアすべき状況になった場合に発行されます。環境の属性の中に情報をキャッシュしておくような拡張機能ためのイベントです。

例えば、環境の中にすべてのモジュールのキャッシュが存在してる場合、ソースファイルが変更されると、ファイルからモジュール宣言から削除されてから、そのファイルに関するキャッシュのエントリーはクリアされます。

バージョン 0.5 で追加.

env-before-read-docs(app, env, docnames)

環境がすべての追加および変更されたファイルのリストを決定し、そのリストを読み込む直前に発行されるイベントです。拡張機能の作者は処理の直前にドキュメント名リストの順序を(インプレイスで)変更したり、Sphinxが変更を把握出来なかったドキュメント名を追加(ただし env.found_doc にないドキュメント名は決して追加しないでください)することができます。

イベントハンドラはドキュメント名をリストから削除することもできます; 注意深くこの方法を利用することで、Sphinxに変更済みのファイルを未変更であるとして扱わせることができます。

バージョン 1.3 で追加.

source-read(app, docname, source)

ソースファイルが読み込まれる時に発行されます。 source 引数はリストで、ひとつの要素はソースファイルのコンテンツを表します。コンテンツに関する処理を行ったり、要素に関してソースレベルでの変換を実装したりできます。

もしも、LaTeXと同じように、 $ 記号を、インラインの数式の区切り文字にしたい場合には、このイベントハンドラの中で、正規表現を使用して $...$:math:`...` に置き換えることで実現できます。

バージョン 0.5 で追加.

include-read(app, relative_path, parent_docname, content)

Emitted when a file has been read with the include directive. The relative_path argument is a Path object representing the relative path of the included file from the source directory. The parent_docname argument is the name of the document that contains the include directive. The source argument is a list whose single element is the contents of the included file. You can process the contents and replace this item to transform the included content, as with the source-read event.

バージョン 7.2.5 で追加.

参考

The include directive and the source-read event.

object-description-transform(app, domain, objtype, contentnode)

Emitted when an object description directive has run. The domain and objtype arguments are strings indicating object description of the object. And contentnode is a content for the object. It can be modified in-place.

バージョン 2.4 で追加.

doctree-read(app, doctree)

doctreeがパースされ、環境から読み込まれ、pickle化される時に発行されます。 doctree をその場で変更できます。

missing-reference(app, env, node, contnode)

Emitted when a cross-reference to an 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. If the handler can not resolve the cross-reference, it can either return None to let other handlers try, or raise NoUri to prevent other handlers in trying and suppress a warning about this cross-reference being unresolved.

パラメータ:
  • env -- ビルド環境 (app.builder.env)

  • node -- The pending_xref node to be resolved. Its reftype, reftarget, modname and classname attributes determine the type and target of the reference.

  • contnode -- このノードは、将来の参照が持つ、テキストとフォーマット情報を持ちます。これは返される参照ノードの子供にならなければなりません。

バージョン 0.5 で追加.

warn-missing-reference(app, domain, node)

Emitted when a cross-reference to an object cannot be resolved even after missing-reference. If the event handler can emit warnings for the missing reference, it should return True. The configuration variables nitpick_ignore and nitpick_ignore_regex prevent the event from being emitted for the corresponding nodes.

バージョン 3.4 で追加.

doctree-resolved(app, doctree, docname)

環境がdoctreeに関して"resolved(解決)"と判断したときに発行されます。これは、すべての参照が解決され、目次が挿入された時、ということになります。 doctree はこのイベントハンドラ内で操作できます。

このイベントは、ライタークラスにビジターメソッドが存在しない、カスタムのノードを置換して処理するのに使用できます。もしもここで設定しない場合、未知のノードを見つけると、ライターはエラーを出しますが、設定することでエラーが出なくなります。

env-merge-info(app, env, docnames, other)

このイベントはドキュメントの並列読み込みが有効の場合にのみ発行されます。それぞれのサブプロセスがドキュメントを読み込んだ場合に一度だけ発行されます。

このイベントは拡張機能が特定の場所の環境中にデータを保存する場合に使用される必要があります。使用しないと、サブプロセス中で保存された情報をメインプロセスの環境内で利用できなくなります。

other はサブプロセス中での環境、env はメインプロセスでの環境です。docnames はこのサブプロセスにおいて読み込まれたドキュメント名のセットです。

バージョン 1.3 で追加.

env-updated(app, env)

Emitted after reading all documents, when the environment and all doctrees are now up-to-date.

イベントハンドラより、ドキュメント名のイテレータを返すことができます。これらのドキュメントはアップデートされたとみなされ、書き込みフェイズにて新規書き込み(または書き換え)が行われます。

バージョン 0.5 で追加.

バージョン 1.3 で変更: イベントハンドラからの戻り値が利用されるようになりました。

env-check-consistency(app, env)

Emitted when Consistency checks phase. You can check consistency of metadata for whole of documents.

バージョン 1.6 で追加: As a experimental event

html-collect-pages(app)

HTMLビルダーが、ドキュメント以外のページの書き込みを開始するときに発行されます。 (pagename, context, templatename) という構成の要素を含むシーケンスを返すと、ページを追加できます。

バージョン 1.0 で追加.

html-page-context(app, pagename, templatename, context, doctree)

HTMLビルダーがコンテキストの辞書を作り、テンプレートを使用してレンダリングを行う時に発行されます。このイベントは、追加のカスタムの要素をコンテキストに追加する場合に使用できます。

pagename 引数はレンダリングされるページの、規範に則った名前です。規範というのは、 .html が付かず、パス区切りとしてスラッシュ(/)が使われている状態です。 templatename はレンダリングに使用するテンプレートの名前です。 reSTドキュメントのページのレンダリング時には、必ず 'page.html' となります。

context 引数はテンプレートエンジンがページをレンダリングする際に与えられる値の辞書になります。カスタムの値を持つように、変更することが可能です。キーは必ず文字列です。

doctree 引数はreSTドキュメントから作成する場合にはdoctreeとなります。もしもHTMLテンプレートからのみ作成されるページの場合には、 None となります。

イベントハンドラは文字列を返すことができます、この文字列は 'page.html' に代わりHTMLテンプレートとして、このページのレンダリングに利用されるテンプレート名になります。

注釈

You can install JS/CSS files for the specific page via Sphinx.add_js_file() and Sphinx.add_css_file() since v3.5.0.

バージョン 0.4 で追加.

バージョン 1.3 で変更: 戻り値により使用するテンプレート名を指定できるようになりました。

linkcheck-process-uri(app, uri)

Emitted when the linkcheck builder collects hyperlinks from document. uri is a collected URI. The event handlers can modify the URI by returning a string.

バージョン 4.1 で追加.

build-finished(app, exception)

ビルドが完了し、Sphinxが終了する際に発行されます。通常はクリーンアップに使用されます。このイベントは、ビルドプロセスが例外を上げたときにも発行されます。その場合には、 exception 引数が渡されます。アプリケーションの中で発生した例外は、このイベントハンドラが終了した段階で、再度投げられます。もしもビルドプロセスが例外を発生しなかった場合には、 exceptionNone になります。これによって、例外の種類ごとの、クリーンアップの処理をカスタム化できます。

バージョン 0.5 で追加.

Sphinx のバージョン確認

作製した拡張をSphinxのAPI変更に追従させる為、この仕組みを使用してください。

sphinx.version_info = (7, 3, 0, 'beta', 0)

プログラムから扱いやすい形式の Sphinx バージョンです。

バージョン情報は 5要素のタプルで表現されます。バージョン 1.2.1 beta 3 では (1, 2, 1, 'beta', 3) と表現されます。4番目の要素は alphabetarcfinal のいずれかの値を取ります。 final の場合、最後の要素は常に 0 となります。

バージョン 1.2 で追加: バージョン1.2より前では sphinx.__version__ (文字列) を参照してください。

Config オブジェクト

class sphinx.config.Config(config: dict[str, Any] | None = None, overrides: dict[str, Any] | None = None)[ソース]

ビルド設定ファイルを抽象化したオブジェクトです。

The Config object makes the values of all config options available as attributes.

It is exposed via the Sphinx.config and sphinx.environment.BuildEnvironment.config attributes. For example, to get the value of language, use either app.config.language or env.config.language.

テンプレートブリッジ

class sphinx.application.TemplateBridge[ソース]

このクラスは、"テンプレートへのブリッジ"を定義しています。テンプレートブリッジというのは、与えられたテンプレート名と、コンテキストを利用して、テンプレートをレンダリングするクラスのことです。

init(builder: Builder, theme: Theme | None = None, dirs: list[str] | None = None) None[ソース]

テンプレートのシステムの初期化を行うために、ビルダーから呼ばれます。

builder はビルダーオブジェクトで、 builder.config.templates_path の値を使用することになるでしょう。

themesphinx.theming.Theme オブジェクト、あるいは None になります。後者の場合には、 dirs に固定ディレクトリのパスが入ったリストが渡され、この中からテンプレートを探します。

newest_template_mtime() float[ソース]

このメソッドはビルダーから呼ばれます。テンプレートが変更されたことで、出力ファイルを再レンダリングする必要があるかどうかの判断をするために使用されます。変更された、最新のテンプレートのmtimeを返します。デフォルトの実装では 0 を返します。

render(template: str, context: dict) None[ソース]

指定された context (Python辞書)を使用して、 template で指定されたファイル名のテンプレートのレンダリングを行います。ビルダーから呼ばれます。

render_string(template: str, context: dict) str[ソース]

指定された context (Python辞書)を使用して、 template で指定された文字列形式のテンプレートのレンダリングを行います。ビルダーから呼ばれます。

例外

exception sphinx.errors.SphinxError[ソース]

Base class for Sphinx errors.

これは "ナイスな" 例外を作成するための基底クラスです。この例外が発生すると、Sphinxはビルドを中止し、例外のカテゴリとメッセージをユーザーに表示します。

拡張プログラムでは、この例外を継承しカスタマイズすることが強く推奨されます。

SphinxError から 継承されない 例外は予期しない例外として扱われ、トレースバックの一部を表示(そして、全部を一時ファイルに保存)します。

category

例外の "category" の記述部分は、例外内容を文字列に変換する場合に利用されます("category: message" という書式)。 例外のサブクラスに応じて適切に設定するべきです。

exception sphinx.errors.ConfigError[ソース]

Configuration error.

exception sphinx.errors.ExtensionError(message: str, orig_exc: Exception | None = None, modname: str | None = None)[ソース]

Extension error.

exception sphinx.errors.ThemeError[ソース]

Theme error.

exception sphinx.errors.VersionRequirementError[ソース]

Incompatible Sphinx version error.