16.8. "readline" --- GNU readline のインタフェース
**************************************************

"readline" モジュールでは、補完や Python インタプリタからの履歴ファイ
ルの読み書きを容易にするための多くの関数を定義しています。 このモジュ
ールは直接、または "rlcompleter" モジュールを介して使うことができます
。 "rlcompleter" モジュールは対話的プロンプトで Python 識別子の補完を
サポートするものです。 このモジュールを使って設定した内容は、インタプ
リタの対話プロンプトと、組み込み関数の "raw_input()" および "input()"
"input()" が提示するプロンプトの両方の挙動に影響します。

注釈: 下層の Readline ライブラリー API は GNU readline ではなく
  "libedit" ライブラリーで実装される可能性があります。 MacOS X では
  "readline" モジュールはどのライブラリーが使われているかを実行時に検
  出します。 "libedit" の設定ファイルは GNU readline のものとは異なり
  ます。もし設 定文字列をプログラムからロードしているなら、 GNU
  readline と libedit を区別するために "libedit" という文字列が
  "readline.__doc__" に含ま れているかどうかチェックしてください。

readline のキーバインディングは初期化ファイルで設定できます。 このファ
イルは、たいていはホームディレクトリに ".inputrc" という名前で置いてあ
ります。 GNU Readline マニュアルの  Readline Init File を参照して、そ
のファイルの形式や可能な構成、 Readline ライブラリ全体の機能を知ってく
ださい。


16.8.1. 初期化ファイル
======================

以下の関数は初期化ファイルならびにユーザ設定関連のものです:

readline.parse_and_bind(string)

   *string* 引数で渡された最初の行を実行します。これにより下層のライブ
   ラリーの "rl_parse_and_bind()" が呼ばれます。

readline.read_init_file([filename])

   readline 初期化ファイルを実行します。デフォルトのファイル名は最後に
   使用されたファイル名です。これにより下層のライブラリーの
   "rl_read_init_file()" が呼ばれます。


16.8.2. 行バッファ
==================

以下の関数は行バッファを操作します:

readline.get_line_buffer()

   行バッファ  (下層のライブラリーの "rl_line_buffer") の現在の内容を
   返します。

readline.insert_text(string)

   テキストをカーサー位置の行バッファに挿入します。これにより下層のラ
   イブラリーの "rl_insert_text()" が呼ばれますが、戻り値は無視されま
   す。

readline.redisplay()

   スクリーンの表示を変更して行バッファの現在の内容を反映させます。こ
   れにより下層のライブラリーの "rl_redisplay()" が呼ばれます。


16.8.3. 履歴ファイル
====================

以下の関数は履歴ファイルを操作します:

readline.read_history_file([filename])

   readline 履歴ファイルを読み込み、履歴リストに追加します。デフォルト
   のファイル名は "~/.history" です。これにより下層のライブラリーの
   "read_history()" が呼ばれます。

readline.write_history_file([filename])

   履歴リストを readline 履歴ファイルに保存します。既存のファイルは上
   書きされます。デフォルトのファイル名は "~/.history" です。これによ
   り下層のライブラリーの "write_history()" が呼ばれます。

readline.get_history_length()
readline.set_history_length(length)

   Set or return the desired number of lines to save in the history
   file. The "write_history_file()" function uses this value to
   truncate the history file, by calling "history_truncate_file()" in
   the underlying library.  Negative values imply unlimited history
   file size.


16.8.4. 履歴リスト
==================

以下の関数はグローバルな履歴リストを操作します:

readline.clear_history()

   現在の履歴をクリアします。これにより下層のライブラリーの
   "clear_history()" が呼ばれます。Python がこの機能をサポートするライ
   ブラリーのバージョンでコンパイルされたときのみ、この関数は存在しま
   す。

   バージョン 2.4 で追加.

readline.get_current_history_length()

   履歴に現在ある項目の数を返します。 ("get_history_length()" は履歴フ
   ァイルに書かれる最大行数を返します。)

   バージョン 2.3 で追加.

readline.get_history_item(index)

   現在の履歴の *index* 番目の項目を返します。添字は1から始まります。
   これにより下層のライブラリーの "history_get()" が呼ばれます。

   バージョン 2.3 で追加.

readline.remove_history_item(pos)

   履歴から指定された位置の項目を削除します。添字は0から始まります。こ
   れにより下層のライブラリーの "remove_history()" が呼ばれます。

   バージョン 2.4 で追加.

readline.replace_history_item(pos, line)

   指定された位置の項目を *line* で置き換えます。添字は0から始まります
   。これにより下層のライブラリーの "replace_history_entry()" が呼ばれ
   ます。

   バージョン 2.4 で追加.

