reStructuredText入門

reStructuredText is the default plaintext markup language used by Sphinx. This section is a brief introduction to reStructuredText (reST) concepts and syntax, intended to provide authors with enough information to author documents productively. Since reST was designed to be a simple, unobtrusive markup language, this will not take too long.

参考

The authoritative reStructuredText User Documentation. The "ref" links in this document link to the description of the individual constructs in the reST reference.

段落(パラグラフ)

段落(ref)はreSTドキュメントにおける、もっとも基本的な要素です。段落は1行以上の空行で区切られた、シンプルなテキストの固まりです。 Pythonにおいてインデントが重要な意味を持つのと同様、reSTでもインデントは重要です。同じ段落のすべての行は、インデントを同じ高さにそろえて、左揃えにしなければなりません。

インラインマークアップ

標準のreSTインラインマークアップは極めてシンプルです。

  • アスタリスク1つ: *テキスト* 強調(イタリック)

  • アスタリスク2つ: **テキスト** 強い強調(太文字)

  • バッククオート: ``テキスト`` コードサンプル

もしも、アスタリスクかバッククオートがテキスト中に使用する場合は、インラインマークアップの区切り文字と間違ってしまうことがあります。そのような場合には、バックスラッシュ(訳注:日本語フォントだと円記号)を使ってエスケープしてください。

このマークアップにはいくつかの制限があります。

  • ネストすることはできません

  • 中のテキストの最初、もしくは最後にスペースを入れることもできません。 * text* と書くことはできません

  • 周囲のテキストとは、テキスト以外の文字(スペース、カッコなど)で区切る必要があります。もしも空白を空けずに、続けて表記したい場合には、 thisis\ *one*\ word と、バックスラッシュでエスケープしたテキスト(スペースは表示されません)を使用してください。

これらの制限は、docutilsの将来のバージョンでも残るでしょう。

It is also possible to replace or expand upon some of this inline markup with roles. Refer to ロール for more information.

リストと引用のようなブロック

リストを表現するマークアップ (ref) はほぼ結果の見た目通りです。パラグラフの最初をアスタリスクで開始して、適切にインデントをしてやるだけです。ナンバー付きのリストも同様です。 # を使うことで、ナンバリングを自動で行うこともできます:

* This is a bulleted list.
* It has two items, the second
  item uses two lines.

1. This is a numbered list.
2. It has two items too.

#. This is a numbered list.
#. It has two items too.

ネストされたリストも使用できますが、親のリストとは空白行で区切る必要があります:

* this is
* a list

  * with a nested list
  * and some subitems

* and here the parent list continues

定義リスト(ref)は以下のようにして作成します:

term (up to a line of text)
   Definition of the term, which must be indented

   and can even consist of multiple paragraphs

next term
   Description.

用語のテキストは複数行書くことができないことに注意してください。

引用パラグラフ(ref)は周囲のパラグラフよりもインデントすることで作成できます。

ラインブロック(ref)を利用すると、改行状態をそのまま維持したまま出力できます:

| These lines are
| broken exactly like in
| the source file.

次のような特別なブロックも利用できます:

  • field lists (ref, with caveats noted in Field Lists)

  • オプションリスト (ref)

  • 引用リテラルブロック (ref)

  • doctestブロック (ref)

Literal blocks

リテラルコードブロック(ref)は、前の段落の行末を特別な記号 :: にすることで開始できます。リテラルコードブロックはインデントする必要があります。また、他のパラグラフ同様、空白行で前後をかこう必要があります:

This is a normal text paragraph. The next paragraph is a code sample::

   It is not processed in any way, except
   that the indentation is removed.

   It can span multiple lines.

This is a normal text paragraph again.

:: マーカーの扱いはとてもスマートです:

  • もしマーカーがリテラルコードブロックのパラグラフの中に出てきた場合には、そのパラグラフは完全にそのままドキュメント中に残されます。

  • もしもマーカーの前がホワイトスペースだった場合には、マーカー自身は非表示になります。

  • もしもマーカーの前がホワイトスペース以外だった場合には、コロン(:)1つだけが表示されます。

3つ目のルールが適用されるため、上記のサンプルの最初の段落中の2つめの文をレンダリングすると、 "次のパラグラフはコードサンプルです:" という表記になります。

Code highlighting can be enabled for these literal blocks on a document-wide basis using the highlight directive and on a project-wide basis using the highlight_language configuration option. The code-block directive can be used to set highlighting on a block-by-block basis. These directives are discussed later.

