##// END OF EJS Templates
Merge pull request #12321 from marciomazza/patch-1
Matthias Bussonnier -
r25740:c1e602c3 merge
parent child Browse files
Show More
@@ -1,313 +1,313 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 # Register the shortcut if IPython is using prompt_toolkit
220 220 if getattr(ip, 'pt_app', None):
221 221 registry = ip.pt_app.key_bindings
222 222 registry.add_binding(Keys.ControlN,
223 223 filter=(HasFocus(DEFAULT_BUFFER)
224 224 & ~HasSelection()
225 225 & insert_mode))(insert_unexpected)
226 226
227 227
228 228 Here is a second example that bind the key sequence ``j``, ``k`` to switch to
229 229 VI input mode to ``Normal`` when in insert mode::
230 230
231 231 from IPython import get_ipython
232 232 from prompt_toolkit.enums import DEFAULT_BUFFER
233 233 from prompt_toolkit.filters import HasFocus, ViInsertMode
234 234 from prompt_toolkit.key_binding.vi_state import InputMode
235 235
236 236 ip = get_ipython()
237 237
238 238 def switch_to_navigation_mode(event):
239 239 vi_state = event.cli.vi_state
240 240 vi_state.input_mode = InputMode.NAVIGATION
241 241
242 242 if getattr(ip, 'pt_app', None):
243 243 registry = ip.pt_app.key_bindings
244 244 registry.add_binding(u'j',u'k',
245 245 filter=(HasFocus(DEFAULT_BUFFER)
246 246 & ViInsertMode()))(switch_to_navigation_mode)
247 247
248 248 For more information on filters and what you can do with the ``event`` object,
249 249 `see the prompt_toolkit docs
250 <http://python-prompt-toolkit.readthedocs.io/en/latest/pages/building_prompts.html#adding-custom-key-bindings>`__.
250 <https://python-prompt-toolkit.readthedocs.io/en/latest/pages/asking_for_input.html#adding-custom-key-bindings>`__.
251 251
252 252
253 253 Enter to execute
254 254 ----------------
255 255
256 256 In the Terminal IPython shell – which by default uses the ``prompt_toolkit``
257 257 interface, the semantic meaning of pressing the :kbd:`Enter` key can be
258 258 ambiguous. In some case :kbd:`Enter` should execute code, and in others it
259 259 should add a new line. IPython uses heuristics to decide whether to execute or
260 260 insert a new line at cursor position. For example, if we detect that the current
261 261 code is not valid Python, then the user is likely editing code and the right
262 262 behavior is to likely to insert a new line. If the current code is a simple
263 263 statement like `ord('*')`, then the right behavior is likely to execute. Though
264 264 the exact desired semantics often varies from users to users.
265 265
266 266 As the exact behavior of :kbd:`Enter` is ambiguous, it has been special cased
267 267 to allow users to completely configure the behavior they like. Hence you can
268 268 have enter always execute code. If you prefer fancier behavior, you need to get
269 269 your hands dirty and read the ``prompt_toolkit`` and IPython documentation
270 270 though. See :ghpull:`10500`, set the
271 271 ``c.TerminalInteractiveShell.handle_return`` option and get inspiration from the
272 272 following example that only auto-executes the input if it begins with a bang or
273 273 a modulo character (``!`` or ``%``). To use the following code, add it to your
274 274 IPython configuration::
275 275
276 276 def custom_return(shell):
277 277
278 278 """This function is required by the API. It takes a reference to
279 279 the shell, which is the same thing `get_ipython()` evaluates to.
280 280 This function must return a function that handles each keypress
281 281 event. That function, named `handle` here, references `shell`
282 282 by closure."""
283 283
284 284 def handle(event):
285 285
286 286 """This function is called each time `Enter` is pressed,
287 287 and takes a reference to a Prompt Toolkit event object.
288 288 If the current input starts with a bang or modulo, then
289 289 the input is executed, otherwise a newline is entered,
290 290 followed by any spaces needed to auto-indent."""
291 291
292 292 # set up a few handy references to nested items...
293 293
294 294 buffer = event.current_buffer
295 295 document = buffer.document
296 296 text = document.text
297 297
298 298 if text.startswith('!') or text.startswith('%'): # execute the input...
299 299
300 300 buffer.accept_action.validate_and_handle(event.cli, buffer)
301 301
302 302 else: # insert a newline with auto-indentation...
303 303
304 304 if document.line_count > 1: text = text[:document.cursor_position]
305 305 indent = shell.check_complete(text)[1]
306 306 buffer.insert_text('\n' + indent)
307 307
308 308 # if you just wanted a plain newline without any indentation, you
309 309 # could use `buffer.insert_text('\n')` instead of the lines above
310 310
311 311 return handle
312 312
313 313 c.TerminalInteractiveShell.handle_return = custom_return
General Comments 0
You need to be logged in to leave comments. Login now