key_bindings.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. """
  2. Key bindings registry.
  3. A `KeyBindings` object is a container that holds a list of key bindings. It has a
  4. very efficient internal data structure for checking which key bindings apply
  5. for a pressed key.
  6. Typical usage::
  7. kb = KeyBindings()
  8. @kb.add(Keys.ControlX, Keys.ControlC, filter=INSERT)
  9. def handler(event):
  10. # Handle ControlX-ControlC key sequence.
  11. pass
  12. It is also possible to combine multiple KeyBindings objects. We do this in the
  13. default key bindings. There are some KeyBindings objects that contain the Emacs
  14. bindings, while others contain the Vi bindings. They are merged together using
  15. `merge_key_bindings`.
  16. We also have a `ConditionalKeyBindings` object that can enable/disable a group of
  17. key bindings at once.
  18. It is also possible to add a filter to a function, before a key binding has
  19. been assigned, through the `key_binding` decorator.::
  20. # First define a key handler with the `filter`.
  21. @key_binding(filter=condition)
  22. def my_key_binding(event):
  23. ...
  24. # Later, add it to the key bindings.
  25. kb.add(Keys.A, my_key_binding)
  26. """
  27. from __future__ import annotations
  28. from abc import ABCMeta, abstractmethod, abstractproperty
  29. from inspect import isawaitable
  30. from typing import (
  31. TYPE_CHECKING,
  32. Any,
  33. Callable,
  34. Coroutine,
  35. Hashable,
  36. Sequence,
  37. Tuple,
  38. TypeVar,
  39. Union,
  40. cast,
  41. )
  42. from prompt_toolkit.cache import SimpleCache
  43. from prompt_toolkit.filters import FilterOrBool, Never, to_filter
  44. from prompt_toolkit.keys import KEY_ALIASES, Keys
  45. if TYPE_CHECKING:
  46. # Avoid circular imports.
  47. from .key_processor import KeyPressEvent
  48. # The only two return values for a mouse handler (and key bindings) are
  49. # `None` and `NotImplemented`. For the type checker it's best to annotate
  50. # this as `object`. (The consumer never expects a more specific instance:
  51. # checking for NotImplemented can be done using `is NotImplemented`.)
  52. NotImplementedOrNone = object
  53. # Other non-working options are:
  54. # * Optional[Literal[NotImplemented]]
  55. # --> Doesn't work, Literal can't take an Any.
  56. # * None
  57. # --> Doesn't work. We can't assign the result of a function that
  58. # returns `None` to a variable.
  59. # * Any
  60. # --> Works, but too broad.
  61. __all__ = [
  62. "NotImplementedOrNone",
  63. "Binding",
  64. "KeyBindingsBase",
  65. "KeyBindings",
  66. "ConditionalKeyBindings",
  67. "merge_key_bindings",
  68. "DynamicKeyBindings",
  69. "GlobalOnlyKeyBindings",
  70. ]
  71. # Key bindings can be regular functions or coroutines.
  72. # In both cases, if they return `NotImplemented`, the UI won't be invalidated.
  73. # This is mainly used in case of mouse move events, to prevent excessive
  74. # repainting during mouse move events.
  75. KeyHandlerCallable = Callable[
  76. ["KeyPressEvent"],
  77. Union["NotImplementedOrNone", Coroutine[Any, Any, "NotImplementedOrNone"]],
  78. ]
  79. class Binding:
  80. """
  81. Key binding: (key sequence + handler + filter).
  82. (Immutable binding class.)
  83. :param record_in_macro: When True, don't record this key binding when a
  84. macro is recorded.
  85. """
  86. def __init__(
  87. self,
  88. keys: tuple[Keys | str, ...],
  89. handler: KeyHandlerCallable,
  90. filter: FilterOrBool = True,
  91. eager: FilterOrBool = False,
  92. is_global: FilterOrBool = False,
  93. save_before: Callable[[KeyPressEvent], bool] = (lambda e: True),
  94. record_in_macro: FilterOrBool = True,
  95. ) -> None:
  96. self.keys = keys
  97. self.handler = handler
  98. self.filter = to_filter(filter)
  99. self.eager = to_filter(eager)
  100. self.is_global = to_filter(is_global)
  101. self.save_before = save_before
  102. self.record_in_macro = to_filter(record_in_macro)
  103. def call(self, event: KeyPressEvent) -> None:
  104. result = self.handler(event)
  105. # If the handler is a coroutine, create an asyncio task.
  106. if isawaitable(result):
  107. awaitable = cast(Coroutine[Any, Any, "NotImplementedOrNone"], result)
  108. async def bg_task() -> None:
  109. result = await awaitable
  110. if result != NotImplemented:
  111. event.app.invalidate()
  112. event.app.create_background_task(bg_task())
  113. elif result != NotImplemented:
  114. event.app.invalidate()
  115. def __repr__(self) -> str:
  116. return (
  117. f"{self.__class__.__name__}(keys={self.keys!r}, handler={self.handler!r})"
  118. )
  119. # Sequence of keys presses.
  120. KeysTuple = Tuple[Union[Keys, str], ...]
  121. class KeyBindingsBase(metaclass=ABCMeta):
  122. """
  123. Interface for a KeyBindings.
  124. """
  125. @abstractproperty
  126. def _version(self) -> Hashable:
  127. """
  128. For cache invalidation. - This should increase every time that
  129. something changes.
  130. """
  131. return 0
  132. @abstractmethod
  133. def get_bindings_for_keys(self, keys: KeysTuple) -> list[Binding]:
  134. """
  135. Return a list of key bindings that can handle these keys.
  136. (This return also inactive bindings, so the `filter` still has to be
  137. called, for checking it.)
  138. :param keys: tuple of keys.
  139. """
  140. return []
  141. @abstractmethod
  142. def get_bindings_starting_with_keys(self, keys: KeysTuple) -> list[Binding]:
  143. """
  144. Return a list of key bindings that handle a key sequence starting with
  145. `keys`. (It does only return bindings for which the sequences are
  146. longer than `keys`. And like `get_bindings_for_keys`, it also includes
  147. inactive bindings.)
  148. :param keys: tuple of keys.
  149. """
  150. return []
  151. @abstractproperty
  152. def bindings(self) -> list[Binding]:
  153. """
  154. List of `Binding` objects.
  155. (These need to be exposed, so that `KeyBindings` objects can be merged
  156. together.)
  157. """
  158. return []
  159. # `add` and `remove` don't have to be part of this interface.
  160. T = TypeVar("T", bound=Union[KeyHandlerCallable, Binding])
  161. class KeyBindings(KeyBindingsBase):
  162. """
  163. A container for a set of key bindings.
  164. Example usage::
  165. kb = KeyBindings()
  166. @kb.add('c-t')
  167. def _(event):
  168. print('Control-T pressed')
  169. @kb.add('c-a', 'c-b')
  170. def _(event):
  171. print('Control-A pressed, followed by Control-B')
  172. @kb.add('c-x', filter=is_searching)
  173. def _(event):
  174. print('Control-X pressed') # Works only if we are searching.
  175. """
  176. def __init__(self) -> None:
  177. self._bindings: list[Binding] = []
  178. self._get_bindings_for_keys_cache: SimpleCache[KeysTuple, list[Binding]] = (
  179. SimpleCache(maxsize=10000)
  180. )
  181. self._get_bindings_starting_with_keys_cache: SimpleCache[
  182. KeysTuple, list[Binding]
  183. ] = SimpleCache(maxsize=1000)
  184. self.__version = 0 # For cache invalidation.
  185. def _clear_cache(self) -> None:
  186. self.__version += 1
  187. self._get_bindings_for_keys_cache.clear()
  188. self._get_bindings_starting_with_keys_cache.clear()
  189. @property
  190. def bindings(self) -> list[Binding]:
  191. return self._bindings
  192. @property
  193. def _version(self) -> Hashable:
  194. return self.__version
  195. def add(
  196. self,
  197. *keys: Keys | str,
  198. filter: FilterOrBool = True,
  199. eager: FilterOrBool = False,
  200. is_global: FilterOrBool = False,
  201. save_before: Callable[[KeyPressEvent], bool] = (lambda e: True),
  202. record_in_macro: FilterOrBool = True,
  203. ) -> Callable[[T], T]:
  204. """
  205. Decorator for adding a key bindings.
  206. :param filter: :class:`~prompt_toolkit.filters.Filter` to determine
  207. when this key binding is active.
  208. :param eager: :class:`~prompt_toolkit.filters.Filter` or `bool`.
  209. When True, ignore potential longer matches when this key binding is
  210. hit. E.g. when there is an active eager key binding for Ctrl-X,
  211. execute the handler immediately and ignore the key binding for
  212. Ctrl-X Ctrl-E of which it is a prefix.
  213. :param is_global: When this key bindings is added to a `Container` or
  214. `Control`, make it a global (always active) binding.
  215. :param save_before: Callable that takes an `Event` and returns True if
  216. we should save the current buffer, before handling the event.
  217. (That's the default.)
  218. :param record_in_macro: Record these key bindings when a macro is
  219. being recorded. (True by default.)
  220. """
  221. assert keys
  222. keys = tuple(_parse_key(k) for k in keys)
  223. if isinstance(filter, Never):
  224. # When a filter is Never, it will always stay disabled, so in that
  225. # case don't bother putting it in the key bindings. It will slow
  226. # down every key press otherwise.
  227. def decorator(func: T) -> T:
  228. return func
  229. else:
  230. def decorator(func: T) -> T:
  231. if isinstance(func, Binding):
  232. # We're adding an existing Binding object.
  233. self.bindings.append(
  234. Binding(
  235. keys,
  236. func.handler,
  237. filter=func.filter & to_filter(filter),
  238. eager=to_filter(eager) | func.eager,
  239. is_global=to_filter(is_global) | func.is_global,
  240. save_before=func.save_before,
  241. record_in_macro=func.record_in_macro,
  242. )
  243. )
  244. else:
  245. self.bindings.append(
  246. Binding(
  247. keys,
  248. cast(KeyHandlerCallable, func),
  249. filter=filter,
  250. eager=eager,
  251. is_global=is_global,
  252. save_before=save_before,
  253. record_in_macro=record_in_macro,
  254. )
  255. )
  256. self._clear_cache()
  257. return func
  258. return decorator
  259. def remove(self, *args: Keys | str | KeyHandlerCallable) -> None:
  260. """
  261. Remove a key binding.
  262. This expects either a function that was given to `add` method as
  263. parameter or a sequence of key bindings.
  264. Raises `ValueError` when no bindings was found.
  265. Usage::
  266. remove(handler) # Pass handler.
  267. remove('c-x', 'c-a') # Or pass the key bindings.
  268. """
  269. found = False
  270. if callable(args[0]):
  271. assert len(args) == 1
  272. function = args[0]
  273. # Remove the given function.
  274. for b in self.bindings:
  275. if b.handler == function:
  276. self.bindings.remove(b)
  277. found = True
  278. else:
  279. assert len(args) > 0
  280. args = cast(Tuple[Union[Keys, str]], args)
  281. # Remove this sequence of key bindings.
  282. keys = tuple(_parse_key(k) for k in args)
  283. for b in self.bindings:
  284. if b.keys == keys:
  285. self.bindings.remove(b)
  286. found = True
  287. if found:
  288. self._clear_cache()
  289. else:
  290. # No key binding found for this function. Raise ValueError.
  291. raise ValueError(f"Binding not found: {function!r}")
  292. # For backwards-compatibility.
  293. add_binding = add
  294. remove_binding = remove
  295. def get_bindings_for_keys(self, keys: KeysTuple) -> list[Binding]:
  296. """
  297. Return a list of key bindings that can handle this key.
  298. (This return also inactive bindings, so the `filter` still has to be
  299. called, for checking it.)
  300. :param keys: tuple of keys.
  301. """
  302. def get() -> list[Binding]:
  303. result: list[tuple[int, Binding]] = []
  304. for b in self.bindings:
  305. if len(keys) == len(b.keys):
  306. match = True
  307. any_count = 0
  308. for i, j in zip(b.keys, keys):
  309. if i != j and i != Keys.Any:
  310. match = False
  311. break
  312. if i == Keys.Any:
  313. any_count += 1
  314. if match:
  315. result.append((any_count, b))
  316. # Place bindings that have more 'Any' occurrences in them at the end.
  317. result = sorted(result, key=lambda item: -item[0])
  318. return [item[1] for item in result]
  319. return self._get_bindings_for_keys_cache.get(keys, get)
  320. def get_bindings_starting_with_keys(self, keys: KeysTuple) -> list[Binding]:
  321. """
  322. Return a list of key bindings that handle a key sequence starting with
  323. `keys`. (It does only return bindings for which the sequences are
  324. longer than `keys`. And like `get_bindings_for_keys`, it also includes
  325. inactive bindings.)
  326. :param keys: tuple of keys.
  327. """
  328. def get() -> list[Binding]:
  329. result = []
  330. for b in self.bindings:
  331. if len(keys) < len(b.keys):
  332. match = True
  333. for i, j in zip(b.keys, keys):
  334. if i != j and i != Keys.Any:
  335. match = False
  336. break
  337. if match:
  338. result.append(b)
  339. return result
  340. return self._get_bindings_starting_with_keys_cache.get(keys, get)
  341. def _parse_key(key: Keys | str) -> str | Keys:
  342. """
  343. Replace key by alias and verify whether it's a valid one.
  344. """
  345. # Already a parse key? -> Return it.
  346. if isinstance(key, Keys):
  347. return key
  348. # Lookup aliases.
  349. key = KEY_ALIASES.get(key, key)
  350. # Replace 'space' by ' '
  351. if key == "space":
  352. key = " "
  353. # Return as `Key` object when it's a special key.
  354. try:
  355. return Keys(key)
  356. except ValueError:
  357. pass
  358. # Final validation.
  359. if len(key) != 1:
  360. raise ValueError(f"Invalid key: {key}")
  361. return key
  362. def key_binding(
  363. filter: FilterOrBool = True,
  364. eager: FilterOrBool = False,
  365. is_global: FilterOrBool = False,
  366. save_before: Callable[[KeyPressEvent], bool] = (lambda event: True),
  367. record_in_macro: FilterOrBool = True,
  368. ) -> Callable[[KeyHandlerCallable], Binding]:
  369. """
  370. Decorator that turn a function into a `Binding` object. This can be added
  371. to a `KeyBindings` object when a key binding is assigned.
  372. """
  373. assert save_before is None or callable(save_before)
  374. filter = to_filter(filter)
  375. eager = to_filter(eager)
  376. is_global = to_filter(is_global)
  377. save_before = save_before
  378. record_in_macro = to_filter(record_in_macro)
  379. keys = ()
  380. def decorator(function: KeyHandlerCallable) -> Binding:
  381. return Binding(
  382. keys,
  383. function,
  384. filter=filter,
  385. eager=eager,
  386. is_global=is_global,
  387. save_before=save_before,
  388. record_in_macro=record_in_macro,
  389. )
  390. return decorator
  391. class _Proxy(KeyBindingsBase):
  392. """
  393. Common part for ConditionalKeyBindings and _MergedKeyBindings.
  394. """
  395. def __init__(self) -> None:
  396. # `KeyBindings` to be synchronized with all the others.
  397. self._bindings2: KeyBindingsBase = KeyBindings()
  398. self._last_version: Hashable = ()
  399. def _update_cache(self) -> None:
  400. """
  401. If `self._last_version` is outdated, then this should update
  402. the version and `self._bindings2`.
  403. """
  404. raise NotImplementedError
  405. # Proxy methods to self._bindings2.
  406. @property
  407. def bindings(self) -> list[Binding]:
  408. self._update_cache()
  409. return self._bindings2.bindings
  410. @property
  411. def _version(self) -> Hashable:
  412. self._update_cache()
  413. return self._last_version
  414. def get_bindings_for_keys(self, keys: KeysTuple) -> list[Binding]:
  415. self._update_cache()
  416. return self._bindings2.get_bindings_for_keys(keys)
  417. def get_bindings_starting_with_keys(self, keys: KeysTuple) -> list[Binding]:
  418. self._update_cache()
  419. return self._bindings2.get_bindings_starting_with_keys(keys)
  420. class ConditionalKeyBindings(_Proxy):
  421. """
  422. Wraps around a `KeyBindings`. Disable/enable all the key bindings according to
  423. the given (additional) filter.::
  424. @Condition
  425. def setting_is_true():
  426. return True # or False
  427. registry = ConditionalKeyBindings(key_bindings, setting_is_true)
  428. When new key bindings are added to this object. They are also
  429. enable/disabled according to the given `filter`.
  430. :param registries: List of :class:`.KeyBindings` objects.
  431. :param filter: :class:`~prompt_toolkit.filters.Filter` object.
  432. """
  433. def __init__(
  434. self, key_bindings: KeyBindingsBase, filter: FilterOrBool = True
  435. ) -> None:
  436. _Proxy.__init__(self)
  437. self.key_bindings = key_bindings
  438. self.filter = to_filter(filter)
  439. def _update_cache(self) -> None:
  440. "If the original key bindings was changed. Update our copy version."
  441. expected_version = self.key_bindings._version
  442. if self._last_version != expected_version:
  443. bindings2 = KeyBindings()
  444. # Copy all bindings from `self.key_bindings`, adding our condition.
  445. for b in self.key_bindings.bindings:
  446. bindings2.bindings.append(
  447. Binding(
  448. keys=b.keys,
  449. handler=b.handler,
  450. filter=self.filter & b.filter,
  451. eager=b.eager,
  452. is_global=b.is_global,
  453. save_before=b.save_before,
  454. record_in_macro=b.record_in_macro,
  455. )
  456. )
  457. self._bindings2 = bindings2
  458. self._last_version = expected_version
  459. class _MergedKeyBindings(_Proxy):
  460. """
  461. Merge multiple registries of key bindings into one.
  462. This class acts as a proxy to multiple :class:`.KeyBindings` objects, but
  463. behaves as if this is just one bigger :class:`.KeyBindings`.
  464. :param registries: List of :class:`.KeyBindings` objects.
  465. """
  466. def __init__(self, registries: Sequence[KeyBindingsBase]) -> None:
  467. _Proxy.__init__(self)
  468. self.registries = registries
  469. def _update_cache(self) -> None:
  470. """
  471. If one of the original registries was changed. Update our merged
  472. version.
  473. """
  474. expected_version = tuple(r._version for r in self.registries)
  475. if self._last_version != expected_version:
  476. bindings2 = KeyBindings()
  477. for reg in self.registries:
  478. bindings2.bindings.extend(reg.bindings)
  479. self._bindings2 = bindings2
  480. self._last_version = expected_version
  481. def merge_key_bindings(bindings: Sequence[KeyBindingsBase]) -> _MergedKeyBindings:
  482. """
  483. Merge multiple :class:`.Keybinding` objects together.
  484. Usage::
  485. bindings = merge_key_bindings([bindings1, bindings2, ...])
  486. """
  487. return _MergedKeyBindings(bindings)
  488. class DynamicKeyBindings(_Proxy):
  489. """
  490. KeyBindings class that can dynamically returns any KeyBindings.
  491. :param get_key_bindings: Callable that returns a :class:`.KeyBindings` instance.
  492. """
  493. def __init__(self, get_key_bindings: Callable[[], KeyBindingsBase | None]) -> None:
  494. self.get_key_bindings = get_key_bindings
  495. self.__version = 0
  496. self._last_child_version = None
  497. self._dummy = KeyBindings() # Empty key bindings.
  498. def _update_cache(self) -> None:
  499. key_bindings = self.get_key_bindings() or self._dummy
  500. assert isinstance(key_bindings, KeyBindingsBase)
  501. version = id(key_bindings), key_bindings._version
  502. self._bindings2 = key_bindings
  503. self._last_version = version
  504. class GlobalOnlyKeyBindings(_Proxy):
  505. """
  506. Wrapper around a :class:`.KeyBindings` object that only exposes the global
  507. key bindings.
  508. """
  509. def __init__(self, key_bindings: KeyBindingsBase) -> None:
  510. _Proxy.__init__(self)
  511. self.key_bindings = key_bindings
  512. def _update_cache(self) -> None:
  513. """
  514. If one of the original registries was changed. Update our merged
  515. version.
  516. """
  517. expected_version = self.key_bindings._version
  518. if self._last_version != expected_version:
  519. bindings2 = KeyBindings()
  520. for b in self.key_bindings.bindings:
  521. if b.is_global():
  522. bindings2.bindings.append(b)
  523. self._bindings2 = bindings2
  524. self._last_version = expected_version