##// END OF EJS Templates
Merge pull request #12588 from mskar/vim_cursor...
Matthias Bussonnier -
r26163:40472930 merge
parent child Browse files
Show More
@@ -1,653 +1,683 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 should
235 If your terminal supports true color, the following command should
206 print ``TRUECOLOR`` in orange::
236 print ``TRUECOLOR`` in orange::
207
237
208 printf \"\\x1b[38;2;255;100;0mTRUECOLOR\\x1b[0m\\n\"
238 printf \"\\x1b[38;2;255;100;0mTRUECOLOR\\x1b[0m\\n\"
209 """,
239 """,
210 ).tag(config=True)
240 ).tag(config=True)
211
241
212 editor = Unicode(get_default_editor(),
242 editor = Unicode(get_default_editor(),
213 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
243 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
214 ).tag(config=True)
244 ).tag(config=True)
215
245
216 prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True)
246 prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True)
217
247
218 prompts = Instance(Prompts)
248 prompts = Instance(Prompts)
219
249
220 @default('prompts')
250 @default('prompts')
221 def _prompts_default(self):
251 def _prompts_default(self):
222 return self.prompts_class(self)
252 return self.prompts_class(self)
223
253
224 # @observe('prompts')
254 # @observe('prompts')
225 # def _(self, change):
255 # def _(self, change):
226 # self._update_layout()
256 # self._update_layout()
227
257
228 @default('displayhook_class')
258 @default('displayhook_class')
229 def _displayhook_class_default(self):
259 def _displayhook_class_default(self):
230 return RichPromptDisplayHook
260 return RichPromptDisplayHook
231
261
232 term_title = Bool(True,
262 term_title = Bool(True,
233 help="Automatically set the terminal title"
263 help="Automatically set the terminal title"
234 ).tag(config=True)
264 ).tag(config=True)
235
265
236 term_title_format = Unicode("IPython: {cwd}",
266 term_title_format = Unicode("IPython: {cwd}",
237 help="Customize the terminal title format. This is a python format string. " +
267 help="Customize the terminal title format. This is a python format string. " +
238 "Available substitutions are: {cwd}."
268 "Available substitutions are: {cwd}."
239 ).tag(config=True)
269 ).tag(config=True)
240
270
241 display_completions = Enum(('column', 'multicolumn','readlinelike'),
271 display_completions = Enum(('column', 'multicolumn','readlinelike'),
242 help= ( "Options for displaying tab completions, 'column', 'multicolumn', and "
272 help= ( "Options for displaying tab completions, 'column', 'multicolumn', and "
243 "'readlinelike'. These options are for `prompt_toolkit`, see "
273 "'readlinelike'. These options are for `prompt_toolkit`, see "
244 "`prompt_toolkit` documentation for more information."
274 "`prompt_toolkit` documentation for more information."
245 ),
275 ),
246 default_value='multicolumn').tag(config=True)
276 default_value='multicolumn').tag(config=True)
247
277
248 highlight_matching_brackets = Bool(True,
278 highlight_matching_brackets = Bool(True,
249 help="Highlight matching brackets.",
279 help="Highlight matching brackets.",
250 ).tag(config=True)
280 ).tag(config=True)
251
281
252 extra_open_editor_shortcuts = Bool(False,
282 extra_open_editor_shortcuts = Bool(False,
253 help="Enable vi (v) or Emacs (C-X C-E) shortcuts to open an external editor. "
283 help="Enable vi (v) or Emacs (C-X C-E) shortcuts to open an external editor. "
254 "This is in addition to the F2 binding, which is always enabled."
284 "This is in addition to the F2 binding, which is always enabled."
255 ).tag(config=True)
285 ).tag(config=True)
256
286
257 handle_return = Any(None,
287 handle_return = Any(None,
258 help="Provide an alternative handler to be called when the user presses "
288 help="Provide an alternative handler to be called when the user presses "
259 "Return. This is an advanced option intended for debugging, which "
289 "Return. This is an advanced option intended for debugging, which "
260 "may be changed or removed in later releases."
290 "may be changed or removed in later releases."
261 ).tag(config=True)
291 ).tag(config=True)
262
292
263 enable_history_search = Bool(True,
293 enable_history_search = Bool(True,
264 help="Allows to enable/disable the prompt toolkit history search"
294 help="Allows to enable/disable the prompt toolkit history search"
265 ).tag(config=True)
295 ).tag(config=True)
266
296
267 prompt_includes_vi_mode = Bool(True,
297 prompt_includes_vi_mode = Bool(True,
268 help="Display the current vi mode (when using vi editing mode)."
298 help="Display the current vi mode (when using vi editing mode)."
269 ).tag(config=True)
299 ).tag(config=True)
270
300
271 @observe('term_title')
301 @observe('term_title')
272 def init_term_title(self, change=None):
302 def init_term_title(self, change=None):
273 # Enable or disable the terminal title.
303 # Enable or disable the terminal title.
274 if self.term_title:
304 if self.term_title:
275 toggle_set_term_title(True)
305 toggle_set_term_title(True)
276 set_term_title(self.term_title_format.format(cwd=abbrev_cwd()))
306 set_term_title(self.term_title_format.format(cwd=abbrev_cwd()))
277 else:
307 else:
278 toggle_set_term_title(False)
308 toggle_set_term_title(False)
279
309
280 def restore_term_title(self):
310 def restore_term_title(self):
281 if self.term_title:
311 if self.term_title:
282 restore_term_title()
312 restore_term_title()
283
313
284 def init_display_formatter(self):
314 def init_display_formatter(self):
285 super(TerminalInteractiveShell, self).init_display_formatter()
315 super(TerminalInteractiveShell, self).init_display_formatter()
286 # terminal only supports plain text
316 # terminal only supports plain text
287 self.display_formatter.active_types = ['text/plain']
317 self.display_formatter.active_types = ['text/plain']
288 # disable `_ipython_display_`
318 # disable `_ipython_display_`
289 self.display_formatter.ipython_display_formatter.enabled = False
319 self.display_formatter.ipython_display_formatter.enabled = False
290
320
291 def init_prompt_toolkit_cli(self):
321 def init_prompt_toolkit_cli(self):
292 if self.simple_prompt:
322 if self.simple_prompt:
293 # Fall back to plain non-interactive output for tests.
323 # Fall back to plain non-interactive output for tests.
294 # This is very limited.
324 # This is very limited.
295 def prompt():
325 def prompt():
296 prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens())
326 prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens())
297 lines = [input(prompt_text)]
327 lines = [input(prompt_text)]
298 prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens())
328 prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens())
299 while self.check_complete('\n'.join(lines))[0] == 'incomplete':
329 while self.check_complete('\n'.join(lines))[0] == 'incomplete':
300 lines.append( input(prompt_continuation) )
330 lines.append( input(prompt_continuation) )
301 return '\n'.join(lines)
331 return '\n'.join(lines)
302 self.prompt_for_code = prompt
332 self.prompt_for_code = prompt
303 return
333 return
304
334
305 # Set up keyboard shortcuts
335 # Set up keyboard shortcuts
306 key_bindings = create_ipython_shortcuts(self)
336 key_bindings = create_ipython_shortcuts(self)
307
337
308 # Pre-populate history from IPython's history database
338 # Pre-populate history from IPython's history database
309 history = InMemoryHistory()
339 history = InMemoryHistory()
310 last_cell = u""
340 last_cell = u""
311 for __, ___, cell in self.history_manager.get_tail(self.history_load_length,
341 for __, ___, cell in self.history_manager.get_tail(self.history_load_length,
312 include_latest=True):
342 include_latest=True):
313 # Ignore blank lines and consecutive duplicates
343 # Ignore blank lines and consecutive duplicates
314 cell = cell.rstrip()
344 cell = cell.rstrip()
315 if cell and (cell != last_cell):
345 if cell and (cell != last_cell):
316 history.append_string(cell)
346 history.append_string(cell)
317 last_cell = cell
347 last_cell = cell
318
348
319 self._style = self._make_style_from_name_or_cls(self.highlighting_style)
349 self._style = self._make_style_from_name_or_cls(self.highlighting_style)
320 self.style = DynamicStyle(lambda: self._style)
350 self.style = DynamicStyle(lambda: self._style)
321
351
322 editing_mode = getattr(EditingMode, self.editing_mode.upper())
352 editing_mode = getattr(EditingMode, self.editing_mode.upper())
323
353
324 self.pt_loop = asyncio.new_event_loop()
354 self.pt_loop = asyncio.new_event_loop()
325 self.pt_app = PromptSession(
355 self.pt_app = PromptSession(
326 editing_mode=editing_mode,
356 editing_mode=editing_mode,
327 key_bindings=key_bindings,
357 key_bindings=key_bindings,
328 history=history,
358 history=history,
329 completer=IPythonPTCompleter(shell=self),
359 completer=IPythonPTCompleter(shell=self),
330 enable_history_search = self.enable_history_search,
360 enable_history_search = self.enable_history_search,
331 style=self.style,
361 style=self.style,
332 include_default_pygments_style=False,
362 include_default_pygments_style=False,
333 mouse_support=self.mouse_support,
363 mouse_support=self.mouse_support,
334 enable_open_in_editor=self.extra_open_editor_shortcuts,
364 enable_open_in_editor=self.extra_open_editor_shortcuts,
335 color_depth=self.color_depth,
365 color_depth=self.color_depth,
336 tempfile_suffix=".py",
366 tempfile_suffix=".py",
337 **self._extra_prompt_options())
367 **self._extra_prompt_options())
338
368
339 def _make_style_from_name_or_cls(self, name_or_cls):
369 def _make_style_from_name_or_cls(self, name_or_cls):
340 """
370 """
341 Small wrapper that make an IPython compatible style from a style name
371 Small wrapper that make an IPython compatible style from a style name
342
372
343 We need that to add style for prompt ... etc.
373 We need that to add style for prompt ... etc.
344 """
374 """
345 style_overrides = {}
375 style_overrides = {}
346 if name_or_cls == 'legacy':
376 if name_or_cls == 'legacy':
347 legacy = self.colors.lower()
377 legacy = self.colors.lower()
348 if legacy == 'linux':
378 if legacy == 'linux':
349 style_cls = get_style_by_name('monokai')
379 style_cls = get_style_by_name('monokai')
350 style_overrides = _style_overrides_linux
380 style_overrides = _style_overrides_linux
351 elif legacy == 'lightbg':
381 elif legacy == 'lightbg':
352 style_overrides = _style_overrides_light_bg
382 style_overrides = _style_overrides_light_bg
353 style_cls = get_style_by_name('pastie')
383 style_cls = get_style_by_name('pastie')
354 elif legacy == 'neutral':
384 elif legacy == 'neutral':
355 # The default theme needs to be visible on both a dark background
385 # The default theme needs to be visible on both a dark background
356 # and a light background, because we can't tell what the terminal
386 # and a light background, because we can't tell what the terminal
357 # looks like. These tweaks to the default theme help with that.
387 # looks like. These tweaks to the default theme help with that.
358 style_cls = get_style_by_name('default')
388 style_cls = get_style_by_name('default')
359 style_overrides.update({
389 style_overrides.update({
360 Token.Number: '#ansigreen',
390 Token.Number: '#ansigreen',
361 Token.Operator: 'noinherit',
391 Token.Operator: 'noinherit',
362 Token.String: '#ansiyellow',
392 Token.String: '#ansiyellow',
363 Token.Name.Function: '#ansiblue',
393 Token.Name.Function: '#ansiblue',
364 Token.Name.Class: 'bold #ansiblue',
394 Token.Name.Class: 'bold #ansiblue',
365 Token.Name.Namespace: 'bold #ansiblue',
395 Token.Name.Namespace: 'bold #ansiblue',
366 Token.Name.Variable.Magic: '#ansiblue',
396 Token.Name.Variable.Magic: '#ansiblue',
367 Token.Prompt: '#ansigreen',
397 Token.Prompt: '#ansigreen',
368 Token.PromptNum: '#ansibrightgreen bold',
398 Token.PromptNum: '#ansibrightgreen bold',
369 Token.OutPrompt: '#ansired',
399 Token.OutPrompt: '#ansired',
370 Token.OutPromptNum: '#ansibrightred bold',
400 Token.OutPromptNum: '#ansibrightred bold',
371 })
401 })
372
402
373 # Hack: Due to limited color support on the Windows console
403 # Hack: Due to limited color support on the Windows console
374 # the prompt colors will be wrong without this
404 # the prompt colors will be wrong without this
375 if os.name == 'nt':
405 if os.name == 'nt':
376 style_overrides.update({
406 style_overrides.update({
377 Token.Prompt: '#ansidarkgreen',
407 Token.Prompt: '#ansidarkgreen',
378 Token.PromptNum: '#ansigreen bold',
408 Token.PromptNum: '#ansigreen bold',
379 Token.OutPrompt: '#ansidarkred',
409 Token.OutPrompt: '#ansidarkred',
380 Token.OutPromptNum: '#ansired bold',
410 Token.OutPromptNum: '#ansired bold',
381 })
411 })
382 elif legacy =='nocolor':
412 elif legacy =='nocolor':
383 style_cls=_NoStyle
413 style_cls=_NoStyle
384 style_overrides = {}
414 style_overrides = {}
385 else :
415 else :
386 raise ValueError('Got unknown colors: ', legacy)
416 raise ValueError('Got unknown colors: ', legacy)
387 else :
417 else :
388 if isinstance(name_or_cls, str):
418 if isinstance(name_or_cls, str):
389 style_cls = get_style_by_name(name_or_cls)
419 style_cls = get_style_by_name(name_or_cls)
390 else:
420 else:
391 style_cls = name_or_cls
421 style_cls = name_or_cls
392 style_overrides = {
422 style_overrides = {
393 Token.Prompt: '#ansigreen',
423 Token.Prompt: '#ansigreen',
394 Token.PromptNum: '#ansibrightgreen bold',
424 Token.PromptNum: '#ansibrightgreen bold',
395 Token.OutPrompt: '#ansired',
425 Token.OutPrompt: '#ansired',
396 Token.OutPromptNum: '#ansibrightred bold',
426 Token.OutPromptNum: '#ansibrightred bold',
397 }
427 }
398 style_overrides.update(self.highlighting_style_overrides)
428 style_overrides.update(self.highlighting_style_overrides)
399 style = merge_styles([
429 style = merge_styles([
400 style_from_pygments_cls(style_cls),
430 style_from_pygments_cls(style_cls),
401 style_from_pygments_dict(style_overrides),
431 style_from_pygments_dict(style_overrides),
402 ])
432 ])
403
433
404 return style
434 return style
405
435
406 @property
436 @property
407 def pt_complete_style(self):
437 def pt_complete_style(self):
408 return {
438 return {
409 'multicolumn': CompleteStyle.MULTI_COLUMN,
439 'multicolumn': CompleteStyle.MULTI_COLUMN,
410 'column': CompleteStyle.COLUMN,
440 'column': CompleteStyle.COLUMN,
411 'readlinelike': CompleteStyle.READLINE_LIKE,
441 'readlinelike': CompleteStyle.READLINE_LIKE,
412 }[self.display_completions]
442 }[self.display_completions]
413
443
414 @property
444 @property
415 def color_depth(self):
445 def color_depth(self):
416 return (ColorDepth.TRUE_COLOR if self.true_color else None)
446 return (ColorDepth.TRUE_COLOR if self.true_color else None)
417
447
418 def _extra_prompt_options(self):
448 def _extra_prompt_options(self):
419 """
449 """
420 Return the current layout option for the current Terminal InteractiveShell
450 Return the current layout option for the current Terminal InteractiveShell
421 """
451 """
422 def get_message():
452 def get_message():
423 return PygmentsTokens(self.prompts.in_prompt_tokens())
453 return PygmentsTokens(self.prompts.in_prompt_tokens())
424
454
425 if self.editing_mode == 'emacs':
455 if self.editing_mode == 'emacs':
426 # with emacs mode the prompt is (usually) static, so we call only
456 # with emacs mode the prompt is (usually) static, so we call only
427 # the function once. With VI mode it can toggle between [ins] and
457 # the function once. With VI mode it can toggle between [ins] and
428 # [nor] so we can't precompute.
458 # [nor] so we can't precompute.
429 # here I'm going to favor the default keybinding which almost
459 # here I'm going to favor the default keybinding which almost
430 # everybody uses to decrease CPU usage.
460 # everybody uses to decrease CPU usage.
431 # if we have issues with users with custom Prompts we can see how to
461 # if we have issues with users with custom Prompts we can see how to
432 # work around this.
462 # work around this.
433 get_message = get_message()
463 get_message = get_message()
434
464
435 options = {
465 options = {
436 'complete_in_thread': False,
466 'complete_in_thread': False,
437 'lexer':IPythonPTLexer(),
467 'lexer':IPythonPTLexer(),
438 'reserve_space_for_menu':self.space_for_menu,
468 'reserve_space_for_menu':self.space_for_menu,
439 'message': get_message,
469 'message': get_message,
440 'prompt_continuation': (
470 'prompt_continuation': (
441 lambda width, lineno, is_soft_wrap:
471 lambda width, lineno, is_soft_wrap:
442 PygmentsTokens(self.prompts.continuation_prompt_tokens(width))),
472 PygmentsTokens(self.prompts.continuation_prompt_tokens(width))),
443 'multiline': True,
473 'multiline': True,
444 'complete_style': self.pt_complete_style,
474 'complete_style': self.pt_complete_style,
445
475
446 # Highlight matching brackets, but only when this setting is
476 # Highlight matching brackets, but only when this setting is
447 # enabled, and only when the DEFAULT_BUFFER has the focus.
477 # enabled, and only when the DEFAULT_BUFFER has the focus.
448 'input_processors': [ConditionalProcessor(
478 'input_processors': [ConditionalProcessor(
449 processor=HighlightMatchingBracketProcessor(chars='[](){}'),
479 processor=HighlightMatchingBracketProcessor(chars='[](){}'),
450 filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() &
480 filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() &
451 Condition(lambda: self.highlight_matching_brackets))],
481 Condition(lambda: self.highlight_matching_brackets))],
452 }
482 }
453 if not PTK3:
483 if not PTK3:
454 options['inputhook'] = self.inputhook
484 options['inputhook'] = self.inputhook
455
485
456 return options
486 return options
457
487
458 def prompt_for_code(self):
488 def prompt_for_code(self):
459 if self.rl_next_input:
489 if self.rl_next_input:
460 default = self.rl_next_input
490 default = self.rl_next_input
461 self.rl_next_input = None
491 self.rl_next_input = None
462 else:
492 else:
463 default = ''
493 default = ''
464
494
465 # In order to make sure that asyncio code written in the
495 # In order to make sure that asyncio code written in the
466 # interactive shell doesn't interfere with the prompt, we run the
496 # interactive shell doesn't interfere with the prompt, we run the
467 # prompt in a different event loop.
497 # prompt in a different event loop.
468 # If we don't do this, people could spawn coroutine with a
498 # If we don't do this, people could spawn coroutine with a
469 # while/true inside which will freeze the prompt.
499 # while/true inside which will freeze the prompt.
470
500
471 try:
501 try:
472 old_loop = asyncio.get_event_loop()
502 old_loop = asyncio.get_event_loop()
473 except RuntimeError:
503 except RuntimeError:
474 # This happens when the user used `asyncio.run()`.
504 # This happens when the user used `asyncio.run()`.
475 old_loop = None
505 old_loop = None
476
506
477 asyncio.set_event_loop(self.pt_loop)
507 asyncio.set_event_loop(self.pt_loop)
478 try:
508 try:
479 with patch_stdout(raw=True):
509 with patch_stdout(raw=True):
480 text = self.pt_app.prompt(
510 text = self.pt_app.prompt(
481 default=default,
511 default=default,
482 **self._extra_prompt_options())
512 **self._extra_prompt_options())
483 finally:
513 finally:
484 # Restore the original event loop.
514 # Restore the original event loop.
485 asyncio.set_event_loop(old_loop)
515 asyncio.set_event_loop(old_loop)
486
516
487 return text
517 return text
488
518
489 def enable_win_unicode_console(self):
519 def enable_win_unicode_console(self):
490 # Since IPython 7.10 doesn't support python < 3.6 and PEP 528, Python uses the unicode APIs for the Windows
520 # Since IPython 7.10 doesn't support python < 3.6 and PEP 528, Python uses the unicode APIs for the Windows
491 # console by default, so WUC shouldn't be needed.
521 # console by default, so WUC shouldn't be needed.
492 from warnings import warn
522 from warnings import warn
493 warn("`enable_win_unicode_console` is deprecated since IPython 7.10, does not do anything and will be removed in the future",
523 warn("`enable_win_unicode_console` is deprecated since IPython 7.10, does not do anything and will be removed in the future",
494 DeprecationWarning,
524 DeprecationWarning,
495 stacklevel=2)
525 stacklevel=2)
496
526
497 def init_io(self):
527 def init_io(self):
498 if sys.platform not in {'win32', 'cli'}:
528 if sys.platform not in {'win32', 'cli'}:
499 return
529 return
500
530
501 import colorama
531 import colorama
502 colorama.init()
532 colorama.init()
503
533
504 # For some reason we make these wrappers around stdout/stderr.
534 # For some reason we make these wrappers around stdout/stderr.
505 # For now, we need to reset them so all output gets coloured.
535 # For now, we need to reset them so all output gets coloured.
506 # https://github.com/ipython/ipython/issues/8669
536 # https://github.com/ipython/ipython/issues/8669
507 # io.std* are deprecated, but don't show our own deprecation warnings
537 # io.std* are deprecated, but don't show our own deprecation warnings
508 # during initialization of the deprecated API.
538 # during initialization of the deprecated API.
509 with warnings.catch_warnings():
539 with warnings.catch_warnings():
510 warnings.simplefilter('ignore', DeprecationWarning)
540 warnings.simplefilter('ignore', DeprecationWarning)
511 io.stdout = io.IOStream(sys.stdout)
541 io.stdout = io.IOStream(sys.stdout)
512 io.stderr = io.IOStream(sys.stderr)
542 io.stderr = io.IOStream(sys.stderr)
513
543
514 def init_magics(self):
544 def init_magics(self):
515 super(TerminalInteractiveShell, self).init_magics()
545 super(TerminalInteractiveShell, self).init_magics()
516 self.register_magics(TerminalMagics)
546 self.register_magics(TerminalMagics)
517
547
518 def init_alias(self):
548 def init_alias(self):
519 # The parent class defines aliases that can be safely used with any
549 # The parent class defines aliases that can be safely used with any
520 # frontend.
550 # frontend.
521 super(TerminalInteractiveShell, self).init_alias()
551 super(TerminalInteractiveShell, self).init_alias()
522
552
523 # Now define aliases that only make sense on the terminal, because they
553 # Now define aliases that only make sense on the terminal, because they
524 # need direct access to the console in a way that we can't emulate in
554 # need direct access to the console in a way that we can't emulate in
525 # GUI or web frontend
555 # GUI or web frontend
526 if os.name == 'posix':
556 if os.name == 'posix':
527 for cmd in ('clear', 'more', 'less', 'man'):
557 for cmd in ('clear', 'more', 'less', 'man'):
528 self.alias_manager.soft_define_alias(cmd, cmd)
558 self.alias_manager.soft_define_alias(cmd, cmd)
529
559
530
560
531 def __init__(self, *args, **kwargs):
561 def __init__(self, *args, **kwargs):
532 super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
562 super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
533 self.init_prompt_toolkit_cli()
563 self.init_prompt_toolkit_cli()
534 self.init_term_title()
564 self.init_term_title()
535 self.keep_running = True
565 self.keep_running = True
536
566
537 self.debugger_history = InMemoryHistory()
567 self.debugger_history = InMemoryHistory()
538
568
539 def ask_exit(self):
569 def ask_exit(self):
540 self.keep_running = False
570 self.keep_running = False
541
571
542 rl_next_input = None
572 rl_next_input = None
543
573
544 def interact(self, display_banner=DISPLAY_BANNER_DEPRECATED):
574 def interact(self, display_banner=DISPLAY_BANNER_DEPRECATED):
545
575
546 if display_banner is not DISPLAY_BANNER_DEPRECATED:
576 if display_banner is not DISPLAY_BANNER_DEPRECATED:
547 warn('interact `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
577 warn('interact `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
548
578
549 self.keep_running = True
579 self.keep_running = True
550 while self.keep_running:
580 while self.keep_running:
551 print(self.separate_in, end='')
581 print(self.separate_in, end='')
552
582
553 try:
583 try:
554 code = self.prompt_for_code()
584 code = self.prompt_for_code()
555 except EOFError:
585 except EOFError:
556 if (not self.confirm_exit) \
586 if (not self.confirm_exit) \
557 or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
587 or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
558 self.ask_exit()
588 self.ask_exit()
559
589
560 else:
590 else:
561 if code:
591 if code:
562 self.run_cell(code, store_history=True)
592 self.run_cell(code, store_history=True)
563
593
564 def mainloop(self, display_banner=DISPLAY_BANNER_DEPRECATED):
594 def mainloop(self, display_banner=DISPLAY_BANNER_DEPRECATED):
565 # An extra layer of protection in case someone mashing Ctrl-C breaks
595 # An extra layer of protection in case someone mashing Ctrl-C breaks
566 # out of our internal code.
596 # out of our internal code.
567 if display_banner is not DISPLAY_BANNER_DEPRECATED:
597 if display_banner is not DISPLAY_BANNER_DEPRECATED:
568 warn('mainloop `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
598 warn('mainloop `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
569 while True:
599 while True:
570 try:
600 try:
571 self.interact()
601 self.interact()
572 break
602 break
573 except KeyboardInterrupt as e:
603 except KeyboardInterrupt as e:
574 print("\n%s escaped interact()\n" % type(e).__name__)
604 print("\n%s escaped interact()\n" % type(e).__name__)
575 finally:
605 finally:
576 # An interrupt during the eventloop will mess up the
606 # An interrupt during the eventloop will mess up the
577 # internal state of the prompt_toolkit library.
607 # internal state of the prompt_toolkit library.
578 # Stopping the eventloop fixes this, see
608 # Stopping the eventloop fixes this, see
579 # https://github.com/ipython/ipython/pull/9867
609 # https://github.com/ipython/ipython/pull/9867
580 if hasattr(self, '_eventloop'):
610 if hasattr(self, '_eventloop'):
581 self._eventloop.stop()
611 self._eventloop.stop()
582
612
583 self.restore_term_title()
613 self.restore_term_title()
584
614
585
615
586 _inputhook = None
616 _inputhook = None
587 def inputhook(self, context):
617 def inputhook(self, context):
588 if self._inputhook is not None:
618 if self._inputhook is not None:
589 self._inputhook(context)
619 self._inputhook(context)
590
620
591 active_eventloop = None
621 active_eventloop = None
592 def enable_gui(self, gui=None):
622 def enable_gui(self, gui=None):
593 if gui and (gui != 'inline') :
623 if gui and (gui != 'inline') :
594 self.active_eventloop, self._inputhook =\
624 self.active_eventloop, self._inputhook =\
595 get_inputhook_name_and_func(gui)
625 get_inputhook_name_and_func(gui)
596 else:
626 else:
597 self.active_eventloop = self._inputhook = None
627 self.active_eventloop = self._inputhook = None
598
628
599 # For prompt_toolkit 3.0. We have to create an asyncio event loop with
629 # For prompt_toolkit 3.0. We have to create an asyncio event loop with
600 # this inputhook.
630 # this inputhook.
601 if PTK3:
631 if PTK3:
602 import asyncio
632 import asyncio
603 from prompt_toolkit.eventloop import new_eventloop_with_inputhook
633 from prompt_toolkit.eventloop import new_eventloop_with_inputhook
604
634
605 if gui == 'asyncio':
635 if gui == 'asyncio':
606 # When we integrate the asyncio event loop, run the UI in the
636 # When we integrate the asyncio event loop, run the UI in the
607 # same event loop as the rest of the code. don't use an actual
637 # same event loop as the rest of the code. don't use an actual
608 # input hook. (Asyncio is not made for nesting event loops.)
638 # input hook. (Asyncio is not made for nesting event loops.)
609 self.pt_loop = asyncio.get_event_loop()
639 self.pt_loop = asyncio.get_event_loop()
610
640
611 elif self._inputhook:
641 elif self._inputhook:
612 # If an inputhook was set, create a new asyncio event loop with
642 # If an inputhook was set, create a new asyncio event loop with
613 # this inputhook for the prompt.
643 # this inputhook for the prompt.
614 self.pt_loop = new_eventloop_with_inputhook(self._inputhook)
644 self.pt_loop = new_eventloop_with_inputhook(self._inputhook)
615 else:
645 else:
616 # When there's no inputhook, run the prompt in a separate
646 # When there's no inputhook, run the prompt in a separate
617 # asyncio event loop.
647 # asyncio event loop.
618 self.pt_loop = asyncio.new_event_loop()
648 self.pt_loop = asyncio.new_event_loop()
619
649
620 # Run !system commands directly, not through pipes, so terminal programs
650 # Run !system commands directly, not through pipes, so terminal programs
621 # work correctly.
651 # work correctly.
622 system = InteractiveShell.system_raw
652 system = InteractiveShell.system_raw
623
653
624 def auto_rewrite_input(self, cmd):
654 def auto_rewrite_input(self, cmd):
625 """Overridden from the parent class to use fancy rewriting prompt"""
655 """Overridden from the parent class to use fancy rewriting prompt"""
626 if not self.show_rewritten_input:
656 if not self.show_rewritten_input:
627 return
657 return
628
658
629 tokens = self.prompts.rewrite_prompt_tokens()
659 tokens = self.prompts.rewrite_prompt_tokens()
630 if self.pt_app:
660 if self.pt_app:
631 print_formatted_text(PygmentsTokens(tokens), end='',
661 print_formatted_text(PygmentsTokens(tokens), end='',
632 style=self.pt_app.app.style)
662 style=self.pt_app.app.style)
633 print(cmd)
663 print(cmd)
634 else:
664 else:
635 prompt = ''.join(s for t, s in tokens)
665 prompt = ''.join(s for t, s in tokens)
636 print(prompt, cmd, sep='')
666 print(prompt, cmd, sep='')
637
667
638 _prompts_before = None
668 _prompts_before = None
639 def switch_doctest_mode(self, mode):
669 def switch_doctest_mode(self, mode):
640 """Switch prompts to classic for %doctest_mode"""
670 """Switch prompts to classic for %doctest_mode"""
641 if mode:
671 if mode:
642 self._prompts_before = self.prompts
672 self._prompts_before = self.prompts
643 self.prompts = ClassicPrompts(self)
673 self.prompts = ClassicPrompts(self)
644 elif self._prompts_before:
674 elif self._prompts_before:
645 self.prompts = self._prompts_before
675 self.prompts = self._prompts_before
646 self._prompts_before = None
676 self._prompts_before = None
647 # self._update_layout()
677 # self._update_layout()
648
678
649
679
650 InteractiveShellABC.register(TerminalInteractiveShell)
680 InteractiveShellABC.register(TerminalInteractiveShell)
651
681
652 if __name__ == '__main__':
682 if __name__ == '__main__':
653 TerminalInteractiveShell.instance().interact()
683 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))
@@ -1,90 +1,92 b''
1 from os.path import abspath, dirname, join
1 from os.path import abspath, dirname, join
2
2
3 from IPython.terminal.shortcuts import create_ipython_shortcuts
3 from IPython.terminal.shortcuts import create_ipython_shortcuts
4
4
5 def name(c):
5 def name(c):
6 s = c.__class__.__name__
6 s = c.__class__.__name__
7 if s == '_Invert':
7 if s == '_Invert':
8 return '(Not: %s)' % name(c.filter)
8 return '(Not: %s)' % name(c.filter)
9 if s in log_filters.keys():
9 if s in log_filters.keys():
10 return '(%s: %s)' % (log_filters[s], ', '.join(name(x) for x in c.filters))
10 return '(%s: %s)' % (log_filters[s], ', '.join(name(x) for x in c.filters))
11 return log_filters[s] if s in log_filters.keys() else s
11 return log_filters[s] if s in log_filters.keys() else s
12
12
13
13
14 def sentencize(s):
14 def sentencize(s):
15 """Extract first sentence
15 """Extract first sentence
16 """
16 """
17 s = s.replace('\n', ' ').strip().split('.')
17 s = s.replace('\n', ' ').strip().split('.')
18 s = s[0] if len(s) else s
18 s = s[0] if len(s) else s
19 try:
19 try:
20 return " ".join(s.split())
20 return " ".join(s.split())
21 except AttributeError:
21 except AttributeError:
22 return s
22 return s
23
23
24
24
25 def most_common(lst, n=3):
25 def most_common(lst, n=3):
26 """Most common elements occurring more then `n` times
26 """Most common elements occurring more then `n` times
27 """
27 """
28 from collections import Counter
28 from collections import Counter
29
29
30 c = Counter(lst)
30 c = Counter(lst)
31 return [k for (k, v) in c.items() if k and v > n]
31 return [k for (k, v) in c.items() if k and v > n]
32
32
33
33
34 def multi_filter_str(flt):
34 def multi_filter_str(flt):
35 """Yield readable conditional filter
35 """Yield readable conditional filter
36 """
36 """
37 assert hasattr(flt, 'filters'), 'Conditional filter required'
37 assert hasattr(flt, 'filters'), 'Conditional filter required'
38 yield name(flt)
38 yield name(flt)
39
39
40
40
41 log_filters = {'_AndList': 'And', '_OrList': 'Or'}
41 log_filters = {'_AndList': 'And', '_OrList': 'Or'}
42 log_invert = {'_Invert'}
42 log_invert = {'_Invert'}
43
43
44 class _DummyTerminal(object):
44 class _DummyTerminal:
45 """Used as a buffer to get prompt_toolkit bindings
45 """Used as a buffer to get prompt_toolkit bindings
46 """
46 """
47 handle_return = None
47 handle_return = None
48 input_transformer_manager = None
48 input_transformer_manager = None
49 display_completions = None
49 display_completions = None
50 editing_mode = "emacs"
51
50
52
51 ipy_bindings = create_ipython_shortcuts(_DummyTerminal()).bindings
53 ipy_bindings = create_ipython_shortcuts(_DummyTerminal()).bindings
52
54
53 dummy_docs = [] # ignore bindings without proper documentation
55 dummy_docs = [] # ignore bindings without proper documentation
54
56
55 common_docs = most_common([kb.handler.__doc__ for kb in ipy_bindings])
57 common_docs = most_common([kb.handler.__doc__ for kb in ipy_bindings])
56 if common_docs:
58 if common_docs:
57 dummy_docs.extend(common_docs)
59 dummy_docs.extend(common_docs)
58
60
59 dummy_docs = list(set(dummy_docs))
61 dummy_docs = list(set(dummy_docs))
60
62
61 single_filter = {}
63 single_filter = {}
62 multi_filter = {}
64 multi_filter = {}
63 for kb in ipy_bindings:
65 for kb in ipy_bindings:
64 doc = kb.handler.__doc__
66 doc = kb.handler.__doc__
65 if not doc or doc in dummy_docs:
67 if not doc or doc in dummy_docs:
66 continue
68 continue
67
69
68 shortcut = ' '.join([k if isinstance(k, str) else k.name for k in kb.keys])
70 shortcut = ' '.join([k if isinstance(k, str) else k.name for k in kb.keys])
69 shortcut += shortcut.endswith('\\') and '\\' or ''
71 shortcut += shortcut.endswith('\\') and '\\' or ''
70 if hasattr(kb.filter, 'filters'):
72 if hasattr(kb.filter, 'filters'):
71 flt = ' '.join(multi_filter_str(kb.filter))
73 flt = ' '.join(multi_filter_str(kb.filter))
72 multi_filter[(shortcut, flt)] = sentencize(doc)
74 multi_filter[(shortcut, flt)] = sentencize(doc)
73 else:
75 else:
74 single_filter[(shortcut, name(kb.filter))] = sentencize(doc)
76 single_filter[(shortcut, name(kb.filter))] = sentencize(doc)
75
77
76
78
77 if __name__ == '__main__':
79 if __name__ == '__main__':
78
80
79 sort_key = lambda k:(str(k[0][1]),str(k[0][0]))
81 sort_key = lambda k:(str(k[0][1]),str(k[0][0]))
80
82
81 here = abspath(dirname(__file__))
83 here = abspath(dirname(__file__))
82 dest = join(here, 'source', 'config', 'shortcuts')
84 dest = join(here, 'source', 'config', 'shortcuts')
83
85
84 with open(join(dest, 'single_filtered.csv'), 'w') as csv:
86 with open(join(dest, 'single_filtered.csv'), 'w') as csv:
85 for k, v in sorted(single_filter.items(), key=sort_key):
87 for k, v in sorted(single_filter.items(), key=sort_key):
86 csv.write(':kbd:`{}`\t{}\t{}\n'.format(k[0], k[1], v))
88 csv.write(':kbd:`{}`\t{}\t{}\n'.format(k[0], k[1], v))
87
89
88 with open(join(dest, 'multi_filtered.csv'), 'w') as csv:
90 with open(join(dest, 'multi_filtered.csv'), 'w') as csv:
89 for k, v in sorted(multi_filter.items(), key=sort_key):
91 for k, v in sorted(multi_filter.items(), key=sort_key):
90 csv.write(':kbd:`{}`\t{}\t{}\n'.format(k[0], k[1], v))
92 csv.write(':kbd:`{}`\t{}\t{}\n'.format(k[0], k[1], v))
General Comments 0
You need to be logged in to leave comments. Login now