readline.add_history(line)

   最後に入力したかのように、 *line* を履歴バッファに追加します。これ
   により下層のライブラリーの "add_history()" が呼ばれます。


16.8.5. 開始フック
==================

   バージョン 2.3 で追加.

readline.set_startup_hook([function])

   Set or remove the function invoked by the "rl_startup_hook"
   callback of the underlying library.  If *function* is specified, it
   will be used as the new hook function; if omitted or "None", any
   function already installed is removed.  The hook is called with no
   arguments just before readline prints the first prompt.

readline.set_pre_input_hook([function])

   Set or remove the function invoked by the "rl_pre_input_hook"
   callback of the underlying library.  If *function* is specified, it
   will be used as the new hook function; if omitted or "None", any
   function already installed is removed.  The hook is called with no
   arguments after the first prompt has been printed and just before
   readline starts reading input characters.  This function only
   exists if Python was compiled for a version of the library that
   supports it.


16.8.6. 補完
============

The following functions relate to implementing a custom word
completion function.  This is typically operated by the Tab key, and
can suggest and automatically complete a word being typed.  By
default, Readline is set up to be used by "rlcompleter" to complete
Python identifiers for the interactive interpreter.  If the "readline"
module is to be used with a custom completer, a different set of word
delimiters should be set.

readline.set_completer([function])

   completer 関数を設定または削除します。*function* が指定された場合、
   新たな completer 関数として用いられます;  省略された場合や "None"
   の場合、現在インストールされている completer 関数は削除されます。
   completer 関数は "function(text, state)" の形式で、関数が文字列でな
   い値を返すまで *state* を "0", "1", "2", ..., にして呼び出します。
   この関数は *text* から始まる補完結果として次に来そうなものを返さな
   ければなりません。

   The installed completer function is invoked by the *entry_func*
   callback passed to "rl_completion_matches()" in the underlying
   library. The *text* string comes from the first parameter to the
   "rl_attempted_completion_function" callback of the underlying
   library.

readline.get_completer()

   completer 関数を取得します。completer 関数が設定されていなければ
   "None" を返します。

   バージョン 2.3 で追加.

readline.get_completion_type()

   Get the type of completion being attempted.  This returns the
   "rl_completion_type" variable in the underlying library as an
   integer.

   バージョン 2.6 で追加.

readline.get_begidx()
readline.get_endidx()

   Get the beginning or ending index of the completion scope. These
   indexes are the *start* and *end* arguments passed to the
   "rl_attempted_completion_function" callback of the underlying
   library.

readline.set_completer_delims(string)
readline.get_completer_delims()

   Set or get the word delimiters for completion.  These determine the
   start of the word to be considered for completion (the completion
   scope). These functions access the
   "rl_completer_word_break_characters" variable in the underlying
   library.

readline.set_completion_display_matches_hook([function])

   Set or remove the completion display function.  If *function* is
   specified, it will be used as the new completion display function;
   if omitted or "None", any completion display function already
   installed is removed.  This sets or clears the
   "rl_completion_display_matches_hook" callback in the underlying
   library.  The completion display function is called as
   "function(substitution, [matches], longest_match_length)" once each
   time matches need to be displayed.

   バージョン 2.6 で追加.


16.8.7. 例
==========

以下の例では、ユーザのホームディレクトリにある ".pyhist" という名前の
ヒストリファイルを自動的に読み書きするために、 "readline" モジュールに
よるヒストリの読み書き関数をどのように使うかを例示しています。以下のソ
ースコードは通常、対話セッションの中で "PYTHONSTARTUP" ファイルから読
み込まれ自動的に実行されることになります。

   import os
   import readline
   histfile = os.path.join(os.path.expanduser("~"), ".pyhist")
   try:
       readline.read_history_file(histfile)
       # default history len is -1 (infinite), which may grow unruly
       readline.set_history_length(1000)
   except IOError:
       pass
   import atexit
   atexit.register(readline.write_history_file, histfile)
   del os, histfile

次の例では "code.InteractiveConsole" クラスを拡張し、履歴の保存・復旧
をサポートします。

   import code
   import readline
   import atexit
   import os

   class HistoryConsole(code.InteractiveConsole):
       def __init__(self, locals=None, filename="<console>",
                    histfile=os.path.expanduser("~/.console-history")):
           code.InteractiveConsole.__init__(self, locals, filename)
           self.init_history(histfile)

       def init_history(self, histfile):
           readline.parse_and_bind("tab: complete")
           if hasattr(readline, "read_history_file"):
               try:
                   readline.read_history_file(histfile)
               except IOError:
                   pass
               atexit.register(self.save_history, histfile)

       def save_history(self, histfile):
           readline.set_history_length(1000)
           readline.write_history_file(histfile)
