Sphinx API

多くのプロジェクトはドキュメントの作成に関して特別な機能を必要とするでしょう。Sphinxはさまざまなレベルで拡張ができるように設計されています。

Here are a few things you can do in an extension:

  • Add new builders to support new output formats or actions on the parsed documents.

  • Register custom reStructuredText roles and directives, extending the markup using the Docutils マークアップ API.

  • Add custom code to so-called "hook points" at strategic places throughout the build process, allowing you to register a hook and run specialized code. For example, see the Event callbacks API.

An extension is simply a Python module with a setup() function. A user activates the extension by placing the extension's module name (or a sub-module) in their extensions configuration value.

When sphinx-build is executed, Sphinx will attempt to import each module that is listed, and execute yourmodule.setup(app). This function is used to prepare the extension (e.g., by executing Python code), linking resources that Sphinx uses in the build process (like CSS or HTML files), and notifying Sphinx of everything the extension offers (such as directive or role definitions). The app argument is an instance of Sphinx and gives you control over most aspects of the Sphinx build.

注釈

設定ファイルそのものも、setup()関数を持っている場合には拡張機能として扱われます。それ以外のロードが必要なすべての拡張機能は、設定ファイルの中の extensions の中にリストアップしてください。

The rest of this page describes some high-level aspects of developing extensions and various parts of Sphinx's behavior that you can control. For some examples of how extensions can be built and used to control different parts of Sphinx, see the Tutorials.

重要なオブジェクト

There are several key objects whose API you will use while writing an extension. These are:

アプリケーション

The application object (usually called app) is an instance of Sphinx. It controls most high-level functionality, such as loading config, initialising the environment, and the setup of extensions.

Environment

ビルド環境オブジェクト(通常 env と呼ばれる)は BuildEnvironment のインスタンスです。これはドキュメントソースのパースを行い、ドキュメントセットに関する全てのメタデータを保持し、それらをビルド後にディスクにシリアライズする責任を持っています。

環境オブジェクトはメタデータにアクセスするためのAPIや、参照を解決するAPIなどを持っています。それはまた、拡張から情報のキャッシュとして使われ、それによって漸進的な再ビルドができます。

If you have the application or builder object, the environment is available as app.env or builder.env. In SphinxDirective, SphinxRole, or SphinxTransform subclasses, the environment is available as self.env.

ビルダー

ビルダーオブジェクト(通常 builder と呼ばれる)は Builder のサブクラスのインスタンスです。各ビルダークラスはパースしたドキュメントを使って、出力フォーマットに変換したり、データ処理したりします(例えば、外部リンクのチェックなど)。

もしアプリケーションオブジェクトがあれば、 app.builder のようにビルダーオブジェクトが提供されます。

Config

コンフィグオブジェクト(通常 config と呼ばれる)は conf.py の設定値を属性として提供します。これは Config のインスタンスです。

The config is available as env.config, builder.config, or app.config. In SphinxDirective, SphinxRole, or SphinxTransform subclasses, the environment is available as self.config.

Events

The event manager object (usually called events) manages and dispatches Sphinx's events system. It is an instance of EventManager.

The event manager is available as env.events, builder.events, or app.events.

To see an example of use of these objects, refer to the tutorials.

Build phases

Sphinxのプロジェクトがビルドされる過程で、拡張機能がどのように実行されるのかということを理解することは、拡張機能の開発をするうえで必要不可欠です。この作業は以下のいくつかのフェーズから構成されています。

digraph phases {

    graph [
        rankdir = LR
    ]

    node [
        shape = rect;
        style = filled;
        fillcolor ="#f7f7f7";
        fontcolor = "#0a507a"
    ]

    Initialization -> Reading;
    Reading -> "Consistency checks";
    "Consistency checks" -> Resolving;
    Resolving -> Writing;
}

Build phases

フェーズ 0: 初期化

