(1日目) Sphinx のインストール〜使い方 (Debian 編)

こんばんは、@tk0miya です。
恐れていた 待ちに待った Sphinx & blockdiag アドベントカレンダーの初日です。
12月1日になったので早速スタートします。
なにせ今夜は blockdiag リリースパーティーで書く時間がとれそうにないので…

最初に紹介するのは Sphinx のインストール方法と簡単なドキュメントの作り方についてです。
インストール環境は、みんな大好き Debian/GNU Linux (sqeeze) です。
おそらく Ubuntu でもこのやり方でインストールできると思います。

Sphinx とは

まず Sphinx についてざっとおさらいしましょう。

Sphinx とは Georg Brandl さんが開発したドキュメントツールです。
reST (restructured text) と呼ばれるテキストから HTML や PDF、ePub など多様な形式に変換することができます。

  • メリット
    • 自分の好みのエディタで編集することができる
    • テキスト形式であるためバージョン管理ツールと相性がいい (差分の把握、マージの容易性)
    • シンプルな形式であるため読みやすく書きやすい
  • デメリット
    • 図/画像を作成するのは別ツールが必要
    • 変換しないと変換結果を見ることができない (見ながら編集できない)
    • reST はやや取っつきづらい


僕の印象ですが、Sphinx は万人にとって使いやすいツールではありませんが、
UNIX 的なツールに慣れている人は好んで使うのではないかと思います。

オフィススイートを使って編集するのと比べるとかなり気楽に書くことができます。
Sphinx-users.jp で付けた「ドキュメントを作りたくなってしまう魔法のツール」という呼び名の通り、
これまで面倒でなかなかやる気のでなかったドキュメント作成作業が楽しくなる可能性を持っていると思います。

Sphinx をインストールする

では早速 Sphinx をインストールしてみましょう。
Debian では Sphinxpython-sphinx という名前でパッケージングされていますが、
squeeze に収録されている Sphinx は 0.6.6 とかなり古いものになっています。*1 *2
そのため、ここでは easy_install コマンドを使って最新版をインストールする方法を紹介します。
easy_install コマンドは python-setuptools パッケージに含まれているので、こちらは apt でインストールします。

$ sudo apt-get install make python-setuptools
$ sudo easy_install sphinx

上記のコマンドを実行すると Sphinx パッケージに含まれるコマンドがインストールされているはずです。

$ ls -l /usr/local/bin/sphinx-*

Sphinx でドキュメントを書いてみよう

ここまでで Sphinx のインストールが完了したので、ドキュメントを書いてみましょう。

Sphinx ではドキュメントをプロジェクトという単位で管理しているため、
ドキュメントを書き始める前に sphinx-quickstart コマンドを使ってプロジェクトを作成します。

$ mkdir testdoc
$ cd testdoc
$ sphinx-quickstart
Welcome to the Sphinx 1.1.2 quickstart utility.

Please enter values for the following settings (just press Enter to
accept a default value, if one is given in brackets).

Enter the root path for documentation.
> Root path for the documentation [.]:

You have two options for placing the build directory for Sphinx output.
Either, you use a directory "_build" within the root path, or you separate
"source" and "build" directories within the root path.
> Separate source and build directories (y/N) [n]:

Inside the root directory, two more directories will be created; "_templates"
for custom HTML templates and "_static" for custom stylesheets and other static
files. You can enter another prefix (such as ".") to replace the underscore.
> Name prefix for templates and static dir [_]:

The project name will occur in several places in the built documentation.
<span class="deco" style="color:#FF0000;">> Project name: test document</span>
<span class="deco" style="color:#FF0000;">> Author name(s): Takeshi Komiya</span>

Sphinx has the notion of a "version" and a "release" for the
software. Each version can have multiple releases. For example, for
Python the version is something like 2.5 or 3.0, while the release is
something like 2.5.1 or 3.0a1.  If you don't need this dual structure,
just set both to the same value.
<span class="deco" style="color:#FF0000;">> Project version: 1.0</span>
> Project release [1.0]:

The file name suffix for source files. Commonly, this is either ".txt"
or ".rst".  Only files with this suffix are considered documents.
> Source file suffix [.rst]:

One document is special in that it is considered the top node of the
"contents tree", that is, it is the root of the hierarchical structure
of the documents. Normally, this is "index", but if your "index"
document is a custom template, you can also set this to another filename.
> Name of your master document (without suffix) [index]:

Sphinx can also add configuration for epub output:
<span class="deco" style="color:#FF9900;">> Do you want to use the epub builder (y/N) [n]: y</span>

