##// END OF EJS Templates
Add narrative docs for customizing enter behavior....
Matthias Bussonnier -
Show More
@@ -1,230 +1,272 b''
1 1 =======================
2 2 Specific config details
3 3 =======================
4 4
5 5 .. _custom_prompts:
6 6
7 7 Custom Prompts
8 8 ==============
9 9
10 10 .. versionchanged:: 5.0
11 11
12 12 From IPython 5, prompts are produced as a list of Pygments tokens, which are
13 13 tuples of (token_type, text). You can customise prompts by writing a method
14 14 which generates a list of tokens.
15 15
16 16 There are four kinds of prompt:
17 17
18 18 * The **in** prompt is shown before the first line of input
19 19 (default like ``In [1]:``).
20 20 * The **continuation** prompt is shown before further lines of input
21 21 (default like ``...:``).
22 22 * The **rewrite** prompt is shown to highlight how special syntax has been
23 23 interpreted (default like ``----->``).
24 24 * The **out** prompt is shown before the result from evaluating the input
25 25 (default like ``Out[1]:``).
26 26
27 27 Custom prompts are supplied together as a class. If you want to customise only
28 28 some of the prompts, inherit from :class:`IPython.terminal.prompts.Prompts`,
29 29 which defines the defaults. The required interface is like this:
30 30
31 31 .. class:: MyPrompts(shell)
32 32
33 33 Prompt style definition. *shell* is a reference to the
34 34 :class:`~.TerminalInteractiveShell` instance.
35 35
36 36 .. method:: in_prompt_tokens(cli=None)
37 37 continuation_prompt_tokens(self, cli=None, width=None)
38 38 rewrite_prompt_tokens()
39 39 out_prompt_tokens()
40 40
41 41 Return the respective prompts as lists of ``(token_type, text)`` tuples.
42 42
43 43 For continuation prompts, *width* is an integer representing the width of
44 44 the prompt area in terminal columns.
45 45
46 46 *cli*, where used, is the prompt_toolkit ``CommandLineInterface`` instance.
47 47 This is mainly for compatibility with the API prompt_toolkit expects.
48 48
49 49 Here is an example Prompt class that will show the current working directory
50 50 in the input prompt:
51 51
52 52 .. code-block:: python
53 53
54 54 from IPython.terminal.prompts import Prompts, Token
55 55 import os
56 56
57 57 class MyPrompt(Prompts):
58 58 def in_prompt_tokens(self, cli=None):
59 59 return [(Token, os.getcwd()),
60 60 (Token.Prompt, ' >>>')]
61 61
62 62 To set the new prompt, assign it to the ``prompts`` attribute of the IPython
63 63 shell:
64 64
65 65 .. code-block:: python
66 66
67 67 In [2]: ip = get_ipython()
68 68 ...: ip.prompts = MyPrompt(ip)
69 69
70 70 /home/bob >>> # it works
71 71
72 72 See ``IPython/example/utils/cwd_prompt.py`` for an example of how to write an
73 73 extensions to customise prompts.
74 74
75 75 Inside IPython or in a startup script, you can use a custom prompts class
76 76 by setting ``get_ipython().prompts`` to an *instance* of the class.
77 77 In configuration, ``TerminalInteractiveShell.prompts_class`` may be set to
78 78 either the class object, or a string of its full importable name.
79 79
80 80 To include invisible terminal control sequences in a prompt, use
81 81 ``Token.ZeroWidthEscape`` as the token type. Tokens with this type are ignored
82 82 when calculating the width.
83 83
84 84 Colours in the prompt are determined by the token types and the highlighting
85 85 style; see below for more details. The tokens used in the default prompts are
86 86 ``Prompt``, ``PromptNum``, ``OutPrompt`` and ``OutPromptNum``.
87 87
88 88 .. _termcolour:
89 89
90 90 Terminal Colors
91 91 ===============
92 92
93 93 .. versionchanged:: 5.0
94 94
95 95 There are two main configuration options controlling colours.
96 96
97 97 ``InteractiveShell.colors`` sets the colour of tracebacks and object info (the
98 98 output from e.g. ``zip?``). It may also affect other things if the option below
99 99 is set to ``'legacy'``. It has four case-insensitive values:
100 100 ``'nocolor', 'neutral', 'linux', 'lightbg'``. The default is *neutral*, which
101 101 should be legible on either dark or light terminal backgrounds. *linux* is
102 102 optimised for dark backgrounds and *lightbg* for light ones.
103 103
104 104 ``TerminalInteractiveShell.highlighting_style`` determines prompt colours and
105 105 syntax highlighting. It takes the name (as a string) or class (as a subclass of
106 106 ``pygments.style.Style``) of a Pygments style, or the special value ``'legacy'``
107 107 to pick a style in accordance with ``InteractiveShell.colors``.
108 108
109 109 You can see the Pygments styles available on your system by running::
110 110
111 111 import pygments
112 112 list(pygments.styles.get_all_styles())
113 113
114 114 Additionally, ``TerminalInteractiveShell.highlighting_style_overrides`` can override
115 115 specific styles in the highlighting. It should be a dictionary mapping Pygments
116 116 token types to strings defining the style. See `Pygments' documentation
117 117 <http://pygments.org/docs/styles/#creating-own-styles>`__ for the language used
118 118 to define styles.
119 119
120 120 Colors in the pager
121 121 -------------------
122 122
123 123 On some systems, the default pager has problems with ANSI colour codes.
124 124 To configure your default pager to allow these:
125 125
126 126 1. Set the environment PAGER variable to ``less``.
127 127 2. Set the environment LESS variable to ``-r`` (plus any other options
128 128 you always want to pass to less by default). This tells less to
129 129 properly interpret control sequences, which is how color
130 130 information is given to your terminal.
131 131
132 132 .. _editors:
133 133
134 134 Editor configuration
135 135 ====================
136 136
137 137 IPython can integrate with text editors in a number of different ways:
138 138
139 139 * Editors (such as `(X)Emacs`_, vim_ and TextMate_) can
140 140 send code to IPython for execution.
141 141
142 142 * IPython's ``%edit`` magic command can open an editor of choice to edit
143 143 a code block.
144 144
145 145 The %edit command (and its alias %ed) will invoke the editor set in your
146 146 environment as :envvar:`EDITOR`. If this variable is not set, it will default
147 147 to vi under Linux/Unix and to notepad under Windows. You may want to set this
148 148 variable properly and to a lightweight editor which doesn't take too long to
149 149 start (that is, something other than a new instance of Emacs). This way you
150 150 can edit multi-line code quickly and with the power of a real editor right
151 151 inside IPython.
152 152
153 153 You can also control the editor by setting :attr:`TerminalInteractiveShell.editor`
154 154 in :file:`ipython_config.py`.
155 155
156 156 Vim
157 157 ---
158 158
159 159 Paul Ivanov's `vim-ipython <https://github.com/ivanov/vim-ipython>`_ provides
160 160 powerful IPython integration for vim.
161 161
162 162 .. _emacs:
163 163
164 164 (X)Emacs
165 165 --------
166 166
167 167 If you are a dedicated Emacs user, and want to use Emacs when IPython's
168 168 ``%edit`` magic command is called you should set up the Emacs server so that
169 169 new requests are handled by the original process. This means that almost no
170 170 time is spent in handling the request (assuming an Emacs process is already
171 171 running). For this to work, you need to set your EDITOR environment variable
172 172 to 'emacsclient'. The code below, supplied by Francois Pinard, can then be
173 173 used in your :file:`.emacs` file to enable the server:
174 174
175 175 .. code-block:: common-lisp
176 176
177 177 (defvar server-buffer-clients)
178 178 (when (and (fboundp 'server-start) (string-equal (getenv "TERM") 'xterm))
179 179 (server-start)
180 180 (defun fp-kill-server-with-buffer-routine ()
181 181 (and server-buffer-clients (server-done)))
182 182 (add-hook 'kill-buffer-hook 'fp-kill-server-with-buffer-routine))
183 183
184 184 Thanks to the work of Alexander Schmolck and Prabhu Ramachandran,
185 185 currently (X)Emacs and IPython get along very well in other ways.
186 186
187 187 With (X)EMacs >= 24, You can enable IPython in python-mode with:
188 188
189 189 .. code-block:: common-lisp
190 190
191 191 (require 'python)
192 192 (setq python-shell-interpreter "ipython")
193 193
194 194 .. _`(X)Emacs`: http://www.gnu.org/software/emacs/
195 195 .. _TextMate: http://macromates.com/
196 196 .. _vim: http://www.vim.org/
197 197
198 198 .. _custom_keyboard_shortcuts:
199 199
200 200 Keyboard Shortcuts
201 201 ==================
202 202
203 203 .. versionchanged:: 5.0
204 204
205 205 You can customise keyboard shortcuts for terminal IPython. Put code like this in
206 206 a :ref:`startup file <startup_files>`::
207 207
208 208 from IPython import get_ipython
209 209 from prompt_toolkit.enums import DEFAULT_BUFFER
210 210 from prompt_toolkit.keys import Keys
211 211 from prompt_toolkit.filters import HasFocus, HasSelection, ViInsertMode, EmacsInsertMode
212 212
213 213 ip = get_ipython()
214 214 insert_mode = ViInsertMode() | EmacsInsertMode()
215 215
216 216 def insert_unexpected(event):
217 217 buf = event.current_buffer
218 218 buf.insert_text('The Spanish Inquisition')
219 219
220 220 # Register the shortcut if IPython is using prompt_toolkit
221 221 if getattr(ip, 'pt_cli'):
222 222 registry = ip.pt_cli.application.key_bindings_registry
223 223 registry.add_binding(Keys.ControlN,
224 224 filter=(HasFocus(DEFAULT_BUFFER)
225 225 & ~HasSelection()
226 226 & insert_mode))(insert_unexpected)
227 227
228 228 For more information on filters and what you can do with the ``event`` object,
229 229 `see the prompt_toolkit docs
230 230 <http://python-prompt-toolkit.readthedocs.io/en/latest/pages/building_prompts.html#adding-custom-key-bindings>`__.
231
232
233 Enter to execute
234 ----------------
235
236 In the Terminal IPython shell – which by default use the ``prompt_toolkit``
237 interface, the semantic of pressing the :kbd:`Enter` key can be ambiguous, in
238 some case :kbd:`Enter` should execute code, and in others it should add a new
239 line. IPython is using some heuristics to decide whether to execute or insert a
240 new line at cursor position. For example, if we detect that the current code is
241 not valid Python, then the user is likely editing code and the right behavior is
242 to likely to insert a new line. If the current code is a simple statement like
243 `ord('*')`, then the right behavior is likely to execute. Though the exact
244 desired semantics often varies from users to users.
245
246 As the exact behavior of :kbd:`Enter` is subject to disagreement, it has been
247 special cased in order for users to completely configure the behavior they like.
248 Hence you can have enter to simply alway execute code, if you prefer more fancy
249 behavior : start your coffee machine on even days of odd month. You'll have to
250 get your hands dirty and read prompt_toolkit and IPython documentation though.
251 See :ghpull:`10500`, set the `c.TerminalInteractiveShell.handle_return` option
252 and get inspiration from the following example that insert new lines only after
253 a pipe (``|``). Place the following in your configuration to do so::
254
255 def new_line_after_pipe(shell):
256 # shell is the same as get_ipython()
257 def insert(event):
258 """When the user presses return, insert"""
259 b = event.current_buffer
260 d = b.document
261
262 # if character before cursor is `|`
263 if d.text[d.cursor_position-1] == '|':
264 # insert a new line
265 b.insert_text('\n')
266 else:
267 # otherwise execute.
268 b.accept_action.validate_and_handle(event.cli, b)
269 return insert
270
271 # set the heuristic to our new function
272 c.TerminalInteractiveShell.handle_return = new_line_after_pipe
General Comments 0
You need to be logged in to leave comments. Login now