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