Please indicate if you want to use one of the following Sphinx extensions:
> autodoc: automatically insert docstrings from modules (y/N) [n]:
> doctest: automatically test code snippets in doctest blocks (y/N) [n]:
> intersphinx: link between Sphinx documentation of different projects (y/N) [n]:
<span class="deco" style="color:#FF9900;">> todo: write "todo" entries that can be shown or hidden on build (y/N) [n]: y</span>
> coverage: checks for documentation coverage (y/N) [n]:
> pngmath: include math, rendered as PNG images (y/N) [n]:
> mathjax: include math, rendered in the browser by MathJax (y/N) [n]:
> ifconfig: conditional inclusion of content based on config values (y/N) [n]:
> viewcode: include links to the source code of documented Python objects (y/N) [n]:

A Makefile and a Windows command file can be generated for you so that you
only have to run e.g. `make html' instead of invoking sphinx-build
directly.
> Create Makefile? (Y/n) [y]:
> Create Windows command file? (Y/n) [y]:

Creating file ./conf.py.
Creating file ./index.rst.
Creating file ./Makefile.
Creating file ./make.bat.

Finished: An initial directory structure has been created.

You should now populate your master file ./index.rst and create other documentation
source files. Use the Makefile to build the docs, like so:
   make builder
where "builder" is one of the supported builders, e.g. html, latex or linkcheck.

sphinx-quickstart コマンドはウィザード形式のプログラムになっており、
設問に答えていくとプロジェクトのひな形が生成されます。
ほとんどの項目は Enter キーを押してスキップすることができますが、
赤字にした 3つの設問(タイトル、著者、バージョン)は必須項目なので明示的に入力が必要です。

個人的なおすすめとしては、オレンジ色にした 2箇所(epub builder, todoモジュール)は Yes に設定するとよいでしょう。
(他の項目は使う場面になったことがないので使っていません)

sphinx-quickstart コマンドの実行が終わると以下のファイルが生成されます。

$ ls
Makefile  _build/  _static/  _templates/  conf.py  index.rst  make.bat

生成されたファイルはそれぞれ以下の役割を持っています。

  • Makefile, make.bat
    • ドキュメントをビルドするときの Makefile です。変更の必要はありません。
  • _build/
    • ビルドされたドキュメントが格納されるディレクトリです。
  • _static/
    • ドキュメントで利用する画像などのファイルを格納するディレクトリです。今回は利用しません。
  • _templates/
    • 自分でテンプレートをカスタマイズするときに利用するディレクトリです。今回は利用しません。
  • conf.py
    • Sphinx の設定ファイルです。たまにいじります。
  • index.rst
    • Sphinx の文書は .rst という拡張子がついています。

この index.rst はこのドキュメントのトップページに当たるファイルです。
新たに .rst ファイルを追加しながら、これらのファイルを編集していきます。

では早速 index.rst に何か書いてみましょう。
vi や emacs などテキストエディタで index.rst を開いてテキストを打ち込んでみてください。
まずはマニュアルや議事録など、簡単なものを題材にドキュメントを書いてみるとよいと思います。

見出しや強調表示など、いくつかのスタイルを適用する場合は
Sphinx-users.jp の ドキュメントのパワーアップリファレンス を参考にするとよいでしょう。

.rst ファイルを更新したあとは、閲覧用のフォーマットに変換してみましょう。
ここでは HTML に変換してみます。
コマンドラインから以下のコマンドを実行してみましょう。

$ make html
sphinx-build -b html -d _build/doctrees   . _build/html
Making output directory...
Running Sphinx v1.1.2
loading pickled environment... not yet created
building [html]: targets for 1 source files that are out of date
updating environment: 1 added, 0 changed, 0 removed
reading sources... [100%] index

looking for now-outdated files... none found
pickling environment... done
checking consistency... done
preparing documents... done
writing output... [100%] index

writing additional files... genindex search
copying static files... done
dumping search index... done
dumping object inventory... done
build succeeded.

Build finished. The HTML pages are in _build/html.

変換された HTML ファイルは _build/html 以下に生成されます。

他に変換できるフォーマットについては引数なしの make コマンドで確認することができます。
他にも ePub や PDF 出力などもよく使われます。
*3

ここまでが Sphinx の基本的な使い方です。
より詳しい内容が知りたくなった方は Sphinx-users.jp のページを見てみてください。

また、使い方が分からない場合や困ったこと、知りたいことがある場合は
メーリングリストTwitter#sphinxjp タグで質問するとよいでしょう。

*1:sid では 1.0.8 と比較的あたらしいバージョンがパッケージングされています。sid をお使いの方や pinning に慣れている方は apt 経由がおすすめです。

*2:追記:: [http://packages.debian.org/squeeze-backports/python-sphinx:title=backports.debian.org] にはsqueeze 用の 1.0.8 がアップロードされているので、こちらを使うとよいかもしれません。(thanks to @henrich)

*3:PDF 出力については後日まとめる予定です。