"readline" --- GNU readline 인터페이스
**************************************

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

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

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

가용성: not Android, not iOS, not WASI.

이 모듈은 모바일 플랫폼이나 웹어셈블리 플랫폼에서 지원되지 않습니다.

참고:

  하부 Readline 라이브러리 API는 GNU readline 대신 "editline"
  ("libedit") 라이브러리로 구현될 수 있습니다. macOS에서 "readline" 모
  듈은 실행 시간에 사용 중인 라이브러리를 감지합니다."editline"의 구성
  파일은 GNU readline의 구성 파일과 다릅니다. 프로그래밍 방식으로 구성
  문자열을 로드하는 경우 어떤 라이브러리가 사용되고 있는지 "backend"를
  사용하여 확인할 수 있습니다.macOS에서 "editline"/"libedit" readline
  에뮬레이션을 사용하는 경우, 홈 디렉터리에 있는 초기화 파일의 이름은
  ".editrc"입니다. 예를 들어, "~/.editrc"의 다음 내용은 *vi* 키 바인딩
  과 TAB 완성을 켭니다:

     python:bind -v
     python:bind ^I rl_complete

  Also note that different libraries may use different history file
  formats. When switching the underlying library, existing history
  files may become unusable.

readline.backend

   The name of the underlying Readline library being used, either
   ""readline"" or ""editline"".

   Added in version 3.13.


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

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

readline.parse_and_bind(string)

   *string* 인자에 제공된 초기화 줄을 실행합니다. 하부 라이브러리에서
   "rl_parse_and_bind()"를 호출합니다.

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. It raises an auditing event "open" with the
   file name if given, and ""<readline_init_file>"" otherwise,
   regardless of which file the library resolves.

   버전 3.14에서 변경: The auditing event was added.


줄 버퍼
=======

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

readline.get_line_buffer()

   줄 버퍼의 현재 내용(하부 라이브러리의 "rl_line_buffer")을 반환합니
   다.

readline.insert_text(string)

   줄 버퍼의 커서 위치에 텍스트를 삽입합니다. 하부 라이브러리에서
   "rl_insert_text()"를 호출하지만, 반환 값은 무시합니다.

readline.redisplay()

   줄 버퍼의 현재 내용을 반영하도록 화면에 표시되는 내용을 변경합니다.
   하부 라이브러리에서 "rl_redisplay()"를 호출합니다.


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

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

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 and raises an auditing event "open" with
   the file name if given and ""~/.history"" otherwise.

   버전 3.14에서 변경: The auditing event was added.

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 and raises an auditing
   event "open" with the file name if given and ""~/.history""
   otherwise.

   버전 3.14에서 변경: The auditing event was added.

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. It raises an auditing event "open" with
   the file name if given and ""~/.history"" otherwise.

   Added in version 3.5.

   버전 3.14에서 변경: The auditing event was added.

readline.get_history_length()
readline.set_history_length(length)

   히스토리 파일에 저장하기 원하는 줄 수를 설정하거나 반환합니다.
   "write_history_file()" 함수는 이 값을 사용하여, 하부 라이브러리에서
   "history_truncate_file()"을 호출하여 히스토리 파일을 자릅니다. 음수
   값은 제한 없는 히스토리 파일 크기를 의미합니다.


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

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

readline.clear_history()

   현재 히스토리를 지웁니다. 하부 라이브러리에서 "clear_history()"를
   호출합니다. 파이썬 함수는 파이썬이 이를 지원하는 라이브러리 버전으
   로 컴파일된 경우에만 존재합니다.

readline.get_current_history_length()

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

readline.get_history_item(index)

   *index*에 있는 히스토리 항목의 현재 내용을 반환합니다. 항목 인덱스
   는 1부터 시작합니다. 하부 라이브러리에서 "history_get()"을 호출합니
   다.

readline.remove_history_item(pos)

   히스토리에서 위치(pos)로 지정된 히스토리 항목을 제거합니다. 위치는
   0부터 시작합니다. 하부 라이브러리에서 "remove_history()"를 호출합니
   다.

