##// END OF EJS Templates
Merge pull request #12603 from mskar/emacs_bindings_in_vi_insert_mode
Matthias Bussonnier -
r26098:262b3920 merge
parent child Browse files
Show More
@@ -1,646 +1,651 b''
1 """IPython terminal interface using prompt_toolkit"""
1 """IPython terminal interface using prompt_toolkit"""
2
2
3 import asyncio
3 import asyncio
4 import os
4 import os
5 import sys
5 import sys
6 import warnings
6 import warnings
7 from warnings import warn
7 from warnings import warn
8
8
9 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
9 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
10 from IPython.utils import io
10 from IPython.utils import io
11 from IPython.utils.py3compat import input
11 from IPython.utils.py3compat import input
12 from IPython.utils.terminal import toggle_set_term_title, set_term_title, restore_term_title
12 from IPython.utils.terminal import toggle_set_term_title, set_term_title, restore_term_title
13 from IPython.utils.process import abbrev_cwd
13 from IPython.utils.process import abbrev_cwd
14 from traitlets import (
14 from traitlets import (
15 Bool, Unicode, Dict, Integer, observe, Instance, Type, default, Enum, Union,
15 Bool, Unicode, Dict, Integer, observe, Instance, Type, default, Enum, Union,
16 Any, validate
16 Any, validate
17 )
17 )
18
18
19 from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode
19 from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode
20 from prompt_toolkit.filters import (HasFocus, Condition, IsDone)
20 from prompt_toolkit.filters import (HasFocus, Condition, IsDone)
21 from prompt_toolkit.formatted_text import PygmentsTokens
21 from prompt_toolkit.formatted_text import PygmentsTokens
22 from prompt_toolkit.history import InMemoryHistory
22 from prompt_toolkit.history import InMemoryHistory
23 from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor
23 from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor
24 from prompt_toolkit.output import ColorDepth
24 from prompt_toolkit.output import ColorDepth
25 from prompt_toolkit.patch_stdout import patch_stdout
25 from prompt_toolkit.patch_stdout import patch_stdout
26 from prompt_toolkit.shortcuts import PromptSession, CompleteStyle, print_formatted_text
26 from prompt_toolkit.shortcuts import PromptSession, CompleteStyle, print_formatted_text
27 from prompt_toolkit.styles import DynamicStyle, merge_styles
27 from prompt_toolkit.styles import DynamicStyle, merge_styles
28 from prompt_toolkit.styles.pygments import style_from_pygments_cls, style_from_pygments_dict
28 from prompt_toolkit.styles.pygments import style_from_pygments_cls, style_from_pygments_dict
29 from prompt_toolkit import __version__ as ptk_version
29 from prompt_toolkit import __version__ as ptk_version
30
30
31 from pygments.styles import get_style_by_name
31 from pygments.styles import get_style_by_name
32 from pygments.style import Style
32 from pygments.style import Style
33 from pygments.token import Token
33 from pygments.token import Token
34
34
35 from .debugger import TerminalPdb, Pdb
35 from .debugger import TerminalPdb, Pdb
36 from .magics import TerminalMagics
36 from .magics import TerminalMagics
37 from .pt_inputhooks import get_inputhook_name_and_func
37 from .pt_inputhooks import get_inputhook_name_and_func
38 from .prompts import Prompts, ClassicPrompts, RichPromptDisplayHook
38 from .prompts import Prompts, ClassicPrompts, RichPromptDisplayHook
39 from .ptutils import IPythonPTCompleter, IPythonPTLexer
39 from .ptutils import IPythonPTCompleter, IPythonPTLexer
40 from .shortcuts import create_ipython_shortcuts
40 from .shortcuts import create_ipython_shortcuts
41
41
42 DISPLAY_BANNER_DEPRECATED = object()
42 DISPLAY_BANNER_DEPRECATED = object()
43 PTK3 = ptk_version.startswith('3.')
43 PTK3 = ptk_version.startswith('3.')
44
44
45
45
46 class _NoStyle(Style): pass
46 class _NoStyle(Style): pass
47
47
48
48
49
49
50 _style_overrides_light_bg = {
50 _style_overrides_light_bg = {
51 Token.Prompt: '#ansibrightblue',
51 Token.Prompt: '#ansibrightblue',
52 Token.PromptNum: '#ansiblue bold',
52 Token.PromptNum: '#ansiblue bold',
53 Token.OutPrompt: '#ansibrightred',
53 Token.OutPrompt: '#ansibrightred',
54 Token.OutPromptNum: '#ansired bold',
54 Token.OutPromptNum: '#ansired bold',
55 }
55 }
56
56
57 _style_overrides_linux = {
57 _style_overrides_linux = {
58 Token.Prompt: '#ansibrightgreen',
58 Token.Prompt: '#ansibrightgreen',
59 Token.PromptNum: '#ansigreen bold',
59 Token.PromptNum: '#ansigreen bold',
60 Token.OutPrompt: '#ansibrightred',
60 Token.OutPrompt: '#ansibrightred',
61 Token.OutPromptNum: '#ansired bold',
61 Token.OutPromptNum: '#ansired bold',
62 }
62 }
63
63
64 def get_default_editor():
64 def get_default_editor():
65 try:
65 try:
66 return os.environ['EDITOR']
66 return os.environ['EDITOR']
67 except KeyError:
67 except KeyError:
68 pass
68 pass
69 except UnicodeError:
69 except UnicodeError:
70 warn("$EDITOR environment variable is not pure ASCII. Using platform "
70 warn("$EDITOR environment variable is not pure ASCII. Using platform "
71 "default editor.")
71 "default editor.")
72
72
73 if os.name == 'posix':
73 if os.name == 'posix':
74 return 'vi' # the only one guaranteed to be there!
74 return 'vi' # the only one guaranteed to be there!
75 else:
75 else:
76 return 'notepad' # same in Windows!
76 return 'notepad' # same in Windows!
77
77
78 # conservatively check for tty
78 # conservatively check for tty
79 # overridden streams can result in things like:
79 # overridden streams can result in things like:
80 # - sys.stdin = None
80 # - sys.stdin = None
81 # - no isatty method
81 # - no isatty method
82 for _name in ('stdin', 'stdout', 'stderr'):
82 for _name in ('stdin', 'stdout', 'stderr'):
83 _stream = getattr(sys, _name)
83 _stream = getattr(sys, _name)
84 if not _stream or not hasattr(_stream, 'isatty') or not _stream.isatty():
84 if not _stream or not hasattr(_stream, 'isatty') or not _stream.isatty():
85 _is_tty = False
85 _is_tty = False
86 break
86 break
87 else:
87 else:
88 _is_tty = True
88 _is_tty = True
89
89
90
90
91 _use_simple_prompt = ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or (not _is_tty)
91 _use_simple_prompt = ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or (not _is_tty)
92
92
93 def black_reformat_handler(text_before_cursor):
93 def black_reformat_handler(text_before_cursor):
94 import black
94 import black
95 formatted_text = black.format_str(text_before_cursor, mode=black.FileMode())
95 formatted_text = black.format_str(text_before_cursor, mode=black.FileMode())
96 if not text_before_cursor.endswith('\n') and formatted_text.endswith('\n'):
96 if not text_before_cursor.endswith('\n') and formatted_text.endswith('\n'):
97 formatted_text = formatted_text[:-1]
97 formatted_text = formatted_text[:-1]
98 return formatted_text
98 return formatted_text
99
99
100
100
101 class TerminalInteractiveShell(InteractiveShell):
101 class TerminalInteractiveShell(InteractiveShell):
102 mime_renderers = Dict().tag(config=True)
102 mime_renderers = Dict().tag(config=True)
103
103
104 space_for_menu = Integer(6, help='Number of line at the bottom of the screen '
104 space_for_menu = Integer(6, help='Number of line at the bottom of the screen '
105 'to reserve for the tab completion menu, '
105 'to reserve for the tab completion menu, '
106 'search history, ...etc, the height of '
106 'search history, ...etc, the height of '
107 'these menus will at most this value. '
107 'these menus will at most this value. '
108 'Increase it is you prefer long and skinny '
108 'Increase it is you prefer long and skinny '
109 'menus, decrease for short and wide.'
109 'menus, decrease for short and wide.'
110 ).tag(config=True)
110 ).tag(config=True)
111
111
112 pt_app = None
112 pt_app = None
113 debugger_history = None
113 debugger_history = None
114
114
115 simple_prompt = Bool(_use_simple_prompt,
115 simple_prompt = Bool(_use_simple_prompt,
116 help="""Use `raw_input` for the REPL, without completion and prompt colors.
116 help="""Use `raw_input` for the REPL, without completion and prompt colors.
117
117
118 Useful when controlling IPython as a subprocess, and piping STDIN/OUT/ERR. Known usage are:
118 Useful when controlling IPython as a subprocess, and piping STDIN/OUT/ERR. Known usage are:
119 IPython own testing machinery, and emacs inferior-shell integration through elpy.
119 IPython own testing machinery, and emacs inferior-shell integration through elpy.
120
120
121 This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT`
121 This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT`
122 environment variable is set, or the current terminal is not a tty."""
122 environment variable is set, or the current terminal is not a tty."""
123 ).tag(config=True)
123 ).tag(config=True)
124
124
125 @property
125 @property
126 def debugger_cls(self):
126 def debugger_cls(self):
127 return Pdb if self.simple_prompt else TerminalPdb
127 return Pdb if self.simple_prompt else TerminalPdb
128
128
129 confirm_exit = Bool(True,
129 confirm_exit = Bool(True,
130 help="""
130 help="""
131 Set to confirm when you try to exit IPython with an EOF (Control-D
131 Set to confirm when you try to exit IPython with an EOF (Control-D
132 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
132 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
133 you can force a direct exit without any confirmation.""",
133 you can force a direct exit without any confirmation.""",
134 ).tag(config=True)
134 ).tag(config=True)
135
135
136 editing_mode = Unicode('emacs',
136 editing_mode = Unicode('emacs',
137 help="Shortcut style to use at the prompt. 'vi' or 'emacs'.",
137 help="Shortcut style to use at the prompt. 'vi' or 'emacs'.",
138 ).tag(config=True)
138 ).tag(config=True)
139
139
140 emacs_bindings_in_vi_insert_mode = Bool(
141 True,
142 help="Add shortcuts from 'emacs' insert mode to 'vi' insert mode.",
143 ).tag(config=True)
144
140 autoformatter = Unicode(None,
145 autoformatter = Unicode(None,
141 help="Autoformatter to reformat Terminal code. Can be `'black'` or `None`",
146 help="Autoformatter to reformat Terminal code. Can be `'black'` or `None`",
142 allow_none=True
147 allow_none=True
143 ).tag(config=True)
148 ).tag(config=True)
144
149
145 mouse_support = Bool(False,
150 mouse_support = Bool(False,
146 help="Enable mouse support in the prompt\n(Note: prevents selecting text with the mouse)"
151 help="Enable mouse support in the prompt\n(Note: prevents selecting text with the mouse)"
147 ).tag(config=True)
152 ).tag(config=True)
148
153
149 # We don't load the list of styles for the help string, because loading
154 # We don't load the list of styles for the help string, because loading
150 # Pygments plugins takes time and can cause unexpected errors.
155 # Pygments plugins takes time and can cause unexpected errors.
151 highlighting_style = Union([Unicode('legacy'), Type(klass=Style)],
156 highlighting_style = Union([Unicode('legacy'), Type(klass=Style)],
152 help="""The name or class of a Pygments style to use for syntax
157 help="""The name or class of a Pygments style to use for syntax
153 highlighting. To see available styles, run `pygmentize -L styles`."""
158 highlighting. To see available styles, run `pygmentize -L styles`."""
154 ).tag(config=True)
159 ).tag(config=True)
155
160
156 @validate('editing_mode')
161 @validate('editing_mode')
157 def _validate_editing_mode(self, proposal):
162 def _validate_editing_mode(self, proposal):
158 if proposal['value'].lower() == 'vim':
163 if proposal['value'].lower() == 'vim':
159 proposal['value']= 'vi'
164 proposal['value']= 'vi'
160 elif proposal['value'].lower() == 'default':
165 elif proposal['value'].lower() == 'default':
161 proposal['value']= 'emacs'
166 proposal['value']= 'emacs'
162
167
163 if hasattr(EditingMode, proposal['value'].upper()):
168 if hasattr(EditingMode, proposal['value'].upper()):
164 return proposal['value'].lower()
169 return proposal['value'].lower()
165
170
166 return self.editing_mode
171 return self.editing_mode
167
172
168
173
169 @observe('editing_mode')
174 @observe('editing_mode')
170 def _editing_mode(self, change):
175 def _editing_mode(self, change):
171 u_mode = change.new.upper()
176 u_mode = change.new.upper()
172 if self.pt_app:
177 if self.pt_app:
173 self.pt_app.editing_mode = u_mode
178 self.pt_app.editing_mode = u_mode
174
179
175 @observe('autoformatter')
180 @observe('autoformatter')
176 def _autoformatter_changed(self, change):
181 def _autoformatter_changed(self, change):
177 formatter = change.new
182 formatter = change.new
178 if formatter is None:
183 if formatter is None:
179 self.reformat_handler = lambda x:x
184 self.reformat_handler = lambda x:x
180 elif formatter == 'black':
185 elif formatter == 'black':
181 self.reformat_handler = black_reformat_handler
186 self.reformat_handler = black_reformat_handler
182 else:
187 else:
183 raise ValueError
188 raise ValueError
184
189
185 @observe('highlighting_style')
190 @observe('highlighting_style')
186 @observe('colors')
191 @observe('colors')
187 def _highlighting_style_changed(self, change):
192 def _highlighting_style_changed(self, change):
188 self.refresh_style()
193 self.refresh_style()
189
194
190 def refresh_style(self):
195 def refresh_style(self):
191 self._style = self._make_style_from_name_or_cls(self.highlighting_style)
196 self._style = self._make_style_from_name_or_cls(self.highlighting_style)
192
197
193
198
194 highlighting_style_overrides = Dict(
199 highlighting_style_overrides = Dict(
195 help="Override highlighting format for specific tokens"
200 help="Override highlighting format for specific tokens"
196 ).tag(config=True)
201 ).tag(config=True)
197
202
198 true_color = Bool(False,
203 true_color = Bool(False,
199 help=("Use 24bit colors instead of 256 colors in prompt highlighting. "
204 help=("Use 24bit colors instead of 256 colors in prompt highlighting. "
200 "If your terminal supports true color, the following command "
205 "If your terminal supports true color, the following command "
201 "should print 'TRUECOLOR' in orange: "
206 "should print 'TRUECOLOR' in orange: "
202 "printf \"\\x1b[38;2;255;100;0mTRUECOLOR\\x1b[0m\\n\"")
207 "printf \"\\x1b[38;2;255;100;0mTRUECOLOR\\x1b[0m\\n\"")
203 ).tag(config=True)
208 ).tag(config=True)
204
209
205 editor = Unicode(get_default_editor(),
210 editor = Unicode(get_default_editor(),
206 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
211 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
207 ).tag(config=True)
212 ).tag(config=True)
208
213
209 prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True)
214 prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True)
210
215
211 prompts = Instance(Prompts)
216 prompts = Instance(Prompts)
212
217
213 @default('prompts')
218 @default('prompts')
214 def _prompts_default(self):
219 def _prompts_default(self):
215 return self.prompts_class(self)
220 return self.prompts_class(self)
216
221
217 # @observe('prompts')
222 # @observe('prompts')
218 # def _(self, change):
223 # def _(self, change):
219 # self._update_layout()
224 # self._update_layout()
220
225
221 @default('displayhook_class')
226 @default('displayhook_class')
222 def _displayhook_class_default(self):
227 def _displayhook_class_default(self):
223 return RichPromptDisplayHook
228 return RichPromptDisplayHook
224
229
225 term_title = Bool(True,
230 term_title = Bool(True,
226 help="Automatically set the terminal title"
231 help="Automatically set the terminal title"
227 ).tag(config=True)
232 ).tag(config=True)
228
233
229 term_title_format = Unicode("IPython: {cwd}",
234 term_title_format = Unicode("IPython: {cwd}",
230 help="Customize the terminal title format. This is a python format string. " +
235 help="Customize the terminal title format. This is a python format string. " +
231 "Available substitutions are: {cwd}."
236 "Available substitutions are: {cwd}."
232 ).tag(config=True)
237 ).tag(config=True)
233
238
234 display_completions = Enum(('column', 'multicolumn','readlinelike'),
239 display_completions = Enum(('column', 'multicolumn','readlinelike'),
235 help= ( "Options for displaying tab completions, 'column', 'multicolumn', and "
240 help= ( "Options for displaying tab completions, 'column', 'multicolumn', and "
236 "'readlinelike'. These options are for `prompt_toolkit`, see "
241 "'readlinelike'. These options are for `prompt_toolkit`, see "
237 "`prompt_toolkit` documentation for more information."
242 "`prompt_toolkit` documentation for more information."
238 ),
243 ),
239 default_value='multicolumn').tag(config=True)
244 default_value='multicolumn').tag(config=True)
240
245
241 highlight_matching_brackets = Bool(True,
246 highlight_matching_brackets = Bool(True,
242 help="Highlight matching brackets.",
247 help="Highlight matching brackets.",
243 ).tag(config=True)
248 ).tag(config=True)
244
249
245 extra_open_editor_shortcuts = Bool(False,
250 extra_open_editor_shortcuts = Bool(False,
246 help="Enable vi (v) or Emacs (C-X C-E) shortcuts to open an external editor. "
251 help="Enable vi (v) or Emacs (C-X C-E) shortcuts to open an external editor. "
247 "This is in addition to the F2 binding, which is always enabled."
252 "This is in addition to the F2 binding, which is always enabled."
248 ).tag(config=True)
253 ).tag(config=True)
249
254
250 handle_return = Any(None,
255 handle_return = Any(None,
251 help="Provide an alternative handler to be called when the user presses "
256 help="Provide an alternative handler to be called when the user presses "
252 "Return. This is an advanced option intended for debugging, which "
257 "Return. This is an advanced option intended for debugging, which "
253 "may be changed or removed in later releases."
258 "may be changed or removed in later releases."
254 ).tag(config=True)
259 ).tag(config=True)
255
260
256 enable_history_search = Bool(True,
261 enable_history_search = Bool(True,
257 help="Allows to enable/disable the prompt toolkit history search"
262 help="Allows to enable/disable the prompt toolkit history search"
258 ).tag(config=True)
263 ).tag(config=True)
259
264
260 prompt_includes_vi_mode = Bool(True,
265 prompt_includes_vi_mode = Bool(True,
261 help="Display the current vi mode (when using vi editing mode)."
266 help="Display the current vi mode (when using vi editing mode)."
262 ).tag(config=True)
267 ).tag(config=True)
263
268
264 @observe('term_title')
269 @observe('term_title')
265 def init_term_title(self, change=None):
270 def init_term_title(self, change=None):
266 # Enable or disable the terminal title.
271 # Enable or disable the terminal title.
267 if self.term_title:
272 if self.term_title:
268 toggle_set_term_title(True)
273 toggle_set_term_title(True)
269 set_term_title(self.term_title_format.format(cwd=abbrev_cwd()))
274 set_term_title(self.term_title_format.format(cwd=abbrev_cwd()))
270 else:
275 else:
271 toggle_set_term_title(False)
276 toggle_set_term_title(False)
272
277
273 def restore_term_title(self):
278 def restore_term_title(self):
274 if self.term_title:
279 if self.term_title:
275 restore_term_title()
280 restore_term_title()
276
281
277 def init_display_formatter(self):
282 def init_display_formatter(self):
278 super(TerminalInteractiveShell, self).init_display_formatter()
283 super(TerminalInteractiveShell, self).init_display_formatter()
279 # terminal only supports plain text
284 # terminal only supports plain text
280 self.display_formatter.active_types = ['text/plain']
285 self.display_formatter.active_types = ['text/plain']
281 # disable `_ipython_display_`
286 # disable `_ipython_display_`
282 self.display_formatter.ipython_display_formatter.enabled = False
287 self.display_formatter.ipython_display_formatter.enabled = False
283
288
284 def init_prompt_toolkit_cli(self):
289 def init_prompt_toolkit_cli(self):
285 if self.simple_prompt:
290 if self.simple_prompt:
286 # Fall back to plain non-interactive output for tests.
291 # Fall back to plain non-interactive output for tests.
287 # This is very limited.
292 # This is very limited.
288 def prompt():
293 def prompt():
289 prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens())
294 prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens())
290 lines = [input(prompt_text)]
295 lines = [input(prompt_text)]
291 prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens())
296 prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens())
292 while self.check_complete('\n'.join(lines))[0] == 'incomplete':
297 while self.check_complete('\n'.join(lines))[0] == 'incomplete':
293 lines.append( input(prompt_continuation) )
298 lines.append( input(prompt_continuation) )
294 return '\n'.join(lines)
299 return '\n'.join(lines)
295 self.prompt_for_code = prompt
300 self.prompt_for_code = prompt
296 return
301 return
297
302
298 # Set up keyboard shortcuts
303 # Set up keyboard shortcuts
299 key_bindings = create_ipython_shortcuts(self)
304 key_bindings = create_ipython_shortcuts(self)
300
305
301 # Pre-populate history from IPython's history database
306 # Pre-populate history from IPython's history database
302 history = InMemoryHistory()
307 history = InMemoryHistory()
303 last_cell = u""
308 last_cell = u""
304 for __, ___, cell in self.history_manager.get_tail(self.history_load_length,
309 for __, ___, cell in self.history_manager.get_tail(self.history_load_length,
305 include_latest=True):
310 include_latest=True):
306 # Ignore blank lines and consecutive duplicates
311 # Ignore blank lines and consecutive duplicates
307 cell = cell.rstrip()
312 cell = cell.rstrip()
308 if cell and (cell != last_cell):
313 if cell and (cell != last_cell):
309 history.append_string(cell)
314 history.append_string(cell)
310 last_cell = cell
315 last_cell = cell
311
316
312 self._style = self._make_style_from_name_or_cls(self.highlighting_style)
317 self._style = self._make_style_from_name_or_cls(self.highlighting_style)
313 self.style = DynamicStyle(lambda: self._style)
318 self.style = DynamicStyle(lambda: self._style)
314
319
315 editing_mode = getattr(EditingMode, self.editing_mode.upper())
320 editing_mode = getattr(EditingMode, self.editing_mode.upper())
316
321
317 self.pt_loop = asyncio.new_event_loop()
322 self.pt_loop = asyncio.new_event_loop()
318 self.pt_app = PromptSession(
323 self.pt_app = PromptSession(
319 editing_mode=editing_mode,
324 editing_mode=editing_mode,
320 key_bindings=key_bindings,
325 key_bindings=key_bindings,
321 history=history,
326 history=history,
322 completer=IPythonPTCompleter(shell=self),
327 completer=IPythonPTCompleter(shell=self),
323 enable_history_search = self.enable_history_search,
328 enable_history_search = self.enable_history_search,
324 style=self.style,
329 style=self.style,
325 include_default_pygments_style=False,
330 include_default_pygments_style=False,
326 mouse_support=self.mouse_support,
331 mouse_support=self.mouse_support,
327 enable_open_in_editor=self.extra_open_editor_shortcuts,
332 enable_open_in_editor=self.extra_open_editor_shortcuts,
328 color_depth=self.color_depth,
333 color_depth=self.color_depth,
329 tempfile_suffix=".py",
334 tempfile_suffix=".py",
330 **self._extra_prompt_options())
335 **self._extra_prompt_options())
331
336
332 def _make_style_from_name_or_cls(self, name_or_cls):
337 def _make_style_from_name_or_cls(self, name_or_cls):
333 """
338 """
334 Small wrapper that make an IPython compatible style from a style name
339 Small wrapper that make an IPython compatible style from a style name
335
340
336 We need that to add style for prompt ... etc.
341 We need that to add style for prompt ... etc.
337 """
342 """
338 style_overrides = {}
343 style_overrides = {}
339 if name_or_cls == 'legacy':
344 if name_or_cls == 'legacy':
340 legacy = self.colors.lower()
345 legacy = self.colors.lower()
341 if legacy == 'linux':
346 if legacy == 'linux':
342 style_cls = get_style_by_name('monokai')
347 style_cls = get_style_by_name('monokai')
343 style_overrides = _style_overrides_linux
348 style_overrides = _style_overrides_linux
344 elif legacy == 'lightbg':
349 elif legacy == 'lightbg':
345 style_overrides = _style_overrides_light_bg
350 style_overrides = _style_overrides_light_bg
346 style_cls = get_style_by_name('pastie')
351 style_cls = get_style_by_name('pastie')
347 elif legacy == 'neutral':
352 elif legacy == 'neutral':
348 # The default theme needs to be visible on both a dark background
353 # The default theme needs to be visible on both a dark background
349 # and a light background, because we can't tell what the terminal
354 # and a light background, because we can't tell what the terminal
350 # looks like. These tweaks to the default theme help with that.
355 # looks like. These tweaks to the default theme help with that.
351 style_cls = get_style_by_name('default')
356 style_cls = get_style_by_name('default')
352 style_overrides.update({
357 style_overrides.update({
353 Token.Number: '#ansigreen',
358 Token.Number: '#ansigreen',
354 Token.Operator: 'noinherit',
359 Token.Operator: 'noinherit',
355 Token.String: '#ansiyellow',
360 Token.String: '#ansiyellow',
356 Token.Name.Function: '#ansiblue',
361 Token.Name.Function: '#ansiblue',
357 Token.Name.Class: 'bold #ansiblue',
362 Token.Name.Class: 'bold #ansiblue',
358 Token.Name.Namespace: 'bold #ansiblue',
363 Token.Name.Namespace: 'bold #ansiblue',
359 Token.Name.Variable.Magic: '#ansiblue',
364 Token.Name.Variable.Magic: '#ansiblue',
360 Token.Prompt: '#ansigreen',
365 Token.Prompt: '#ansigreen',
361 Token.PromptNum: '#ansibrightgreen bold',
366 Token.PromptNum: '#ansibrightgreen bold',
362 Token.OutPrompt: '#ansired',
367 Token.OutPrompt: '#ansired',
363 Token.OutPromptNum: '#ansibrightred bold',
368 Token.OutPromptNum: '#ansibrightred bold',
364 })
369 })
365
370
366 # Hack: Due to limited color support on the Windows console
371 # Hack: Due to limited color support on the Windows console
367 # the prompt colors will be wrong without this
372 # the prompt colors will be wrong without this
368 if os.name == 'nt':
373 if os.name == 'nt':
369 style_overrides.update({
374 style_overrides.update({
370 Token.Prompt: '#ansidarkgreen',
375 Token.Prompt: '#ansidarkgreen',
371 Token.PromptNum: '#ansigreen bold',
376 Token.PromptNum: '#ansigreen bold',
372 Token.OutPrompt: '#ansidarkred',
377 Token.OutPrompt: '#ansidarkred',
373 Token.OutPromptNum: '#ansired bold',
378 Token.OutPromptNum: '#ansired bold',
374 })
379 })
375 elif legacy =='nocolor':
380 elif legacy =='nocolor':
376 style_cls=_NoStyle
381 style_cls=_NoStyle
377 style_overrides = {}
382 style_overrides = {}
378 else :
383 else :
379 raise ValueError('Got unknown colors: ', legacy)
384 raise ValueError('Got unknown colors: ', legacy)
380 else :
385 else :
381 if isinstance(name_or_cls, str):
386 if isinstance(name_or_cls, str):
382 style_cls = get_style_by_name(name_or_cls)
387 style_cls = get_style_by_name(name_or_cls)
383 else:
388 else:
384 style_cls = name_or_cls
389 style_cls = name_or_cls
385 style_overrides = {
390 style_overrides = {
386 Token.Prompt: '#ansigreen',
391 Token.Prompt: '#ansigreen',
387 Token.PromptNum: '#ansibrightgreen bold',
392 Token.PromptNum: '#ansibrightgreen bold',
388 Token.OutPrompt: '#ansired',
393 Token.OutPrompt: '#ansired',
389 Token.OutPromptNum: '#ansibrightred bold',
394 Token.OutPromptNum: '#ansibrightred bold',
390 }
395 }
391 style_overrides.update(self.highlighting_style_overrides)
396 style_overrides.update(self.highlighting_style_overrides)
392 style = merge_styles([
397 style = merge_styles([
393 style_from_pygments_cls(style_cls),
398 style_from_pygments_cls(style_cls),
394 style_from_pygments_dict(style_overrides),
399 style_from_pygments_dict(style_overrides),
395 ])
400 ])
396
401
397 return style
402 return style
398
403
399 @property
404 @property
400 def pt_complete_style(self):
405 def pt_complete_style(self):
401 return {
406 return {
402 'multicolumn': CompleteStyle.MULTI_COLUMN,
407 'multicolumn': CompleteStyle.MULTI_COLUMN,
403 'column': CompleteStyle.COLUMN,
408 'column': CompleteStyle.COLUMN,
404 'readlinelike': CompleteStyle.READLINE_LIKE,
409 'readlinelike': CompleteStyle.READLINE_LIKE,
405 }[self.display_completions]
410 }[self.display_completions]
406
411
407 @property
412 @property
408 def color_depth(self):
413 def color_depth(self):
409 return (ColorDepth.TRUE_COLOR if self.true_color else None)
414 return (ColorDepth.TRUE_COLOR if self.true_color else None)
410
415
411 def _extra_prompt_options(self):
416 def _extra_prompt_options(self):
412 """
417 """
413 Return the current layout option for the current Terminal InteractiveShell
418 Return the current layout option for the current Terminal InteractiveShell
414 """
419 """
415 def get_message():
420 def get_message():
416 return PygmentsTokens(self.prompts.in_prompt_tokens())
421 return PygmentsTokens(self.prompts.in_prompt_tokens())
417
422
418 if self.editing_mode == 'emacs':
423 if self.editing_mode == 'emacs':
419 # with emacs mode the prompt is (usually) static, so we call only
424 # with emacs mode the prompt is (usually) static, so we call only
420 # the function once. With VI mode it can toggle between [ins] and
425 # the function once. With VI mode it can toggle between [ins] and
421 # [nor] so we can't precompute.
426 # [nor] so we can't precompute.
422 # here I'm going to favor the default keybinding which almost
427 # here I'm going to favor the default keybinding which almost
423 # everybody uses to decrease CPU usage.
428 # everybody uses to decrease CPU usage.
424 # if we have issues with users with custom Prompts we can see how to
429 # if we have issues with users with custom Prompts we can see how to
425 # work around this.
430 # work around this.
426 get_message = get_message()
431 get_message = get_message()
427
432
428 options = {
433 options = {
429 'complete_in_thread': False,
434 'complete_in_thread': False,
430 'lexer':IPythonPTLexer(),
435 'lexer':IPythonPTLexer(),
431 'reserve_space_for_menu':self.space_for_menu,
436 'reserve_space_for_menu':self.space_for_menu,
432 'message': get_message,
437 'message': get_message,
433 'prompt_continuation': (
438 'prompt_continuation': (
434 lambda width, lineno, is_soft_wrap:
439 lambda width, lineno, is_soft_wrap:
435 PygmentsTokens(self.prompts.continuation_prompt_tokens(width))),
440 PygmentsTokens(self.prompts.continuation_prompt_tokens(width))),
436 'multiline': True,
441 'multiline': True,
437 'complete_style': self.pt_complete_style,
442 'complete_style': self.pt_complete_style,
438
443
439 # Highlight matching brackets, but only when this setting is
444 # Highlight matching brackets, but only when this setting is
440 # enabled, and only when the DEFAULT_BUFFER has the focus.
445 # enabled, and only when the DEFAULT_BUFFER has the focus.
441 'input_processors': [ConditionalProcessor(
446 'input_processors': [ConditionalProcessor(
442 processor=HighlightMatchingBracketProcessor(chars='[](){}'),
447 processor=HighlightMatchingBracketProcessor(chars='[](){}'),
443 filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() &
448 filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() &
444 Condition(lambda: self.highlight_matching_brackets))],
449 Condition(lambda: self.highlight_matching_brackets))],
445 }
450 }
446 if not PTK3:
451 if not PTK3:
447 options['inputhook'] = self.inputhook
452 options['inputhook'] = self.inputhook
448
453
449 return options
454 return options
450
455
451 def prompt_for_code(self):
456 def prompt_for_code(self):
452 if self.rl_next_input:
457 if self.rl_next_input:
453 default = self.rl_next_input
458 default = self.rl_next_input
454 self.rl_next_input = None
459 self.rl_next_input = None
455 else:
460 else:
456 default = ''
461 default = ''
457
462
458 # In order to make sure that asyncio code written in the
463 # In order to make sure that asyncio code written in the
459 # interactive shell doesn't interfere with the prompt, we run the
464 # interactive shell doesn't interfere with the prompt, we run the
460 # prompt in a different event loop.
465 # prompt in a different event loop.
461 # If we don't do this, people could spawn coroutine with a
466 # If we don't do this, people could spawn coroutine with a
462 # while/true inside which will freeze the prompt.
467 # while/true inside which will freeze the prompt.
463
468
464 try:
469 try:
465 old_loop = asyncio.get_event_loop()
470 old_loop = asyncio.get_event_loop()
466 except RuntimeError:
471 except RuntimeError:
467 # This happens when the user used `asyncio.run()`.
472 # This happens when the user used `asyncio.run()`.
468 old_loop = None
473 old_loop = None
469
474
470 asyncio.set_event_loop(self.pt_loop)
475 asyncio.set_event_loop(self.pt_loop)
471 try:
476 try:
472 with patch_stdout(raw=True):
477 with patch_stdout(raw=True):
473 text = self.pt_app.prompt(
478 text = self.pt_app.prompt(
474 default=default,
479 default=default,
475 **self._extra_prompt_options())
480 **self._extra_prompt_options())
476 finally:
481 finally:
477 # Restore the original event loop.
482 # Restore the original event loop.
478 asyncio.set_event_loop(old_loop)
483 asyncio.set_event_loop(old_loop)
479
484
480 return text
485 return text
481
486
482 def enable_win_unicode_console(self):
487 def enable_win_unicode_console(self):
483 # Since IPython 7.10 doesn't support python < 3.6 and PEP 528, Python uses the unicode APIs for the Windows
488 # Since IPython 7.10 doesn't support python < 3.6 and PEP 528, Python uses the unicode APIs for the Windows
484 # console by default, so WUC shouldn't be needed.
489 # console by default, so WUC shouldn't be needed.
485 from warnings import warn
490 from warnings import warn
486 warn("`enable_win_unicode_console` is deprecated since IPython 7.10, does not do anything and will be removed in the future",
491 warn("`enable_win_unicode_console` is deprecated since IPython 7.10, does not do anything and will be removed in the future",
487 DeprecationWarning,
492 DeprecationWarning,
488 stacklevel=2)
493 stacklevel=2)
489
494
490 def init_io(self):
495 def init_io(self):
491 if sys.platform not in {'win32', 'cli'}:
496 if sys.platform not in {'win32', 'cli'}:
492 return
497 return
493
498
494 import colorama
499 import colorama
495 colorama.init()
500 colorama.init()
496
501
497 # For some reason we make these wrappers around stdout/stderr.
502 # For some reason we make these wrappers around stdout/stderr.
498 # For now, we need to reset them so all output gets coloured.
503 # For now, we need to reset them so all output gets coloured.
499 # https://github.com/ipython/ipython/issues/8669
504 # https://github.com/ipython/ipython/issues/8669
500 # io.std* are deprecated, but don't show our own deprecation warnings
505 # io.std* are deprecated, but don't show our own deprecation warnings
501 # during initialization of the deprecated API.
506 # during initialization of the deprecated API.
502 with warnings.catch_warnings():
507 with warnings.catch_warnings():
503 warnings.simplefilter('ignore', DeprecationWarning)
508 warnings.simplefilter('ignore', DeprecationWarning)
504 io.stdout = io.IOStream(sys.stdout)
509 io.stdout = io.IOStream(sys.stdout)
505 io.stderr = io.IOStream(sys.stderr)
510 io.stderr = io.IOStream(sys.stderr)
506
511
507 def init_magics(self):
512 def init_magics(self):
508 super(TerminalInteractiveShell, self).init_magics()
513 super(TerminalInteractiveShell, self).init_magics()
509 self.register_magics(TerminalMagics)
514 self.register_magics(TerminalMagics)
510
515
511 def init_alias(self):
516 def init_alias(self):
512 # The parent class defines aliases that can be safely used with any
517 # The parent class defines aliases that can be safely used with any
513 # frontend.
518 # frontend.
514 super(TerminalInteractiveShell, self).init_alias()
519 super(TerminalInteractiveShell, self).init_alias()
515
520
516 # Now define aliases that only make sense on the terminal, because they
521 # Now define aliases that only make sense on the terminal, because they
517 # need direct access to the console in a way that we can't emulate in
522 # need direct access to the console in a way that we can't emulate in
518 # GUI or web frontend
523 # GUI or web frontend
519 if os.name == 'posix':
524 if os.name == 'posix':
520 for cmd in ('clear', 'more', 'less', 'man'):
525 for cmd in ('clear', 'more', 'less', 'man'):
521 self.alias_manager.soft_define_alias(cmd, cmd)
526 self.alias_manager.soft_define_alias(cmd, cmd)
522
527
523
528
524 def __init__(self, *args, **kwargs):
529 def __init__(self, *args, **kwargs):
525 super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
530 super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
526 self.init_prompt_toolkit_cli()
531 self.init_prompt_toolkit_cli()
527 self.init_term_title()
532 self.init_term_title()
528 self.keep_running = True
533 self.keep_running = True
529
534
530 self.debugger_history = InMemoryHistory()
535 self.debugger_history = InMemoryHistory()
531
536
532 def ask_exit(self):
537 def ask_exit(self):
533 self.keep_running = False
538 self.keep_running = False
534
539
535 rl_next_input = None
540 rl_next_input = None
536
541
537 def interact(self, display_banner=DISPLAY_BANNER_DEPRECATED):
542 def interact(self, display_banner=DISPLAY_BANNER_DEPRECATED):
538
543
539 if display_banner is not DISPLAY_BANNER_DEPRECATED:
544 if display_banner is not DISPLAY_BANNER_DEPRECATED:
540 warn('interact `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
545 warn('interact `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
541
546
542 self.keep_running = True
547 self.keep_running = True
543 while self.keep_running:
548 while self.keep_running:
544 print(self.separate_in, end='')
549 print(self.separate_in, end='')
545
550
546 try:
551 try:
547 code = self.prompt_for_code()
552 code = self.prompt_for_code()
548 except EOFError:
553 except EOFError:
549 if (not self.confirm_exit) \
554 if (not self.confirm_exit) \
550 or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
555 or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
551 self.ask_exit()
556 self.ask_exit()
552
557
553 else:
558 else:
554 if code:
559 if code:
555 self.run_cell(code, store_history=True)
560 self.run_cell(code, store_history=True)
556
561
557 def mainloop(self, display_banner=DISPLAY_BANNER_DEPRECATED):
562 def mainloop(self, display_banner=DISPLAY_BANNER_DEPRECATED):
558 # An extra layer of protection in case someone mashing Ctrl-C breaks
563 # An extra layer of protection in case someone mashing Ctrl-C breaks
559 # out of our internal code.
564 # out of our internal code.
560 if display_banner is not DISPLAY_BANNER_DEPRECATED:
565 if display_banner is not DISPLAY_BANNER_DEPRECATED:
561 warn('mainloop `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
566 warn('mainloop `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
562 while True:
567 while True:
563 try:
568 try:
564 self.interact()
569 self.interact()
565 break
570 break
566 except KeyboardInterrupt as e:
571 except KeyboardInterrupt as e:
567 print("\n%s escaped interact()\n" % type(e).__name__)
572 print("\n%s escaped interact()\n" % type(e).__name__)
568 finally:
573 finally:
569 # An interrupt during the eventloop will mess up the
574 # An interrupt during the eventloop will mess up the
570 # internal state of the prompt_toolkit library.
575 # internal state of the prompt_toolkit library.
571 # Stopping the eventloop fixes this, see
576 # Stopping the eventloop fixes this, see
572 # https://github.com/ipython/ipython/pull/9867
577 # https://github.com/ipython/ipython/pull/9867
573 if hasattr(self, '_eventloop'):
578 if hasattr(self, '_eventloop'):
574 self._eventloop.stop()
579 self._eventloop.stop()
575
580
576 self.restore_term_title()
581 self.restore_term_title()
577
582
578
583
579 _inputhook = None
584 _inputhook = None
580 def inputhook(self, context):
585 def inputhook(self, context):
581 if self._inputhook is not None:
586 if self._inputhook is not None:
582 self._inputhook(context)
587 self._inputhook(context)
583
588
584 active_eventloop = None
589 active_eventloop = None
585 def enable_gui(self, gui=None):
590 def enable_gui(self, gui=None):
586 if gui and (gui != 'inline') :
591 if gui and (gui != 'inline') :
587 self.active_eventloop, self._inputhook =\
592 self.active_eventloop, self._inputhook =\
588 get_inputhook_name_and_func(gui)
593 get_inputhook_name_and_func(gui)
589 else:
594 else:
590 self.active_eventloop = self._inputhook = None
595 self.active_eventloop = self._inputhook = None
591
596
592 # For prompt_toolkit 3.0. We have to create an asyncio event loop with
597 # For prompt_toolkit 3.0. We have to create an asyncio event loop with
593 # this inputhook.
598 # this inputhook.
594 if PTK3:
599 if PTK3:
595 import asyncio
600 import asyncio
596 from prompt_toolkit.eventloop import new_eventloop_with_inputhook
601 from prompt_toolkit.eventloop import new_eventloop_with_inputhook
597
602
598 if gui == 'asyncio':
603 if gui == 'asyncio':
599 # When we integrate the asyncio event loop, run the UI in the
604 # When we integrate the asyncio event loop, run the UI in the
600 # same event loop as the rest of the code. don't use an actual
605 # same event loop as the rest of the code. don't use an actual
601 # input hook. (Asyncio is not made for nesting event loops.)
606 # input hook. (Asyncio is not made for nesting event loops.)
602 self.pt_loop = asyncio.get_event_loop()
607 self.pt_loop = asyncio.get_event_loop()
603
608
604 elif self._inputhook:
609 elif self._inputhook:
605 # If an inputhook was set, create a new asyncio event loop with
610 # If an inputhook was set, create a new asyncio event loop with
606 # this inputhook for the prompt.
611 # this inputhook for the prompt.
607 self.pt_loop = new_eventloop_with_inputhook(self._inputhook)
612 self.pt_loop = new_eventloop_with_inputhook(self._inputhook)
608 else:
613 else:
609 # When there's no inputhook, run the prompt in a separate
614 # When there's no inputhook, run the prompt in a separate
610 # asyncio event loop.
615 # asyncio event loop.
611 self.pt_loop = asyncio.new_event_loop()
616 self.pt_loop = asyncio.new_event_loop()
612
617
613 # Run !system commands directly, not through pipes, so terminal programs
618 # Run !system commands directly, not through pipes, so terminal programs
614 # work correctly.
619 # work correctly.
615 system = InteractiveShell.system_raw
620 system = InteractiveShell.system_raw
616
621
617 def auto_rewrite_input(self, cmd):
622 def auto_rewrite_input(self, cmd):
618 """Overridden from the parent class to use fancy rewriting prompt"""
623 """Overridden from the parent class to use fancy rewriting prompt"""
619 if not self.show_rewritten_input:
624 if not self.show_rewritten_input:
620 return
625 return
621
626
622 tokens = self.prompts.rewrite_prompt_tokens()
627 tokens = self.prompts.rewrite_prompt_tokens()
623 if self.pt_app:
628 if self.pt_app:
624 print_formatted_text(PygmentsTokens(tokens), end='',
629 print_formatted_text(PygmentsTokens(tokens), end='',
625 style=self.pt_app.app.style)
630 style=self.pt_app.app.style)
626 print(cmd)
631 print(cmd)
627 else:
632 else:
628 prompt = ''.join(s for t, s in tokens)
633 prompt = ''.join(s for t, s in tokens)
629 print(prompt, cmd, sep='')
634 print(prompt, cmd, sep='')
630
635
631 _prompts_before = None
636 _prompts_before = None
632 def switch_doctest_mode(self, mode):
637 def switch_doctest_mode(self, mode):
633 """Switch prompts to classic for %doctest_mode"""
638 """Switch prompts to classic for %doctest_mode"""
634 if mode:
639 if mode:
635 self._prompts_before = self.prompts
640 self._prompts_before = self.prompts
636 self.prompts = ClassicPrompts(self)
641 self.prompts = ClassicPrompts(self)
637 elif self._prompts_before:
642 elif self._prompts_before:
638 self.prompts = self._prompts_before
643 self.prompts = self._prompts_before
639 self._prompts_before = None
644 self._prompts_before = None
640 # self._update_layout()
645 # self._update_layout()
641
646
642
647
643 InteractiveShellABC.register(TerminalInteractiveShell)
648 InteractiveShellABC.register(TerminalInteractiveShell)
644
649
645 if __name__ == '__main__':
650 if __name__ == '__main__':
646 TerminalInteractiveShell.instance().interact()
651 TerminalInteractiveShell.instance().interact()
@@ -1,276 +1,344 b''
1 """
1 """
2 Module to define and register Terminal IPython shortcuts with
2 Module to define and register Terminal IPython shortcuts with
3 :mod:`prompt_toolkit`
3 :mod:`prompt_toolkit`
4 """
4 """
5
5
6 # Copyright (c) IPython Development Team.
6 # Copyright (c) IPython Development Team.
7 # Distributed under the terms of the Modified BSD License.
7 # Distributed under the terms of the Modified BSD License.
8
8
9 import warnings
9 import warnings
10 import signal
10 import signal
11 import sys
11 import sys
12 from typing import Callable
12 from typing import Callable
13
13
14
14
15 from prompt_toolkit.application.current import get_app
15 from prompt_toolkit.application.current import get_app
16 from prompt_toolkit.enums import DEFAULT_BUFFER, SEARCH_BUFFER
16 from prompt_toolkit.enums import DEFAULT_BUFFER, SEARCH_BUFFER
17 from prompt_toolkit.filters import (has_focus, has_selection, Condition,
17 from prompt_toolkit.filters import (has_focus, has_selection, Condition,
18 vi_insert_mode, emacs_insert_mode, has_completions, vi_mode)
18 vi_insert_mode, emacs_insert_mode, has_completions, vi_mode)
19 from prompt_toolkit.key_binding.bindings.completion import display_completions_like_readline
19 from prompt_toolkit.key_binding.bindings.completion import display_completions_like_readline
20 from prompt_toolkit.key_binding import KeyBindings
20 from prompt_toolkit.key_binding import KeyBindings
21 from prompt_toolkit.key_binding.bindings import named_commands as nc
21
22
22 from IPython.utils.decorators import undoc
23 from IPython.utils.decorators import undoc
23
24
24 @undoc
25 @undoc
25 @Condition
26 @Condition
26 def cursor_in_leading_ws():
27 def cursor_in_leading_ws():
27 before = get_app().current_buffer.document.current_line_before_cursor
28 before = get_app().current_buffer.document.current_line_before_cursor
28 return (not before) or before.isspace()
29 return (not before) or before.isspace()
29
30
30
31
31 def create_ipython_shortcuts(shell):
32 def create_ipython_shortcuts(shell):
32 """Set up the prompt_toolkit keyboard shortcuts for IPython"""
33 """Set up the prompt_toolkit keyboard shortcuts for IPython"""
33
34
34 kb = KeyBindings()
35 kb = KeyBindings()
35 insert_mode = vi_insert_mode | emacs_insert_mode
36 insert_mode = vi_insert_mode | emacs_insert_mode
36
37
37 if getattr(shell, 'handle_return', None):
38 if getattr(shell, 'handle_return', None):
38 return_handler = shell.handle_return(shell)
39 return_handler = shell.handle_return(shell)
39 else:
40 else:
40 return_handler = newline_or_execute_outer(shell)
41 return_handler = newline_or_execute_outer(shell)
41
42
42 kb.add('enter', filter=(has_focus(DEFAULT_BUFFER)
43 kb.add('enter', filter=(has_focus(DEFAULT_BUFFER)
43 & ~has_selection
44 & ~has_selection
44 & insert_mode
45 & insert_mode
45 ))(return_handler)
46 ))(return_handler)
46
47
47 def reformat_and_execute(event):
48 def reformat_and_execute(event):
48 reformat_text_before_cursor(event.current_buffer, event.current_buffer.document, shell)
49 reformat_text_before_cursor(event.current_buffer, event.current_buffer.document, shell)
49 event.current_buffer.validate_and_handle()
50 event.current_buffer.validate_and_handle()
50
51
51 kb.add('escape', 'enter', filter=(has_focus(DEFAULT_BUFFER)
52 kb.add('escape', 'enter', filter=(has_focus(DEFAULT_BUFFER)
52 & ~has_selection
53 & ~has_selection
53 & insert_mode
54 & insert_mode
54 ))(reformat_and_execute)
55 ))(reformat_and_execute)
55
56
56 kb.add('c-\\')(force_exit)
57 kb.add('c-\\')(force_exit)
57
58
58 kb.add('c-p', filter=(vi_insert_mode & has_focus(DEFAULT_BUFFER))
59 kb.add('c-p', filter=(vi_insert_mode & has_focus(DEFAULT_BUFFER))
59 )(previous_history_or_previous_completion)
60 )(previous_history_or_previous_completion)
60
61
61 kb.add('c-n', filter=(vi_insert_mode & has_focus(DEFAULT_BUFFER))
62 kb.add('c-n', filter=(vi_insert_mode & has_focus(DEFAULT_BUFFER))
62 )(next_history_or_next_completion)
63 )(next_history_or_next_completion)
63
64
64 kb.add('c-g', filter=(has_focus(DEFAULT_BUFFER) & has_completions)
65 kb.add('c-g', filter=(has_focus(DEFAULT_BUFFER) & has_completions)
65 )(dismiss_completion)
66 )(dismiss_completion)
66
67
67 kb.add('c-c', filter=has_focus(DEFAULT_BUFFER))(reset_buffer)
68 kb.add('c-c', filter=has_focus(DEFAULT_BUFFER))(reset_buffer)
68
69
69 kb.add('c-c', filter=has_focus(SEARCH_BUFFER))(reset_search_buffer)
70 kb.add('c-c', filter=has_focus(SEARCH_BUFFER))(reset_search_buffer)
70
71
71 supports_suspend = Condition(lambda: hasattr(signal, 'SIGTSTP'))
72 supports_suspend = Condition(lambda: hasattr(signal, 'SIGTSTP'))
72 kb.add('c-z', filter=supports_suspend)(suspend_to_bg)
73 kb.add('c-z', filter=supports_suspend)(suspend_to_bg)
73
74
74 # Ctrl+I == Tab
75 # Ctrl+I == Tab
75 kb.add('tab', filter=(has_focus(DEFAULT_BUFFER)
76 kb.add('tab', filter=(has_focus(DEFAULT_BUFFER)
76 & ~has_selection
77 & ~has_selection
77 & insert_mode
78 & insert_mode
78 & cursor_in_leading_ws
79 & cursor_in_leading_ws
79 ))(indent_buffer)
80 ))(indent_buffer)
80 kb.add('c-o', filter=(has_focus(DEFAULT_BUFFER) & emacs_insert_mode)
81 kb.add('c-o', filter=(has_focus(DEFAULT_BUFFER) & emacs_insert_mode)
81 )(newline_autoindent_outer(shell.input_transformer_manager))
82 )(newline_autoindent_outer(shell.input_transformer_manager))
82
83
83 kb.add('f2', filter=has_focus(DEFAULT_BUFFER))(open_input_in_editor)
84 kb.add('f2', filter=has_focus(DEFAULT_BUFFER))(open_input_in_editor)
84
85
85 if shell.display_completions == 'readlinelike':
86 if shell.display_completions == 'readlinelike':
86 kb.add('c-i', filter=(has_focus(DEFAULT_BUFFER)
87 kb.add('c-i', filter=(has_focus(DEFAULT_BUFFER)
87 & ~has_selection
88 & ~has_selection
88 & insert_mode
89 & insert_mode
89 & ~cursor_in_leading_ws
90 & ~cursor_in_leading_ws
90 ))(display_completions_like_readline)
91 ))(display_completions_like_readline)
91
92
92 if sys.platform == 'win32':
93 if sys.platform == "win32":
93 kb.add('c-v', filter=(has_focus(DEFAULT_BUFFER) & ~vi_mode))(win_paste)
94 kb.add("c-v", filter=(has_focus(DEFAULT_BUFFER) & ~vi_mode))(win_paste)
95
96 @Condition
97 def ebivim():
98 return shell.emacs_bindings_in_vi_insert_mode
99
100 focused_insert = has_focus(DEFAULT_BUFFER) & vi_insert_mode
101
102 # Needed for to accept autosuggestions in vi insert mode
103 @kb.add("c-e", filter=focused_insert & ebivim)
104 def _(event):
105 b = event.current_buffer
106 suggestion = b.suggestion
107 if suggestion:
108 b.insert_text(suggestion.text)
109 else:
110 nc.end_of_line(event)
111
112 @kb.add("c-f", filter=focused_insert & ebivim)
113 def _(event):
114 b = event.current_buffer
115 suggestion = b.suggestion
116 if suggestion:
117 b.insert_text(suggestion.text)
118 else:
119 nc.forward_char(event)
120
121 @kb.add("escape", "f", filter=focused_insert & ebivim)
122 def _(event):
123 b = event.current_buffer
124 suggestion = b.suggestion
125 if suggestion:
126 t = re.split(r"(\S+\s+)", suggestion.text)
127 b.insert_text(next((x for x in t if x), ""))
128 else:
129 nc.forward_word(event)
130
131 # Simple Control keybindings
132 key_cmd_dict = {
133 "c-a": nc.beginning_of_line,
134 "c-b": nc.backward_char,
135 "c-k": nc.kill_line,
136 "c-w": nc.backward_kill_word,
137 "c-y": nc.yank,
138 "c-_": nc.undo,
139 }
140
141 for key, cmd in key_cmd_dict.items():
142 kb.add(key, filter=focused_insert & ebivim)(cmd)
143
144 # Alt and Combo Control keybindings
145 keys_cmd_dict = {
146 # Control Combos
147 ("c-x", "c-e"): nc.edit_and_execute,
148 ("c-x", "e"): nc.edit_and_execute,
149 # Alt
150 ("escape", "b"): nc.backward_word,
151 ("escape", "c"): nc.capitalize_word,
152 ("escape", "d"): nc.kill_word,
153 ("escape", "h"): nc.backward_kill_word,
154 ("escape", "l"): nc.downcase_word,
155 ("escape", "u"): nc.uppercase_word,
156 ("escape", "y"): nc.yank_pop,
157 ("escape", "."): nc.yank_last_arg,
158 }
159
160 for keys, cmd in keys_cmd_dict.items():
161 kb.add(*keys, filter=focused_insert & ebivim)(cmd)
94
162
95 return kb
163 return kb
96
164
97
165
98 def reformat_text_before_cursor(buffer, document, shell):
166 def reformat_text_before_cursor(buffer, document, shell):
99 text = buffer.delete_before_cursor(len(document.text[:document.cursor_position]))
167 text = buffer.delete_before_cursor(len(document.text[:document.cursor_position]))
100 try:
168 try:
101 formatted_text = shell.reformat_handler(text)
169 formatted_text = shell.reformat_handler(text)
102 buffer.insert_text(formatted_text)
170 buffer.insert_text(formatted_text)
103 except Exception as e:
171 except Exception as e:
104 buffer.insert_text(text)
172 buffer.insert_text(text)
105
173
106
174
107 def newline_or_execute_outer(shell):
175 def newline_or_execute_outer(shell):
108
176
109 def newline_or_execute(event):
177 def newline_or_execute(event):
110 """When the user presses return, insert a newline or execute the code."""
178 """When the user presses return, insert a newline or execute the code."""
111 b = event.current_buffer
179 b = event.current_buffer
112 d = b.document
180 d = b.document
113
181
114 if b.complete_state:
182 if b.complete_state:
115 cc = b.complete_state.current_completion
183 cc = b.complete_state.current_completion
116 if cc:
184 if cc:
117 b.apply_completion(cc)
185 b.apply_completion(cc)
118 else:
186 else:
119 b.cancel_completion()
187 b.cancel_completion()
120 return
188 return
121
189
122 # If there's only one line, treat it as if the cursor is at the end.
190 # If there's only one line, treat it as if the cursor is at the end.
123 # See https://github.com/ipython/ipython/issues/10425
191 # See https://github.com/ipython/ipython/issues/10425
124 if d.line_count == 1:
192 if d.line_count == 1:
125 check_text = d.text
193 check_text = d.text
126 else:
194 else:
127 check_text = d.text[:d.cursor_position]
195 check_text = d.text[:d.cursor_position]
128 status, indent = shell.check_complete(check_text)
196 status, indent = shell.check_complete(check_text)
129
197
130 # if all we have after the cursor is whitespace: reformat current text
198 # if all we have after the cursor is whitespace: reformat current text
131 # before cursor
199 # before cursor
132 after_cursor = d.text[d.cursor_position:]
200 after_cursor = d.text[d.cursor_position:]
133 reformatted = False
201 reformatted = False
134 if not after_cursor.strip():
202 if not after_cursor.strip():
135 reformat_text_before_cursor(b, d, shell)
203 reformat_text_before_cursor(b, d, shell)
136 reformatted = True
204 reformatted = True
137 if not (d.on_last_line or
205 if not (d.on_last_line or
138 d.cursor_position_row >= d.line_count - d.empty_line_count_at_the_end()
206 d.cursor_position_row >= d.line_count - d.empty_line_count_at_the_end()
139 ):
207 ):
140 if shell.autoindent:
208 if shell.autoindent:
141 b.insert_text('\n' + indent)
209 b.insert_text('\n' + indent)
142 else:
210 else:
143 b.insert_text('\n')
211 b.insert_text('\n')
144 return
212 return
145
213
146 if (status != 'incomplete') and b.accept_handler:
214 if (status != 'incomplete') and b.accept_handler:
147 if not reformatted:
215 if not reformatted:
148 reformat_text_before_cursor(b, d, shell)
216 reformat_text_before_cursor(b, d, shell)
149 b.validate_and_handle()
217 b.validate_and_handle()
150 else:
218 else:
151 if shell.autoindent:
219 if shell.autoindent:
152 b.insert_text('\n' + indent)
220 b.insert_text('\n' + indent)
153 else:
221 else:
154 b.insert_text('\n')
222 b.insert_text('\n')
155 return newline_or_execute
223 return newline_or_execute
156
224
157
225
158 def previous_history_or_previous_completion(event):
226 def previous_history_or_previous_completion(event):
159 """
227 """
160 Control-P in vi edit mode on readline is history next, unlike default prompt toolkit.
228 Control-P in vi edit mode on readline is history next, unlike default prompt toolkit.
161
229
162 If completer is open this still select previous completion.
230 If completer is open this still select previous completion.
163 """
231 """
164 event.current_buffer.auto_up()
232 event.current_buffer.auto_up()
165
233
166
234
167 def next_history_or_next_completion(event):
235 def next_history_or_next_completion(event):
168 """
236 """
169 Control-N in vi edit mode on readline is history previous, unlike default prompt toolkit.
237 Control-N in vi edit mode on readline is history previous, unlike default prompt toolkit.
170
238
171 If completer is open this still select next completion.
239 If completer is open this still select next completion.
172 """
240 """
173 event.current_buffer.auto_down()
241 event.current_buffer.auto_down()
174
242
175
243
176 def dismiss_completion(event):
244 def dismiss_completion(event):
177 b = event.current_buffer
245 b = event.current_buffer
178 if b.complete_state:
246 if b.complete_state:
179 b.cancel_completion()
247 b.cancel_completion()
180
248
181
249
182 def reset_buffer(event):
250 def reset_buffer(event):
183 b = event.current_buffer
251 b = event.current_buffer
184 if b.complete_state:
252 if b.complete_state:
185 b.cancel_completion()
253 b.cancel_completion()
186 else:
254 else:
187 b.reset()
255 b.reset()
188
256
189
257
190 def reset_search_buffer(event):
258 def reset_search_buffer(event):
191 if event.current_buffer.document.text:
259 if event.current_buffer.document.text:
192 event.current_buffer.reset()
260 event.current_buffer.reset()
193 else:
261 else:
194 event.app.layout.focus(DEFAULT_BUFFER)
262 event.app.layout.focus(DEFAULT_BUFFER)
195
263
196 def suspend_to_bg(event):
264 def suspend_to_bg(event):
197 event.app.suspend_to_background()
265 event.app.suspend_to_background()
198
266
199 def force_exit(event):
267 def force_exit(event):
200 """
268 """
201 Force exit (with a non-zero return value)
269 Force exit (with a non-zero return value)
202 """
270 """
203 sys.exit("Quit")
271 sys.exit("Quit")
204
272
205 def indent_buffer(event):
273 def indent_buffer(event):
206 event.current_buffer.insert_text(' ' * 4)
274 event.current_buffer.insert_text(' ' * 4)
207
275
208 @undoc
276 @undoc
209 def newline_with_copy_margin(event):
277 def newline_with_copy_margin(event):
210 """
278 """
211 DEPRECATED since IPython 6.0
279 DEPRECATED since IPython 6.0
212
280
213 See :any:`newline_autoindent_outer` for a replacement.
281 See :any:`newline_autoindent_outer` for a replacement.
214
282
215 Preserve margin and cursor position when using
283 Preserve margin and cursor position when using
216 Control-O to insert a newline in EMACS mode
284 Control-O to insert a newline in EMACS mode
217 """
285 """
218 warnings.warn("`newline_with_copy_margin(event)` is deprecated since IPython 6.0. "
286 warnings.warn("`newline_with_copy_margin(event)` is deprecated since IPython 6.0. "
219 "see `newline_autoindent_outer(shell)(event)` for a replacement.",
287 "see `newline_autoindent_outer(shell)(event)` for a replacement.",
220 DeprecationWarning, stacklevel=2)
288 DeprecationWarning, stacklevel=2)
221
289
222 b = event.current_buffer
290 b = event.current_buffer
223 cursor_start_pos = b.document.cursor_position_col
291 cursor_start_pos = b.document.cursor_position_col
224 b.newline(copy_margin=True)
292 b.newline(copy_margin=True)
225 b.cursor_up(count=1)
293 b.cursor_up(count=1)
226 cursor_end_pos = b.document.cursor_position_col
294 cursor_end_pos = b.document.cursor_position_col
227 if cursor_start_pos != cursor_end_pos:
295 if cursor_start_pos != cursor_end_pos:
228 pos_diff = cursor_start_pos - cursor_end_pos
296 pos_diff = cursor_start_pos - cursor_end_pos
229 b.cursor_right(count=pos_diff)
297 b.cursor_right(count=pos_diff)
230
298
231 def newline_autoindent_outer(inputsplitter) -> Callable[..., None]:
299 def newline_autoindent_outer(inputsplitter) -> Callable[..., None]:
232 """
300 """
233 Return a function suitable for inserting a indented newline after the cursor.
301 Return a function suitable for inserting a indented newline after the cursor.
234
302
235 Fancier version of deprecated ``newline_with_copy_margin`` which should
303 Fancier version of deprecated ``newline_with_copy_margin`` which should
236 compute the correct indentation of the inserted line. That is to say, indent
304 compute the correct indentation of the inserted line. That is to say, indent
237 by 4 extra space after a function definition, class definition, context
305 by 4 extra space after a function definition, class definition, context
238 manager... And dedent by 4 space after ``pass``, ``return``, ``raise ...``.
306 manager... And dedent by 4 space after ``pass``, ``return``, ``raise ...``.
239 """
307 """
240
308
241 def newline_autoindent(event):
309 def newline_autoindent(event):
242 """insert a newline after the cursor indented appropriately."""
310 """insert a newline after the cursor indented appropriately."""
243 b = event.current_buffer
311 b = event.current_buffer
244 d = b.document
312 d = b.document
245
313
246 if b.complete_state:
314 if b.complete_state:
247 b.cancel_completion()
315 b.cancel_completion()
248 text = d.text[:d.cursor_position] + '\n'
316 text = d.text[:d.cursor_position] + '\n'
249 _, indent = inputsplitter.check_complete(text)
317 _, indent = inputsplitter.check_complete(text)
250 b.insert_text('\n' + (' ' * (indent or 0)), move_cursor=False)
318 b.insert_text('\n' + (' ' * (indent or 0)), move_cursor=False)
251
319
252 return newline_autoindent
320 return newline_autoindent
253
321
254
322
255 def open_input_in_editor(event):
323 def open_input_in_editor(event):
256 event.app.current_buffer.open_in_editor()
324 event.app.current_buffer.open_in_editor()
257
325
258
326
259 if sys.platform == 'win32':
327 if sys.platform == 'win32':
260 from IPython.core.error import TryNext
328 from IPython.core.error import TryNext
261 from IPython.lib.clipboard import (ClipboardEmpty,
329 from IPython.lib.clipboard import (ClipboardEmpty,
262 win32_clipboard_get,
330 win32_clipboard_get,
263 tkinter_clipboard_get)
331 tkinter_clipboard_get)
264
332
265 @undoc
333 @undoc
266 def win_paste(event):
334 def win_paste(event):
267 try:
335 try:
268 text = win32_clipboard_get()
336 text = win32_clipboard_get()
269 except TryNext:
337 except TryNext:
270 try:
338 try:
271 text = tkinter_clipboard_get()
339 text = tkinter_clipboard_get()
272 except (TryNext, ClipboardEmpty):
340 except (TryNext, ClipboardEmpty):
273 return
341 return
274 except ClipboardEmpty:
342 except ClipboardEmpty:
275 return
343 return
276 event.current_buffer.insert_text(text.replace('\t', ' ' * 4))
344 event.current_buffer.insert_text(text.replace('\t', ' ' * 4))
General Comments 0
You need to be logged in to leave comments. Login now