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