summaryrefslogtreecommitdiff
path: root/alot/completion/query.py
blob: 88bf3ae42f4f9be2a1e53e580e36775b03367e05 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# Copyright (C) 2011-2019  Patrick Totzke <patricktotzke@gmail.com>
# This file is released under the GNU GPL, version 3 or a later revision.
# For further details see the COPYING file

import re

from alot.settings.const import settings
from .completer import Completer
from .abooks import AbooksCompleter
from .tag import TagCompleter
from .namedquery import NamedQueryCompleter


class QueryCompleter(Completer):
    """completion for a notmuch query string"""

    _abookscompleter = None
    _tagcompleter    = None
    _nquerycompleter = None

    _KEYWORDS = (
        'body', 'from', 'to', 'subject', 'attachment', 'mimetype',
        'tag', 'id', 'thread', 'path', 'folder', 'date', 'lastmod',
        'query', 'property',
    )

    def __init__(self, dbman):
        """
        :param dbman: used to look up available tagstrings
        :type dbman: :class:`~alot.db.DBManager`
        """
        abooks = settings.get_addressbooks()
        self._abookscompleter = AbooksCompleter(abooks, addressesonly=True)
        self._tagcompleter = TagCompleter(dbman)
        self._nquerycompleter = NamedQueryCompleter(dbman)

        super().__init__()

    def complete(self, original, pos):
        mypart, start, end, mypos = self.relevant_part(original, pos)
        myprefix = mypart[:mypos]
        m = re.search(r'(tag|is|to|from|query):(\w*)', myprefix)
        if m:
            cmd, _ = m.groups()
            cmdlen = len(cmd) + 1  # length of the keyword part including colon
            if cmd in ['to', 'from']:
                localres = self._abookscompleter.complete(mypart[cmdlen:],
                                                          mypos - cmdlen)
            elif cmd in ['query']:
                localres = self._nquerycompleter.complete(mypart[cmdlen:],
                                                          mypos - cmdlen)
            else:
                localres = self._tagcompleter.complete(mypart[cmdlen:],
                                                       mypos - cmdlen)
            resultlist = []
            for ltxt, lpos in localres:
                newtext = original[:start] + cmd + ':' + ltxt + original[end:]
                newpos = start + len(cmd) + 1 + lpos
                resultlist.append((newtext, newpos))
            return resultlist
        else:
            matched = (t for t in self._KEYWORDS if t.startswith(myprefix))
            resultlist = []
            for keyword in matched:
                newprefix = original[:start] + keyword + ':'
                resultlist.append((newprefix + original[end:], len(newprefix)))
            return resultlist