Completed
Push — master ( 2e9895...6383ba )
by Lambda
01:23
created

Keystroke.__str__()   A

Complexity

Conditions 2

Size

Total Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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