blob: 56890cdaaa4d70af7dc7c98d33fd603c793b58de [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001.. _tut-interacting:
2
3**************************************************
4Interactive Input Editing and History Substitution
5**************************************************
6
7Some versions of the Python interpreter support editing of the current input
8line and history substitution, similar to facilities found in the Korn shell and
9the GNU Bash shell. This is implemented using the *GNU Readline* library, which
10supports Emacs-style and vi-style editing. This library has its own
11documentation which I won't duplicate here; however, the basics are easily
12explained. The interactive editing and history described here are optionally
13available in the Unix and Cygwin versions of the interpreter.
14
15This chapter does *not* document the editing facilities of Mark Hammond's
16PythonWin package or the Tk-based environment, IDLE, distributed with Python.
17The command line history recall which operates within DOS boxes on NT and some
18other DOS and Windows flavors is yet another beast.
19
20
21.. _tut-lineediting:
22
23Line Editing
24============
25
26If supported, input line editing is active whenever the interpreter prints a
27primary or secondary prompt. The current line can be edited using the
28conventional Emacs control characters. The most important of these are:
29:kbd:`C-A` (Control-A) moves the cursor to the beginning of the line, :kbd:`C-E`
30to the end, :kbd:`C-B` moves it one position to the left, :kbd:`C-F` to the
31right. Backspace erases the character to the left of the cursor, :kbd:`C-D` the
32character to its right. :kbd:`C-K` kills (erases) the rest of the line to the
33right of the cursor, :kbd:`C-Y` yanks back the last killed string.
34:kbd:`C-underscore` undoes the last change you made; it can be repeated for
35cumulative effect.
36
37
38.. _tut-history:
39
40History Substitution
41====================
42
43History substitution works as follows. All non-empty input lines issued are
44saved in a history buffer, and when a new prompt is given you are positioned on
45a new line at the bottom of this buffer. :kbd:`C-P` moves one line up (back) in
46the history buffer, :kbd:`C-N` moves one down. Any line in the history buffer
47can be edited; an asterisk appears in front of the prompt to mark a line as
48modified. Pressing the :kbd:`Return` key passes the current line to the
49interpreter. :kbd:`C-R` starts an incremental reverse search; :kbd:`C-S` starts
50a forward search.
51
52
53.. _tut-keybindings:
54
55Key Bindings
56============
57
58The key bindings and some other parameters of the Readline library can be
59customized by placing commands in an initialization file called
60:file:`~/.inputrc`. Key bindings have the form ::
61
62 key-name: function-name
63
64or ::
65
66 "string": function-name
67
68and options can be set with ::
69
70 set option-name value
71
72For example::
73
74 # I prefer vi-style editing:
75 set editing-mode vi
76
77 # Edit using a single line:
78 set horizontal-scroll-mode On
79
80 # Rebind some keys:
81 Meta-h: backward-kill-word
82 "\C-u": universal-argument
83 "\C-x\C-r": re-read-init-file
84
85Note that the default binding for :kbd:`Tab` in Python is to insert a :kbd:`Tab`
86character instead of Readline's default filename completion function. If you
87insist, you can override this by putting ::
88
89 Tab: complete
90
91in your :file:`~/.inputrc`. (Of course, this makes it harder to type indented
92continuation lines if you're accustomed to using :kbd:`Tab` for that purpose.)
93
94.. index::
95 module: rlcompleter
96 module: readline
97
98Automatic completion of variable and module names is optionally available. To
99enable it in the interpreter's interactive mode, add the following to your
100startup file: [#]_ ::
101
102 import rlcompleter, readline
103 readline.parse_and_bind('tab: complete')
104
105This binds the :kbd:`Tab` key to the completion function, so hitting the
106:kbd:`Tab` key twice suggests completions; it looks at Python statement names,
107the current local variables, and the available module names. For dotted
108expressions such as ``string.a``, it will evaluate the expression up to the
109final ``'.'`` and then suggest completions from the attributes of the resulting
110object. Note that this may execute application-defined code if an object with a
111:meth:`__getattr__` method is part of the expression.
112
113A more capable startup file might look like this example. Note that this
114deletes the names it creates once they are no longer needed; this is done since
115the startup file is executed in the same namespace as the interactive commands,
116and removing the names avoids creating side effects in the interactive
117environment. You may find it convenient to keep some of the imported modules,
118such as :mod:`os`, which turn out to be needed in most sessions with the
119interpreter. ::
120
121 # Add auto-completion and a stored history file of commands to your Python
122 # interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
123 # bound to the Esc key by default (you can change it - see readline docs).
124 #
125 # Store the file in ~/.pystartup, and set an environment variable to point
Georg Brandl9afde1c2007-11-01 20:32:30 +0000126 # to it: "export PYTHONSTARTUP=/home/user/.pystartup" in bash.
Georg Brandl116aa622007-08-15 14:28:22 +0000127 #
128 # Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the
129 # full path to your home directory.
130
131 import atexit
132 import os
133 import readline
134 import rlcompleter
135
136 historyPath = os.path.expanduser("~/.pyhistory")
137
138 def save_history(historyPath=historyPath):
139 import readline
140 readline.write_history_file(historyPath)
141
142 if os.path.exists(historyPath):
143 readline.read_history_file(historyPath)
144
145 atexit.register(save_history)
146 del os, atexit, readline, rlcompleter, save_history, historyPath
147
148
149.. _tut-commentary:
150
151Commentary
152==========
153
154This facility is an enormous step forward compared to earlier versions of the
155interpreter; however, some wishes are left: It would be nice if the proper
156indentation were suggested on continuation lines (the parser knows if an indent
157token is required next). The completion mechanism might use the interpreter's
158symbol table. A command to check (or even suggest) matching parentheses,
159quotes, etc., would also be useful.
160
Guido van Rossum0616b792007-08-31 03:25:11 +0000161.. %
162 Do we mention IPython? DUBOIS
Georg Brandl116aa622007-08-15 14:28:22 +0000163
164.. rubric:: Footnotes
165
166.. [#] Python will execute the contents of a file identified by the
167 :envvar:`PYTHONSTARTUP` environment variable when you start an interactive
168 interpreter.
169