summaryrefslogtreecommitdiff
path: root/alot/commands/search.py
blob: 8e179e0036d1a2902558620feb1eef0ffa161492 (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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
# Copyright (C) 2011-2012  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 argparse
import logging

from alot.commands import Command, registerCommand
from alot.commands.globals import PromptCommand

from alot.db.errors import DatabaseROError
from alot import commands
from alot import buffers
from alot.walker import PipeWalker
from alot.widgets.search import ThreadlineWidget


MODE = 'search'


@registerCommand(MODE, 'select')
class OpenThreadCommand(Command):
    """open thread in a new buffer"""
    def __init__(self, thread=None, **kwargs):
        """
        :param thread: thread to open (Uses focussed thread if unset)
        :type thread: :class:`~alot.db.Thread`
        """
        self.thread = thread
        Command.__init__(self, **kwargs)

    def apply(self, ui):
        if not self.thread:
            self.thread = ui.current_buffer.get_selected_thread()
        if self.thread:
            query = ui.current_buffer.querystring
            logging.info('open thread view for %s' % self.thread)

            sb = buffers.ThreadBuffer(ui, self.thread)
            ui.buffer_open(sb)
            sb.unfold_matching(query)


@registerCommand(MODE, 'refine', help='refine query', arguments=[
    (['--sort'], {'help':'sort order', 'choices':[
                  'oldest_first', 'newest_first', 'message_id', 'unsorted']}),
    (['query'], {'nargs':argparse.REMAINDER, 'help':'search string'})])
@registerCommand(MODE, 'sort', help='set sort order', arguments=[
    (['sort'], {'help':'sort order', 'choices':[
                'oldest_first', 'newest_first', 'message_id', 'unsorted']}),
])
class RefineCommand(Command):
    """refine the querystring of this buffer"""
    def __init__(self, query=None, sort=None, **kwargs):
        """
        :param query: new querystring given as list of strings as returned by
                      argparse
        :type query: list of str
        """
        if query is None:
            self.querystring = None
        else:
            self.querystring = ' '.join(query)
        self.sort_order = sort
        Command.__init__(self, **kwargs)

    def apply(self, ui):
        if self.querystring or self.sort_order:
            sbuffer = ui.current_buffer
            oldquery = sbuffer.querystring
            if self.querystring not in [None, oldquery]:
                sbuffer.querystring = self.querystring
                sbuffer = ui.current_buffer
            if self.sort_order:
                sbuffer.sort_order = self.sort_order
            sbuffer.rebuild()
            ui.update()
        else:
            ui.notify('empty query string')


@registerCommand(MODE, 'refineprompt')
class RefinePromptCommand(Command):
    """prompt to change this buffers querystring"""
    def apply(self, ui):
        sbuffer = ui.current_buffer
        oldquery = sbuffer.querystring
        ui.apply_command(PromptCommand('refine ' + oldquery))


@registerCommand(MODE, 'retagprompt')
class RetagPromptCommand(Command):
    """prompt to retag selected threads\' tags"""
    def apply(self, ui):
        thread = ui.current_buffer.get_selected_thread()
        if not thread:
            return
        tags = []
        for tag in thread.get_tags():
            if ' ' in tag:
                tags.append('"%s"' % tag)
            else:
                tags.append(tag)
        initial_tagstring = ','.join(tags)
        ui.apply_command(PromptCommand('retag ' + initial_tagstring))


@registerCommand(MODE, 'tag', forced={'action': 'add'}, arguments=[
    (['--all'], {'action': 'store_true', 'dest': 'all', 'default': 'True',
                 'help':'tag all messages in selection'}),
    (['--match'], {'action': 'store_false', 'dest': 'all',
                   'help':'tag matching messages in selection'}),
    (['--no-flush'], {'action': 'store_false', 'dest': 'flush',
                      'default': 'True',
                      'help': 'postpone a writeout to the index'}),
    (['--target'], {'help':'search or thread',
                    'choices':['search', 'thread'], 'default': 'thread'}),
    (['tags'], {'help':'comma separated list of tags'})],
    help='add tags to all messages in the thread',
)
@registerCommand(MODE, 'retag', forced={'action': 'set'}, arguments=[
    (['--all'], {'action': 'store_true', 'dest': 'all', 'default': 'True',
                 'help':'retag all messages in selection'}),
    (['--match'], {'action': 'store_false', 'dest': 'all',
                   'help':'retag matching messages in selection'}),
    (['--no-flush'], {'action': 'store_false', 'dest': 'flush',
                      'default': 'True',
                      'help': 'postpone a writeout to the index'}),
    (['--target'], {'help':'search or thread',
                    'choices':['search', 'thread'], 'default': 'thread'}),
    (['tags'], {'help':'comma separated list of tags'})],
    help='set tags of all messages in the thread',
)
@registerCommand(MODE, 'untag', forced={'action': 'remove'}, arguments=[
    (['--all'], {'action': 'store_true', 'dest': 'all', 'default': 'True',
                 'help':'untag all messages in selection'}),
    (['--match'], {'action': 'store_false', 'dest': 'all',
                   'help':'untag matching messages in selection'}),
    (['--no-flush'], {'action': 'store_false', 'dest': 'flush',
                      'default': 'True',
                      'help': 'postpone a writeout to the index'}),
    (['--target'], {'help':'search or thread',
                    'choices':['search', 'thread'], 'default': 'thread'}),
    (['tags'], {'help':'comma separated list of tags'})],
    help='remove tags from all messages in the thread',
)
@registerCommand(MODE, 'toggletags', forced={'action': 'toggle'}, arguments=[
    (['--no-flush'], {'action': 'store_false', 'dest': 'flush',
                      'default': 'True',
                      'help': 'postpone a writeout to the index'}),
    (['--target'], {'help':'search or thread',
                    'choices':['search', 'thread'], 'default': 'thread'}),
    (['tags'], {'help':'comma separated list of tags'})],
    help="""flip presence of tags on this thread.
    A tag is considered present if at least one message contained in this
    thread is tagged with it. In that case this command will remove the tag
    from every message in the thread.
    """)
class TagCommand(Command):
    """manipulate message tags"""
    def __init__(self, tags=u'', action='add', all=True, flush=True,
                 target='thread', **kwargs):
        """
        :param tags: comma separated list of tagstrings to set
        :type tags: str
        :param action: adds tags if 'add', removes them if 'remove', adds tags
                       and removes all other if 'set' or toggle individually if
                       'toggle'
        :type action: str
        :param target: if 'search' apply changes to search results, if 'thread'
                       apply changes to currently selected thread(s)
        :type target: str
        :param all: tag all messages in target set
        :type all: bool
        :param match: tag only matching messages in target set
        :type match: bool
        :param flush: imediately write out to the index
        :type flush: bool
        """
        self.tagsstring = tags
        self.action = action
        self.all = all
        self.target = target
        self.flush = flush
        Command.__init__(self, **kwargs)

    def apply(self, ui):
        logging.debug('TagCommand.apply target: %s' % self.target)
        searchbuffer = ui.current_buffer
        threadline_widget = searchbuffer.get_selected_threadline()
        # pass if the current buffer has no selected threadline
        # (displays an empty search result)
        if threadline_widget is None:
            return

        if self.all:
            testquery = searchbuffer.querystring
            thread = threadline_widget.get_thread()
            if self.target == 'thread':
                testquery = "(%s) AND thread:%s" % (testquery,
                                                    thread.get_thread_id())

            hitcount_before = ui.dbman.count_messages(testquery)
            thread_count = ui.dbman.count_threads(testquery)
            pipe, proc = ui.dbman.get_threads(testquery)
            threadlist = PipeWalker(pipe, ThreadlineWidget, dbman=ui.dbman)

            def remove_thread():
                logging.debug('remove thread from result list: %s' % thread)
                if threadline_widget in searchbuffer.threadlist:
                    # remove this thread from result list
                    searchbuffer.threadlist.remove(threadline_widget)

            def refresh():
                # remove thread from resultset if it doesn't match the search query
                # any more and refresh selected threadline otherwise
                hitcount_after = ui.dbman.count_messages(testquery)
                # update total result count
                if self.target == 'thread':
                    if hitcount_after == 0:
                        remove_thread()
                    else:
                        threadline_widget.rebuild()
                else:
                    searchbuffer.rebuild()

                searchbuffer.result_count += (hitcount_after - hitcount_before)
                ui.update()

            tags = filter(lambda x: x, self.tagsstring.split(','))
            try:
                pos = -1
                while pos < thread_count - 1:
                    (threadline,size) = threadlist.get_next(pos)
                    thread = threadline.get_thread()
                    if self.action == 'add':
                        thread.add_tags(tags)
                    if self.action == 'set':
                        thread.add_tags(tags, remove_rest=True)
                    elif self.action == 'remove':
                        thread.remove_tags(tags)
                    elif self.action == 'toggle':
                        to_remove = []
                        to_add = []
                        for t in tags:
                            if t in thread.get_tags():
                                to_remove.append(t)
                            else:
                                to_add.append(t)
                        thread.remove_tags(to_remove)
                        thread.add_tags(to_add)
                    pos += 1
            except DatabaseROError:
                ui.notify('index in read-only mode', priority='error')
                return

            # flush index
            if self.flush:
                ui.apply_command(commands.globals.FlushCommand())

            refresh()

        else: # not self.all
            testquery = searchbuffer.querystring
            thread = threadline_widget.get_thread()
            if self.target == 'thread':
                testquery = "(%s) AND thread:%s" % (testquery,
                                                    thread.get_thread_id())

            hitcount_before = ui.dbman.count_messages(testquery)
            thread_count = ui.dbman.count_threads(testquery)

            def remove_thread():
                logging.debug('remove thread from result list: %s' % thread)
                if threadline_widget in searchbuffer.threadlist:
                    # remove this thread from result list
                    searchbuffer.threadlist.remove(threadline_widget)

            def refresh():
                # remove thread from resultset if it doesn't match the search query
                # any more and refresh selected threadline otherwise
                hitcount_after = ui.dbman.count_messages(testquery)
                # update total result count
                if hitcount_after == 0 and self.target == 'thread':
                    remove_thread()

                searchbuffer.result_count += (hitcount_after - hitcount_before)
                searchbuffer.rebuild()
                ui.update()

            tags = filter(lambda x: x, self.tagsstring.split(','))
            try:
                if self.action == 'add':
                    ui.dbman.tag(testquery, tags,
                                 remove_rest=False, afterwards=refresh)
                if self.action == 'set':
                    ui.dbman.tag(testquery, tags,
                                 remove_rest=True, afterwards=refresh)
                elif self.action == 'remove':
                    ui.dbman.untag(testquery, tags, afterwards=refresh)
                elif self.action == 'toggle':
                    ui.notify('toggletags on search matches not supported',
                              priority='error')
            except DatabaseROError:
                ui.notify('index in read-only mode', priority='error')
                return

            # flush index
            if self.flush:
                ui.apply_command(commands.globals.FlushCommand())