readline.replace_history_item(pos, line)

   위치(pos)로 지정된 히스토리 항목을 *line*으로 교체합니다. 위치는 0
   부터 시작합니다. 하부 라이브러리에서 "replace_history_entry()"를 호
   출합니다.

readline.add_history(line)

   마지막 줄이 입력된 것처럼 히스토리 버퍼에 *line*을 추가합니다. 하부
   라이브러리에서 "add_history()"를 호출합니다.

readline.set_auto_history(enabled)

   readline을 통해 입력을 읽을 때 "add_history()"에 대한 자동 호출을
   활성화 또는 비활성화합니다. *enabled* 인자는 참일 때 자동 히스토리
   를 활성화하고, 거짓일 때 자동 기록을 비활성화하는 불리언 값이어야
   합니다.

   Added in version 3.6.

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


시동 훅
=======

readline.set_startup_hook([function])

   하부 라이브러리의 "rl_startup_hook" 콜백에 의해 호출되는 함수를 설
   정하거나 제거합니다. *function*이 지정되면 새 훅(hook) 함수로 사용
   됩니다; 생략되거나 "None"이면, 이미 설치된 함수가 제거됩니다. 이 훅
   은 readline이 첫 번째 프롬프트를 인쇄하기 직전에 인자 없이 호출됩니
   다.

readline.set_pre_input_hook([function])

   하부 라이브러리의 "rl_pre_input_hook" 콜백에 의해 호출되는 함수를
   설정하거나 제거합니다. *function*이 지정되면, 새 훅 함수로 사용됩니
   다; 생략되거나 "None"이면, 이미 설치된 함수가 제거됩니다. 이 훅은
   첫 번째 프롬프트가 인쇄된 후 readline이 입력 문자를 읽기 시작하기
   직전에 인자 없이 호출됩니다. 이 함수는 파이썬이 이를 지원하는 라이
   브러리 버전으로 컴파일된 경우에만 존재합니다.


완성
====

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

readline.set_completer([function])

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

   설치된 완성 함수는 하부 라이브러리의 "rl_completion_matches()"로 전
   달된 *entry_func* 콜백에 의해 호출됩니다. *text* 문자열은 하부 라이
   브러리의 "rl_attempted_completion_function" 콜백의 첫 번째 매개 변
   수로부터 옵니다.

readline.get_completer()

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

readline.get_completion_type()

   시도 중인 완성 유형을 가져옵니다. 하부 라이브러리의
   "rl_completion_type" 변수를 정수로 반환합니다.

readline.get_begidx()
readline.get_endidx()

   완성 범위(completion scope)의 시작이나 끝 인덱스를 가져옵니다. 이
   인덱스는 하부 라이브러리의 "rl_attempted_completion_function" 콜백
   에 전달된 *start*와 *end* 인자입니다. 같은 입력 편집 시나리오에서
   하부 C readline 구현에 따라 값이 다를 수 있습니다. 예: libedit는
   libreadline과 다르게 동작하는 것으로 알려져 있습니다.

readline.set_completer_delims(string)
readline.get_completer_delims()

   완성을 위한 단어 구분자를 설정하거나 가져옵니다. 이것들은 완성을 위
   해 고려할 단어의 시작(완성 범위)을 결정합니다. 이 함수는 하부 라이
   브러리의 "rl_completer_word_break_characters" 변수를 액세스합니다.

readline.set_completion_display_matches_hook([function])

   완성 표시 함수를 설정하거나 제거합니다. *function*이 지정되면, 새로
   운 완성 표시 함수로 사용됩니다; 생략하거나 "None"이면, 이미 설치된
   완성 표시 함수가 제거됩니다. 하부 라이브러리에서
   "rl_completion_display_matches_hook" 콜백을 설정하거나 지웁니다. 완
   성 표시 함수는 일치를 표시해야 할 때마다 한 번
   "function(substitution, [matches], longest_match_length)"로 호출됩
   니다.


예제
====

다음 예는 "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)
       # 기본 히스토리 길이는 -1(무한)이며, 제약 없이 커질 수 있습니다
       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)
