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