1:mod:`readline` --- GNU readline interface 2========================================== 3 4.. module:: readline 5 :platform: Unix 6 :synopsis: GNU readline support for Python. 7.. sectionauthor:: Skip Montanaro <skip@pobox.com> 8 9 10The :mod:`readline` module defines a number of functions to facilitate 11completion and reading/writing of history files from the Python interpreter. 12This module can be used directly, or via the :mod:`rlcompleter` module, which 13supports completion of Python identifiers at the interactive prompt. Settings 14made using this module affect the behaviour of both the interpreter's 15interactive prompt and the prompts offered by the :func:`raw_input` and 16:func:`input` built-in functions. 17 18.. note:: 19 20 The underlying Readline library API may be implemented by 21 the ``libedit`` library instead of GNU readline. 22 On MacOS X the :mod:`readline` module detects which library is being used 23 at run time. 24 25 The configuration file for ``libedit`` is different from that 26 of GNU readline. If you programmatically load configuration strings 27 you can check for the text "libedit" in :const:`readline.__doc__` 28 to differentiate between GNU readline and libedit. 29 30Readline keybindings may be configured via an initialization file, typically 31``.inputrc`` in your home directory. See `Readline Init File 32<https://cnswww.cns.cwru.edu/php/chet/readline/rluserman.html#SEC9>`_ 33in the GNU Readline manual for information about the format and 34allowable constructs of that file, and the capabilities of the 35Readline library in general. 36 37 38Init file 39--------- 40 41The following functions relate to the init file and user configuration: 42 43 44.. function:: parse_and_bind(string) 45 46 Execute the init line provided in the *string* argument. This calls 47 :c:func:`rl_parse_and_bind` in the underlying library. 48 49 50.. function:: read_init_file([filename]) 51 52 Execute a readline initialization file. The default filename is the last filename 53 used. This calls :c:func:`rl_read_init_file` in the underlying library. 54 55 56Line buffer 57----------- 58 59The following functions operate on the line buffer: 60 61 62.. function:: get_line_buffer() 63 64 Return the current contents of the line buffer (:c:data:`rl_line_buffer` 65 in the underlying library). 66 67 68.. function:: insert_text(string) 69 70 Insert text into the line buffer at the cursor position. This calls 71 :c:func:`rl_insert_text` in the underlying library, but ignores 72 the return value. 73 74 75.. function:: redisplay() 76 77 Change what's displayed on the screen to reflect the current contents of the 78 line buffer. This calls :c:func:`rl_redisplay` in the underlying library. 79 80 81History file 82------------ 83 84The following functions operate on a history file: 85 86 87.. function:: read_history_file([filename]) 88 89 Load a readline history file, and append it to the history list. 90 The default filename is :file:`~/.history`. This calls 91 :c:func:`read_history` in the underlying library. 92 93 94.. function:: write_history_file([filename]) 95 96 Save the history list to a readline history file, overwriting any 97 existing file. The default filename is :file:`~/.history`. This calls 98 :c:func:`write_history` in the underlying library. 99 100 101.. function:: get_history_length() 102 set_history_length(length) 103 104 Set or return the desired number of lines to save in the history file. 105 The :func:`write_history_file` function uses this value to truncate 106 the history file, by calling :c:func:`history_truncate_file` in 107 the underlying library. Negative values imply 108 unlimited history file size. 109 110 111History list 112------------ 113 114The following functions operate on a global history list: 115 116 117.. function:: clear_history() 118 119 Clear the current history. This calls :c:func:`clear_history` in the 120 underlying library. The Python function only exists if Python was 121 compiled for a version of the library that supports it. 122 123 .. versionadded:: 2.4 124 125 126.. function:: get_current_history_length() 127 128 Return the number of items currently in the history. (This is different from 129 :func:`get_history_length`, which returns the maximum number of lines that will 130 be written to a history file.) 131 132 .. versionadded:: 2.3 133 134 135.. function:: get_history_item(index) 136 137 Return the current contents of history item at *index*. The item index 138 is one-based. This calls :c:func:`history_get` in the underlying library. 139 140 .. versionadded:: 2.3 141 142 143.. function:: remove_history_item(pos) 144 145 Remove history item specified by its position from the history. 146 The position is zero-based. This calls :c:func:`remove_history` in 147 the underlying library. 148 149 .. versionadded:: 2.4 150 151 152.. function:: replace_history_item(pos, line) 153 154 Replace history item specified by its position with *line*. 155 The position is zero-based. This calls :c:func:`replace_history_entry` 156 in the underlying library. 157 158 .. versionadded:: 2.4 159 160 161.. function:: add_history(line) 162 163 Append *line* to the history buffer, as if it was the last line typed. 164 This calls :c:func:`add_history` in the underlying library. 165 166 167Startup hooks 168------------- 169 170 .. versionadded:: 2.3 171 172 173.. function:: set_startup_hook([function]) 174 175 Set or remove the function invoked by the :c:data:`rl_startup_hook` 176 callback of the underlying library. If *function* is specified, it will 177 be used as the new hook function; if omitted or ``None``, any function 178 already installed is removed. The hook is called with no 179 arguments just before readline prints the first prompt. 180 181 182.. function:: set_pre_input_hook([function]) 183 184 Set or remove the function invoked by the :c:data:`rl_pre_input_hook` 185 callback of the underlying library. If *function* is specified, it will 186 be used as the new hook function; if omitted or ``None``, any 187 function already installed is removed. The hook is called 188 with no arguments after the first prompt has been printed and just before 189 readline starts reading input characters. This function only exists 190 if Python was compiled for a version of the library that supports it. 191 192 193Completion 194---------- 195 196The following functions relate to implementing a custom word completion 197function. This is typically operated by the Tab key, and can suggest and 198automatically complete a word being typed. By default, Readline is set up 199to be used by :mod:`rlcompleter` to complete Python identifiers for 200the interactive interpreter. If the :mod:`readline` module is to be used 201with a custom completer, a different set of word delimiters should be set. 202 203 204.. function:: set_completer([function]) 205 206 Set or remove the completer function. If *function* is specified, it will be 207 used as the new completer function; if omitted or ``None``, any completer 208 function already installed is removed. The completer function is called as 209 ``function(text, state)``, for *state* in ``0``, ``1``, ``2``, ..., until it 210 returns a non-string value. It should return the next possible completion 211 starting with *text*. 212 213 The installed completer function is invoked by the *entry_func* callback 214 passed to :c:func:`rl_completion_matches` in the underlying library. 215 The *text* string comes from the first parameter to the 216 :c:data:`rl_attempted_completion_function` callback of the 217 underlying library. 218 219 220.. function:: get_completer() 221 222 Get the completer function, or ``None`` if no completer function has been set. 223 224 .. versionadded:: 2.3 225 226 227.. function:: get_completion_type() 228 229 Get the type of completion being attempted. This returns the 230 :c:data:`rl_completion_type` variable in the underlying library as 231 an integer. 232 233 .. versionadded:: 2.6 234 235.. function:: get_begidx() 236 get_endidx() 237 238 Get the beginning or ending index of the completion scope. 239 These indexes are the *start* and *end* arguments passed to the 240 :c:data:`rl_attempted_completion_function` callback of the 241 underlying library. 242 243 244.. function:: set_completer_delims(string) 245 get_completer_delims() 246 247 Set or get the word delimiters for completion. These determine the 248 start of the word to be considered for completion (the completion scope). 249 These functions access the :c:data:`rl_completer_word_break_characters` 250 variable in the underlying library. 251 252.. function:: set_completion_display_matches_hook([function]) 253 254 Set or remove the completion display function. If *function* is 255 specified, it will be used as the new completion display function; 256 if omitted or ``None``, any completion display function already 257 installed is removed. This sets or clears the 258 :c:data:`rl_completion_display_matches_hook` callback in the 259 underlying library. The completion display function is called as 260 ``function(substitution, [matches], longest_match_length)`` once 261 each time matches need to be displayed. 262 263 .. versionadded:: 2.6 264 265.. _readline-example: 266 267Example 268------- 269 270The following example demonstrates how to use the :mod:`readline` module's 271history reading and writing functions to automatically load and save a history 272file named :file:`.pyhist` from the user's home directory. The code below would 273normally be executed automatically during interactive sessions from the user's 274:envvar:`PYTHONSTARTUP` file. :: 275 276 import os 277 import readline 278 histfile = os.path.join(os.path.expanduser("~"), ".pyhist") 279 try: 280 readline.read_history_file(histfile) 281 # default history len is -1 (infinite), which may grow unruly 282 readline.set_history_length(1000) 283 except IOError: 284 pass 285 import atexit 286 atexit.register(readline.write_history_file, histfile) 287 del os, histfile 288 289The following example extends the :class:`code.InteractiveConsole` class to 290support history save/restore. :: 291 292 import code 293 import readline 294 import atexit 295 import os 296 297 class HistoryConsole(code.InteractiveConsole): 298 def __init__(self, locals=None, filename="<console>", 299 histfile=os.path.expanduser("~/.console-history")): 300 code.InteractiveConsole.__init__(self, locals, filename) 301 self.init_history(histfile) 302 303 def init_history(self, histfile): 304 readline.parse_and_bind("tab: complete") 305 if hasattr(readline, "read_history_file"): 306 try: 307 readline.read_history_file(histfile) 308 except IOError: 309 pass 310 atexit.register(self.save_history, histfile) 311 312 def save_history(self, histfile): 313 readline.set_history_length(1000) 314 readline.write_history_file(histfile) 315 316