このフェーズでは拡張作成者にとって面白いものは何もありません。 ソースディレクトリ内のソースファイルを探索し、拡張機能を初期化します。 保存されたビルド環境があればそれをロードし、なければ新しいビルド環境を作成します。

フェーズ 1: 読み込み

フェーズ 1ではすべてのソースファイルが読み込まれ、パースされます。なお、この後のフェーズは新規のファイルか変更されたファイルに対して実行されます。このフェーズではdocutilsによってディレクティブやロールが処理され、それに対応するコードが実行されます。このフェーズの出力は、ソースファイルごとのdoctreeです。これは、docutilsのノードがツリー上に構成されているものです。すべてのファイルを読み込むまでは完全に解釈できないドキュメントの要素に関しては、一時的なノードが作られます。

There are nodes provided by docutils, which are documented in the docutils documentation. Additional nodes are provided by Sphinx and documented here.

ソースを読み込んでいる間は、ラベルや見出し名、説明されているPythonオブジェクト、索引のエントリーなどのメタな情報やクロスファンレスの情報がビルド環境に出力されます。これらの情報は、後で一時的なノードと置き換えられます。

パースされたDOCツリーはすべてのメモリ上で保存しておくことができないため、ディスク上に保存されます。

フェーズ 2: 一貫性チェック

ビルドされたドキュメントの中に、びっくりするようなものがないか、いくつかのチェックを行います。

フェーズ 3: 解決

Now that the metadata and cross-reference data of all existing documents is known, all temporary nodes are replaced by nodes that can be converted into output using components called transforms. For example, links are created for object references that exist, and simple literal nodes are created for those that don't.

フェーズ 4: 書き出し

このフェーズでは参照が解決されたDOCツリーを、HTMLやLaTeXなどの指定された出力フォーマットに変換します。このプロセス中では、docutilsのライターと呼ばれるものがDOCツリーの個々のノードをたどって、出力を行っていきます。

注釈

いくつかのビルダーの中には、この一般的なビルド計画から外れているものもあります。 例えば、外部リンクチェックのビルダーはdoctreeのパースをする以上の情報は不要なので、フェーズ2~4を行いません。

To see an example of application, refer to Extending the build process.

拡張機能のメタデータ

Added in version 1.3.

The setup() function should return a dictionary. This is treated by Sphinx as metadata of the extension. Metadata keys currently recognized are:

'version'

A string that identifies the extension version. It is used for extension version requirement checking (see needs_extensions) and informational purposes. If no version string is returned, 'unknown version' is used by default.

'env_version'

A non-zero positive integer integer that records the version of data stored in the environment by the extension.

注意

If 'env_version' is not set, the extension must not store any data or state directly on the environment object (env).

This key must be defined if the extension uses the env object to store data. The version number must be incremented whenever the type, structure, or meaning of the stored data change, to ensure Sphinx does not try and load invalid data from a cached environment.

Added in version 1.8.

'parallel_read_safe'

A boolean that specifies if parallel reading of source files can be used when the extension is loaded. It defaults to False, meaning that you have to explicitly specify your extension to be safe for parallel reading after checking that it is.

重要

When parallel-read-safe is True, the extension must satisfy the following conditions:

  • The core logic of the extension is parallelly executable during the reading phase.

  • It has event handlers for env-merge-info and env-purge-doc events if it stores data to the build environment object (env) during the reading phase.

'parallel_write_safe'

A boolean that specifies if parallel writing of output files can be used when the extension is loaded. Since extensions usually don't negatively influence the process, this defaults to True.

重要

When parallel-write-safe is True, the extension must satisfy the following conditions:

  • The core logic of the extension is parallelly executable during the writing phase.

拡張機能を書く際に利用するAPI

These sections provide a more complete description of the tools at your disposal when developing Sphinx extensions. Some are core to Sphinx (such as the アプリケーションAPI) while others trigger specific behavior (such as the i18n API)