Exemple #1
0
    def test_partial_parsing(self, config_stub):
        """Test partial parsing with a runner where it's enabled.

        The same with it being disabled is tested by test_parse_all.
        """
        p = parser.CommandParser(partial_match=True)
        result = p.parse('on')
        assert result.cmd.name == 'one'
Exemple #2
0
    def test_parse_empty_with_alias(self, command):
        """An empty command should not crash.

        See https://github.com/qutebrowser/qutebrowser/issues/1690
        and https://github.com/qutebrowser/qutebrowser/issues/1773
        """
        p = parser.CommandParser()
        with pytest.raises(cmdexc.EmptyCommandError):
            p.parse_all(command)
Exemple #3
0
    def test_use_best_match(self, config_stub):
        """Test multiple completion options with use_best_match set to true.

        The resulting command should be the best match
        """
        config_stub.val.completion.use_best_match = True
        p = parser.CommandParser(partial_match=True)

        result = p.parse('tw')
        assert result.cmd.name == 'two'
Exemple #4
0
    def test_dont_use_best_match(self, config_stub):
        """Test multiple completion options with use_best_match set to false.

        Should raise NoSuchCommandError
        """
        config_stub.val.completion.use_best_match = False
        p = parser.CommandParser(partial_match=True)

        with pytest.raises(cmdexc.NoSuchCommandError):
            p.parse('tw')
Exemple #5
0
 def __init__(self,
              win_id,
              partial_match=False,
              find_similar=True,
              parent=None):
     super().__init__(parent)
     self._parser = parser.CommandParser(
         partial_match=partial_match,
         find_similar=find_similar,
     )
     self._win_id = win_id
Exemple #6
0
    def test_parse_all_with_alias(self, cmdline_test, monkeypatch,
                                  config_stub):
        if not cmdline_test.cmd:
            pytest.skip("Empty command")

        config_stub.val.aliases = {'alias_name': cmdline_test.cmd}

        p = parser.CommandParser()
        if cmdline_test.valid:
            assert len(p.parse_all("alias_name")) > 0
        else:
            with pytest.raises(cmdexc.NoSuchCommandError):
                p.parse_all("alias_name")
Exemple #7
0
    def test_parse_all(self, cmdline_test):
        """Test parsing of commands.

        See https://github.com/qutebrowser/qutebrowser/issues/615

        Args:
            cmdline_test: A pytest fixture which provides testcases.
        """
        p = parser.CommandParser()
        if cmdline_test.valid:
            p.parse_all(cmdline_test.cmd, aliases=False)
        else:
            with pytest.raises(cmdexc.NoSuchCommandError):
                p.parse_all(cmdline_test.cmd, aliases=False)
Exemple #8
0
    def _implied_cmd(self, cmdline: str) -> Optional[str]:
        """Return cmdline, or the implied cmd if cmdline is a set-cmd-text."""
        try:
            results = parser.CommandParser().parse_all(cmdline)
        except cmdexc.NoSuchCommandError:
            return None

        result = results[0]
        if result.cmd.name != "set-cmd-text":
            return cmdline
        *flags, cmd = result.args
        if "-a" in flags or "--append" in flags or not cmd.startswith(":"):
            return None  # doesn't look like this sets a command
        return cmd.lstrip(":")
def _bind_current_default(key, info):
    """Get current/default data for the given key."""
    data = []
    try:
        seq = keyutils.KeySequence.parse(key)
    except keyutils.KeyParseError as e:
        data.append(('', str(e), key))
        return data

    cmd_text = info.keyconf.get_command(seq, 'normal')
    if cmd_text:
        try:
            cmd = parser.CommandParser().parse(cmd_text).cmd
        except cmdexc.NoSuchCommandError:
            data.append((cmd_text, '(Current) Invalid command!', key))
        else:
            data.append((cmd_text, '(Current) {}'.format(cmd.desc), key))

    cmd_text = info.keyconf.get_command(seq, 'normal', default=True)
    if cmd_text:
        cmd = parser.CommandParser().parse(cmd_text).cmd
        data.append((cmd_text, '(Default) {}'.format(cmd.desc), key))

    return data
Exemple #10
0
    def _partition(self):
        """Divide the commandline text into chunks around the cursor position.

        Return:
            ([parts_before_cursor], 'part_under_cursor', [parts_after_cursor])
        """
        text = self._cmd.text()[len(self._cmd.prefix()):]
        if not text or not text.strip():
            # Only ":", empty part under the cursor with nothing before/after
            return [], '', []

        try:
            parse_result = parser.CommandParser().parse(text, keep=True)
        except cmdexc.NoSuchCommandError:
            cmdline = split.split(text, keep=True)
        else:
            cmdline = parse_result.cmdline

        parts = [x for x in cmdline if x]
        pos = self._cmd.cursorPosition() - len(self._cmd.prefix())
        pos = min(pos, len(text))  # Qt treats 2-byte UTF-16 chars as 2 chars
        log.completion.debug(f'partitioning {parts} around position {pos}')
        for i, part in enumerate(parts):
            pos -= len(part)
            if pos <= 0:
                if part[pos - 1:pos + 1].isspace():
                    # cursor is in a space between two existing words
                    parts.insert(i, '')
                prefix = [x.strip() for x in parts[:i]]
                # pylint: disable-next=unnecessary-list-index-lookup
                center = parts[i].strip()
                # strip trailing whitespace included as a separate token
                postfix = [x.strip() for x in parts[i + 1:] if not x.isspace()]
                log.completion.debug(
                    f"partitioned: {prefix} '{center}' {postfix}")
                return prefix, center, postfix

        raise utils.Unreachable(f"Not all parts consumed: {parts}")
 def __init__(self, win_id, partial_match=False, parent=None):
     super().__init__(parent)
     self._parser = parser.CommandParser(partial_match=partial_match)
     self._win_id = win_id
Exemple #12
0
 def test_parse_result(self, config_stub, command, name, args):
     p = parser.CommandParser()
     result = p.parse_all(command)[0]
     assert result.cmd.name == name
     assert result.args == args
Exemple #13
0
def test_find_similar(find_similar, msg):
    p = parser.CommandParser(find_similar=find_similar)
    with pytest.raises(cmdexc.NoSuchCommandError, match=re.escape(msg)):
        p.parse_all("tabfocus", aliases=False)