"readline" --- GNU readline interface
*************************************

======================================================================

"readline" 모듈은 파이썬 인터프리터에서 완성(completion)과 히스토리 파
일의 읽기/쓰기를 용이하게 하는 여러 함수를 정의합니다. 이 모듈은 직접
사용하거나, 대화식 프롬프트에서 파이썬 식별자 완성을 지원하는
"rlcompleter" 모듈을 통해 사용할 수 있습니다. 이 모듈을 사용하여 설정
한 내용은 인터프리터의 대화식 프롬프트와 내장 "input()" 함수가 제공하
는 프롬프트의 동작에 영향을 줍니다.

Readline 키 바인딩은 초기화 파일을 통해 구성할 수 있습니다, 일반적으로
홈 디렉터리의 ".inputrc". 이 파일의 형식과 허용되는 구성 및 Readline
라이브러리의 기능에 대한 일반적인 정보는 GNU Readline 매뉴얼의
Readline Init File을 참조하십시오.

참고:

  The underlying Readline library API may be implemented by the
  "libedit" library instead of GNU readline. On macOS the "readline"
  module detects which library is being used at run time.The
  configuration file for "libedit" is different from that of GNU
  readline. If you programmatically load configuration strings you can
  check for the text "libedit" in "readline.__doc__" to differentiate
  between GNU readline and libedit.If you use *editline*/"libedit"
  readline emulation on macOS, the initialization file located in your
  home directory is named ".editrc". For example, the following
  content in "~/.editrc" will turn ON *vi* keybindings and TAB
  completion:

     python:bind -v
     python:bind ^I rl_complete


초기화 파일
===========

다음 함수는 초기화 파일 및 사용자 구성과 관련이 있습니다:

readline.parse_and_bind(string)

   Execute the init line provided in the *string* argument. This calls
   "rl_parse_and_bind()" in the underlying library.

readline.read_init_file([filename])

   Execute a readline initialization file. The default filename is the
   last filename used. This calls "rl_read_init_file()" in the
   underlying library.


줄 버퍼
=======

다음 함수는 라인 버퍼에 대해 작용합니다:

readline.get_line_buffer()

   Return the current contents of the line buffer ("rl_line_buffer" in
   the underlying library).

readline.insert_text(string)

   Insert text into the line buffer at the cursor position.  This
   calls "rl_insert_text()" in the underlying library, but ignores the
   return value.

readline.redisplay()

   Change what's displayed on the screen to reflect the current
   contents of the line buffer.  This calls "rl_redisplay()" in the
   underlying library.


히스토리 파일
=============

다음 함수는 히스토리 파일에 대해 작용합니다:

readline.read_history_file([filename])

   Load a readline history file, and append it to the history list.
   The default filename is "~/.history".  This calls "read_history()"
   in the underlying library.

readline.write_history_file([filename])

   Save the history list to a readline history file, overwriting any
   existing file.  The default filename is "~/.history".  This calls
   "write_history()" in the underlying library.

readline.append_history_file(nelements[, filename])

   Append the last *nelements* items of history to a file.  The
   default filename is "~/.history".  The file must already exist.
   This calls "append_history()" in the underlying library.  This
   function only exists if Python was compiled for a version of the
   library that supports it.

   버전 3.5에 추가.

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.


히스토리 목록
=============

다음 함수는 전역 히스토리 목록에 대해 작용합니다:

readline.clear_history()

   Clear the current history.  This calls "clear_history()" in the
   underlying library.  The Python function only exists if Python was
   compiled for a version of the library that supports it.

readline.get_current_history_length()

   현재 히스토리에 있는 항목 수를 반환합니다. (이것은 히스토리 파일에
   기록될 최대 줄 수를 반환하는 "get_history_length()"와 다릅니다.)

readline.get_history_item(index)

   Return the current contents of history item at *index*.  The item
   index is one-based.  This calls "history_get()" in the underlying
   library.

