Debian Codegraph @

IPython/terminal/shortcuts/filters.py

raw
1 """
2 Filters restricting scope of IPython Terminal shortcuts.
3 """
4
5 # Copyright (c) IPython Development Team.
6 # Distributed under the terms of the Modified BSD License.
7
8 import ast
9 import re
10 import signal
11 import sys
12 from typing import Dict, Union
13 from collections.abc import Callable
14
15 from prompt_toolkit.application.current import get_app
16 from prompt_toolkit.enums import DEFAULT_BUFFER, SEARCH_BUFFER
17 from prompt_toolkit.key_binding import KeyPressEvent
18 from prompt_toolkit.filters import Condition, Filter, emacs_insert_mode, has_completions
19 from prompt_toolkit.filters import has_focus as has_focus_impl
20 from prompt_toolkit.filters import (
21 Always,
22 Never,
23 has_selection,
24 has_suggestion,
25 vi_insert_mode,
26 vi_mode,
27 )
28 from prompt_toolkit.layout.layout import FocusableElement
29
30 from IPython.core.getipython import get_ipython
31 from IPython.core.guarded_eval import _find_dunder, BINARY_OP_DUNDERS, UNARY_OP_DUNDERS
32 from IPython.terminal.shortcuts import auto_suggest
33 from IPython.utils.decorators import undoc
34
35
36 @undoc
37 @Condition
38 def cursor_in_leading_ws():
39 before = get_app().current_buffer.document.current_line_before_cursor
40 return (not before) or before.isspace()
41
42
43 def has_focus(value: FocusableElement):
44 """Wrapper around has_focus adding a nice `__name__` to tester function"""
45 tester = has_focus_impl(value).func
46 tester.__name__ = f"is_focused({value})"
47 return Condition(tester)
48
49
50 @undoc
51 @Condition
52 def has_line_below() -> bool:
53 document = get_app().current_buffer.document
54 return document.cursor_position_row < len(document.lines) - 1
55
56
57 @undoc
58 @Condition
59 def is_cursor_at_the_end_of_line() -> bool:
60 document = get_app().current_buffer.document
61 return document.is_cursor_at_the_end_of_line
62
63
64 @undoc
65 @Condition
66 def has_line_above() -> bool:
67 document = get_app().current_buffer.document
68 return document.cursor_position_row != 0
69
70
71 @Condition
72 def ebivim():
73 shell = get_ipython()
74 return shell.emacs_bindings_in_vi_insert_mode
75
76
77 @Condition
78 def supports_suspend():
79 return hasattr(signal, "SIGTSTP")
80
81
82 @Condition
83 def auto_match():
84 shell = get_ipython()
85 return shell.auto_match
86
87
88 def all_quotes_paired(quote, buf):
89 paired = True
90 i = 0
91 while i < len(buf):
92 c = buf[i]
93 if c == quote:
94 paired = not paired
95 elif c == "\\":
96 i += 1
97 i += 1
98 return paired
99
100
101 _preceding_text_cache: Dict[Union[str, Callable], Condition] = {}
102 _following_text_cache: Dict[Union[str, Callable], Condition] = {}
103
104
105 def preceding_text(pattern: Union[str, Callable]):
106 if pattern in _preceding_text_cache:
107 return _preceding_text_cache[pattern]
108
109 if callable(pattern):
110
111 def _preceding_text():
112 app = get_app()
113 before_cursor = app.current_buffer.document.current_line_before_cursor
114 # mypy can't infer if(callable): https://github.com/python/mypy/issues/3603
115 return bool(pattern(before_cursor)) # type: ignore[operator]
116
117 else:
118 m = re.compile(pattern)
119
120 def _preceding_text():
121 app = get_app()
122 before_cursor = app.current_buffer.document.current_line_before_cursor
123 return bool(m.match(before_cursor))
124
125 _preceding_text.__name__ = f"preceding_text({pattern!r})"
126
127 condition = Condition(_preceding_text)
128 _preceding_text_cache[pattern] = condition
129 return condition
130
131
132 def following_text(pattern):
133 try:
134 return _following_text_cache[pattern]
135 except KeyError:
136 pass
137 m = re.compile(pattern)
138
139 def _following_text():
140 app = get_app()
141 return bool(m.match(app.current_buffer.document.current_line_after_cursor))
142
143 _following_text.__name__ = f"following_text({pattern!r})"
144
145 condition = Condition(_following_text)
146 _following_text_cache[pattern] = condition
147 return condition
148
149
150 @Condition
151 def not_inside_unclosed_string():
152 app = get_app()
153 s = app.current_buffer.document.text_before_cursor
154 # remove escaped quotes
155 s = s.replace('\\"', "").replace("\\'", "")
156 # remove triple-quoted string literals
157 s = re.sub(r"(?:\"\"\"[\s\S]*\"\"\"|'''[\s\S]*''')", "", s)
158 # remove single-quoted string literals
159 s = re.sub(r"""(?:"[^"]*["\n]|'[^']*['\n])""", "", s)
160 return not ('"' in s or "'" in s)
161
162
163 @Condition
164 def navigable_suggestions():
165 shell = get_ipython()
166 return isinstance(shell.auto_suggest, auto_suggest.NavigableAutoSuggestFromHistory)
167
168
169 @Condition
170 def readline_like_completions():
171 shell = get_ipython()
172 return shell.display_completions == "readlinelike"
173
174
175 @Condition
176 def is_windows_os():
177 return sys.platform == "win32"
178
179
180 class PassThrough(Filter):
181 """A filter allowing to implement pass-through behaviour of keybindings.
182
183 Prompt toolkit key processor dispatches only one event per binding match,
184 which means that adding a new shortcut will suppress the old shortcut
185 if the keybindings are the same (unless one is filtered out).
186
187 To stop a shortcut binding from suppressing other shortcuts:
188 - add the `pass_through` filter to list of filter, and
189 - call `pass_through.reply(event)` in the shortcut handler.
190 """
191
192 def __init__(self):
193 self._is_replying = False
194
195 def reply(self, event: KeyPressEvent):
196 self._is_replying = True
197 try:
198 event.key_processor.reset()
199 event.key_processor.feed_multiple(event.key_sequence)
200 event.key_processor.process_keys()
201 finally:
202 self._is_replying = False
203
204 def __call__(self):
205 return not self._is_replying
206
207
208 pass_through = PassThrough()
209
210 # these one is callable and re-used multiple times hence needs to be
211 # only defined once beforehand so that transforming back to human-readable
212 # names works well in the documentation.
213 default_buffer_focused = has_focus(DEFAULT_BUFFER)
214
215 KEYBINDING_FILTERS = {
216 "always": Always(),
217 # never is used for exposing commands which have no default keybindings
218 "never": Never(),
219 "has_line_below": has_line_below,
220 "has_line_above": has_line_above,
221 "is_cursor_at_the_end_of_line": is_cursor_at_the_end_of_line,
222 "has_selection": has_selection,
223 "has_suggestion": has_suggestion,
224 "vi_mode": vi_mode,
225 "vi_insert_mode": vi_insert_mode,
226 "emacs_insert_mode": emacs_insert_mode,
227 # https://github.com/ipython/ipython/pull/12603 argued for inclusion of
228 # emacs key bindings with a configurable `emacs_bindings_in_vi_insert_mode`
229 # toggle; when the toggle is on user can access keybindigns like `ctrl + e`
230 # in vi insert mode. Because some of the emacs bindings involve `escape`
231 # followed by another key, e.g. `escape` followed by `f`, prompt-toolkit
232 # needs to wait to see if there will be another character typed in before
233 # executing pure `escape` keybinding; in vi insert mode `escape` switches to
234 # command mode which is common and performance critical action for vi users.
235 # To avoid the delay users employ a workaround:
236 # https://github.com/ipython/ipython/issues/13443#issuecomment-1032753703
237 # which involves switching `emacs_bindings_in_vi_insert_mode` off.
238 #
239 # For the workaround to work:
240 # 1) end users need to toggle `emacs_bindings_in_vi_insert_mode` off
241 # 2) all keybindings which would involve `escape` need to respect that
242 # toggle by including either:
243 # - `vi_insert_mode & ebivim` for actions which have emacs keybindings
244 # predefined upstream in prompt-toolkit, or
245 # - `emacs_like_insert_mode` for actions which do not have existing
246 # emacs keybindings predefined upstream (or need overriding of the
247 # upstream bindings to modify behaviour), defined below.
248 "emacs_like_insert_mode": (vi_insert_mode & ebivim) | emacs_insert_mode,
249 "has_completions": has_completions,
250 "insert_mode": vi_insert_mode | emacs_insert_mode,
251 "default_buffer_focused": default_buffer_focused,
252 "search_buffer_focused": has_focus(SEARCH_BUFFER),
253 # `ebivim` stands for emacs bindings in vi insert mode
254 "ebivim": ebivim,
255 "supports_suspend": supports_suspend,
256 "is_windows_os": is_windows_os,
257 "auto_match": auto_match,
258 "focused_insert": (vi_insert_mode | emacs_insert_mode) & default_buffer_focused,
259 "not_inside_unclosed_string": not_inside_unclosed_string,
260 "readline_like_completions": readline_like_completions,
261 "preceded_by_paired_double_quotes": preceding_text(
262 lambda line: all_quotes_paired('"', line)
263 ),
264 "preceded_by_paired_single_quotes": preceding_text(
265 lambda line: all_quotes_paired("'", line)
266 ),
267 "preceded_by_raw_str_prefix": preceding_text(r".*(r|R)[\"'](-*)$"),
268 "preceded_by_two_double_quotes": preceding_text(r'^.*""$'),
269 "preceded_by_two_single_quotes": preceding_text(r"^.*''$"),
270 "followed_by_closing_paren_or_end": following_text(r"[,)}\]]|$"),
271 "preceded_by_opening_round_paren": preceding_text(r".*\($"),
272 "preceded_by_opening_bracket": preceding_text(r".*\[$"),
273 "preceded_by_opening_brace": preceding_text(r".*\{$"),
274 "preceded_by_double_quote": preceding_text('.*"$'),
275 "preceded_by_single_quote": preceding_text(r".*'$"),
276 "followed_by_closing_round_paren": following_text(r"^\)"),
277 "followed_by_closing_bracket": following_text(r"^\]"),
278 "followed_by_closing_brace": following_text(r"^\}"),
279 "followed_by_double_quote": following_text('^"'),
280 "followed_by_single_quote": following_text("^'"),
281 "navigable_suggestions": navigable_suggestions,
282 "cursor_in_leading_ws": cursor_in_leading_ws,
283 "pass_through": pass_through,
284 }
285
286
287 def eval_node(node: Union[ast.AST, None]):
288 if node is None:
289 return None
290 if isinstance(node, ast.Expression):
291 return eval_node(node.body)
292 if isinstance(node, ast.BinOp):
293 left = eval_node(node.left)
294 right = eval_node(node.right)
295 dunders = _find_dunder(node.op, BINARY_OP_DUNDERS)
296 if dunders:
297 return getattr(left, dunders[0])(right)
298 raise ValueError(f"Unknown binary operation: {node.op}")
299 if isinstance(node, ast.UnaryOp):
300 value = eval_node(node.operand)
301 dunders = _find_dunder(node.op, UNARY_OP_DUNDERS)
302 if dunders:
303 return getattr(value, dunders[0])()
304 raise ValueError(f"Unknown unary operation: {node.op}")
305 if isinstance(node, ast.Name):
306 if node.id in KEYBINDING_FILTERS:
307 return KEYBINDING_FILTERS[node.id]
308 else:
309 sep = "\n - "
310 known_filters = sep.join(sorted(KEYBINDING_FILTERS))
311 raise NameError(
312 f"{node.id} is not a known shortcut filter."
313 f" Known filters are: {sep}{known_filters}."
314 )
315 raise ValueError("Unhandled node", ast.dump(node))
316
317
318 def filter_from_string(code: str):
319 expression = ast.parse(code, mode="eval")
320 return eval_node(expression)
321
322
323 __all__ = ["KEYBINDING_FILTERS", "filter_from_string"]