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