readline.remove_history_item(pos)

   Remove history item specified by its position from the history. The
   position is zero-based.  This calls "remove_history()" in the
   underlying library.

readline.replace_history_item(pos, line)

   Replace history item specified by its position with *line*. The
   position is zero-based.  This calls "replace_history_entry()" in
   the underlying library.

readline.add_history(line)

   Append *line* to the history buffer, as if it was the last line
   typed. This calls "add_history()" in the underlying library.

readline.set_auto_history(enabled)

   Enable or disable automatic calls to "add_history()" when reading
   input via readline.  The *enabled* argument should be a Boolean
   value that when true, enables auto history, and that when false,
   disables auto history.

   버전 3.6에 추가.

   **CPython 구현 상세:** Auto history is enabled by default, and
   changes to this do not persist across multiple sessions.


시동 훅
=======

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.


완성
====

다음 함수는 사용자 정의 단어 완성 기능 구현과 관련이 있습니다. 이것은
일반적으로 Tab 키로 작동하며, 입력되는 단어를 제안하고 자동으로 완성할
수 있습니다. 기본적으로, Readline은 대화식 인터프리터를 위해 파이썬 식
별자를 완성하는 "rlcompleter"에서 사용하도록 설정되어 있습니다.
"readline" 모듈을 사용자 정의 완성기와 함께 사용하려면, 다른 단어 구분
자 집합을 설정해야 합니다.

readline.set_completer([function])

   완성 함수를 설정하거나 제거합니다. *function*이 지정되면 새 완성 함
   수로 사용됩니다; 생략하거나 "None"이면, 이미 설치된 완성 함수가 제
   거됩니다. 완성 함수는 문자열이 아닌 값을 반환할 때까지 "0", "1",
   "2" 등의 *state*에 대해 "function(text, state)"로 호출됩니다.
   *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()

   완성 함수나, 완성 함수가 설정되지 않았으면 "None"을 얻습니다.

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.

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.  The values may be different in the same input editing
   scenario based on the underlying C readline implementation. Ex:
   libedit is known to behave differently than libreadline.

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.


예제
====

다음 예는 "readline" 모듈의 히스토리 읽기와 쓰기 함수를 사용하여 사용
자의 홈 디렉터리에서 ".python_history"라는 이름의 히스토리 파일을 자동
으로 로드하고 저장하는 방법을 보여줍니다. 아래 코드는 일반적으로 사용
자의 "PYTHONSTARTUP" 파일에서 대화식 세션 중에 자동으로 실행됩니다.

   import atexit
   import os
   import readline

   histfile = os.path.join(os.path.expanduser("~"), ".python_history")
   try:
       readline.read_history_file(histfile)
       # default history len is -1 (infinite), which may grow unruly
       readline.set_history_length(1000)
   except FileNotFoundError:
       pass

   atexit.register(readline.write_history_file, histfile)

이 코드는 실제로 파이썬이 대화형 모드로 실행될 때 자동으로 실행됩니다
(Readline 구성을 참조하십시오).

다음 예는 같은 목표를 달성하지만 새 히스토리를 덧붙이기만 해서 동시적
인(concurrent) 대화형 세션을 지원합니다.

   import atexit
   import os
   import readline
   histfile = os.path.join(os.path.expanduser("~"), ".python_history")

   try:
       readline.read_history_file(histfile)
       h_len = readline.get_current_history_length()
   except FileNotFoundError:
       open(histfile, 'wb').close()
       h_len = 0

   def save(prev_h_len, histfile):
       new_h_len = readline.get_current_history_length()
       readline.set_history_length(1000)
       readline.append_history_file(new_h_len - prev_h_len, histfile)
   atexit.register(save, h_len, histfile)

다음 예는 히스토리 저장/복원을 지원하도록 "code.InteractiveConsole" 클
래스를 확장합니다.

   import atexit
   import code
   import os
   import readline

   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 FileNotFoundError:
                   pass
               atexit.register(self.save_history, histfile)

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