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