]> git.notmuchmail.org Git - notmuch/blob - notmuch-show.c
test: update documentation for test_emacs in test/README
[notmuch] / notmuch-show.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 http://www.gnu.org/licenses/ .
17  *
18  * Author: Carl Worth <cworth@cworth.org>
19  */
20
21 #include "notmuch-client.h"
22
23 static void
24 format_message_text (unused (const void *ctx),
25                      notmuch_message_t *message,
26                      int indent);
27 static void
28 format_headers_text (const void *ctx,
29                      notmuch_message_t *message);
30
31 static void
32 format_headers_message_part_text (GMimeMessage *message);
33
34 static void
35 format_part_start_text (GMimeObject *part,
36                         int *part_count);
37
38 static void
39 format_part_content_text (GMimeObject *part);
40
41 static void
42 format_part_end_text (GMimeObject *part);
43
44 static const notmuch_show_format_t format_text = {
45     "",
46         "\fmessage{ ", format_message_text,
47             "\fheader{\n", format_headers_text, format_headers_message_part_text, "\fheader}\n",
48             "\fbody{\n",
49                 format_part_start_text,
50                 NULL,
51                 NULL,
52                 format_part_content_text,
53                 format_part_end_text,
54                 "",
55             "\fbody}\n",
56         "\fmessage}\n", "",
57     ""
58 };
59
60 static void
61 format_message_json (const void *ctx,
62                      notmuch_message_t *message,
63                      unused (int indent));
64 static void
65 format_headers_json (const void *ctx,
66                      notmuch_message_t *message);
67
68 static void
69 format_headers_message_part_json (GMimeMessage *message);
70
71 static void
72 format_part_start_json (unused (GMimeObject *part),
73                         int *part_count);
74
75 static void
76 format_part_encstatus_json (int status);
77
78 static void
79 format_part_sigstatus_json (const GMimeSignatureValidity* validity);
80
81 static void
82 format_part_content_json (GMimeObject *part);
83
84 static void
85 format_part_end_json (GMimeObject *part);
86
87 static const notmuch_show_format_t format_json = {
88     "[",
89         "{", format_message_json,
90             "\"headers\": {", format_headers_json, format_headers_message_part_json, "}",
91             ", \"body\": [",
92                 format_part_start_json,
93                 format_part_encstatus_json,
94                 format_part_sigstatus_json,
95                 format_part_content_json,
96                 format_part_end_json,
97                 ", ",
98             "]",
99         "}", ", ",
100     "]"
101 };
102
103 static void
104 format_message_mbox (const void *ctx,
105                      notmuch_message_t *message,
106                      unused (int indent));
107
108 static const notmuch_show_format_t format_mbox = {
109     "",
110         "", format_message_mbox,
111             "", NULL, NULL, "",
112             "",
113                 NULL,
114                 NULL,
115                 NULL,
116                 NULL,
117                 NULL,
118                 "",
119             "",
120         "", "",
121     ""
122 };
123
124 static void
125 format_part_content_raw (GMimeObject *part);
126
127 static const notmuch_show_format_t format_raw = {
128     "",
129         "", NULL,
130             "", NULL, format_headers_message_part_text, "\n",
131             "",
132                 NULL,
133                 NULL,
134                 NULL,
135                 format_part_content_raw,
136                 NULL,
137                 "",
138             "",
139         "", "",
140     ""
141 };
142
143 static const char *
144 _get_tags_as_string (const void *ctx, notmuch_message_t *message)
145 {
146     notmuch_tags_t *tags;
147     int first = 1;
148     const char *tag;
149     char *result;
150
151     result = talloc_strdup (ctx, "");
152     if (result == NULL)
153         return NULL;
154
155     for (tags = notmuch_message_get_tags (message);
156          notmuch_tags_valid (tags);
157          notmuch_tags_move_to_next (tags))
158     {
159         tag = notmuch_tags_get (tags);
160
161         result = talloc_asprintf_append (result, "%s%s",
162                                          first ? "" : " ", tag);
163         first = 0;
164     }
165
166     return result;
167 }
168
169 /* Get a nice, single-line summary of message. */
170 static const char *
171 _get_one_line_summary (const void *ctx, notmuch_message_t *message)
172 {
173     const char *from;
174     time_t date;
175     const char *relative_date;
176     const char *tags;
177
178     from = notmuch_message_get_header (message, "from");
179
180     date = notmuch_message_get_date (message);
181     relative_date = notmuch_time_relative_date (ctx, date);
182
183     tags = _get_tags_as_string (ctx, message);
184
185     return talloc_asprintf (ctx, "%s (%s) (%s)",
186                             from, relative_date, tags);
187 }
188
189 static void
190 format_message_text (unused (const void *ctx), notmuch_message_t *message, int indent)
191 {
192     printf ("id:%s depth:%d match:%d filename:%s\n",
193             notmuch_message_get_message_id (message),
194             indent,
195             notmuch_message_get_flag (message, NOTMUCH_MESSAGE_FLAG_MATCH),
196             notmuch_message_get_filename (message));
197 }
198
199 static void
200 format_message_json (const void *ctx, notmuch_message_t *message, unused (int indent))
201 {
202     notmuch_tags_t *tags;
203     int first = 1;
204     void *ctx_quote = talloc_new (ctx);
205     time_t date;
206     const char *relative_date;
207
208     date = notmuch_message_get_date (message);
209     relative_date = notmuch_time_relative_date (ctx, date);
210
211     printf ("\"id\": %s, \"match\": %s, \"filename\": %s, \"timestamp\": %ld, \"date_relative\": \"%s\", \"tags\": [",
212             json_quote_str (ctx_quote, notmuch_message_get_message_id (message)),
213             notmuch_message_get_flag (message, NOTMUCH_MESSAGE_FLAG_MATCH) ? "true" : "false",
214             json_quote_str (ctx_quote, notmuch_message_get_filename (message)),
215             date, relative_date);
216
217     for (tags = notmuch_message_get_tags (message);
218          notmuch_tags_valid (tags);
219          notmuch_tags_move_to_next (tags))
220     {
221          printf("%s%s", first ? "" : ",",
222                json_quote_str (ctx_quote, notmuch_tags_get (tags)));
223          first = 0;
224     }
225     printf("], ");
226     talloc_free (ctx_quote);
227 }
228
229 /* Extract just the email address from the contents of a From:
230  * header. */
231 static const char *
232 _extract_email_address (const void *ctx, const char *from)
233 {
234     InternetAddressList *addresses;
235     InternetAddress *address;
236     InternetAddressMailbox *mailbox;
237     const char *email = "MAILER-DAEMON";
238
239     addresses = internet_address_list_parse_string (from);
240
241     /* Bail if there is no address here. */
242     if (addresses == NULL || internet_address_list_length (addresses) < 1)
243         goto DONE;
244
245     /* Otherwise, just use the first address. */
246     address = internet_address_list_get_address (addresses, 0);
247
248     /* The From header should never contain an address group rather
249      * than a mailbox. So bail if it does. */
250     if (! INTERNET_ADDRESS_IS_MAILBOX (address))
251         goto DONE;
252
253     mailbox = INTERNET_ADDRESS_MAILBOX (address);
254     email = internet_address_mailbox_get_addr (mailbox);
255     email = talloc_strdup (ctx, email);
256
257   DONE:
258     /* XXX: How to free addresses here? */
259     return email;
260    }
261
262 /* Return 1 if 'line' is an mbox From_ line---that is, a line
263  * beginning with zero or more '>' characters followed by the
264  * characters 'F', 'r', 'o', 'm', and space.
265  *
266  * Any characters at all may appear after that in the line.
267  */
268 static int
269 _is_from_line (const char *line)
270 {
271     const char *s = line;
272
273     if (line == NULL)
274         return 0;
275
276     while (*s == '>')
277         s++;
278
279     if (STRNCMP_LITERAL (s, "From ") == 0)
280         return 1;
281     else
282         return 0;
283 }
284
285 /* Print a message in "mboxrd" format as documented, for example,
286  * here:
287  *
288  * http://qmail.org/qmail-manual-html/man5/mbox.html
289  */
290 static void
291 format_message_mbox (const void *ctx,
292                      notmuch_message_t *message,
293                      unused (int indent))
294 {
295     const char *filename;
296     FILE *file;
297     const char *from;
298
299     time_t date;
300     struct tm date_gmtime;
301     char date_asctime[26];
302
303     char *line = NULL;
304     size_t line_size;
305     ssize_t line_len;
306
307     filename = notmuch_message_get_filename (message);
308     file = fopen (filename, "r");
309     if (file == NULL) {
310         fprintf (stderr, "Failed to open %s: %s\n",
311                  filename, strerror (errno));
312         return;
313     }
314
315     from = notmuch_message_get_header (message, "from");
316     from = _extract_email_address (ctx, from);
317
318     date = notmuch_message_get_date (message);
319     gmtime_r (&date, &date_gmtime);
320     asctime_r (&date_gmtime, date_asctime);
321
322     printf ("From %s %s", from, date_asctime);
323
324     while ((line_len = getline (&line, &line_size, file)) != -1 ) {
325         if (_is_from_line (line))
326             putchar ('>');
327         printf ("%s", line);
328     }
329
330     printf ("\n");
331
332     fclose (file);
333 }
334
335
336 static void
337 format_headers_text (const void *ctx, notmuch_message_t *message)
338 {
339     const char *headers[] = {
340         "Subject", "From", "To", "Cc", "Bcc", "Date"
341     };
342     const char *name, *value;
343     unsigned int i;
344
345     printf ("%s\n", _get_one_line_summary (ctx, message));
346
347     for (i = 0; i < ARRAY_SIZE (headers); i++) {
348         name = headers[i];
349         value = notmuch_message_get_header (message, name);
350         if (value && strlen (value))
351             printf ("%s: %s\n", name, value);
352     }
353 }
354
355 static void
356 format_headers_message_part_text (GMimeMessage *message)
357 {
358     InternetAddressList *recipients;
359     const char *recipients_string;
360
361     printf ("From: %s\n", g_mime_message_get_sender (message));
362     recipients = g_mime_message_get_recipients (message, GMIME_RECIPIENT_TYPE_TO);
363     recipients_string = internet_address_list_to_string (recipients, 0);
364     if (recipients_string)
365         printf ("To: %s\n",
366                 recipients_string);
367     recipients = g_mime_message_get_recipients (message, GMIME_RECIPIENT_TYPE_CC);
368     recipients_string = internet_address_list_to_string (recipients, 0);
369     if (recipients_string)
370         printf ("Cc: %s\n",
371                 recipients_string);
372     printf ("Subject: %s\n", g_mime_message_get_subject (message));
373     printf ("Date: %s\n", g_mime_message_get_date_as_string (message));
374 }
375
376 static void
377 format_headers_json (const void *ctx, notmuch_message_t *message)
378 {
379     const char *headers[] = {
380         "Subject", "From", "To", "Cc", "Bcc", "Date"
381     };
382     const char *name, *value;
383     unsigned int i;
384     int first_header = 1;
385     void *ctx_quote = talloc_new (ctx);
386
387     for (i = 0; i < ARRAY_SIZE (headers); i++) {
388         name = headers[i];
389         value = notmuch_message_get_header (message, name);
390         if (value)
391         {
392             if (!first_header)
393                 fputs (", ", stdout);
394             first_header = 0;
395
396             printf ("%s: %s",
397                     json_quote_str (ctx_quote, name),
398                     json_quote_str (ctx_quote, value));
399         }
400     }
401
402     talloc_free (ctx_quote);
403 }
404
405 static void
406 format_headers_message_part_json (GMimeMessage *message)
407 {
408     void *ctx = talloc_new (NULL);
409     void *ctx_quote = talloc_new (ctx);
410     InternetAddressList *recipients;
411     const char *recipients_string;
412
413     printf ("%s: %s",
414             json_quote_str (ctx_quote, "From"),
415             json_quote_str (ctx_quote, g_mime_message_get_sender (message)));
416     recipients = g_mime_message_get_recipients (message, GMIME_RECIPIENT_TYPE_TO);
417     recipients_string = internet_address_list_to_string (recipients, 0);
418     if (recipients_string)
419         printf (", %s: %s",
420                 json_quote_str (ctx_quote, "To"),
421                 json_quote_str (ctx_quote, recipients_string));
422     recipients = g_mime_message_get_recipients (message, GMIME_RECIPIENT_TYPE_CC);
423     recipients_string = internet_address_list_to_string (recipients, 0);
424     if (recipients_string)
425         printf (", %s: %s",
426                 json_quote_str (ctx_quote, "Cc"),
427                 json_quote_str (ctx_quote, recipients_string));
428     printf (", %s: %s",
429             json_quote_str (ctx_quote, "Subject"),
430             json_quote_str (ctx_quote, g_mime_message_get_subject (message)));
431     printf (", %s: %s",
432             json_quote_str (ctx_quote, "Date"),
433             json_quote_str (ctx_quote, g_mime_message_get_date_as_string (message)));
434
435     talloc_free (ctx_quote);
436     talloc_free (ctx);
437 }
438
439 /* Write a MIME text part out to the given stream.
440  *
441  * Both line-ending conversion (CRLF->LF) and charset conversion ( ->
442  * UTF-8) will be performed, so it is inappropriate to call this
443  * function with a non-text part. Doing so will trigger an internal
444  * error.
445  */
446 static void
447 show_text_part_content (GMimeObject *part, GMimeStream *stream_out)
448 {
449     GMimeContentType *content_type = g_mime_object_get_content_type (GMIME_OBJECT (part));
450     GMimeStream *stream_filter = NULL;
451     GMimeDataWrapper *wrapper;
452     const char *charset;
453
454     if (! g_mime_content_type_is_type (content_type, "text", "*"))
455         INTERNAL_ERROR ("Illegal request to format non-text part (%s) as text.",
456                         g_mime_content_type_to_string (content_type));
457
458     if (stream_out == NULL)
459         return;
460
461     stream_filter = g_mime_stream_filter_new (stream_out);
462     g_mime_stream_filter_add(GMIME_STREAM_FILTER (stream_filter),
463                              g_mime_filter_crlf_new (FALSE, FALSE));
464
465     charset = g_mime_object_get_content_type_parameter (part, "charset");
466     if (charset) {
467         GMimeFilter *charset_filter;
468         charset_filter = g_mime_filter_charset_new (charset, "UTF-8");
469         /* This result can be NULL for things like "unknown-8bit".
470          * Don't set a NULL filter as that makes GMime print
471          * annoying assertion-failure messages on stderr. */
472         if (charset_filter)
473             g_mime_stream_filter_add (GMIME_STREAM_FILTER (stream_filter),
474                                       charset_filter);
475     }
476
477     wrapper = g_mime_part_get_content_object (GMIME_PART (part));
478     if (wrapper && stream_filter)
479         g_mime_data_wrapper_write_to_stream (wrapper, stream_filter);
480     if (stream_filter)
481         g_object_unref(stream_filter);
482 }
483
484 static const char*
485 signer_status_to_string (GMimeSignerStatus x)
486 {
487     switch (x) {
488     case GMIME_SIGNER_STATUS_NONE:
489         return "none";
490     case GMIME_SIGNER_STATUS_GOOD:
491         return "good";
492     case GMIME_SIGNER_STATUS_BAD:
493         return "bad";
494     case GMIME_SIGNER_STATUS_ERROR:
495         return "error";
496     }
497     return "unknown";
498 }
499
500 static void
501 format_part_start_text (GMimeObject *part, int *part_count)
502 {
503     GMimeContentDisposition *disposition = g_mime_object_get_content_disposition (part);
504
505     if (disposition &&
506         strcmp (disposition->disposition, GMIME_DISPOSITION_ATTACHMENT) == 0)
507     {
508         printf ("\fattachment{ ID: %d", *part_count);
509
510     } else {
511
512         printf ("\fpart{ ID: %d", *part_count);
513     }
514 }
515
516 static void
517 format_part_content_text (GMimeObject *part)
518 {
519     const char *cid = g_mime_object_get_content_id (part);
520     GMimeContentType *content_type = g_mime_object_get_content_type (GMIME_OBJECT (part));
521
522     if (GMIME_IS_PART (part))
523     {
524         const char *filename = g_mime_part_get_filename (GMIME_PART (part));
525         if (filename)
526             printf (", Filename: %s", filename);
527     }
528
529     if (cid)
530         printf (", Content-id: %s", cid);
531
532     printf (", Content-type: %s\n", g_mime_content_type_to_string (content_type));
533
534     if (g_mime_content_type_is_type (content_type, "text", "*") &&
535         !g_mime_content_type_is_type (content_type, "text", "html"))
536     {
537         GMimeStream *stream_stdout = g_mime_stream_file_new (stdout);
538         g_mime_stream_file_set_owner (GMIME_STREAM_FILE (stream_stdout), FALSE);
539         show_text_part_content (part, stream_stdout);
540         g_object_unref(stream_stdout);
541     }
542     else if (g_mime_content_type_is_type (content_type, "multipart", "*") ||
543              g_mime_content_type_is_type (content_type, "message", "rfc822"))
544     {
545         /* Do nothing for multipart since its content will be printed
546          * when recursing. */
547     }
548     else
549     {
550         printf ("Non-text part: %s\n",
551                 g_mime_content_type_to_string (content_type));
552     }
553 }
554
555 static void
556 format_part_end_text (GMimeObject *part)
557 {
558     GMimeContentDisposition *disposition;
559
560     disposition = g_mime_object_get_content_disposition (part);
561     if (disposition &&
562         strcmp (disposition->disposition, GMIME_DISPOSITION_ATTACHMENT) == 0)
563     {
564         printf ("\fattachment}\n");
565     }
566     else
567     {
568         printf ("\fpart}\n");
569     }
570 }
571
572 static void
573 format_part_start_json (unused (GMimeObject *part), int *part_count)
574 {
575     printf ("{\"id\": %d", *part_count);
576 }
577
578 static void
579 format_part_encstatus_json (int status)
580 {
581     printf (", \"encstatus\": [{\"status\": ");
582     if (status) {
583         printf ("\"good\"");
584     } else {
585         printf ("\"bad\"");
586     }
587     printf ("}]");
588 }
589
590 static void
591 format_part_sigstatus_json (const GMimeSignatureValidity* validity)
592 {
593     printf (", \"sigstatus\": [");
594
595     if (!validity) {
596         printf ("]");
597         return;
598     }
599
600     const GMimeSigner *signer = g_mime_signature_validity_get_signers (validity);
601     int first = 1;
602     void *ctx_quote = talloc_new (NULL);
603
604     while (signer) {
605         if (first)
606             first = 0;
607         else
608             printf (", ");
609
610         printf ("{");
611
612         /* status */
613         printf ("\"status\": %s",
614                 json_quote_str (ctx_quote,
615                                 signer_status_to_string (signer->status)));
616
617         if (signer->status == GMIME_SIGNER_STATUS_GOOD)
618         {
619             if (signer->fingerprint)
620                 printf (", \"fingerprint\": %s", json_quote_str (ctx_quote, signer->fingerprint));
621             /* these dates are seconds since the epoch; should we
622              * provide a more human-readable format string? */
623             if (signer->created)
624                 printf (", \"created\": %d", (int) signer->created);
625             if (signer->expires)
626                 printf (", \"expires\": %d", (int) signer->expires);
627             /* output user id only if validity is FULL or ULTIMATE. */
628             /* note that gmime is using the term "trust" here, which
629              * is WRONG.  It's actually user id "validity". */
630             if ((signer->name) && (signer->trust)) {
631                 if ((signer->trust == GMIME_SIGNER_TRUST_FULLY) || (signer->trust == GMIME_SIGNER_TRUST_ULTIMATE))
632                     printf (", \"userid\": %s", json_quote_str (ctx_quote, signer->name));
633            }
634        } else {
635            if (signer->keyid)
636                printf (", \"keyid\": %s", json_quote_str (ctx_quote, signer->keyid));
637        }
638        if (signer->errors != GMIME_SIGNER_ERROR_NONE) {
639            printf (", \"errors\": %x", signer->errors);
640        }
641
642        printf ("}");
643        signer = signer->next;
644     }
645
646     printf ("]");
647
648     talloc_free (ctx_quote);
649 }
650
651 static void
652 format_part_content_json (GMimeObject *part)
653 {
654     GMimeContentType *content_type = g_mime_object_get_content_type (GMIME_OBJECT (part));
655     GMimeStream *stream_memory = g_mime_stream_mem_new ();
656     const char *cid = g_mime_object_get_content_id (part);
657     void *ctx = talloc_new (NULL);
658     GByteArray *part_content;
659
660     printf (", \"content-type\": %s",
661             json_quote_str (ctx, g_mime_content_type_to_string (content_type)));
662
663     if (cid != NULL)
664             printf(", \"content-id\": %s", json_quote_str (ctx, cid));
665
666     if (GMIME_IS_PART (part))
667     {
668         const char *filename = g_mime_part_get_filename (GMIME_PART (part));
669         if (filename)
670             printf (", \"filename\": %s", json_quote_str (ctx, filename));
671     }
672
673     if (g_mime_content_type_is_type (content_type, "text", "*") &&
674         !g_mime_content_type_is_type (content_type, "text", "html"))
675     {
676         show_text_part_content (part, stream_memory);
677         part_content = g_mime_stream_mem_get_byte_array (GMIME_STREAM_MEM (stream_memory));
678
679         printf (", \"content\": %s", json_quote_chararray (ctx, (char *) part_content->data, part_content->len));
680     }
681     else if (g_mime_content_type_is_type (content_type, "multipart", "*"))
682     {
683         printf (", \"content\": [");
684     }
685     else if (g_mime_content_type_is_type (content_type, "message", "rfc822"))
686     {
687         printf (", \"content\": [{");
688     }
689
690     talloc_free (ctx);
691     if (stream_memory)
692         g_object_unref (stream_memory);
693 }
694
695 static void
696 format_part_end_json (GMimeObject *part)
697 {
698     GMimeContentType *content_type = g_mime_object_get_content_type (GMIME_OBJECT (part));
699
700     if (g_mime_content_type_is_type (content_type, "multipart", "*"))
701         printf ("]");
702     else if (g_mime_content_type_is_type (content_type, "message", "rfc822"))
703         printf ("}]");
704
705     printf ("}");
706 }
707
708 static void
709 format_part_content_raw (GMimeObject *part)
710 {
711     if (! GMIME_IS_PART (part))
712         return;
713
714     GMimeStream *stream_stdout;
715     GMimeStream *stream_filter = NULL;
716     GMimeDataWrapper *wrapper;
717
718     stream_stdout = g_mime_stream_file_new (stdout);
719     g_mime_stream_file_set_owner (GMIME_STREAM_FILE (stream_stdout), FALSE);
720
721     stream_filter = g_mime_stream_filter_new (stream_stdout);
722
723     wrapper = g_mime_part_get_content_object (GMIME_PART (part));
724
725     if (wrapper && stream_filter)
726         g_mime_data_wrapper_write_to_stream (wrapper, stream_filter);
727
728     if (stream_filter)
729         g_object_unref (stream_filter);
730
731     if (stream_stdout)
732         g_object_unref(stream_stdout);
733 }
734
735 static void
736 show_message (void *ctx,
737               const notmuch_show_format_t *format,
738               notmuch_message_t *message,
739               int indent,
740               notmuch_show_params_t *params)
741 {
742     if (params->part <= 0) {
743         fputs (format->message_start, stdout);
744         if (format->message)
745             format->message(ctx, message, indent);
746
747         fputs (format->header_start, stdout);
748         if (format->header)
749             format->header(ctx, message);
750         fputs (format->header_end, stdout);
751
752         fputs (format->body_start, stdout);
753     }
754
755     if (format->part_content)
756         show_message_body (notmuch_message_get_filename (message),
757                            format, params);
758
759     if (params->part <= 0) {
760         fputs (format->body_end, stdout);
761
762         fputs (format->message_end, stdout);
763     }
764 }
765
766 static void
767 show_messages (void *ctx,
768                const notmuch_show_format_t *format,
769                notmuch_messages_t *messages,
770                int indent,
771                notmuch_show_params_t *params)
772 {
773     notmuch_message_t *message;
774     notmuch_bool_t match;
775     int first_set = 1;
776     int next_indent;
777
778     fputs (format->message_set_start, stdout);
779
780     for (;
781          notmuch_messages_valid (messages);
782          notmuch_messages_move_to_next (messages))
783     {
784         if (!first_set)
785             fputs (format->message_set_sep, stdout);
786         first_set = 0;
787
788         fputs (format->message_set_start, stdout);
789
790         message = notmuch_messages_get (messages);
791
792         match = notmuch_message_get_flag (message, NOTMUCH_MESSAGE_FLAG_MATCH);
793
794         next_indent = indent;
795
796         if (match || params->entire_thread) {
797             show_message (ctx, format, message, indent, params);
798             next_indent = indent + 1;
799
800             fputs (format->message_set_sep, stdout);
801         }
802
803         show_messages (ctx,
804                        format,
805                        notmuch_message_get_replies (message),
806                        next_indent,
807                        params);
808
809         notmuch_message_destroy (message);
810
811         fputs (format->message_set_end, stdout);
812     }
813
814     fputs (format->message_set_end, stdout);
815 }
816
817 /* Formatted output of single message */
818 static int
819 do_show_single (void *ctx,
820                 notmuch_query_t *query,
821                 const notmuch_show_format_t *format,
822                 notmuch_show_params_t *params)
823 {
824     notmuch_messages_t *messages;
825     notmuch_message_t *message;
826
827     if (notmuch_query_count_messages (query) != 1) {
828         fprintf (stderr, "Error: search term did not match precisely one message.\n");
829         return 1;
830     }
831
832     messages = notmuch_query_search_messages (query);
833     message = notmuch_messages_get (messages);
834
835     if (message == NULL) {
836         fprintf (stderr, "Error: Cannot find matching message.\n");
837         return 1;
838     }
839
840     notmuch_message_set_flag (message, NOTMUCH_MESSAGE_FLAG_MATCH, 1);
841
842     /* Special case for --format=raw of full single message, just cat out file */
843     if (params->raw && 0 == params->part) {
844
845         const char *filename;
846         FILE *file;
847         size_t size;
848         char buf[4096];
849
850         filename = notmuch_message_get_filename (message);
851         if (filename == NULL) {
852             fprintf (stderr, "Error: Cannot message filename.\n");
853             return 1;
854         }
855
856         file = fopen (filename, "r");
857         if (file == NULL) {
858             fprintf (stderr, "Error: Cannot open file %s: %s\n", filename, strerror (errno));
859             return 1;
860         }
861
862         while (!feof (file)) {
863             size = fread (buf, 1, sizeof (buf), file);
864             fwrite (buf, size, 1, stdout);
865         }
866
867         fclose (file);
868
869     } else {
870
871         show_message (ctx, format, message, 0, params);
872
873     }
874
875     return 0;
876 }
877
878 /* Formatted output of threads */
879 static int
880 do_show (void *ctx,
881          notmuch_query_t *query,
882          const notmuch_show_format_t *format,
883          notmuch_show_params_t *params)
884 {
885     notmuch_threads_t *threads;
886     notmuch_thread_t *thread;
887     notmuch_messages_t *messages;
888     int first_toplevel = 1;
889
890     fputs (format->message_set_start, stdout);
891
892     for (threads = notmuch_query_search_threads (query);
893          notmuch_threads_valid (threads);
894          notmuch_threads_move_to_next (threads))
895     {
896         thread = notmuch_threads_get (threads);
897
898         messages = notmuch_thread_get_toplevel_messages (thread);
899
900         if (messages == NULL)
901             INTERNAL_ERROR ("Thread %s has no toplevel messages.\n",
902                             notmuch_thread_get_thread_id (thread));
903
904         if (!first_toplevel)
905             fputs (format->message_set_sep, stdout);
906         first_toplevel = 0;
907
908         show_messages (ctx, format, messages, 0, params);
909
910         notmuch_thread_destroy (thread);
911
912     }
913
914     fputs (format->message_set_end, stdout);
915
916     return 0;
917 }
918
919 int
920 notmuch_show_command (void *ctx, unused (int argc), unused (char *argv[]))
921 {
922     notmuch_config_t *config;
923     notmuch_database_t *notmuch;
924     notmuch_query_t *query;
925     char *query_string;
926     char *opt;
927     const notmuch_show_format_t *format = &format_text;
928     notmuch_show_params_t params;
929     int mbox = 0;
930     int format_specified = 0;
931     int i;
932
933     params.entire_thread = 0;
934     params.raw = 0;
935     params.part = -1;
936     params.cryptoctx = NULL;
937     params.decrypt = 0;
938
939     for (i = 0; i < argc && argv[i][0] == '-'; i++) {
940         if (strcmp (argv[i], "--") == 0) {
941             i++;
942             break;
943         }
944         if (STRNCMP_LITERAL (argv[i], "--format=") == 0) {
945             opt = argv[i] + sizeof ("--format=") - 1;
946             if (strcmp (opt, "text") == 0) {
947                 format = &format_text;
948             } else if (strcmp (opt, "json") == 0) {
949                 format = &format_json;
950                 params.entire_thread = 1;
951             } else if (strcmp (opt, "mbox") == 0) {
952                 format = &format_mbox;
953                 mbox = 1;
954             } else if (strcmp (opt, "raw") == 0) {
955                 format = &format_raw;
956                 params.raw = 1;
957             } else {
958                 fprintf (stderr, "Invalid value for --format: %s\n", opt);
959                 return 1;
960             }
961             format_specified = 1;
962         } else if (STRNCMP_LITERAL (argv[i], "--part=") == 0) {
963             params.part = atoi(argv[i] + sizeof ("--part=") - 1);
964         } else if (STRNCMP_LITERAL (argv[i], "--entire-thread") == 0) {
965             params.entire_thread = 1;
966         } else if ((STRNCMP_LITERAL (argv[i], "--verify") == 0) ||
967                    (STRNCMP_LITERAL (argv[i], "--decrypt") == 0)) {
968             if (params.cryptoctx == NULL) {
969                 GMimeSession* session = g_object_new(g_mime_session_get_type(), NULL);
970                 if (NULL == (params.cryptoctx = g_mime_gpg_context_new(session, "gpg")))
971                     fprintf (stderr, "Failed to construct gpg context.\n");
972                 else
973                     g_mime_gpg_context_set_always_trust((GMimeGpgContext*)params.cryptoctx, FALSE);
974                 g_object_unref (session);
975                 session = NULL;
976             }
977             if (STRNCMP_LITERAL (argv[i], "--decrypt") == 0)
978                 params.decrypt = 1;
979         } else {
980             fprintf (stderr, "Unrecognized option: %s\n", argv[i]);
981             return 1;
982         }
983     }
984
985     argc -= i;
986     argv += i;
987
988     config = notmuch_config_open (ctx, NULL, NULL);
989     if (config == NULL)
990         return 1;
991
992     query_string = query_string_from_args (ctx, argc, argv);
993     if (query_string == NULL) {
994         fprintf (stderr, "Out of memory\n");
995         return 1;
996     }
997
998     if (mbox && params.part > 0) {
999         fprintf (stderr, "Error: specifying parts is incompatible with mbox output format.\n");
1000         return 1;
1001     }
1002
1003     if (*query_string == '\0') {
1004         fprintf (stderr, "Error: notmuch show requires at least one search term.\n");
1005         return 1;
1006     }
1007
1008     notmuch = notmuch_database_open (notmuch_config_get_database_path (config),
1009                                      NOTMUCH_DATABASE_MODE_READ_ONLY);
1010     if (notmuch == NULL)
1011         return 1;
1012
1013     query = notmuch_query_create (notmuch, query_string);
1014     if (query == NULL) {
1015         fprintf (stderr, "Out of memory\n");
1016         return 1;
1017     }
1018
1019     /* if part was requested and format was not specified, use format=raw */
1020     if (params.part >= 0 && !format_specified)
1021         format = &format_raw;
1022
1023     /* If --format=raw specified without specifying part, we can only
1024      * output single message, so set part=0 */
1025     if (params.raw && params.part < 0)
1026         params.part = 0;
1027
1028     if (params.part >= 0)
1029         return do_show_single (ctx, query, format, &params);
1030     else
1031         return do_show (ctx, query, format, &params);
1032
1033     notmuch_query_destroy (query);
1034     notmuch_database_close (notmuch);
1035
1036     if (params.cryptoctx)
1037         g_object_unref(params.cryptoctx);
1038
1039     return 0;
1040 }