Doctest blocks

Doctest blocks (ref) are interactive Python sessions cut-and-pasted into docstrings. They do not require the literal blocks syntax. The doctest block must end with a blank line and should not end with an unused prompt:

>>> 1 + 1
2

テーブル

グリッドテーブル (ref)は、セルのグリッドを自分で線描する必要があります。これは次のようになります:

+------------------------+------------+----------+----------+
| Header row, column 1   | Header 2   | Header 3 | Header 4 |
| (header rows optional) |            |          |          |
+========================+============+==========+==========+
| body row 1, column 1   | column 2   | column 3 | column 4 |
+------------------------+------------+----------+----------+
| body row 2             | ...        | ...      |          |
+------------------------+------------+----------+----------+

シンプルテーブル (ref)はより書くのが簡単な方法ですが、制限があります。1つ以上の列を含み、最初のカラムには複数行のテキストを書くことができません。次のように表現されます:

=====  =====  =======
A      B      A and B
=====  =====  =======
False  False  False
True   False  False
False  True   False
True   True   True
=====  =====  =======

Two more syntaxes are supported: CSV tables and List tables. They use an explicit markup block. Refer to テーブル for more information.

セクション

セクションのヘッダ(ref)は、セクションのタイトルを句読点などの記号の文字でアンダーラインを引くことで設定します。必要に応じてでオーバーラインも併用できます。アンダーラインはテキストと同じか、それ以上の長さにする必要があります:

=================
This is a heading
=================

Normally, there are no heading levels assigned to certain characters as the structure is determined from the succession of headings. However, this convention is used in Python Developer's Guide for documenting which you may follow:

  • # 部: オーバーライン付き

  • * 章: オーバーライン付き

  • = for sections

  • - for subsections

  • ^ for subsubsections

  • " for paragraphs

もちろん、どのようなマークアップ文字を選択しても自由ですし、組み合わせることで、より深いネストレベルも使用できます。reSTの文章を参照してください。ただし、ほとんどの対象となる出力フォーマット(HTML, LaTeX)は、ネストできる深さには限界が設定されている、ということは忘れないでください。

Field Lists

Field lists (ref) are sequences of fields marked up like this:

:fieldname: Field content

They are commonly used in Python documentation:

def my_function(my_arg, my_other_arg):
    """A function just for me.

    :param my_arg: The first of my arguments.
    :param my_other_arg: The second of my arguments.

    :returns: A message (just for me, of course).
    """

Sphinx extends standard docutils behavior and intercepts field lists specified at the beginning of documents. Refer to Field Lists for more information.

ロール

A role or "custom interpreted text role" (ref) is an inline piece of explicit markup. It signifies that the enclosed text should be interpreted in a specific way. Sphinx uses this to provide semantic markup and cross-referencing of identifiers, as described in the appropriate section. The general syntax is :rolename:`content`.

Docutils supports the following roles:

Refer to ロール for roles added by Sphinx.

明示的なマークアップ

"明示的なマークアップ"(ref)というのは、reSTの中では特別な操作の必要な多くの構成要素のために使用されます。例えば脚注や、言語別のハイライトをする特別な段落、コメントや処理系(Sphinx)に対する指示などです。

明示的なマークアップのブロックは .. で始まる行から始まります。先頭の記号の後ろにはホワイトスペースが一つ入ります。そして、インデントが同じレベルになる次の段落までが1つのブロックとして扱われます。通常のパラグラフと、明示的なマークアップのブロックの間には一行以上のスペースを空ける必要があります。このような説明を聞くとわかりにくいと感じる人も多いと思いますが、実際に自分で書いてみると十分に直感的であるということがわかるでしょう。

ディレクティブ

A directive (ref) is a generic block of explicit markup. Along with roles, it is one of the extension mechanisms of reST, and Sphinx makes heavy use of it.

