ディレクティブ

As previously discussed, a directive is a generic block of explicit markup. While Docutils provides a number of directives, Sphinx provides many more and uses directives as one of the primary extension mechanisms.

See Domains for roles added by domains.

参考

Refer to the reStructuredText Primer for an overview of the directives provided by Docutils.

Table of contents

ReSTにはドキュメント間の連携をサポートする機能はありませんし、結果のドキュメントを複数の出力ファイルに出すこともできません。 Sphinxは、目次など、ドキュメントを構成するファイル群の関係を追加するカスタムディレクティブを使用します。 toctree ディレクティブはその中でも一番中心的なものになります。

注釈

単純に一つのファイルを別のファイルに"挿入"する場合、 include ディレクティブを使えます。

注釈

To create table of contents for current document (.rst file), use the standard reST contents directive.

.. toctree::

このディレクティブは"目次のツリー"を現在の場所に挿入します。目次の生成には、ディレクティブ本体で指定された関連ドキュメントの中の個別の目次("サブ目次ツリー"も含む)も使用されます。(/ で始まらない)相対的なドキュメント名が指定された場合は現在のドキュメントからの相対パスとして、絶対的なドキュメント名が指定された場合はソースディレクトリからの相対パスとして、それぞれ取り扱われます。 maxdepth オプションの数値を設定すると、ツリーの深さを設定できます。デフォルトではすべての階層を含むツリーが作成されます。 [1]

The representation of "TOC tree" is changed in each output format. The builders that output multiple files (ex. HTML) treat it as a collection of hyperlinks. On the other hand, the builders that output a single file (ex. LaTeX, man page, etc.) replace it with the content of the documents on the TOC tree.

このサンプルを見てください。このサンプルはPythonドキュメントのライブラリリファレンスからの引用です:

.. toctree::
   :maxdepth: 2

   intro
   strings
   datatypes
   numeric
   (many more documents listed here)

このディレクティブは二つのことを行っています。

  • ここで指定されたファイル群(intro, stringsなど)の項目も取り込んで目次を作成しています。最大の深さは2に指定されています。つまり、関連するドキュメントからトップの1階層分の項目を取得してきて目次に挿入しています。指定されたファイルに toctree ディレクティブがあればそれも利用されます。

  • Sphinxはこのディレクティブから、関連するドキュメントが intro, strings という順番を持っていて、これらのファイルがライブラリインデックスの子供であるという情報を収集します。これらの情報を使って、"next chapter", "previous chapter", "parent chapter"というリンクが作成されます。

エントリー

toctree の中のドキュメントのタイトルは、参照先のドキュメントのタイトル情報を自動的に読み込んで使用します。もしこの動作が望ましくなければ、reSTのハイパーリンクに似た文法(Sphinxの cross-referencing syntax)を使って明示的に指定できます。サンプルを示します:

.. toctree::

   intro
   All about strings <strings>
   datatypes

上記のサンプルの2行目は strings ドキュメントへのリンクになります。デフォルトの動作では strings ドキュメントのタイトルが使用されますが、ここでは"文字列のすべて"という文字列がタイトルとして使用されます。

また、ドキュメント名の代わりに、HTTPのURLを指定することで外部へのリンクも追加できます。

セクションのナンバリング

HTML 出力においてもセクション番号を利用したい場合は、上位の toctree に numbered オプションを指定します。サンプルを示します:

.. toctree::
   :numbered:

   foo
   bar

ナンバリングは foo の見出しから開始されます。サブの目次のツリーに対しても自動的にナンバリングされています。サブの文章のtoctreeには numbered フラグが設定されていなくても自動的に処理が行われます。

特定の深さまでのナンバリングだけを行うこともできます。 numbered オプションに対して、数値で深さを指定してください。

追加のオプション

You can use the caption option to provide a toctree caption and you can use the name option to provide an implicit target name that can be referenced by using ref:

.. toctree::
   :caption: Table of Contents
   :name: mastertoc

   foo

もしもドキュメントのタイトルだけをツリーに表示して、同じレベルの他の見出しを表示したくない場合には、 titlesonly オプションを使用します:

.. toctree::
   :titlesonly:

   foo
   bar

toctreeディレクティブでは、 glob フラグオプションを指定することで、"GLOB"の使用もできます。使用可能なドキュメントのうち、マッチするエントリーをすべて、アルファベット順に挿入します:

