]> git.notmuchmail.org Git - notmuch/blob - notmuch-search.c
emacs: Add new option notmuch-search-hide-excluded
[notmuch] / notmuch-search.c
1 /* notmuch - Not much of an email program, (just index and search)
2  *
3  * Copyright © 2009 Carl Worth
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see https://www.gnu.org/licenses/ .
17  *
18  * Author: Carl Worth <cworth@cworth.org>
19  */
20
21 #include "notmuch-client.h"
22 #include "sprinter.h"
23 #include "string-util.h"
24
25 typedef enum {
26     /* Search command */
27     OUTPUT_SUMMARY      = 1 << 0,
28     OUTPUT_THREADS      = 1 << 1,
29     OUTPUT_MESSAGES     = 1 << 2,
30     OUTPUT_FILES        = 1 << 3,
31     OUTPUT_TAGS         = 1 << 4,
32
33     /* Address command */
34     OUTPUT_SENDER       = 1 << 5,
35     OUTPUT_RECIPIENTS   = 1 << 6,
36     OUTPUT_COUNT        = 1 << 7,
37     OUTPUT_ADDRESS      = 1 << 8,
38 } output_t;
39
40 typedef enum {
41     DEDUP_NONE,
42     DEDUP_MAILBOX,
43     DEDUP_ADDRESS,
44 } dedup_t;
45
46 typedef enum {
47     NOTMUCH_FORMAT_JSON,
48     NOTMUCH_FORMAT_TEXT,
49     NOTMUCH_FORMAT_TEXT0,
50     NOTMUCH_FORMAT_SEXP
51 } format_sel_t;
52
53 typedef struct {
54     notmuch_database_t *notmuch;
55     void *talloc_ctx;
56     int format_sel;
57     sprinter_t *format;
58     int exclude;
59     int query_syntax;
60     notmuch_query_t *query;
61     int sort;
62     int output;
63     int offset;
64     int limit;
65     int dupe;
66     GHashTable *addresses;
67     int dedup;
68 } search_context_t;
69
70 typedef struct {
71     const char *name;
72     const char *addr;
73     int count;
74 } mailbox_t;
75
76 /* Return two stable query strings that identify exactly the matched
77  * and unmatched messages currently in thread.  If there are no
78  * matched or unmatched messages, the returned buffers will be
79  * NULL. */
80 static int
81 get_thread_query (notmuch_thread_t *thread,
82                   char **matched_out, char **unmatched_out)
83 {
84     notmuch_messages_t *messages;
85     char *escaped = NULL;
86     size_t escaped_len = 0;
87
88     *matched_out = *unmatched_out = NULL;
89
90     for (messages = notmuch_thread_get_messages (thread);
91          notmuch_messages_valid (messages);
92          notmuch_messages_move_to_next (messages)) {
93         notmuch_message_t *message = notmuch_messages_get (messages);
94         const char *mid = notmuch_message_get_message_id (message);
95         notmuch_bool_t is_set;
96         char **buf;
97
98         if (notmuch_message_get_flag_st (message, NOTMUCH_MESSAGE_FLAG_MATCH, &is_set))
99             return -1;
100         /* Determine which query buffer to extend */
101         buf = is_set ? matched_out : unmatched_out;
102         /* Add this message's id: query.  Since "id" is an exclusive
103          * prefix, it is implicitly 'or'd together, so we only need to
104          * join queries with a space. */
105         if (make_boolean_term (thread, "id", mid, &escaped, &escaped_len) < 0)
106             return -1;
107         if (*buf)
108             *buf = talloc_asprintf_append_buffer (*buf, " %s", escaped);
109         else
110             *buf = talloc_strdup (thread, escaped);
111         if (! *buf)
112             return -1;
113     }
114     talloc_free (escaped);
115     return 0;
116 }
117
118 static int
119 do_search_threads (search_context_t *ctx)
120 {
121     notmuch_thread_t *thread;
122     notmuch_threads_t *threads;
123     notmuch_tags_t *tags;
124     sprinter_t *format = ctx->format;
125     time_t date;
126     int i;
127     notmuch_status_t status;
128
129     if (ctx->offset < 0) {
130         unsigned count;
131         notmuch_status_t status;
132         status = notmuch_query_count_threads (ctx->query, &count);
133         if (print_status_query ("notmuch search", ctx->query, status))
134             return 1;
135
136         ctx->offset += count;
137         if (ctx->offset < 0)
138             ctx->offset = 0;
139     }
140
141     status = notmuch_query_search_threads (ctx->query, &threads);
142     if (print_status_query ("notmuch search", ctx->query, status))
143         return 1;
144
145     format->begin_list (format);
146
147     for (i = 0;
148          notmuch_threads_valid (threads) && (ctx->limit < 0 || i < ctx->offset + ctx->limit);
149          notmuch_threads_move_to_next (threads), i++) {
150         thread = notmuch_threads_get (threads);
151
152         if (i < ctx->offset) {
153             notmuch_thread_destroy (thread);
154             continue;
155         }
156
157         if (ctx->output == OUTPUT_THREADS) {
158             format->set_prefix (format, "thread");
159             format->string (format,
160                             notmuch_thread_get_thread_id (thread));
161             format->separator (format);
162         } else { /* output == OUTPUT_SUMMARY */
163             void *ctx_quote = talloc_new (thread);
164             const char *authors = notmuch_thread_get_authors (thread);
165             const char *subject = notmuch_thread_get_subject (thread);
166             const char *thread_id = notmuch_thread_get_thread_id (thread);
167             int matched = notmuch_thread_get_matched_messages (thread);
168             int files = notmuch_thread_get_total_files (thread);
169             int total = notmuch_thread_get_total_messages (thread);
170             const char *relative_date = NULL;
171             bool first_tag = true;
172
173             format->begin_map (format);
174
175             if (ctx->sort == NOTMUCH_SORT_OLDEST_FIRST)
176                 date = notmuch_thread_get_oldest_date (thread);
177             else
178                 date = notmuch_thread_get_newest_date (thread);
179
180             relative_date = notmuch_time_relative_date (ctx_quote, date);
181
182             if (format->is_text_printer) {
183                 /* Special case for the text formatter */
184                 printf ("thread:%s %12s ",
185                         thread_id,
186                         relative_date);
187                 if (total == files)
188                     printf ("[%d/%d] %s; %s (",
189                             matched,
190                             total,
191                             sanitize_string (ctx_quote, authors),
192                             sanitize_string (ctx_quote, subject));
193                 else
194                     printf ("[%d/%d(%d)] %s; %s (",
195                             matched,
196                             total,
197                             files,
198                             sanitize_string (ctx_quote, authors),
199                             sanitize_string (ctx_quote, subject));
200
201             } else { /* Structured Output */
202                 format->map_key (format, "thread");
203                 format->string (format, thread_id);
204                 format->map_key (format, "timestamp");
205                 format->integer (format, date);
206                 format->map_key (format, "date_relative");
207                 format->string (format, relative_date);
208                 format->map_key (format, "matched");
209                 format->integer (format, matched);
210                 format->map_key (format, "total");
211                 format->integer (format, total);
212                 format->map_key (format, "authors");
213                 format->string (format, authors);
214                 format->map_key (format, "subject");
215                 format->string (format, subject);
216                 if (notmuch_format_version >= 2) {
217                     char *matched_query, *unmatched_query;
218                     if (get_thread_query (thread, &matched_query,
219                                           &unmatched_query) < 0) {
220                         fprintf (stderr, "Out of memory\n");
221                         return 1;
222                     }
223                     format->map_key (format, "query");
224                     format->begin_list (format);
225                     if (matched_query)
226                         format->string (format, matched_query);
227                     else
228                         format->null (format);
229                     if (unmatched_query)
230                         format->string (format, unmatched_query);
231                     else
232                         format->null (format);
233                     format->end (format);
234                 }
235             }
236
237             talloc_free (ctx_quote);
238
239             format->map_key (format, "tags");
240             format->begin_list (format);
241
242             for (tags = notmuch_thread_get_tags (thread);
243                  notmuch_tags_valid (tags);
244                  notmuch_tags_move_to_next (tags)) {
245                 const char *tag = notmuch_tags_get (tags);
246
247                 if (format->is_text_printer) {
248                     /* Special case for the text formatter */
249                     if (first_tag)
250                         first_tag = false;
251                     else
252                         fputc (' ', stdout);
253                     fputs (tag, stdout);
254                 } else { /* Structured Output */
255                     format->string (format, tag);
256                 }
257             }
258
259             if (format->is_text_printer)
260                 printf (")");
261
262             format->end (format);
263             format->end (format);
264             format->separator (format);
265         }
266
267         notmuch_thread_destroy (thread);
268     }
269
270     format->end (format);
271
272     return 0;
273 }
274
275 static mailbox_t *
276 new_mailbox (void *ctx, const char *name, const char *addr)
277 {
278     mailbox_t *mailbox;
279
280     mailbox = talloc (ctx, mailbox_t);
281     if (! mailbox)
282         return NULL;
283
284     mailbox->name = talloc_strdup (mailbox, name);
285     mailbox->addr = talloc_strdup (mailbox, addr);
286     mailbox->count = 1;
287
288     return mailbox;
289 }
290
291 static int
292 mailbox_compare (const void *v1, const void *v2)
293 {
294     const mailbox_t *m1 = v1, *m2 = v2;
295     int ret;
296
297     ret = strcmp_null (m1->name, m2->name);
298     if (! ret)
299         ret = strcmp (m1->addr, m2->addr);
300
301     return ret;
302 }
303
304 /* Returns true iff name and addr is duplicate. If not, stores the
305  * name/addr pair in order to detect subsequent duplicates. */
306 static bool
307 is_duplicate (const search_context_t *ctx, const char *name, const char *addr)
308 {
309     char *key;
310     GList *list, *l;
311     mailbox_t *mailbox;
312
313     list = g_hash_table_lookup (ctx->addresses, addr);
314     if (list) {
315         mailbox_t find = {
316             .name = name,
317             .addr = addr,
318         };
319
320         l = g_list_find_custom (list, &find, mailbox_compare);
321         if (l) {
322             mailbox = l->data;
323             mailbox->count++;
324             return true;
325         }
326
327         mailbox = new_mailbox (ctx->format, name, addr);
328         if (! mailbox)
329             return false;
330
331         /*
332          * XXX: It would be more efficient to prepend to the list, but
333          * then we'd have to store the changed list head back to the
334          * hash table. This check is here just to avoid the compiler
335          * warning for unused result.
336          */
337         if (list != g_list_append (list, mailbox))
338             INTERNAL_ERROR ("appending to list changed list head\n");
339
340         return false;
341     }
342
343     key = talloc_strdup (ctx->format, addr);
344     if (! key)
345         return false;
346
347     mailbox = new_mailbox (ctx->format, name, addr);
348     if (! mailbox)
349         return false;
350
351     list = g_list_append (NULL, mailbox);
352     if (! list)
353         return false;
354
355     g_hash_table_insert (ctx->addresses, key, list);
356
357     return false;
358 }
359
360 static void
361 print_mailbox (const search_context_t *ctx, const mailbox_t *mailbox)
362 {
363     const char *name = mailbox->name;
364     const char *addr = mailbox->addr;
365     int count = mailbox->count;
366     sprinter_t *format = ctx->format;
367     InternetAddress *ia = internet_address_mailbox_new (name, addr);
368     char *name_addr;
369
370     /* name_addr has the name part quoted if necessary. Compare
371      * 'John Doe <john@doe.com>' vs. '"Doe, John" <john@doe.com>' */
372     name_addr = internet_address_to_string (ia, NULL, false);
373
374     if (format->is_text_printer) {
375         if (ctx->output & OUTPUT_COUNT) {
376             format->integer (format, count);
377             format->string (format, "\t");
378         }
379         if (ctx->output & OUTPUT_ADDRESS)
380             format->string (format, addr);
381         else
382             format->string (format, name_addr);
383         format->separator (format);
384     } else {
385         format->begin_map (format);
386         format->map_key (format, "name");
387         format->string (format, name);
388         format->map_key (format, "address");
389         format->string (format, addr);
390         format->map_key (format, "name-addr");
391         format->string (format, name_addr);
392         if (ctx->output & OUTPUT_COUNT) {
393             format->map_key (format, "count");
394             format->integer (format, count);
395         }
396         format->end (format);
397         format->separator (format);
398     }
399
400     g_object_unref (ia);
401     g_free (name_addr);
402 }
403
404 /* Print or prepare for printing addresses from InternetAddressList. */
405 static void
406 process_address_list (const search_context_t *ctx,
407                       InternetAddressList *list)
408 {
409     InternetAddress *address;
410     int i;
411
412     for (i = 0; i < internet_address_list_length (list); i++) {
413         address = internet_address_list_get_address (list, i);
414         if (INTERNET_ADDRESS_IS_GROUP (address)) {
415             InternetAddressGroup *group;
416             InternetAddressList *group_list;
417
418             group = INTERNET_ADDRESS_GROUP (address);
419             group_list = internet_address_group_get_members (group);
420             if (group_list == NULL)
421                 continue;
422
423             process_address_list (ctx, group_list);
424         } else {
425             InternetAddressMailbox *mailbox = INTERNET_ADDRESS_MAILBOX (address);
426             mailbox_t mbx = {
427                 .name = internet_address_get_name (address),
428                 .addr = internet_address_mailbox_get_addr (mailbox),
429             };
430
431             /* OUTPUT_COUNT only works with deduplication */
432             if (ctx->dedup != DEDUP_NONE &&
433                 is_duplicate (ctx, mbx.name, mbx.addr))
434                 continue;
435
436             /* OUTPUT_COUNT and DEDUP_ADDRESS require a full pass. */
437             if (ctx->output & OUTPUT_COUNT || ctx->dedup == DEDUP_ADDRESS)
438                 continue;
439
440             print_mailbox (ctx, &mbx);
441         }
442     }
443 }
444
445 /* Print or prepare for printing addresses from a message header. */
446 static void
447 process_address_header (const search_context_t *ctx, const char *value)
448 {
449     InternetAddressList *list;
450
451     if (value == NULL)
452         return;
453
454     list = internet_address_list_parse (NULL, value);
455     if (list == NULL)
456         return;
457
458     process_address_list (ctx, list);
459
460     g_object_unref (list);
461 }
462
463 /* Destructor for talloc-allocated GHashTable keys and values. */
464 static void
465 _talloc_free_for_g_hash (void *ptr)
466 {
467     talloc_free (ptr);
468 }
469
470 static void
471 _list_free_for_g_hash (void *ptr)
472 {
473     g_list_free_full (ptr, _talloc_free_for_g_hash);
474 }
475
476 /* Print the most common variant of a list of unique mailboxes, and
477  * conflate the counts. */
478 static void
479 print_popular (const search_context_t *ctx, GList *list)
480 {
481     GList *l;
482     mailbox_t *mailbox = NULL, *m;
483     int max = 0;
484     int total = 0;
485
486     for (l = list; l; l = l->next) {
487         m = l->data;
488         total += m->count;
489         if (m->count > max) {
490             mailbox = m;
491             max = m->count;
492         }
493     }
494
495     if (! mailbox)
496         INTERNAL_ERROR ("Empty list in address hash table\n");
497
498     /* The original count is no longer needed, so overwrite. */
499     mailbox->count = total;
500
501     print_mailbox (ctx, mailbox);
502 }
503
504 static void
505 print_list_value (void *mailbox, void *context)
506 {
507     print_mailbox (context, mailbox);
508 }
509
510 static void
511 print_hash_value (unused (void *key), void *list, void *context)
512 {
513     const search_context_t *ctx = context;
514
515     if (ctx->dedup == DEDUP_ADDRESS)
516         print_popular (ctx, list);
517     else
518         g_list_foreach (list, print_list_value, context);
519 }
520
521 static int
522 _count_filenames (notmuch_message_t *message)
523 {
524     notmuch_filenames_t *filenames;
525     int i = 0;
526
527     filenames = notmuch_message_get_filenames (message);
528
529     while (notmuch_filenames_valid (filenames)) {
530         notmuch_filenames_move_to_next (filenames);
531         i++;
532     }
533
534     notmuch_filenames_destroy (filenames);
535
536     return i;
537 }
538
539 static int
540 do_search_messages (search_context_t *ctx)
541 {
542     notmuch_message_t *message;
543     notmuch_messages_t *messages;
544     notmuch_filenames_t *filenames;
545     sprinter_t *format = ctx->format;
546     int i;
547     notmuch_status_t status;
548
549     if (ctx->offset < 0) {
550         unsigned count;
551         notmuch_status_t status;
552         status = notmuch_query_count_messages (ctx->query, &count);
553         if (print_status_query ("notmuch search", ctx->query, status))
554             return 1;
555
556         ctx->offset += count;
557         if (ctx->offset < 0)
558             ctx->offset = 0;
559     }
560
561     status = notmuch_query_search_messages (ctx->query, &messages);
562     if (print_status_query ("notmuch search", ctx->query, status))
563         return 1;
564
565     format->begin_list (format);
566
567     for (i = 0;
568          notmuch_messages_valid (messages) && (ctx->limit < 0 || i < ctx->offset + ctx->limit);
569          notmuch_messages_move_to_next (messages), i++) {
570         if (i < ctx->offset)
571             continue;
572
573         message = notmuch_messages_get (messages);
574
575         if (ctx->output == OUTPUT_FILES) {
576             int j;
577             filenames = notmuch_message_get_filenames (message);
578
579             for (j = 1;
580                  notmuch_filenames_valid (filenames);
581                  notmuch_filenames_move_to_next (filenames), j++) {
582                 if (ctx->dupe < 0 || ctx->dupe == j) {
583                     format->string (format, notmuch_filenames_get (filenames));
584                     format->separator (format);
585                 }
586             }
587
588             notmuch_filenames_destroy ( filenames );
589
590         } else if (ctx->output == OUTPUT_MESSAGES) {
591             /* special case 1 for speed */
592             if (ctx->dupe <= 1 || ctx->dupe <= _count_filenames (message)) {
593                 format->set_prefix (format, "id");
594                 format->string (format,
595                                 notmuch_message_get_message_id (message));
596                 format->separator (format);
597             }
598         } else {
599             if (ctx->output & OUTPUT_SENDER) {
600                 const char *addrs;
601
602                 addrs = notmuch_message_get_header (message, "from");
603                 process_address_header (ctx, addrs);
604             }
605
606             if (ctx->output & OUTPUT_RECIPIENTS) {
607                 const char *hdrs[] = { "to", "cc", "bcc" };
608                 const char *addrs;
609                 size_t j;
610
611                 for (j = 0; j < ARRAY_SIZE (hdrs); j++) {
612                     addrs = notmuch_message_get_header (message, hdrs[j]);
613                     process_address_header (ctx, addrs);
614                 }
615             }
616         }
617
618         notmuch_message_destroy (message);
619     }
620
621     if (ctx->addresses &&
622         (ctx->output & OUTPUT_COUNT || ctx->dedup == DEDUP_ADDRESS))
623         g_hash_table_foreach (ctx->addresses, print_hash_value, ctx);
624
625     notmuch_messages_destroy (messages);
626
627     format->end (format);
628
629     return 0;
630 }
631
632 static int
633 do_search_tags (const search_context_t *ctx)
634 {
635     notmuch_messages_t *messages = NULL;
636     notmuch_tags_t *tags;
637     const char *tag;
638     sprinter_t *format = ctx->format;
639     notmuch_query_t *query = ctx->query;
640     notmuch_database_t *notmuch = ctx->notmuch;
641
642     /* should the following only special case if no excluded terms
643      * specified? */
644
645     /* Special-case query of "*" for better performance. */
646     if (strcmp (notmuch_query_get_query_string (query), "*") == 0) {
647         tags = notmuch_database_get_all_tags (notmuch);
648     } else {
649         notmuch_status_t status;
650         status = notmuch_query_search_messages (query, &messages);
651         if (print_status_query ("notmuch search", query, status))
652             return 1;
653
654         tags = notmuch_messages_collect_tags (messages);
655     }
656     if (tags == NULL)
657         return 1;
658
659     format->begin_list (format);
660
661     for (;
662          notmuch_tags_valid (tags);
663          notmuch_tags_move_to_next (tags)) {
664         tag = notmuch_tags_get (tags);
665
666         format->string (format, tag);
667         format->separator (format);
668
669     }
670
671     notmuch_tags_destroy (tags);
672
673     if (messages)
674         notmuch_messages_destroy (messages);
675
676     format->end (format);
677
678     return 0;
679 }
680
681 static int
682 _notmuch_search_prepare (search_context_t *ctx, int argc, char *argv[])
683 {
684     char *query_str;
685
686     if (! ctx->talloc_ctx)
687         ctx->talloc_ctx = talloc_new (NULL);
688
689     switch (ctx->format_sel) {
690     case NOTMUCH_FORMAT_TEXT:
691         ctx->format = sprinter_text_create (ctx->talloc_ctx, stdout);
692         break;
693     case NOTMUCH_FORMAT_TEXT0:
694         if (ctx->output == OUTPUT_SUMMARY) {
695             fprintf (stderr, "Error: --format=text0 is not compatible with --output=summary.\n");
696             return EXIT_FAILURE;
697         }
698         ctx->format = sprinter_text0_create (ctx->talloc_ctx, stdout);
699         break;
700     case NOTMUCH_FORMAT_JSON:
701         ctx->format = sprinter_json_create (ctx->talloc_ctx, stdout);
702         break;
703     case NOTMUCH_FORMAT_SEXP:
704         ctx->format = sprinter_sexp_create (ctx->talloc_ctx, stdout);
705         break;
706     default:
707         /* this should never happen */
708         INTERNAL_ERROR ("no output format selected");
709     }
710
711     notmuch_exit_if_unsupported_format ();
712
713     query_str = query_string_from_args (ctx->notmuch, argc, argv);
714     if (query_str == NULL) {
715         fprintf (stderr, "Out of memory.\n");
716         return EXIT_FAILURE;
717     }
718     if (*query_str == '\0') {
719         fprintf (stderr, "Error: notmuch search requires at least one search term.\n");
720         return EXIT_FAILURE;
721     }
722
723     if (print_status_database ("notmuch search", ctx->notmuch,
724                                notmuch_query_create_with_syntax (ctx->notmuch, query_str,
725                                                                  shared_option_query_syntax (),
726                                                                  &ctx->query)))
727         return EXIT_FAILURE;
728
729     notmuch_query_set_sort (ctx->query, ctx->sort);
730
731     if (ctx->exclude == NOTMUCH_EXCLUDE_FLAG && ctx->output != OUTPUT_SUMMARY) {
732         /* If we are not doing summary output there is nowhere to
733          * print the excluded flag so fall back on including the
734          * excluded messages. */
735         fprintf (stderr, "Warning: this output format cannot flag excluded messages.\n");
736         ctx->exclude = NOTMUCH_EXCLUDE_FALSE;
737     }
738
739     if (ctx->exclude != NOTMUCH_EXCLUDE_FALSE) {
740         notmuch_config_values_t *exclude_tags;
741         notmuch_status_t status;
742
743         for (exclude_tags = notmuch_config_get_values (ctx->notmuch, NOTMUCH_CONFIG_EXCLUDE_TAGS);
744              notmuch_config_values_valid (exclude_tags);
745              notmuch_config_values_move_to_next (exclude_tags)) {
746
747             status = notmuch_query_add_tag_exclude (ctx->query,
748                                                     notmuch_config_values_get (exclude_tags));
749             if (status && status != NOTMUCH_STATUS_IGNORED) {
750                 print_status_query ("notmuch search", ctx->query, status);
751                 return EXIT_FAILURE;
752             }
753         }
754         notmuch_query_set_omit_excluded (ctx->query, ctx->exclude);
755     }
756
757     return 0;
758 }
759
760 static void
761 _notmuch_search_cleanup (search_context_t *ctx)
762 {
763     notmuch_query_destroy (ctx->query);
764     notmuch_database_destroy (ctx->notmuch);
765
766     talloc_free (ctx->format);
767 }
768
769 static search_context_t search_context = {
770     .format_sel = NOTMUCH_FORMAT_TEXT,
771     .exclude = NOTMUCH_EXCLUDE_TRUE,
772     .sort = NOTMUCH_SORT_NEWEST_FIRST,
773     .query_syntax = NOTMUCH_QUERY_SYNTAX_XAPIAN,
774     .output = 0,
775     .offset = 0,
776     .limit = -1, /* unlimited */
777     .dupe = -1,
778     .dedup = DEDUP_MAILBOX,
779 };
780
781 static const notmuch_opt_desc_t common_options[] = {
782     { .opt_keyword = &search_context.sort, .name = "sort", .keywords =
783           (notmuch_keyword_t []){ { "oldest-first", NOTMUCH_SORT_OLDEST_FIRST },
784                                   { "newest-first", NOTMUCH_SORT_NEWEST_FIRST },
785                                   { 0, 0 } } },
786     { .opt_keyword = &search_context.format_sel, .name = "format", .keywords =
787           (notmuch_keyword_t []){ { "json", NOTMUCH_FORMAT_JSON },
788                                   { "sexp", NOTMUCH_FORMAT_SEXP },
789                                   { "text", NOTMUCH_FORMAT_TEXT },
790                                   { "text0", NOTMUCH_FORMAT_TEXT0 },
791                                   { 0, 0 } } },
792     { .opt_int = &notmuch_format_version, .name = "format-version" },
793     { }
794 };
795
796 int
797 notmuch_search_command (notmuch_database_t *notmuch, int argc, char *argv[])
798 {
799     search_context_t *ctx = &search_context;
800     int opt_index, ret;
801
802     notmuch_opt_desc_t options[] = {
803         { .opt_keyword = &ctx->output, .name = "output", .keywords =
804               (notmuch_keyword_t []){ { "summary", OUTPUT_SUMMARY },
805                                       { "threads", OUTPUT_THREADS },
806                                       { "messages", OUTPUT_MESSAGES },
807                                       { "files", OUTPUT_FILES },
808                                       { "tags", OUTPUT_TAGS },
809                                       { 0, 0 } } },
810         { .opt_keyword = &ctx->exclude, .name = "exclude", .keywords =
811               (notmuch_keyword_t []){ { "true", NOTMUCH_EXCLUDE_TRUE },
812                                       { "false", NOTMUCH_EXCLUDE_FALSE },
813                                       { "flag", NOTMUCH_EXCLUDE_FLAG },
814                                       { "all", NOTMUCH_EXCLUDE_ALL },
815                                       { 0, 0 } } },
816         { .opt_int = &ctx->offset, .name = "offset" },
817         { .opt_int = &ctx->limit, .name = "limit" },
818         { .opt_int = &ctx->dupe, .name = "duplicate" },
819         { .opt_inherit = common_options },
820         { .opt_inherit = notmuch_shared_options },
821         { }
822     };
823
824     ctx->notmuch = notmuch;
825     ctx->output = OUTPUT_SUMMARY;
826     opt_index = parse_arguments (argc, argv, options, 1);
827     if (opt_index < 0)
828         return EXIT_FAILURE;
829
830     notmuch_process_shared_options (notmuch, argv[0]);
831
832     if (ctx->output != OUTPUT_FILES && ctx->output != OUTPUT_MESSAGES &&
833         ctx->dupe != -1) {
834         fprintf (stderr,
835                  "Error: --duplicate=N is only supported with --output=files and --output=messages.\n");
836         return EXIT_FAILURE;
837     }
838
839     if (_notmuch_search_prepare (ctx, argc - opt_index, argv + opt_index))
840         return EXIT_FAILURE;
841
842     switch (ctx->output) {
843     case OUTPUT_SUMMARY:
844     case OUTPUT_THREADS:
845         ret = do_search_threads (ctx);
846         break;
847     case OUTPUT_MESSAGES:
848     case OUTPUT_FILES:
849         ret = do_search_messages (ctx);
850         break;
851     case OUTPUT_TAGS:
852         ret = do_search_tags (ctx);
853         break;
854     default:
855         INTERNAL_ERROR ("Unexpected output");
856     }
857
858     _notmuch_search_cleanup (ctx);
859
860     return ret ? EXIT_FAILURE : EXIT_SUCCESS;
861 }
862
863 int
864 notmuch_address_command (notmuch_database_t *notmuch, int argc, char *argv[])
865 {
866     search_context_t *ctx = &search_context;
867     int opt_index, ret;
868
869     notmuch_opt_desc_t options[] = {
870         { .opt_flags = &ctx->output, .name = "output", .keywords =
871               (notmuch_keyword_t []){ { "sender", OUTPUT_SENDER },
872                                       { "recipients", OUTPUT_RECIPIENTS },
873                                       { "count", OUTPUT_COUNT },
874                                       { "address", OUTPUT_ADDRESS },
875                                       { 0, 0 } } },
876         { .opt_keyword = &ctx->exclude, .name = "exclude", .keywords =
877               (notmuch_keyword_t []){ { "true", NOTMUCH_EXCLUDE_TRUE },
878                                       { "false", NOTMUCH_EXCLUDE_FALSE },
879                                       { 0, 0 } } },
880         { .opt_keyword = &ctx->dedup, .name = "deduplicate", .keywords =
881               (notmuch_keyword_t []){ { "no", DEDUP_NONE },
882                                       { "mailbox", DEDUP_MAILBOX },
883                                       { "address", DEDUP_ADDRESS },
884                                       { 0, 0 } } },
885         { .opt_inherit = common_options },
886         { .opt_inherit = notmuch_shared_options },
887         { }
888     };
889
890     ctx->notmuch = notmuch;
891
892     opt_index = parse_arguments (argc, argv, options, 1);
893     if (opt_index < 0)
894         return EXIT_FAILURE;
895
896     notmuch_process_shared_options (notmuch, argv[0]);
897
898     if (! (ctx->output & (OUTPUT_SENDER | OUTPUT_RECIPIENTS)))
899         ctx->output |= OUTPUT_SENDER;
900
901     if (ctx->output & OUTPUT_COUNT && ctx->dedup == DEDUP_NONE) {
902         fprintf (stderr, "--output=count is not applicable with --deduplicate=no\n");
903         return EXIT_FAILURE;
904     }
905
906     if (_notmuch_search_prepare (ctx, argc - opt_index, argv + opt_index))
907         return EXIT_FAILURE;
908
909     ctx->addresses = g_hash_table_new_full (strcase_hash, strcase_equal,
910                                             _talloc_free_for_g_hash,
911                                             _list_free_for_g_hash);
912
913     /* The order is not guaranteed if a full pass is required, so go
914      * for fastest. */
915     if (ctx->output & OUTPUT_COUNT || ctx->dedup == DEDUP_ADDRESS)
916         notmuch_query_set_sort (ctx->query, NOTMUCH_SORT_UNSORTED);
917
918     ret = do_search_messages (ctx);
919
920     g_hash_table_unref (ctx->addresses);
921
922
923     _notmuch_search_cleanup (ctx);
924
925     return ret ? EXIT_FAILURE : EXIT_SUCCESS;
926 }