registry.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. """
  2. Key bindings registry.
  3. A `Registry` 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. r = Registry()
  8. @r.add_binding(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 registries. We do this in the default
  13. key bindings. There are some registries that contain Emacs bindings, while
  14. others contain the Vi bindings. They are merged together using a
  15. `MergedRegistry`.
  16. We also have a `ConditionalRegistry` object that can enable/disable a group of
  17. key bindings at once.
  18. """
  19. from __future__ import unicode_literals
  20. from abc import ABCMeta, abstractmethod
  21. from prompt_toolkit.cache import SimpleCache
  22. from prompt_toolkit.filters import CLIFilter, to_cli_filter, Never
  23. from prompt_toolkit.keys import Key, Keys
  24. from six import text_type, with_metaclass
  25. __all__ = (
  26. 'BaseRegistry',
  27. 'Registry',
  28. 'ConditionalRegistry',
  29. 'MergedRegistry',
  30. )
  31. class _Binding(object):
  32. """
  33. (Immutable binding class.)
  34. """
  35. def __init__(self, keys, handler, filter=None, eager=None, save_before=None):
  36. assert isinstance(keys, tuple)
  37. assert callable(handler)
  38. assert isinstance(filter, CLIFilter)
  39. assert isinstance(eager, CLIFilter)
  40. assert callable(save_before)
  41. self.keys = keys
  42. self.handler = handler
  43. self.filter = filter
  44. self.eager = eager
  45. self.save_before = save_before
  46. def call(self, event):
  47. return self.handler(event)
  48. def __repr__(self):
  49. return '%s(keys=%r, handler=%r)' % (
  50. self.__class__.__name__, self.keys, self.handler)
  51. class BaseRegistry(with_metaclass(ABCMeta, object)):
  52. """
  53. Interface for a Registry.
  54. """
  55. _version = 0 # For cache invalidation.
  56. @abstractmethod
  57. def get_bindings_for_keys(self, keys):
  58. pass
  59. @abstractmethod
  60. def get_bindings_starting_with_keys(self, keys):
  61. pass
  62. # `add_binding` and `remove_binding` don't have to be part of this
  63. # interface.
  64. class Registry(BaseRegistry):
  65. """
  66. Key binding registry.
  67. """
  68. def __init__(self):
  69. self.key_bindings = []
  70. self._get_bindings_for_keys_cache = SimpleCache(maxsize=10000)
  71. self._get_bindings_starting_with_keys_cache = SimpleCache(maxsize=1000)
  72. self._version = 0 # For cache invalidation.
  73. def _clear_cache(self):
  74. self._version += 1
  75. self._get_bindings_for_keys_cache.clear()
  76. self._get_bindings_starting_with_keys_cache.clear()
  77. def add_binding(self, *keys, **kwargs):
  78. """
  79. Decorator for annotating key bindings.
  80. :param filter: :class:`~prompt_toolkit.filters.CLIFilter` to determine
  81. when this key binding is active.
  82. :param eager: :class:`~prompt_toolkit.filters.CLIFilter` or `bool`.
  83. When True, ignore potential longer matches when this key binding is
  84. hit. E.g. when there is an active eager key binding for Ctrl-X,
  85. execute the handler immediately and ignore the key binding for
  86. Ctrl-X Ctrl-E of which it is a prefix.
  87. :param save_before: Callable that takes an `Event` and returns True if
  88. we should save the current buffer, before handling the event.
  89. (That's the default.)
  90. """
  91. filter = to_cli_filter(kwargs.pop('filter', True))
  92. eager = to_cli_filter(kwargs.pop('eager', False))
  93. save_before = kwargs.pop('save_before', lambda e: True)
  94. to_cli_filter(kwargs.pop('invalidate_ui', True)) # Deprecated! (ignored.)
  95. assert not kwargs
  96. assert keys
  97. assert all(isinstance(k, (Key, text_type)) for k in keys), \
  98. 'Key bindings should consist of Key and string (unicode) instances.'
  99. assert callable(save_before)
  100. if isinstance(filter, Never):
  101. # When a filter is Never, it will always stay disabled, so in that case
  102. # don't bother putting it in the registry. It will slow down every key
  103. # press otherwise.
  104. def decorator(func):
  105. return func
  106. else:
  107. def decorator(func):
  108. self.key_bindings.append(
  109. _Binding(keys, func, filter=filter, eager=eager,
  110. save_before=save_before))
  111. self._clear_cache()
  112. return func
  113. return decorator
  114. def remove_binding(self, function):
  115. """
  116. Remove a key binding.
  117. This expects a function that was given to `add_binding` method as
  118. parameter. Raises `ValueError` when the given function was not
  119. registered before.
  120. """
  121. assert callable(function)
  122. for b in self.key_bindings:
  123. if b.handler == function:
  124. self.key_bindings.remove(b)
  125. self._clear_cache()
  126. return
  127. # No key binding found for this function. Raise ValueError.
  128. raise ValueError('Binding not found: %r' % (function, ))
  129. def get_bindings_for_keys(self, keys):
  130. """
  131. Return a list of key bindings that can handle this key.
  132. (This return also inactive bindings, so the `filter` still has to be
  133. called, for checking it.)
  134. :param keys: tuple of keys.
  135. """
  136. def get():
  137. result = []
  138. for b in self.key_bindings:
  139. if len(keys) == len(b.keys):
  140. match = True
  141. any_count = 0
  142. for i, j in zip(b.keys, keys):
  143. if i != j and i != Keys.Any:
  144. match = False
  145. break
  146. if i == Keys.Any:
  147. any_count += 1
  148. if match:
  149. result.append((any_count, b))
  150. # Place bindings that have more 'Any' occurences in them at the end.
  151. result = sorted(result, key=lambda item: -item[0])
  152. return [item[1] for item in result]
  153. return self._get_bindings_for_keys_cache.get(keys, get)
  154. def get_bindings_starting_with_keys(self, keys):
  155. """
  156. Return a list of key bindings that handle a key sequence starting with
  157. `keys`. (It does only return bindings for which the sequences are
  158. longer than `keys`. And like `get_bindings_for_keys`, it also includes
  159. inactive bindings.)
  160. :param keys: tuple of keys.
  161. """
  162. def get():
  163. result = []
  164. for b in self.key_bindings:
  165. if len(keys) < len(b.keys):
  166. match = True
  167. for i, j in zip(b.keys, keys):
  168. if i != j and i != Keys.Any:
  169. match = False
  170. break
  171. if match:
  172. result.append(b)
  173. return result
  174. return self._get_bindings_starting_with_keys_cache.get(keys, get)
  175. class _AddRemoveMixin(BaseRegistry):
  176. """
  177. Common part for ConditionalRegistry and MergedRegistry.
  178. """
  179. def __init__(self):
  180. # `Registry` to be synchronized with all the others.
  181. self._registry2 = Registry()
  182. self._last_version = None
  183. # The 'extra' registry. Mostly for backwards compatibility.
  184. self._extra_registry = Registry()
  185. def _update_cache(self):
  186. raise NotImplementedError
  187. # For backwards, compatibility, we allow adding bindings to both
  188. # ConditionalRegistry and MergedRegistry. This is however not the
  189. # recommended way. Better is to create a new registry and merge them
  190. # together using MergedRegistry.
  191. def add_binding(self, *k, **kw):
  192. return self._extra_registry.add_binding(*k, **kw)
  193. def remove_binding(self, *k, **kw):
  194. return self._extra_registry.remove_binding(*k, **kw)
  195. # Proxy methods to self._registry2.
  196. @property
  197. def key_bindings(self):
  198. self._update_cache()
  199. return self._registry2.key_bindings
  200. @property
  201. def _version(self):
  202. self._update_cache()
  203. return self._last_version
  204. def get_bindings_for_keys(self, *a, **kw):
  205. self._update_cache()
  206. return self._registry2.get_bindings_for_keys(*a, **kw)
  207. def get_bindings_starting_with_keys(self, *a, **kw):
  208. self._update_cache()
  209. return self._registry2.get_bindings_starting_with_keys(*a, **kw)
  210. class ConditionalRegistry(_AddRemoveMixin):
  211. """
  212. Wraps around a `Registry`. Disable/enable all the key bindings according to
  213. the given (additional) filter.::
  214. @Condition
  215. def setting_is_true(cli):
  216. return True # or False
  217. registy = ConditionalRegistry(registry, setting_is_true)
  218. When new key bindings are added to this object. They are also
  219. enable/disabled according to the given `filter`.
  220. :param registries: List of `Registry` objects.
  221. :param filter: `CLIFilter` object.
  222. """
  223. def __init__(self, registry=None, filter=True):
  224. registry = registry or Registry()
  225. assert isinstance(registry, BaseRegistry)
  226. _AddRemoveMixin.__init__(self)
  227. self.registry = registry
  228. self.filter = to_cli_filter(filter)
  229. def _update_cache(self):
  230. " If the original registry was changed. Update our copy version. "
  231. expected_version = (self.registry._version, self._extra_registry._version)
  232. if self._last_version != expected_version:
  233. registry2 = Registry()
  234. # Copy all bindings from `self.registry`, adding our condition.
  235. for reg in (self.registry, self._extra_registry):
  236. for b in reg.key_bindings:
  237. registry2.key_bindings.append(
  238. _Binding(
  239. keys=b.keys,
  240. handler=b.handler,
  241. filter=self.filter & b.filter,
  242. eager=b.eager,
  243. save_before=b.save_before))
  244. self._registry2 = registry2
  245. self._last_version = expected_version
  246. class MergedRegistry(_AddRemoveMixin):
  247. """
  248. Merge multiple registries of key bindings into one.
  249. This class acts as a proxy to multiple `Registry` objects, but behaves as
  250. if this is just one bigger `Registry`.
  251. :param registries: List of `Registry` objects.
  252. """
  253. def __init__(self, registries):
  254. assert all(isinstance(r, BaseRegistry) for r in registries)
  255. _AddRemoveMixin.__init__(self)
  256. self.registries = registries
  257. def _update_cache(self):
  258. """
  259. If one of the original registries was changed. Update our merged
  260. version.
  261. """
  262. expected_version = (
  263. tuple(r._version for r in self.registries) +
  264. (self._extra_registry._version, ))
  265. if self._last_version != expected_version:
  266. registry2 = Registry()
  267. for reg in self.registries:
  268. registry2.key_bindings.extend(reg.key_bindings)
  269. # Copy all bindings from `self._extra_registry`.
  270. registry2.key_bindings.extend(self._extra_registry.key_bindings)
  271. self._registry2 = registry2
  272. self._last_version = expected_version