.. toctree::
   :glob:

   intro*
   recipe/*
   *

このディレクティブの先頭では、名前が intro で始まるすべてのドキュメントが挿入されます。その次には、 recipe フォルダの中の全てのドキュメントが挿入されます。最後に、一度も挿入されていない、残ったドキュメントが挿入されます。 [2]

self は特別なエントリー名として扱われます。toctreeディレクティブを含むドキュメント自身を表します。これは、toctreeを使用して、"サイトマップ"を作成したい場合に便利です。

リストのエントリーの順序を反転 するために reversed フラグオプションを使うことができます。 このオプションは、 glob フラグオプションを使ってファイルの順序を反転するときに有用です。

.. toctree::
   :glob:
   :reversed:

   recipe/*

hidden オプションを次のようにディレクティブに設定することもできます:

.. toctree::
   :hidden:

   doc_1
   doc_2

このtoctreeのサンプルは、ドキュメントの階層構造をSphinxに教えますが、このディレクティブがある場所にはドキュメントのリンクは作成されません。これにより、違う形式で出力したり、サイドバーに入れたり、これらのリンクを自分で挿入したい場合にも、きちんとした構造を作ることができます。

トップレベルの単一の toctree だけを残して他のより低いレベルの toctree をすべて隠したい場合、トップレベルの toctree エントリに "includehidden" オプションを加えることができます:

.. toctree::
   :includehidden:

   doc_1
   doc_2

hidden オプションで 他のすべてのTOCツリー内のエントリーを無視出来ます。

最後になりますが ソースディレクトリ (サブディレクトリも含む)の中のドキュメントは、いずれかの toctree ディレクティブの中にリストアップされなければいけません。ソースフォルダには置いてあるが、リストアップされていないファイルがあると、通常のナビゲーションではそのファイルに到達できないということになるため、Sphinxは警告を出力します。

exclude_patterns を使って明示することで、ビルド対象からドキュメントを外すこともできます。ドキュメントをビルドさせる場合には the "orphan" metadata を使用して下さい、toctreeを通じて到達できないことをSphinxへ知らせます。

The "root document" (selected by root_doc) is the "root" of the TOC tree hierarchy. It can be used as the documentation's main page, or as a "full table of contents" if you don't give a maxdepth option.

バージョン 0.3 で変更: "globbing" オプションを追加しました。

バージョン 0.6 で変更: 外部リンクのサポートと"self"参照と同じように、"numbered" と"hidden"オプションを追加しました。

バージョン 1.0 で変更: "titlesonly" オプションを追加しました。

バージョン 1.1 で変更: "numbered" オプションに引数を追加しました。

バージョン 1.2 で変更: "includehidden" オプションを追加しました。

バージョン 1.3 で変更: "caption" と "name" オプションを追加しました。

特別なドキュメント名

Sphinxはいくつかのドキュメント名を、自分で使用するために予約済みとしています。これらの名前を持つドキュメントを作ろうとしてはいけません。問題が発生することになります。

以下の名前(もしくはこれらから作られるページ名)が特別なドキュメント名です:

  • genindexmodindexsearch

    これらの名前は、それぞれ、全体のインデックス、モジュールインデックス、検索ページを作成するのに使用されます。

    全体のインデックスはモジュールに含まれるのエントリーから作られます。すべてのインデックスを生成する オブジェクト説明 と、 rst:dir:index ディレクティブが利用されます。

    モジュールインデックスには rst:dir:module ディレクティブで指定されたエントリーが含まれます。

    検索ページは、ビルドされた文章から生成されたJSONの検索インデックスと、JavaScriptを利用した全文検索を行うフォームを含みます。検索は現代的なJavaScriptをサポートする、主要なブラウザで動作するはずです。

  • _ で始まるすべての名前

    Though few such names are currently used by Sphinx, you should not create documents or document-containing directories with such names. (Using _ as a prefix for a custom template directory is fine.)

警告

ファイル名に特殊文字を使うときは気をつけてください。思いがけない挙動を示すことがあります。

  • HTMLを使うフォーマットに、コロン : を使わないでください。他の箇所へのリンクが動かなくなる場合があります。

  • ePubフォーマットに、プラス + を使わないでください。使用すると、リソースが見つからなくなる場合があります。

パラグラフ階層のマークアップ

These directives create short paragraphs and can be used inside information units as well as normal text.

.. note::

特別に重要な情報が少しだけある場合に使用します。APIを使用する際に、ユーザが気をつけなければならないことの説明をする場合などに使うと良いでしょう。このディレクティブの中身には、適切に句読点が付いた、完全な文章を書くべきです。

サンプル:

.. note::

   This function is not suitable for sending spam e-mails.
.. warning::

noteよりも重要な情報があり、APIを使用する際に、気をつけなければならない警告情報をユーザに伝えるために使用するのに適しています。このディレクティブの中身には、適切に句読点が付いた、完全な文章を書くべきです。 note との違いで言えば、セキュリティに関する情報は note よりもこのディレクティブを使用する方が良いでしょう。

.. versionadded:: version

このディレクティブは説明している機能がライブラリ、もしくはC APIに追加された時のプロジェクトのバージョンについて記述するのに使用します。このディレクティブがモジュール全体に対して適用する場合には、モジュールセクションの先頭の、文章が始まる前の位置に置くべきです。

最初の引数は必須で、バージョン番号を書く必要があります。2番目の引数も追加でき、変化に対する 短い 説明を書くことができます。

サンプル:

.. versionadded:: 2.5
   The *spam* parameter.

ディレクティブヘッドと説明の間には空行を入れてはいけません。マークアップの中では見た目上つながっているようにしなければなりません。

.. versionchanged:: version

versionadded と似ていますが、現在説明している機能がいつどのように変化したのか(新しい引数、副作用の変更など)を説明するのに使用します。

.. deprecated:: version

versionchanged と似ていますが、このディレクティブは、この機能がすでに古くて非推奨になったことを示しています。代替として、今後何を使っていくべきなのかといった説明文を付けることができます:

.. deprecated:: 3.1
   Use :func:`spam` instead.
.. versionremoved:: version

Similar to versionadded, but describes when the feature was removed. An explanation may be provided to inform the reader what to use instead, or why the feature was removed. Example:

.. versionremoved:: 4.0
   The :func:`spam` function is more flexible, and should be used instead.

Added in version 7.3.

.. seealso::

多くのセクションがモジュールのドキュメントへの参照やが、外部ドキュメントへの参照を含む場合、このようなリストは seealso ディレクティブを使用して作ることができます。

seealso ディレクティブはサブセクションの直前のセクションに置かれることが多いです。HTMLアウトプットにおいては、メインのテキストの流れから離されて、箱に囲まれて表示されます。

seealso の中身は、reSTの定義リストを使用しなければなりません。 サンプル:

.. seealso::

   Module :py:mod:`zipfile`
      Documentation of the :py:mod:`zipfile` standard module.

   `GNU tar manual, Basic Tar Format <https://link>`_
      Documentation for tar archive files, including GNU tar extensions.

"短縮形"の書き方もサポートされており、以下のように書くことができます:

.. seealso:: modules :py:mod:`zipfile`, :py:mod:`tarfile`

Added in version 0.5: “短縮形”を追加。

.. rubric:: title

このディレクティブは、目次に表示されないパラグラフの見出しを作成します。(訳注:rubricは注釈の意味です)

注釈

もし rubricディレクティブの タイトル が"Footnotes"(もしくは選択された言語で指定されている、同様の言葉)だった場合には、脚注の定義だけが含まれていると見なして、LaTeXライターでは無視されます。この場合は空の見出しだけが作成されます。

.. centered::

このディレクティブはセンターに置かれた、太字のテキストを作成するのに使用します。以下のように使用されます:

.. centered:: LICENSE AGREEMENT

バージョン 1.1 で非推奨: This presentation-only directive is a legacy from older versions. Use a rst-class directive instead and add an appropriate style.

.. hlist::

このディレクティブは短い文章のリストを含みます。このディレクティブは、水平にも数カラム展開することで、よりコンパクトなリストに変換するか、アイテム間のスペースを小さくします。どちらになるかはビルダー次第です。

水平に展開する機能をサポートしたビルダーでは、 columns オプションを使用して、水平のカラム数の設定できます。デフォルトでは2になっています。サンプルを示します:

.. hlist::
   :columns: 3

   * A list of
   * short items
   * that should be
   * displayed
   * horizontally

Added in version 0.6.

コードサンプルの表示

There are multiple ways to show syntax-highlighted literal code blocks in Sphinx:

Doctest blocks can only be used to show interactive Python sessions, while the remaining three can be used for other languages. Of these three, literal blocks are useful when an entire document, or at least large sections of it, use code blocks with the same syntax and which should be styled in the same manner. On the other hand, the code-block directive makes more sense when you want more fine-tuned control over the styling of each block or when you have a document containing code blocks using multiple varied syntaxes. Finally, the literalinclude directive is useful for including entire code files in your documentation.

In all cases, Syntax highlighting is provided by Pygments. When using literal blocks, this is configured using any highlight directives in the source file. When a highlight directive is encountered, it is used until the next highlight directive is encountered. If there is no highlight directive in the file, the global highlighting language is used. This defaults to python but can be configured using the highlight_language config value. The following values are supported:

  • none (ハイライトしない)

  • default (similar to python3 but with a fallback to none without warning highlighting fails; the default when highlight_language isn't set)

  • guess (Pygmentsに推測させます。推測しやすい言語でないとうまく動作しません)

  • python

  • rest

  • c

  • ... and any other lexer alias that Pygments supports

選択された言語によるハイライトがうまくいかなかった場合(例えば、Pygmentsが"Error"トークンを出す等)には、そのブロックはハイライトされなくなります。

重要

The list of lexer aliases supported is tied to the Pygment version. If you want to ensure consistent highlighting, you should fix your version of Pygments.

.. highlight:: language

サンプル:

.. highlight:: c

This language is used until the next highlight directive is encountered. As discussed previously, language can be any lexer alias supported by Pygments.

options

:linenothreshold: threshold (number (optional))

Enable to generate line numbers for code blocks.

This option takes an optional number as threshold parameter. If any threshold given, the directive will produce line numbers only for the code blocks longer than N lines. If not given, line numbers will be produced for all of code blocks.

サンプル:

.. highlight:: python
   :linenothreshold: 5
:force: (no value)

If given, minor errors on highlighting are ignored.

Added in version 2.1.

.. code-block:: [language]
.. sourcecode:: [language]

サンプル:

.. code-block:: ruby

   Some Ruby code.

The directive's alias name sourcecode works as well. This directive takes a language name as an argument. It can be any lexer alias supported by Pygments. If it is not given, the setting of highlight directive will be used. If not set, highlight_language will be used. To display a code example inline within other text, rather than as a separate block, you can use the code role instead.

バージョン 2.0 で変更: The language argument becomes optional.

options

:linenos: (no value)

Enable to generate line numbers for the code block:

.. code-block:: ruby
   :linenos:

   Some more Ruby code.
:lineno-start: number (number)

Set the first line number of the code block. If present, linenos option is also automatically activated:

.. code-block:: ruby
   :lineno-start: 10

   Some more Ruby code, with line numbering starting at 10.

Added in version 1.3.

:emphasize-lines: line numbers (comma separated numbers)

Emphasize particular lines of the code block:

.. code-block:: python
   :emphasize-lines: 3,5

   def some_function():
       interesting = False
       print('This line is highlighted.')
       print('This one is not...')
       print('...but this one is.')

Added in version 1.1.

バージョン 1.6.6 で変更: LaTeX が emphasize-lines オプションをサポートしました。

:caption: caption of code block (text)

Set a caption to the code block.

Added in version 1.3.

:name: a label for hyperlink (text)

Define implicit target name that can be referenced by using ref. For example:

.. code-block:: python
   :caption: this.py
   :name: this-py

   print('Explicit is better than implicit.')

In order to cross-reference a code-block using either the ref or the numref role, it is necessary that both name and caption be defined. The argument of name can then be given to numref to generate the cross-reference. Example:

See :numref:`this-py` for an example.

When using ref, it is possible to generate a cross-reference with only name defined, provided an explicit title is given. Example:

See :ref:`this code snippet <this-py>` for an example.

Added in version 1.3.

:class: class names (a list of class names separated by spaces)

The class name of the graph.

Added in version 1.4.

:dedent: number (number or no value)

Strip indentation characters from the code block. When number given, leading N characters are removed. When no argument given, leading spaces are removed via textwrap.dedent(). For example:

.. code-block:: ruby
   :linenos:
   :dedent: 4

       some ruby code

Added in version 1.3.

バージョン 3.5 で変更: Support automatic dedent.

:force: (no value)

If given, minor errors on highlighting are ignored.

Added in version 2.1.

.. literalinclude:: filename

Longer displays of verbatim text may be included by storing the example text in an external file containing only plain text. The file may be included using the literalinclude directive. [3] For example, to include the Python source file example.py, use:

.. literalinclude:: example.py

ソースコードのファイルは通常、現在のパスからの相対パスで指定します。 / から開始されているときはトップのソースディレクトリからのパス指定をできます。

追加のオプション

Like code-block, the directive supports the linenos flag option to switch on line numbers, the lineno-start option to select the first line number, the emphasize-lines option to emphasize particular lines, the name option to provide an implicit target name, the dedent option to strip indentation characters for the code block, and a language option to select a language different from the current file's standard language. In addition, it supports the caption option; however, this can be provided with no argument to use the filename as the caption. Example with options:

.. literalinclude:: example.rb
   :language: ruby
   :emphasize-lines: 12,15-18
   :linenos:

tab-width オプションを指定すると、入力ファイル中のタブを希望の幅に展開できます。

読み込むファイルは source_encoding で設定されているエンコードで保存されているものとして処理されます。もし違うエンコーディングのファイルを読み込む場合には encoding オプションで設定できます:

.. literalinclude:: example.py
   :encoding: latin-1

このディレクティブは、ファイル全体ではなく、一部分だけを読み込むこともサポートしています。もしPythonモジュールの場合には、 pyobject オプションを使用してクラス、関数、メソッドの単位でインクルードすることもできます:

.. literalinclude:: example.py
   :pyobject: Timer.start

上記のサンプルを書くと、指定されたファイルに含まれる、 Timer クラスの start() メソッドに属するコード行だけがドキュメントに挿入されます。

これとは別に、 lines オプションを使って行番号を正確に指定することでも部分的なインクルードを行えます:

.. literalinclude:: example.py
   :lines: 1,3,5-10,20-

このサンプルでは、指定されたファイルの 1行目, 3行目, 5〜10行目, そして20行目から最終行までのコードがインクルードされます。

Another way to control which part of the file is included is to use the start-after and end-before options (or only one of them). If start-after is given as a string option, only lines that follow the first line containing that string are included. If end-before is given as a string option, only lines that precede the first lines containing that string are included. The start-at and end-at options behave in a similar way, but the lines containing the matched string are included.

start-after/start-at and end-before/end-at can have same string. start-after/start-at filter lines before the line that contains option string (start-at will keep the line). Then end-before/end-at filter lines after the line that contains option string (end-at will keep the line and end-before skip the first line).

注釈

If you want to select only [second-section] of ini file like the following, you can use :start-at: [second-section] and :end-before: [third-section]:

[first-section]

var_in_first=true

[second-section]

var_in_second=true

[third-section]

var_in_third=true

Useful cases of these option is working with tag comments. :start-after: [initialize] and :end-before: [initialized] options keep lines between comments:

if __name__ == "__main__":
    # [initialize]
    app.start(":8000")
    # [initialized]

先に説明したどれかの方法で行が選択されたとき、 emphasize-lines にある行番号がその選択された行を参照していて、行番号は 1 から始まる連番です。

ファイルの一部を表示するように指定した場合、ファイルの行番号をそのまま表示するように指定することもできます。その場合は、 lineno-match オプションを設定して下さい。ただし、このオプションは選択された行が切れ目なくつながっている場合でのみ有効です。

prepend, append オプションを使用すると、読み込まれた行の前後にコード行を追加できます。例えば、 <?php/?> マーカーを含まないPHPコードをハイライトする際などに役立ちます。

もしあなたがコードの差分を表示したいなら、diff オプションを与えて古いファイルを記述できます:

.. literalinclude:: example.py
   :diff: example.py.orig

This shows the diff between example.py and example.py.orig with unified diff format.

A force option can ignore minor errors on highlighting.

バージョン 0.4.3 で変更: Added the encoding option.

バージョン 0.6 で変更: Added the pyobject, lines, start-after and end-before options, as well as support for absolute filenames.

バージョン 1.0 で変更: Added the prepend, append, and tab-width options.

バージョン 1.3 で変更: Added the diff, lineno-match, caption, name, and dedent options.

バージョン 1.4 で変更: Added the class option.

バージョン 1.5 で変更: Added the start-at, and end-at options.

バージョン 1.6 で変更: start-afterlines の両方を使っているときは、 start-after を基準とした先頭行が lines における行番号 1 となります。

バージョン 2.1 で変更: Added the force option.

バージョン 3.5 で変更: Support automatic dedent.

用語集

.. glossary::

This directive must contain a reST definition-list-like markup with terms and definitions. The definitions will then be referenceable with the term role. Example:

.. glossary::

   environment
      A structure where information about all documents under the root is
      saved, and used for cross-referencing.  The environment is pickled
      after the parsing stage, so that successive runs only need to read
      and parse new and changed documents.

   source directory
      The directory which, including its subdirectories, contains all
      source files for one Sphinx project.

通常の定義リストとは異なり、一つのエントリーに対して、複数の 用語を定義できます。それぞれの用語に対してインラインマークアップを使えます。また、すべての用語への参照も可能です:

.. glossary::

   term 1
   term 2
      Definition of both terms.

(用語集がソートされる場合、最初の項がソート順序を決定します。)

一般的な索引項目に "グループ化キー" を指定する場合は、 "キー" を "term : key" とします。例えば:

.. glossary::

   term 1 : A
   term 2 : B
      Definition of both terms.

キーをそのままグループ化する場合は、 "key" を使用します。 "key" は正規化されません。key "A" とkey "a" は異なるグループになります。 "key" 内のすべての文字が最初の文字の代わりに使用されます。 "文字シーケンスの結合" と "代理ペア" のグルーピングキーに使用します。

i18nの場合、原文が "term" のみの場合でも "localized term : key" を指定できますが、この場合、翻訳された "localized term" は "key" グループに分類されます。

Added in version 0.6: glossary ディレクティブに :sorted: フラグを追加することで、アルファベット順に自動的にソートされるようになりました。

バージョン 1.1 で変更: 複数の用語をサポートし、また、用語の中でインラインマークアップを使えるようになりました。

バージョン 1.4 で変更: Index key for glossary term should be considered experimental.

バージョン 4.4 で変更: In internationalized documentation, the :sorted: flag sorts according to translated terms.

メタ情報マークアップ

.. sectionauthor:: name <email>

現在のセクションの著者名を指定します。引数には必ず、表示するための著者の名前と、電子メールのアドレスを入れます。アドレスのドメイン名の部分は小文字でなければなりません。 サンプル:

.. sectionauthor:: Guido van Rossum <guido@python.org>

デフォルトでは、このマークアップは出力に反映されません(貢献者の名前を調べる手助けにはなります)。しかし、設定ファイルの show_authorsTrue に設定すると、出力ファイルの中にこの情報に関する段落が作成されます。

.. codeauthor:: name <email>

codeauthor ディレクティブは、 sectionauthor の名前と同じく、説明しているコードの作者名について、複数人書くことができます。 show_authors 設定値を True にしないかぎり、出力はされません。

インデックス生成のためのマークアップ

Sphinx automatically creates index entries from all object descriptions (like functions, classes or attributes) like discussed in Domains.

しかし、これ以外に明示的に指定するディレクティブもあります。これを使用することで、言語のリファレンスのように、メインの情報のユニットが存在しない情報をドキュメントの中に書いてインデックスのエントリーを作ることができるようになります。より包括的なインデックスを作成できるようになります。

.. index:: <entries>

このディレクティブは一つ以上のインデックスのエントリーを含みます。それぞれのエントリーはコロン(:)で区切られた、タイプ、値を含みます。

例えば:

.. index::
   single: execution; context
   pair: module; __main__
   pair: module; sys
   triple: module; search; path
   seealso: scope

The execution context
---------------------

...

このディレクティブは5つのエントリーを含んでいます。これらは生成されたインデックスのエントリーに変換され、index文の正確な位置へのリンクが張られることになります。オフラインのメディアに出力される場合には、リンクの代わりに対応するページ番号が出力されます。

indexディレクティブはそのソースの位置のターゲットとのクロスリファレンスを生成するため、それらが参照するものの 前の位置 に置くことが大切になります。上記のサンプルコードの例では、リンクを張りたい見出しの前に配置されています。

設定可能なエントリーのタイプは以下の通りです:

single

Creates a single index entry. Can be made a sub-entry by separating the sub-entry text with a semicolon (this notation is also used below to describe what entries are created). Examples:

.. index:: single: execution
           single: execution; context
  • single: execution creates an index entry labelled execution.

  • single: execution; context creates an sub-entry of execution labelled context.

pair

A shortcut to create two index entries. The pair of values must be separated by a semicolon. Example:

.. index:: pair: loop; statement

This would create two index entries; loop; statement and statement; loop.

triple

A shortcut to create three index entries. All three values must be separated by a semicolon. Example:

.. index:: triple: module; search; path

This would create three index entries; module; search path, search; path, module, and path; module search.

see

A shortcut to create an index entry that refers to another entry. Example:

.. index:: see: entry; other

This would create an index entry referring from entry to other (i.e. 'entry': See 'other').

seealso

Like see, but inserts 'see also' instead of 'see'.

module, keyword, operator, object, exception, statement, builtin

These deprecated shortcuts all create two index entries. For example, module: hashlib creates the entries module; hashlib and hashlib; module.

バージョン 1.0 で非推奨: These Python-specific entry types are deprecated.

バージョン 7.1 で変更: Removal version set to Sphinx 9.0. Using these entry types will now emit warnings with the index category.

もしエクスクラメーションマーク(!)を前に付けると、主要なインデックスエントリーである、ということを表現できます。主要なインデックスは、生成されたインデックスの中で強調されます。例えば、2つのページが次のようなディレクティブを持っていたとします:

.. index:: Python

そして、次の内容を含むページがあったとします:

.. index:: ! Python

この場合、最後のページへのバックリンクが3つの中では強調されて表示されます。

"single"のエントリーだけが含まれるindexディレクティブの場合、以下のように短縮記法で簡単に作成することもできます:

.. index:: BNF, grammar, syntax, notation

これは4つのインデックスのエントリーが作成されます。

バージョン 1.1 で変更: seeseealso を追加しました。

options

:name: a label for hyperlink (text)

Define implicit target name that can be referenced by using ref. For example:

.. index:: Python
   :name: py-index

Added in version 3.0.

:index:

index ディレクティブは、ブロックレベルのマークアップで、次のパラグラフの先頭に対するリンクを生成します。これとは別に、直接リンクターゲットに設定するロールもあります。

ロールのコンテンツは、文章の中にあるシンプルなフレーズで、そのままインデックスのエントリーとして使用されます。テキストと入力エントリーの組み合わせになっていて、明示的なクロスリファレンスのターゲットになります。この場合、ターゲットの部分は上記で説明したディレクティブの機能をフルに使うことができます:

This is a normal reST :index:`paragraph` that contains several
:index:`index entries <pair: index; entry>`.

Added in version 1.1.

タグを使用したインクルード

.. only:: <expression>

条件式(expression) が真のときだけ、ディレクティブの内容をインクルードします。条件式は以下のようにタグで構成されます。

.. only:: html and draft

Undefined tags are false, defined tags (via the -t command-line option or within conf.py, see here) are true. Boolean expressions, also using parentheses (like (latex or html) and draft) are supported.

現在のビルダー (htmllatextext) の フォーマット名前 が常にタグ [4] として設定されます。フォーマットと名前とを明示的に区別するために、 format_builder_ というプレフィックスも追加されました。 例: epubビルダーは htmlepubformat_htmlbuilder_epub の4つのタグが定義されます。

これらの標準タグは、conf.pyを読み込んだ に設定されるため、conf.pyではこれらのタグの有無を参照できません。

All tags must follow the standard Python identifier syntax as set out in the Identifiers and keywords documentation. That is, a tag expression may only consist of tags that conform to the syntax of Python variables. In ASCII, this consists of the uppercase and lowercase letters A through Z, the underscore _ and, except for the first character, the digits 0 through 9.

Added in version 0.6.

バージョン 1.2 で変更: builder名とプレフィックスが追加されました。

警告

このディレクティブはドキュメントの文面を制御するようにデザインされています。セクションやラベルは制御できません。

テーブル

Use reStructuredText tables, i.e. either

The table directive serves as optional wrapper of the grid and simple syntaxes.

They work fine in HTML output, but rendering tables to LaTeX is complex. Check the latex_table_style.

バージョン 1.6 で変更: Merged cells (multi-row, multi-column, both) from grid tables containing complex contents such as multiple paragraphs, blockquotes, lists, literal blocks, will render correctly to LaTeX output.

.. tabularcolumns:: column spec

This directive influences only the LaTeX output for the next table in source. The mandatory argument is a column specification (known as an "alignment preamble" in LaTeX idiom). Please refer to a LaTeX documentation, such as the wiki page, for basics of such a column specification.

Added in version 0.3.

注釈

tabularcolumns conflicts with :widths: option of table directives. If both are specified, :widths: option will be ignored.

Sphinx will render tables with more than 30 rows with longtable. Besides the l, r, c and p{width} column specifiers, one can also use \X{a}{b} (new in version 1.5) which configures the column width to be a fraction a/b of the total line width and \Y{f} (new in version 1.6) where f is a decimal: for example \Y{0.2} means that the column will occupy 0.2 times the line width.

When this directive is used for a table with at most 30 rows, Sphinx will render it with tabulary. One can then use specific column types L (left), R (right), C (centered) and J (justified). They have the effect of a p{width} (i.e. each cell is a LaTeX \parbox) with the specified internal text alignment and an automatically computed width.

警告

  • Cells that contain list-like elements such as object descriptions, blockquotes or any kind of lists are not compatible with the LRCJ column types. The column type must then be some p{width} with an explicit width (or \X{a}{b} or \Y{f}).

  • Literal blocks do not work with tabulary at all. Sphinx will fall back to tabular or longtable environments and generate a suitable column specification.

In absence of the tabularcolumns directive, and for a table with at most 30 rows and no problematic cells as described in the above warning, Sphinx uses tabulary and the J column-type for every column.

バージョン 1.6 で変更: Formerly, the L column-type was used (text is flushed-left). To revert to this, include \newcolumntype{T}{L} in the LaTeX preamble, as in fact Sphinx uses T and sets it by default to be an alias of J.

ヒント

A frequent issue with tabulary is that columns with little contents appear to be "squeezed". One can add to the LaTeX preamble for example \setlength{\tymin}{40pt} to ensure a minimal column width of 40pt, the tabulary default of 10pt being too small.

ヒント

To force usage of the LaTeX longtable environment pass longtable as a :class: option to table, csv-table, or list-table. Use rst-class for other tables.

Math

数式の入力言語としてはLaTeXのマークアップを利用します。これはプレーンテキストで数式を表現する記法としてはデファクトスタンダードになっています。また、LaTeX出力を行う場合には、変換をしないでそのまま利用できるというメリットもあります。

autodoc で読み込まれた Python docstrings の中に数式を入れるときには、すべてのバックスラッシュを二重にするか、Pythonのraw strings (r"raw") を使う必要があることに注意してください。

.. math::

数式を表示するディレクティブです。この数式は1行丸ごと使って表示されます。

このディレクティブは、複数行の等式をサポートしています。複数行に記述したい場合には、空行で区切ります:

.. math::

   (a + b)^2 = a^2 + 2ab + b^2

   (a - b)^2 = a^2 - 2ab + b^2

それぞれの数式は 分割された 環境にセットされます。もしも、複数行の等式をきれいに整列させたい場合には、 \\ で区切って、 & 記号を使って整列させます:

.. math::

   (a + b)^2  &=  (a + b)(a + b) \\
              &=  a^2 + 2ab + b^2

もっと詳しく知りたい場合には AmSMath LaTeX パッケージ のドキュメントを参照してください。

数式が一行のテキストに収まる場合には、ディレクティブの引数として記述もできます:

.. math:: (a + b)^2 = a^2 + 2ab + b^2

通常、数式には番号が付きません。数式に番号をつけたい場合は、 label オプションを使用してください。これが指定されると、数式のラベルを選択できます。この数式のラベルを使ってクロスリファレンスを作成することができます。例は eq を参照してください。ナンバリングの形式は出力フォーマットに依存します。

nowrap オプションを使用することで、math環境で自動的にラッピングされるのを止めることができます。このオプションを指定した場合には、自分自身で適切な設定を行う必要があります。 サンプル:

.. math::
   :nowrap:

   \begin{eqnarray}
      y    & = & ax^2 + bx + c \\
      f(x) & = & x^2 + 2xy + y^2
   \end{eqnarray}

参考

SphinxにおけるHTML出力での数式サポート

Rendering options for math with HTML builders.

latex_engine

Explains how to configure LaTeX builder to support Unicode literals in math mark-up.

文法規則表示

形式がきちんとした文法の規則を表示するための特別なマークアップを利用できます。マークアップはシンプルに作られています。その代わりに、BNFや、BNFの派生の記法をすべてのモデル化することは目標とされていませんが、文脈自由文法を表現するには十分な機能を持っていて、シンボルを書くと、定義にリンクが張られるようにレンダリングされます。以下のディレクティブがあります:

.. productionlist:: [productionGroup]

This directive is used to enclose a group of productions. Each production is given on a single line and consists of a name, separated by a colon from the following definition. If the definition spans multiple lines, each continuation line must begin with a colon placed at the same column as in the first line. Blank lines are not allowed within productionlist directive arguments.

The definition can contain token names which are marked as interpreted text (e.g., "sum ::= `integer` "+" `integer`") -- this generates cross-references to the productions of these tokens. Outside of the production list, you can reference to token productions using token.

The productionGroup argument to productionlist serves to distinguish different sets of production lists that belong to different grammars. Multiple production lists with the same productionGroup thus define rules in the same scope.

Inside of the production list, tokens implicitly refer to productions from the current group. You can refer to the production of another grammar by prefixing the token with its group name and a colon, e.g, "otherGroup:sum". If the group of the token should not be shown in the production, it can be prefixed by a tilde, e.g., "~otherGroup:sum". To refer to a production from an unnamed grammar, the token should be prefixed by a colon, e.g., ":sum".

Outside of the production list, if you have given a productionGroup argument you must prefix the token name in the cross-reference with the group name and a colon, e.g., "myGroup:sum" instead of just "sum". If the group should not be shown in the title of the link either an explicit title can be given (e.g., "myTitle <myGroup:sum>"), or the target can be prefixed with a tilde (e.g., "~myGroup:sum").

規則の中ではreSTパーサは動作しないため、 * や、 | といった文字をエスケープすることはできません。

次のサンプルは、Pythonのリファレンスマニュアルにあった構文をSphinxで表現したものです:

.. productionlist::
   try_stmt: try1_stmt | try2_stmt
   try1_stmt: "try" ":" `suite`
            : ("except" [`expression` ["," `target`]] ":" `suite`)+
            : ["else" ":" `suite`]
            : ["finally" ":" `suite`]
   try2_stmt: "try" ":" `suite`
            : "finally" ":" `suite`

脚注