1# -*- coding: utf-8 -*-
2"""A (tab-)completer for xonsh."""
3import builtins
4import collections.abc as cabc
5
6
7class Completer(object):
8    """This provides a list of optional completions for the xonsh shell."""
9
10    def complete(self, prefix, line, begidx, endidx, ctx=None):
11        """Complete the string, given a possible execution context.
12
13        Parameters
14        ----------
15        prefix : str
16            The string to match
17        line : str
18            The line that prefix appears on.
19        begidx : int
20            The index in line that prefix starts on.
21        endidx : int
22            The index in line that prefix ends on.
23        ctx : Iterable of str (ie dict, set, etc), optional
24            Names in the current execution context.
25
26        Returns
27        -------
28        rtn : list of str
29            Possible completions of prefix, sorted alphabetically.
30        lprefix : int
31            Length of the prefix to be replaced in the completion.
32        """
33        ctx = ctx or {}
34        for func in builtins.__xonsh_completers__.values():
35            try:
36                out = func(prefix, line, begidx, endidx, ctx)
37            except StopIteration:
38                return set(), len(prefix)
39            if isinstance(out, cabc.Sequence):
40                res, lprefix = out
41            else:
42                res = out
43                lprefix = len(prefix)
44            if res is not None and len(res) != 0:
45
46                def sortkey(s):
47                    return s.lstrip(''''"''').lower()
48
49                return tuple(sorted(res, key=sortkey)), lprefix
50        return set(), lprefix
51