1
|
|
|
"""Keystroke module.""" |
2
|
|
|
import re |
3
|
|
|
from .key import Key |
4
|
|
|
from .util import ensure_bytes |
5
|
|
|
|
6
|
|
|
|
7
|
|
|
KEYS_PATTERN = re.compile(rb'(?:<[^>]+>|\x80\xfc.{2}|\x80.{2}|\S|\s)') |
8
|
|
|
|
9
|
|
|
|
10
|
|
|
class Keystroke(tuple): |
11
|
|
|
"""Keystroke class which indicate multiple keys.""" |
12
|
|
|
|
13
|
|
|
__hash__ = tuple.__hash__ |
14
|
|
|
__slots__ = () |
15
|
|
|
|
16
|
|
|
def __str__(self): |
17
|
|
|
"""Return a string representation of the keystroke.""" |
18
|
|
|
return ''.join(str(k) for k in self) |
19
|
|
|
|
20
|
|
|
def startswith(self, other): |
21
|
|
|
"""Check if the keystroke starts from ``other``. |
22
|
|
|
|
23
|
|
|
Args: |
24
|
|
|
other (Keystroke): A keystroke instance will be checked. |
25
|
|
|
|
26
|
|
|
Returns: |
27
|
|
|
bool: True if the keystroke starts from ``other``. |
28
|
|
|
""" |
29
|
|
|
if len(self) < len(other): |
30
|
|
|
return False |
31
|
|
|
return all(lhs == rhs for lhs, rhs in zip(self, other)) |
32
|
|
|
|
33
|
|
|
@classmethod |
34
|
|
|
def parse(cls, nvim, expr): |
35
|
|
|
r"""Parse a keystroke expression and return a Keystroke instance. |
36
|
|
|
|
37
|
|
|
Args: |
38
|
|
|
nvim (neovim.Nvim): A ``neovim.Nvim`` instance. |
39
|
|
|
expr (tuple, bytes, str): A keystroke expression. |
40
|
|
|
|
41
|
|
|
Example: |
42
|
|
|
>>> from unittest.mock import MagicMock |
43
|
|
|
>>> nvim = MagicMock() |
44
|
|
|
>>> nvim.options = {'encoding': 'utf-8'} |
45
|
|
|
>>> Keystroke.parse(nvim, 'abc') |
46
|
|
|
(Key(code=97, ...), Key(code=98, ...), Key(code=99, ...)) |
47
|
|
|
>>> Keystroke.parse(nvim, '<Insert>') |
48
|
|
|
(Key(code=b'\x80kI', char=''),) |
49
|
|
|
|
50
|
|
|
Returns: |
51
|
|
|
Keystroke: A Keystroke instance. |
52
|
|
|
""" |
53
|
|
|
keys = _ensure_keys(nvim, expr) |
54
|
|
|
instance = cls(keys) |
55
|
|
|
return instance |
56
|
|
|
|
57
|
|
|
|
58
|
|
|
def _ensure_keys(nvim, expr): |
59
|
|
|
if isinstance(expr, (bytes, str)): |
60
|
|
|
expr_bytes = ensure_bytes(nvim, expr) |
61
|
|
|
keys = tuple( |
62
|
|
|
Key.parse(nvim, k) |
63
|
|
|
for k in KEYS_PATTERN.findall(expr_bytes) |
64
|
|
|
) |
65
|
|
|
else: |
66
|
|
|
keys = tuple(expr) |
67
|
|
|
return keys |
68
|
|
|
|