Keystroke   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 46
rs 10
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __str__() 0 3 2
A startswith() 0 12 3
A parse() 0 23 1
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