Docutilsは次のようなディレクティブを含みます:

  • 警告: attention, caution, danger, error, hint, important, note, tip, warning ,および、一般的な用途の admonition (ほとんどのテーマは、"note"と"warning"にだけスタイルを適用します)。

  • イメージ:

    • image (画像 も参照してください)

    • figure (キャプション、凡例を含むイメージ)

  • 追加の本体要素:

    • contents (ローカルな、つまり現在のファイル内だけの、目次)

    • container (カスタムのクラスを付加できるコンテナ。HTMLで外部の <div> を生成するのに便利)

    • rubric (ドキュメントのセクションと関係のない見出し)

    • topic, sidebar (特別に強調されたなボディ要素)

    • parsed-literal (インラインマークアップをサポートしたリテラルブロック)

    • epigraph (追加の属性行を付加できるブロック引用)

    • highlights, pull-quote (特有のクラス属性を持つブロック引用)

    • compound (複合パラグラフ)

  • 特別なテーブル:

    • table (タイトル付きのテーブル)

    • csv-table (カンマ区切りの値からテーブル生成)

    • list-table (リストのリストからテーブル生成)

  • 特別なディレクティブ:

    • raw (ターゲットの書式のマークアップを挿入)

    • include (他のファイルからreStructuredTextを取り込み) -- Sphinxでは、絶対パスが指定されると、ソースディレクトリからの相対パスが利用されます。

    • class (assign a class attribute to the next element)

      注釈

      When the default domain contains a class directive, this directive will be shadowed. Therefore, Sphinx re-exports it as rst-class.

  • HTML定義

    • meta (generation of HTML <meta> tags, see also HTML Metadata below)

    • title (ドキュメントのタイトルの上書き)

  • 疑似命令マークアップ:

    • default-role (デフォルトのロールをセット)

    • role (新しいロールの作成)

    これらのマークアップの影響範囲は、そのマークアップが書かれたファイルだけに限定されるため、Sphinxが提供する default_role を設定する方が良いでしょう。

警告

sectnum, header, footer の3つのディレクティブは使用 しない で下さい。

Directives added by Sphinx are described in ディレクティブ.

基本的に、ディレクティブは名前、引数、オプション、コンテンツなどで構成されています。これらの用語を覚えておいてください。これらは次の章でカスタムディレクティブの紹介を行う際に利用します。以下にサンプルを示します:

.. function:: foo(x)
              foo(y, z)
   :module: some.module.name

   Return a line of text input from the user.

function がディレクティブの名前です。ここでは二つの引数が与えられています。1行目の残りの部分と、2行目が引数です。そして1つのオプション module も同様に設定されています。見ての通り、オプションは引数のある行のすぐ次の行に書かれていています。そして、目印としてコロンが付いています。オプションは、ディレクティブのコンテンツと同じインデントの高さにします。

The directive content follows after a blank line and is indented relative to the directive start or if options are present, by the same amount as the options.

Be careful as the indent is not a fixed number of whitespace, e.g. three, but any number whitespace. This can be surprising when a fixed indent is used throughout the document and can make a difference for directives which are sensitive to whitespace. Compare:

.. code-block::
   :caption: A cool example

       The output of this line starts with four spaces.

.. code-block::

       The output of this line has no spaces at the beginning.

In the first code block, the indent for the content was fixated by the option line to three spaces, consequently the content starts with four spaces. In the latter the indent was fixed by the content itself to seven spaces, thus it does not start with a space.

画像

reSTは画像に関するディレクティブ(ref)もサポートしています。以下のように使用します。:

.. image:: gnu.png
   (options)

Sphinx内で使用する場合には、ソースファイルからの相対パスか、トップのソースディレクトリからの絶対パスでファイル名(ここでは gnu.png)を指定します。例えば、 sketch/spam.rst というソースファイルからは、 images/spam.png, ../images/spam.png, /images/spam.png というように書くことができます。

このディレクティブを使用すると、Sphinxはビルド時に、指定された画像ファイルを出力ディレクトリのサブディレクトリにコピーします。HTML出力の場合には、 _static といったディレクトリにコピーされます。

画像サイズのオプション(widthheight)は以下のように解釈されます。もし単位が無い、もしくは単位がピクセル(px)の場合には、与えられたサイズは出力するチャンネルがピクセルをサポートしているかどうかだけが考慮されます。他の単位(ポイントを表す pt など)はHTMLでもLaTeXでも使用されます(後者では 72bp=1in が成り立つTeXの単位となるように ptbp に置き換えます)。

Sphinxは標準のdocutilsを拡張していて、拡張子としてアスタリスク(*)を受け取れるようになっています:

.. image:: gnu.*

Sphinx then searches for all images matching the provided pattern and determines their type. Each builder then chooses the best image out of these candidates. For instance, if the file name gnu.* was given and two files gnu.pdf and gnu.png existed in the source tree, the LaTeX builder would choose the former, while the HTML builder would prefer the latter. Supported image types and choosing priority are defined at Builders.

