Debian Codegraph @

Doc/library/readline.rst

raw
1 :mod:`!readline` --- GNU readline interface
2 ===========================================
3
4 .. module:: readline
5 :synopsis: GNU readline support for Python.
6
7 .. sectionauthor:: Skip Montanaro <[email protected]>
8
9 --------------
10
11 The :mod:`readline` module defines a number of functions to facilitate
12 completion and reading/writing of history files from the Python interpreter.
13 This module can be used directly, or via the :mod:`rlcompleter` module, which
14 supports completion of Python identifiers at the interactive prompt. Settings
15 made using this module affect the behaviour of both the interpreter's
16 interactive prompt and the prompts offered by the built-in :func:`input`
17 function.
18
19 Readline keybindings may be configured via an initialization file, typically
20 ``.inputrc`` in your home directory. See `Readline Init File
21 <https://tiswww.cwru.edu/php/chet/readline/rluserman.html#Readline-Init-File>`_
22 in the GNU Readline manual for information about the format and
23 allowable constructs of that file, and the capabilities of the
24 Readline library in general.
25
26 .. include:: ../includes/wasm-mobile-notavail.rst
27
28 .. availability:: Unix.
29
30 .. note::
31
32 The underlying Readline library API may be implemented by
33 the ``editline`` (``libedit``) library instead of GNU readline.
34 On macOS the :mod:`readline` module detects which library is being used
35 at run time.
36
37 The configuration file for ``editline`` is different from that
38 of GNU readline. If you programmatically load configuration strings
39 you can use :data:`backend` to determine which library is being used.
40
41 If you use ``editline``/``libedit`` readline emulation on macOS, the
42 initialization file located in your home directory is named
43 ``.editrc``. For example, the following content in ``~/.editrc`` will
44 turn ON *vi* keybindings and TAB completion::
45
46 python:bind -v
47 python:bind ^I rl_complete
48
49 Also note that different libraries may use different history file formats.
50 When switching the underlying library, existing history files may become
51 unusable.
52
53 .. data:: backend
54
55 The name of the underlying Readline library being used, either
56 ``"readline"`` or ``"editline"``.
57
58 .. versionadded:: 3.13
59
60 Init file
61 ---------
62
63 The following functions relate to the init file and user configuration:
64
65
66 .. function:: parse_and_bind(string)
67
68 Execute the init line provided in the *string* argument. This calls
69 :c:func:`!rl_parse_and_bind` in the underlying library.
70
71
72 .. function:: read_init_file([filename])
73
74 Execute a readline initialization file. The default filename is the last filename
75 used. This calls :c:func:`!rl_read_init_file` in the underlying library.
76
77
78 Line buffer
79 -----------
80
81 The following functions operate on the line buffer:
82
83
84 .. function:: get_line_buffer()
85
86 Return the current contents of the line buffer (:c:data:`!rl_line_buffer`
87 in the underlying library).
88
89
90 .. function:: insert_text(string)
91
92 Insert text into the line buffer at the cursor position. This calls
93 :c:func:`!rl_insert_text` in the underlying library, but ignores
94 the return value.
95
96
97 .. function:: redisplay()
98
99 Change what's displayed on the screen to reflect the current contents of the
100 line buffer. This calls :c:func:`!rl_redisplay` in the underlying library.
101
102
103 History file
104 ------------
105
106 The following functions operate on a history file:
107
108
109 .. function:: read_history_file([filename])
110
111 Load a readline history file, and append it to the history list.
112 The default filename is :file:`~/.history`. This calls
113 :c:func:`!read_history` in the underlying library.
114
115
116 .. function:: write_history_file([filename])
117
118 Save the history list to a readline history file, overwriting any
119 existing file. The default filename is :file:`~/.history`. This calls
120 :c:func:`!write_history` in the underlying library.
121
122
123 .. function:: append_history_file(nelements[, filename])
124
125 Append the last *nelements* items of history to a file. The default filename is
126 :file:`~/.history`. The file must already exist. This calls
127 :c:func:`!append_history` in the underlying library. This function
128 only exists if Python was compiled for a version of the library
129 that supports it.
130
131 .. versionadded:: 3.5
132
133
134 .. function:: get_history_length()
135 set_history_length(length)
136
137 Set or return the desired number of lines to save in the history file.
138 The :func:`write_history_file` function uses this value to truncate
139 the history file, by calling :c:func:`!history_truncate_file` in
140 the underlying library. Negative values imply
141 unlimited history file size.
142
143
144 History list
145 ------------
146
147 The following functions operate on a global history list:
148
149
150 .. function:: clear_history()
151
152 Clear the current history. This calls :c:func:`!clear_history` in the
153 underlying library. The Python function only exists if Python was
154 compiled for a version of the library that supports it.
155
156
157 .. function:: get_current_history_length()
158
159 Return the number of items currently in the history. (This is different from
160 :func:`get_history_length`, which returns the maximum number of lines that will
161 be written to a history file.)
162
163
164 .. function:: get_history_item(index)
165
166 Return the current contents of history item at *index*. The item index
167 is one-based. This calls :c:func:`!history_get` in the underlying library.
168
169
170 .. function:: remove_history_item(pos)
171
172 Remove history item specified by its position from the history.
173 The position is zero-based. This calls :c:func:`!remove_history` in
174 the underlying library.
175
176
177 .. function:: replace_history_item(pos, line)
178
179 Replace history item specified by its position with *line*.
180 The position is zero-based. This calls :c:func:`!replace_history_entry`
181 in the underlying library.
182
183
184 .. function:: add_history(line)
185
186 Append *line* to the history buffer, as if it was the last line typed.
187 This calls :c:func:`!add_history` in the underlying library.
188
189
190 .. function:: set_auto_history(enabled)
191
192 Enable or disable automatic calls to :c:func:`!add_history` when reading
193 input via readline. The *enabled* argument should be a Boolean value
194 that when true, enables auto history, and that when false, disables
195 auto history.
196
197 .. versionadded:: 3.6
198
199 .. impl-detail::
200 Auto history is enabled by default, and changes to this do not persist
201 across multiple sessions.
202
203
204 Startup hooks
205 -------------
206
207
208 .. function:: set_startup_hook([function])
209
210 Set or remove the function invoked by the :c:data:`!rl_startup_hook`
211 callback of the underlying library. If *function* is specified, it will
212 be used as the new hook function; if omitted or ``None``, any function
213 already installed is removed. The hook is called with no
214 arguments just before readline prints the first prompt.
215
216
217 .. function:: set_pre_input_hook([function])
218
219 Set or remove the function invoked by the :c:data:`!rl_pre_input_hook`
220 callback of the underlying library. If *function* is specified, it will
221 be used as the new hook function; if omitted or ``None``, any
222 function already installed is removed. The hook is called
223 with no arguments after the first prompt has been printed and just before
224 readline starts reading input characters. This function only exists
225 if Python was compiled for a version of the library that supports it.
226
227
228 .. _readline-completion:
229
230 Completion
231 ----------
232
233 The following functions relate to implementing a custom word completion
234 function. This is typically operated by the Tab key, and can suggest and
235 automatically complete a word being typed. By default, Readline is set up
236 to be used by :mod:`rlcompleter` to complete Python identifiers for
237 the interactive interpreter. If the :mod:`readline` module is to be used
238 with a custom completer, a different set of word delimiters should be set.
239
240
241 .. function:: set_completer([function])
242
243 Set or remove the completer function. If *function* is specified, it will be
244 used as the new completer function; if omitted or ``None``, any completer
245 function already installed is removed. The completer function is called as
246 ``function(text, state)``, for *state* in ``0``, ``1``, ``2``, ..., until it
247 returns a non-string value. It should return the next possible completion
248 starting with *text*.
249
250 The installed completer function is invoked by the *entry_func* callback
251 passed to :c:func:`!rl_completion_matches` in the underlying library.
252 The *text* string comes from the first parameter to the
253 :c:data:`!rl_attempted_completion_function` callback of the
254 underlying library.
255
256
257 .. function:: get_completer()
258
259 Get the completer function, or ``None`` if no completer function has been set.
260
261
262 .. function:: get_completion_type()
263
264 Get the type of completion being attempted. This returns the
265 :c:data:`!rl_completion_type` variable in the underlying library as
266 an integer.
267
268
269 .. function:: get_begidx()
270 get_endidx()
271
272 Get the beginning or ending index of the completion scope.
273 These indexes are the *start* and *end* arguments passed to the
274 :c:data:`!rl_attempted_completion_function` callback of the
275 underlying library. The values may be different in the same
276 input editing scenario based on the underlying C readline implementation.
277 Ex: libedit is known to behave differently than libreadline.
278
279
280 .. function:: set_completer_delims(string)
281 get_completer_delims()
282
283 Set or get the word delimiters for completion. These determine the
284 start of the word to be considered for completion (the completion scope).
285 These functions access the :c:data:`!rl_completer_word_break_characters`
286 variable in the underlying library.
287
288
289 .. function:: set_completion_display_matches_hook([function])
290
291 Set or remove the completion display function. If *function* is
292 specified, it will be used as the new completion display function;
293 if omitted or ``None``, any completion display function already
294 installed is removed. This sets or clears the
295 :c:data:`!rl_completion_display_matches_hook` callback in the
296 underlying library. The completion display function is called as
297 ``function(substitution, [matches], longest_match_length)`` once
298 each time matches need to be displayed.
299
300
301 .. _readline-example:
302
303 Example
304 -------
305
306 The following example demonstrates how to use the :mod:`readline` module's
307 history reading and writing functions to automatically load and save a history
308 file named :file:`.python_history` from the user's home directory. The code
309 below would normally be executed automatically during interactive sessions
310 from the user's :envvar:`PYTHONSTARTUP` file. ::
311
312 import atexit
313 import os
314 import readline
315
316 histfile = os.path.join(os.path.expanduser("~"), ".python_history")
317 try:
318 readline.read_history_file(histfile)
319 # default history len is -1 (infinite), which may grow unruly
320 readline.set_history_length(1000)
321 except FileNotFoundError:
322 pass
323
324 atexit.register(readline.write_history_file, histfile)
325
326 This code is actually automatically run when Python is run in
327 :ref:`interactive mode <tut-interactive>` (see :ref:`rlcompleter-config`).
328
329 The following example achieves the same goal but supports concurrent interactive
330 sessions, by only appending the new history. ::
331
332 import atexit
333 import os
334 import readline
335 histfile = os.path.join(os.path.expanduser("~"), ".python_history")
336
337 try:
338 readline.read_history_file(histfile)
339 h_len = readline.get_current_history_length()
340 except FileNotFoundError:
341 open(histfile, 'wb').close()
342 h_len = 0
343
344 def save(prev_h_len, histfile):
345 new_h_len = readline.get_current_history_length()
346 readline.set_history_length(1000)
347 readline.append_history_file(new_h_len - prev_h_len, histfile)
348 atexit.register(save, h_len, histfile)
349
350 The following example extends the :class:`code.InteractiveConsole` class to
351 support history save/restore. ::
352
353 import atexit
354 import code
355 import os
356 import readline
357
358 class HistoryConsole(code.InteractiveConsole):
359 def __init__(self, locals=None, filename="<console>",
360 histfile=os.path.expanduser("~/.console-history")):
361 code.InteractiveConsole.__init__(self, locals, filename)
362 self.init_history(histfile)
363
364 def init_history(self, histfile):
365 readline.parse_and_bind("tab: complete")
366 if hasattr(readline, "read_history_file"):
367 try:
368 readline.read_history_file(histfile)
369 except FileNotFoundError:
370 pass
371 atexit.register(self.save_history, histfile)
372
373 def save_history(self, histfile):
374 readline.set_history_length(1000)
375 readline.write_history_file(histfile)
376
377 .. note::
378
379 The new :term:`REPL` introduced in version 3.13 doesn't support readline.
380 However, readline can still be used by setting the :envvar:`PYTHON_BASIC_REPL`
381 environment variable.