key_bindings.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  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 "{}(keys={!r}, handler={!r})".format(
  117. self.__class__.__name__,
  118. self.keys,
  119. self.handler,
  120. )
  121. # Sequence of keys presses.
  122. KeysTuple = Tuple[Union[Keys, str], ...]
  123. class KeyBindingsBase(metaclass=ABCMeta):
  124. """
  125. Interface for a KeyBindings.
  126. """
  127. @abstractproperty
  128. def _version(self) -> Hashable:
  129. """
  130. For cache invalidation. - This should increase every time that
  131. something changes.
  132. """
  133. return 0
  134. @abstractmethod
  135. def get_bindings_for_keys(self, keys: KeysTuple) -> list[Binding]:
  136. """
  137. Return a list of key bindings that can handle these keys.
  138. (This return also inactive bindings, so the `filter` still has to be
  139. called, for checking it.)
  140. :param keys: tuple of keys.
  141. """
  142. return []
  143. @abstractmethod
  144. def get_bindings_starting_with_keys(self, keys: KeysTuple) -> list[Binding]:
  145. """
  146. Return a list of key bindings that handle a key sequence starting with
  147. `keys`. (It does only return bindings for which the sequences are
  148. longer than `keys`. And like `get_bindings_for_keys`, it also includes
  149. inactive bindings.)
  150. :param keys: tuple of keys.
  151. """
  152. return []
  153. @abstractproperty
  154. def bindings(self) -> list[Binding]:
  155. """
  156. List of `Binding` objects.
  157. (These need to be exposed, so that `KeyBindings` objects can be merged
  158. together.)
  159. """
  160. return []
  161. # `add` and `remove` don't have to be part of this interface.
  162. T = TypeVar("T", bound=Union[KeyHandlerCallable, Binding])
  163. class KeyBindings(KeyBindingsBase):
  164. """
  165. A container for a set of key bindings.
  166. Example usage::
  167. kb = KeyBindings()
  168. @kb.add('c-t')
  169. def _(event):
  170. print('Control-T pressed')
  171. @kb.add('c-a', 'c-b')
  172. def _(event):
  173. print('Control-A pressed, followed by Control-B')
  174. @kb.add('c-x', filter=is_searching)
  175. def _(event):
  176. print('Control-X pressed') # Works only if we are searching.
  177. """
  178. def __init__(self) -> None:
  179. self._bindings: list[Binding] = []
  180. self._get_bindings_for_keys_cache: SimpleCache[
  181. KeysTuple, list[Binding]
  182. ] = SimpleCache(maxsize=10000)
  183. self._get_bindings_starting_with_keys_cache: SimpleCache[
  184. KeysTuple, list[Binding]
  185. ] = SimpleCache(maxsize=1000)
  186. self.__version = 0 # For cache invalidation.
  187. def _clear_cache(self) -> None:
  188. self.__version += 1
  189. self._get_bindings_for_keys_cache.clear()
  190. self._get_bindings_starting_with_keys_cache.clear()
  191. @property
  192. def bindings(self) -> list[Binding]:
  193. return self._bindings
  194. @property
  195. def _version(self) -> Hashable:
  196. return self.__version
  197. def add(
  198. self,
  199. *keys: Keys | str,
  200. filter: FilterOrBool = True,
  201. eager: FilterOrBool = False,
  202. is_global: FilterOrBool = False,
  203. save_before: Callable[[KeyPressEvent], bool] = (lambda e: True),
  204. record_in_macro: FilterOrBool = True,
  205. ) -> Callable[[T], T]:
  206. """
  207. Decorator for adding a key bindings.
  208. :param filter: :class:`~prompt_toolkit.filters.Filter` to determine
  209. when this key binding is active.
  210. :param eager: :class:`~prompt_toolkit.filters.Filter` or `bool`.
  211. When True, ignore potential longer matches when this key binding is
  212. hit. E.g. when there is an active eager key binding for Ctrl-X,
  213. execute the handler immediately and ignore the key binding for
  214. Ctrl-X Ctrl-E of which it is a prefix.
  215. :param is_global: When this key bindings is added to a `Container` or
  216. `Control`, make it a global (always active) binding.
  217. :param save_before: Callable that takes an `Event` and returns True if
  218. we should save the current buffer, before handling the event.
  219. (That's the default.)
  220. :param record_in_macro: Record these key bindings when a macro is
  221. being recorded. (True by default.)
  222. """
  223. assert keys
  224. keys = tuple(_parse_key(k) for k in keys)
  225. if isinstance(filter, Never):
  226. # When a filter is Never, it will always stay disabled, so in that
  227. # case don't bother putting it in the key bindings. It will slow
  228. # down every key press otherwise.
  229. def decorator(func: T) -> T:
  230. return func
  231. else:
  232. def decorator(func: T) -> T:
  233. if isinstance(func, Binding):
  234. # We're adding an existing Binding object.
  235. self.bindings.append(
  236. Binding(
  237. keys,
  238. func.handler,
  239. filter=func.filter & to_filter(filter),
  240. eager=to_filter(eager) | func.eager,
  241. is_global=to_filter(is_global) | func.is_global,
  242. save_before=func.save_before,
  243. record_in_macro=func.record_in_macro,
  244. )
  245. )
  246. else:
  247. self.bindings.append(
  248. Binding(
  249. keys,
  250. cast(KeyHandlerCallable, func),
  251. filter=filter,
  252. eager=eager,
  253. is_global=is_global,
  254. save_before=save_before,
  255. record_in_macro=record_in_macro,
  256. )
  257. )
  258. self._clear_cache()
  259. return func
  260. return decorator
  261. def remove(self, *args: Keys | str | KeyHandlerCallable) -> None:
  262. """
  263. Remove a key binding.
  264. This expects either a function that was given to `add` method as
  265. parameter or a sequence of key bindings.
  266. Raises `ValueError` when no bindings was found.
  267. Usage::
  268. remove(handler) # Pass handler.
  269. remove('c-x', 'c-a') # Or pass the key bindings.
  270. """
  271. found = False
  272. if callable(args[0]):
  273. assert len(args) == 1
  274. function = args[0]
  275. # Remove the given function.
  276. for b in self.bindings:
  277. if b.handler == function:
  278. self.bindings.remove(b)
  279. found = True
  280. else:
  281. assert len(args) > 0
  282. args = cast(Tuple[Union[Keys, str]], args)
  283. # Remove this sequence of key bindings.
  284. keys = tuple(_parse_key(k) for k in args)
  285. for b in self.bindings:
  286. if b.keys == keys:
  287. self.bindings.remove(b)
  288. found = True
  289. if found:
  290. self._clear_cache()
  291. else:
  292. # No key binding found for this function. Raise ValueError.
  293. raise ValueError(f"Binding not found: {function!r}")
  294. # For backwards-compatibility.
  295. add_binding = add
  296. remove_binding = remove
  297. def get_bindings_for_keys(self, keys: KeysTuple) -> list[Binding]:
  298. """
  299. Return a list of key bindings that can handle this key.
  300. (This return also inactive bindings, so the `filter` still has to be
  301. called, for checking it.)
  302. :param keys: tuple of keys.
  303. """
  304. def get() -> list[Binding]:
  305. result: list[tuple[int, Binding]] = []
  306. for b in self.bindings:
  307. if len(keys) == len(b.keys):
  308. match = True
  309. any_count = 0
  310. for i, j in zip(b.keys, keys):
  311. if i != j and i != Keys.Any:
  312. match = False
  313. break
  314. if i == Keys.Any:
  315. any_count += 1
  316. if match:
  317. result.append((any_count, b))
  318. # Place bindings that have more 'Any' occurrences in them at the end.
  319. result = sorted(result, key=lambda item: -item[0])
  320. return [item[1] for item in result]
  321. return self._get_bindings_for_keys_cache.get(keys, get)
  322. def get_bindings_starting_with_keys(self, keys: KeysTuple) -> list[Binding]:
  323. """
  324. Return a list of key bindings that handle a key sequence starting with
  325. `keys`. (It does only return bindings for which the sequences are
  326. longer than `keys`. And like `get_bindings_for_keys`, it also includes
  327. inactive bindings.)
  328. :param keys: tuple of keys.
  329. """
  330. def get() -> list[Binding]:
  331. result = []
  332. for b in self.bindings:
  333. if len(keys) < len(b.keys):
  334. match = True
  335. for i, j in zip(b.keys, keys):
  336. if i != j and i != Keys.Any:
  337. match = False
  338. break
  339. if match:
  340. result.append(b)
  341. return result
  342. return self._get_bindings_starting_with_keys_cache.get(keys, get)
  343. def _parse_key(key: Keys | str) -> str | Keys:
  344. """
  345. Replace key by alias and verify whether it's a valid one.
  346. """
  347. # Already a parse key? -> Return it.
  348. if isinstance(key, Keys):
  349. return key
  350. # Lookup aliases.
  351. key = KEY_ALIASES.get(key, key)
  352. # Replace 'space' by ' '
  353. if key == "space":
  354. key = " "
  355. # Return as `Key` object when it's a special key.
  356. try:
  357. return Keys(key)
  358. except ValueError:
  359. pass
  360. # Final validation.
  361. if len(key) != 1:
  362. raise ValueError(f"Invalid key: {key}")
  363. return key
  364. def key_binding(
  365. filter: FilterOrBool = True,
  366. eager: FilterOrBool = False,
  367. is_global: FilterOrBool = False,
  368. save_before: Callable[[KeyPressEvent], bool] = (lambda event: True),
  369. record_in_macro: FilterOrBool = True,
  370. ) -> Callable[[KeyHandlerCallable], Binding]:
  371. """
  372. Decorator that turn a function into a `Binding` object. This can be added
  373. to a `KeyBindings` object when a key binding is assigned.
  374. """
  375. assert save_before is None or callable(save_before)
  376. filter = to_filter(filter)
  377. eager = to_filter(eager)
  378. is_global = to_filter(is_global)
  379. save_before = save_before
  380. record_in_macro = to_filter(record_in_macro)
  381. keys = ()
  382. def decorator(function: KeyHandlerCallable) -> Binding:
  383. return Binding(
  384. keys,
  385. function,
  386. filter=filter,
  387. eager=eager,
  388. is_global=is_global,
  389. save_before=save_before,
  390. record_in_macro=record_in_macro,
  391. )
  392. return decorator
  393. class _Proxy(KeyBindingsBase):
  394. """
  395. Common part for ConditionalKeyBindings and _MergedKeyBindings.
  396. """
  397. def __init__(self) -> None:
  398. # `KeyBindings` to be synchronized with all the others.
  399. self._bindings2: KeyBindingsBase = KeyBindings()
  400. self._last_version: Hashable = ()
  401. def _update_cache(self) -> None:
  402. """
  403. If `self._last_version` is outdated, then this should update
  404. the version and `self._bindings2`.
  405. """
  406. raise NotImplementedError
  407. # Proxy methods to self._bindings2.
  408. @property
  409. def bindings(self) -> list[Binding]:
  410. self._update_cache()
  411. return self._bindings2.bindings
  412. @property
  413. def _version(self) -> Hashable:
  414. self._update_cache()
  415. return self._last_version
  416. def get_bindings_for_keys(self, keys: KeysTuple) -> list[Binding]:
  417. self._update_cache()
  418. return self._bindings2.get_bindings_for_keys(keys)
  419. def get_bindings_starting_with_keys(self, keys: KeysTuple) -> list[Binding]:
  420. self._update_cache()
  421. return self._bindings2.get_bindings_starting_with_keys(keys)
  422. class ConditionalKeyBindings(_Proxy):
  423. """
  424. Wraps around a `KeyBindings`. Disable/enable all the key bindings according to
  425. the given (additional) filter.::
  426. @Condition
  427. def setting_is_true():
  428. return True # or False
  429. registry = ConditionalKeyBindings(key_bindings, setting_is_true)
  430. When new key bindings are added to this object. They are also
  431. enable/disabled according to the given `filter`.
  432. :param registries: List of :class:`.KeyBindings` objects.
  433. :param filter: :class:`~prompt_toolkit.filters.Filter` object.
  434. """
  435. def __init__(
  436. self, key_bindings: KeyBindingsBase, filter: FilterOrBool = True
  437. ) -> None:
  438. _Proxy.__init__(self)
  439. self.key_bindings = key_bindings
  440. self.filter = to_filter(filter)
  441. def _update_cache(self) -> None:
  442. "If the original key bindings was changed. Update our copy version."
  443. expected_version = self.key_bindings._version
  444. if self._last_version != expected_version:
  445. bindings2 = KeyBindings()
  446. # Copy all bindings from `self.key_bindings`, adding our condition.
  447. for b in self.key_bindings.bindings:
  448. bindings2.bindings.append(
  449. Binding(
  450. keys=b.keys,
  451. handler=b.handler,
  452. filter=self.filter & b.filter,
  453. eager=b.eager,
  454. is_global=b.is_global,
  455. save_before=b.save_before,
  456. record_in_macro=b.record_in_macro,
  457. )
  458. )
  459. self._bindings2 = bindings2
  460. self._last_version = expected_version
  461. class _MergedKeyBindings(_Proxy):
  462. """
  463. Merge multiple registries of key bindings into one.
  464. This class acts as a proxy to multiple :class:`.KeyBindings` objects, but
  465. behaves as if this is just one bigger :class:`.KeyBindings`.
  466. :param registries: List of :class:`.KeyBindings` objects.
  467. """
  468. def __init__(self, registries: Sequence[KeyBindingsBase]) -> None:
  469. _Proxy.__init__(self)
  470. self.registries = registries
  471. def _update_cache(self) -> None:
  472. """
  473. If one of the original registries was changed. Update our merged
  474. version.
  475. """
  476. expected_version = tuple(r._version for r in self.registries)
  477. if self._last_version != expected_version:
  478. bindings2 = KeyBindings()
  479. for reg in self.registries:
  480. bindings2.bindings.extend(reg.bindings)
  481. self._bindings2 = bindings2
  482. self._last_version = expected_version
  483. def merge_key_bindings(bindings: Sequence[KeyBindingsBase]) -> _MergedKeyBindings:
  484. """
  485. Merge multiple :class:`.Keybinding` objects together.
  486. Usage::
  487. bindings = merge_key_bindings([bindings1, bindings2, ...])
  488. """
  489. return _MergedKeyBindings(bindings)
  490. class DynamicKeyBindings(_Proxy):
  491. """
  492. KeyBindings class that can dynamically returns any KeyBindings.
  493. :param get_key_bindings: Callable that returns a :class:`.KeyBindings` instance.
  494. """
  495. def __init__(self, get_key_bindings: Callable[[], KeyBindingsBase | None]) -> None:
  496. self.get_key_bindings = get_key_bindings
  497. self.__version = 0
  498. self._last_child_version = None
  499. self._dummy = KeyBindings() # Empty key bindings.
  500. def _update_cache(self) -> None:
  501. key_bindings = self.get_key_bindings() or self._dummy
  502. assert isinstance(key_bindings, KeyBindingsBase)
  503. version = id(key_bindings), key_bindings._version
  504. self._bindings2 = key_bindings
  505. self._last_version = version
  506. class GlobalOnlyKeyBindings(_Proxy):
  507. """
  508. Wrapper around a :class:`.KeyBindings` object that only exposes the global
  509. key bindings.
  510. """
  511. def __init__(self, key_bindings: KeyBindingsBase) -> None:
  512. _Proxy.__init__(self)
  513. self.key_bindings = key_bindings
  514. def _update_cache(self) -> None:
  515. """
  516. If one of the original registries was changed. Update our merged
  517. version.
  518. """
  519. expected_version = self.key_bindings._version
  520. if self._last_version != expected_version:
  521. bindings2 = KeyBindings()
  522. for b in self.key_bindings.bindings:
  523. if b.is_global():
  524. bindings2.bindings.append(b)
  525. self._bindings2 = bindings2
  526. self._last_version = expected_version