画像ファイルのファイル名にはスペースを含んではいけないことに注意してください。

バージョン 0.4 で変更: ファイル名の末尾をアスタリスク(*)にできる機能が追加されました。

バージョン 0.6 で変更: イメージパスとして、ソースフォルダのルートからの絶対パスが指定できるようになりました。

バージョン 1.5 で変更: latexターゲットがピクセルをサポートするようになりました(デフォルトは 96px=1in です)。

脚注

脚注(ref)を作成するためには、脚注を書きたい場所で [#name]_ というマークアップを書きます。そして、脚注の本体をドキュメントの下の方の "脚注" のためのrubric見出しの中に書きます:

Lorem ipsum [#f1]_ dolor sit amet ... [#f2]_

.. rubric:: Footnotes

.. [#f1] Text of the first footnote.
.. [#f2] Text of the second footnote.

脚注の数値を明示的に指定([1]_)することもできますし、名前を指定しないで脚注の自動採番([#]_)をさせることも可能です。

引用

標準のreSTでも引用(ref)はサポートしていますが、Sphinx独自の追加の機能としては、引用が"グローバル"ということです。そのため、全ての引用はすべてのファイルから参照できます。以下のように使用します:

Lorem ipsum [Ref]_ dolor sit amet.

.. [Ref] Book or article reference, URL or whatever.

引用は、脚注と同じように使用できますが、ラベルは数字ではありませんし、 # でも始まりません。

置換

reSTは"置換"(ref)をサポートしています。これは、テキスト中の |名前| で指定された箇所に、テキストや、マークアップを挿入します。脚注と同じように明示的なマークアップブロックを使って定義します:

.. |name| replace:: replacement *text*

もしくはこのように書きます:

.. |caution| image:: warning.png
             :alt: Warning!

詳しくは reSTリファレンスの置換の説明 を参照してください。

If you want to use some substitutions for all documents, put them into rst_prolog or rst_epilog or put them into a separate file and include it into all documents you want to use them in, using the include directive. (Be sure to give the include file a file name extension differing from that of other source files, to avoid Sphinx finding it as a standalone document.)

Sphinxはデフォルトの置換をいくつか定義しています。詳しくは 置換 を参照してください。

コメント

上記の脚注のような適切な構造をしていない明示的マークアップのブロックはすべてコメント(ref)とみなされます:

.. This is a comment.

コメントがスタートした行からインデントすることによって、複数行コメントにできます:

..
   This whole indented block
   is a comment.

   Still in the comment.

HTML Metadata

The meta directive allows specifying the HTML metadata element of a Sphinx documentation page. For example, the directive:

.. meta::
   :description: The Sphinx documentation builder
   :keywords: Sphinx, documentation, builder

will generate the following HTML output:

<meta name="description" content="The Sphinx documentation builder">
<meta name="keywords" content="Sphinx, documentation, builder">

Also, Sphinx will add the keywords as specified in the meta directive to the search index. Thereby, the lang attribute of the meta element is considered. For example, the directive:

.. meta::
   :keywords: backup
   :keywords lang=en: pleasefindthiskey pleasefindthiskeytoo
   :keywords lang=de: bittediesenkeyfinden

adds the following words to the search indices of builds with different language configurations:

  • pleasefindthiskey, pleasefindthiskeytoo to English builds;

  • bittediesenkeyfinden to German builds;

  • backup to builds in all languages.

ソースエンコーディング

エムダッシュ(アルファベットのMと同じ幅を持つダッシュ)や、コピーライトの記号などの特殊記号をreSTに入れる場合にはユニコードの文字として直接入れるのが一番簡単な方法です。Sphinxはデフォルトでは、UTF-8であるとみなしてソースコードを読み込みます。 source_encoding の設定値を変更することで、このデフォルトのエンコーディングを変更できます。

分かっていること

reSTのドキュメントを書いていると、良く遭遇する問題がいくつかあります:

  • インラインマークアップの分離: 上記の説明でも触れていますが、インラインマークアップを付ける領域の前後はテキスト以外の文字(スペース、カッコなど)や、バックスラッシュ(日本語フォントだと円記号)でエスケープしたスペースでくくる必要があります。詳しくは、 the reference を参照してください。

  • インラインマークアップのネストはできない: *:func:`foo` 参照* といった書き方はできません。