]> git.notmuchmail.org Git - notmuch/blob - notmuch-show.c
man/*: fixup page references
[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     if (addresses)
259         g_object_unref (addresses);
260
261     return email;
262    }
263
264 /* Return 1 if 'line' is an mbox From_ line---that is, a line
265  * beginning with zero or more '>' characters followed by the
266  * characters 'F', 'r', 'o', 'm', and space.
267  *
268  * Any characters at all may appear after that in the line.
269  */
270 static int
271 _is_from_line (const char *line)
272 {
273     const char *s = line;
274
275     if (line == NULL)
276         return 0;
277
278     while (*s == '>')
279         s++;
280
281     if (STRNCMP_LITERAL (s, "From ") == 0)
282         return 1;
283     else
284         return 0;
285 }
286
287 /* Print a message in "mboxrd" format as documented, for example,
288  * here:
289  *
290  * http://qmail.org/qmail-manual-html/man5/mbox.html
291  */
292 static void
293 format_message_mbox (const void *ctx,
294                      notmuch_message_t *message,
295                      unused (int indent))
296 {
297     const char *filename;
298     FILE *file;
299     const char *from;
300
301     time_t date;
302     struct tm date_gmtime;
303     char date_asctime[26];
304
305     char *line = NULL;
306     size_t line_size;
307     ssize_t line_len;
308
309     filename = notmuch_message_get_filename (message);
310     file = fopen (filename, "r");
311     if (file == NULL) {
312         fprintf (stderr, "Failed to open %s: %s\n",
313                  filename, strerror (errno));
314         return;
315     }
316
317     from = notmuch_message_get_header (message, "from");
318     from = _extract_email_address (ctx, from);
319
320     date = notmuch_message_get_date (message);
321     gmtime_r (&date, &date_gmtime);
322     asctime_r (&date_gmtime, date_asctime);
323
324     printf ("From %s %s", from, date_asctime);
325
326     while ((line_len = getline (&line, &line_size, file)) != -1 ) {
327         if (_is_from_line (line))
328             putchar ('>');
329         printf ("%s", line);
330     }
331
332     printf ("\n");
333
334     fclose (file);
335 }
336
337
338 static void
339 format_headers_text (const void *ctx, notmuch_message_t *message)
340 {
341     const char *headers[] = {
342         "Subject", "From", "To", "Cc", "Bcc", "Date"
343     };
344     const char *name, *value;
345     unsigned int i;
346
347     printf ("%s\n", _get_one_line_summary (ctx, message));
348
349     for (i = 0; i < ARRAY_SIZE (headers); i++) {
350         name = headers[i];
351         value = notmuch_message_get_header (message, name);
352         if (value && strlen (value))
353             printf ("%s: %s\n", name, value);
354     }
355 }
356
357 static void
358 format_headers_message_part_text (GMimeMessage *message)
359 {
360     InternetAddressList *recipients;
361     const char *recipients_string;
362
363     printf ("From: %s\n", g_mime_message_get_sender (message));
364     recipients = g_mime_message_get_recipients (message, GMIME_RECIPIENT_TYPE_TO);
365     recipients_string = internet_address_list_to_string (recipients, 0);
366     if (recipients_string)
367         printf ("To: %s\n",
368                 recipients_string);
369     recipients = g_mime_message_get_recipients (message, GMIME_RECIPIENT_TYPE_CC);
370     recipients_string = internet_address_list_to_string (recipients, 0);
371     if (recipients_string)
372         printf ("Cc: %s\n",
373                 recipients_string);
374     printf ("Subject: %s\n", g_mime_message_get_subject (message));
375     printf ("Date: %s\n", g_mime_message_get_date_as_string (message));
376 }
377
378 static void
379 format_headers_json (const void *ctx, notmuch_message_t *message)
380 {
381     const char *headers[] = {
382         "Subject", "From", "To", "Cc", "Bcc", "Date"
383     };
384     const char *name, *value;
385     unsigned int i;
386     int first_header = 1;
387     void *ctx_quote = talloc_new (ctx);
388
389     for (i = 0; i < ARRAY_SIZE (headers); i++) {
390         name = headers[i];
391         value = notmuch_message_get_header (message, name);
392         if (value)
393         {
394             if (!first_header)
395                 fputs (", ", stdout);
396             first_header = 0;
397
398             printf ("%s: %s",
399                     json_quote_str (ctx_quote, name),
400                     json_quote_str (ctx_quote, value));
401         }
402     }
403
404     talloc_free (ctx_quote);
405 }
406
407 static void
408 format_headers_message_part_json (GMimeMessage *message)
409 {
410     void *ctx = talloc_new (NULL);
411     void *ctx_quote = talloc_new (ctx);
412     InternetAddressList *recipients;
413     const char *recipients_string;
414
415     printf ("%s: %s",
416             json_quote_str (ctx_quote, "From"),
417             json_quote_str (ctx_quote, g_mime_message_get_sender (message)));
418     recipients = g_mime_message_get_recipients (message, GMIME_RECIPIENT_TYPE_TO);
419     recipients_string = internet_address_list_to_string (recipients, 0);
420     if (recipients_string)
421         printf (", %s: %s",
422                 json_quote_str (ctx_quote, "To"),
423                 json_quote_str (ctx_quote, recipients_string));
424     recipients = g_mime_message_get_recipients (message, GMIME_RECIPIENT_TYPE_CC);
425     recipients_string = internet_address_list_to_string (recipients, 0);
426     if (recipients_string)
427         printf (", %s: %s",
428                 json_quote_str (ctx_quote, "Cc"),
429                 json_quote_str (ctx_quote, recipients_string));
430     printf (", %s: %s",
431             json_quote_str (ctx_quote, "Subject"),
432             json_quote_str (ctx_quote, g_mime_message_get_subject (message)));
433     printf (", %s: %s",
434             json_quote_str (ctx_quote, "Date"),
435             json_quote_str (ctx_quote, g_mime_message_get_date_as_string (message)));
436
437     talloc_free (ctx_quote);
438     talloc_free (ctx);
439 }
440
441 /* Write a MIME text part out to the given stream.
442  *
443  * Both line-ending conversion (CRLF->LF) and charset conversion ( ->
444  * UTF-8) will be performed, so it is inappropriate to call this
445  * function with a non-text part. Doing so will trigger an internal
446  * error.
447  */
448 static void
449 show_text_part_content (GMimeObject *part, GMimeStream *stream_out)
450 {
451     GMimeContentType *content_type = g_mime_object_get_content_type (GMIME_OBJECT (part));
452     GMimeStream *stream_filter = NULL;
453     GMimeDataWrapper *wrapper;
454     const char *charset;
455
456     if (! g_mime_content_type_is_type (content_type, "text", "*"))
457         INTERNAL_ERROR ("Illegal request to format non-text part (%s) as text.",
458                         g_mime_content_type_to_string (content_type));
459
460     if (stream_out == NULL)
461         return;
462
463     stream_filter = g_mime_stream_filter_new (stream_out);
464     g_mime_stream_filter_add(GMIME_STREAM_FILTER (stream_filter),
465                              g_mime_filter_crlf_new (FALSE, FALSE));
466
467     charset = g_mime_object_get_content_type_parameter (part, "charset");
468     if (charset) {
469         GMimeFilter *charset_filter;
470         charset_filter = g_mime_filter_charset_new (charset, "UTF-8");
471         /* This result can be NULL for things like "unknown-8bit".
472          * Don't set a NULL filter as that makes GMime print
473          * annoying assertion-failure messages on stderr. */
474         if (charset_filter) {
475             g_mime_stream_filter_add (GMIME_STREAM_FILTER (stream_filter),
476                                       charset_filter);
477             g_object_unref (charset_filter);
478         }
479
480     }
481
482     wrapper = g_mime_part_get_content_object (GMIME_PART (part));
483     if (wrapper && stream_filter)
484         g_mime_data_wrapper_write_to_stream (wrapper, stream_filter);
485     if (stream_filter)
486         g_object_unref(stream_filter);
487 }
488
489 static const char*
490 signer_status_to_string (GMimeSignerStatus x)
491 {
492     switch (x) {
493     case GMIME_SIGNER_STATUS_NONE:
494         return "none";
495     case GMIME_SIGNER_STATUS_GOOD:
496         return "good";
497     case GMIME_SIGNER_STATUS_BAD:
498         return "bad";
499     case GMIME_SIGNER_STATUS_ERROR:
500         return "error";
501     }
502     return "unknown";
503 }
504
505 static void
506 format_part_start_text (GMimeObject *part, int *part_count)
507 {
508     GMimeContentDisposition *disposition = g_mime_object_get_content_disposition (part);
509
510     if (disposition &&
511         strcmp (disposition->disposition, GMIME_DISPOSITION_ATTACHMENT) == 0)
512     {
513         printf ("\fattachment{ ID: %d", *part_count);
514
515     } else {
516
517         printf ("\fpart{ ID: %d", *part_count);
518     }
519 }
520
521 static void
522 format_part_content_text (GMimeObject *part)
523 {
524     const char *cid = g_mime_object_get_content_id (part);
525     GMimeContentType *content_type = g_mime_object_get_content_type (GMIME_OBJECT (part));
526
527     if (GMIME_IS_PART (part))
528     {
529         const char *filename = g_mime_part_get_filename (GMIME_PART (part));
530         if (filename)
531             printf (", Filename: %s", filename);
532     }
533
534     if (cid)
535         printf (", Content-id: %s", cid);
536
537     printf (", Content-type: %s\n", g_mime_content_type_to_string (content_type));
538
539     if (g_mime_content_type_is_type (content_type, "text", "*") &&
540         !g_mime_content_type_is_type (content_type, "text", "html"))
541     {
542         GMimeStream *stream_stdout = g_mime_stream_file_new (stdout);
543         g_mime_stream_file_set_owner (GMIME_STREAM_FILE (stream_stdout), FALSE);
544         show_text_part_content (part, stream_stdout);
545         g_object_unref(stream_stdout);
546     }
547     else if (g_mime_content_type_is_type (content_type, "multipart", "*") ||
548              g_mime_content_type_is_type (content_type, "message", "rfc822"))
549     {
550         /* Do nothing for multipart since its content will be printed
551          * when recursing. */
552     }
553     else
554     {
555         printf ("Non-text part: %s\n",
556                 g_mime_content_type_to_string (content_type));
557     }
558 }
559
560 static void
561 format_part_end_text (GMimeObject *part)
562 {
563     GMimeContentDisposition *disposition;
564
565     disposition = g_mime_object_get_content_disposition (part);
566     if (disposition &&
567         strcmp (disposition->disposition, GMIME_DISPOSITION_ATTACHMENT) == 0)
568     {
569         printf ("\fattachment}\n");
570     }
571     else
572     {
573         printf ("\fpart}\n");
574     }
575 }
576
577 static void
578 format_part_start_json (unused (GMimeObject *part), int *part_count)
579 {
580     printf ("{\"id\": %d", *part_count);
581 }
582
583 static void
584 format_part_encstatus_json (int status)
585 {
586     printf (", \"encstatus\": [{\"status\": ");
587     if (status) {
588         printf ("\"good\"");
589     } else {
590         printf ("\"bad\"");
591     }
592     printf ("}]");
593 }
594
595 static void
596 format_part_sigstatus_json (const GMimeSignatureValidity* validity)
597 {
598     printf (", \"sigstatus\": [");
599
600     if (!validity) {
601         printf ("]");
602         return;
603     }
604
605     const GMimeSigner *signer = g_mime_signature_validity_get_signers (validity);
606     int first = 1;
607     void *ctx_quote = talloc_new (NULL);
608
609     while (signer) {
610         if (first)
611             first = 0;
612         else
613             printf (", ");
614
615         printf ("{");
616
617         /* status */
618         printf ("\"status\": %s",
619                 json_quote_str (ctx_quote,
620                                 signer_status_to_string (signer->status)));
621
622         if (signer->status == GMIME_SIGNER_STATUS_GOOD)
623         {
624             if (signer->fingerprint)
625                 printf (", \"fingerprint\": %s", json_quote_str (ctx_quote, signer->fingerprint));
626             /* these dates are seconds since the epoch; should we
627              * provide a more human-readable format string? */
628             if (signer->created)
629                 printf (", \"created\": %d", (int) signer->created);
630             if (signer->expires)
631                 printf (", \"expires\": %d", (int) signer->expires);
632             /* output user id only if validity is FULL or ULTIMATE. */
633             /* note that gmime is using the term "trust" here, which
634              * is WRONG.  It's actually user id "validity". */
635             if ((signer->name) && (signer->trust)) {
636                 if ((signer->trust == GMIME_SIGNER_TRUST_FULLY) || (signer->trust == GMIME_SIGNER_TRUST_ULTIMATE))
637                     printf (", \"userid\": %s", json_quote_str (ctx_quote, signer->name));
638            }
639        } else {
640            if (signer->keyid)
641                printf (", \"keyid\": %s", json_quote_str (ctx_quote, signer->keyid));
642        }
643        if (signer->errors != GMIME_SIGNER_ERROR_NONE) {
644            printf (", \"errors\": %x", signer->errors);
645        }
646
647        printf ("}");
648        signer = signer->next;
649     }
650
651     printf ("]");
652
653     talloc_free (ctx_quote);
654 }
655
656 static void
657 format_part_content_json (GMimeObject *part)
658 {
659     GMimeContentType *content_type = g_mime_object_get_content_type (GMIME_OBJECT (part));
660     GMimeStream *stream_memory = g_mime_stream_mem_new ();
661     const char *cid = g_mime_object_get_content_id (part);
662     void *ctx = talloc_new (NULL);
663     GByteArray *part_content;
664
665     printf (", \"content-type\": %s",
666             json_quote_str (ctx, g_mime_content_type_to_string (content_type)));
667
668     if (cid != NULL)
669             printf(", \"content-id\": %s", json_quote_str (ctx, cid));
670
671     if (GMIME_IS_PART (part))
672     {
673         const char *filename = g_mime_part_get_filename (GMIME_PART (part));
674         if (filename)
675             printf (", \"filename\": %s", json_quote_str (ctx, filename));
676     }
677
678     if (g_mime_content_type_is_type (content_type, "text", "*") &&
679         !g_mime_content_type_is_type (content_type, "text", "html"))
680     {
681         show_text_part_content (part, stream_memory);
682         part_content = g_mime_stream_mem_get_byte_array (GMIME_STREAM_MEM (stream_memory));
683
684         printf (", \"content\": %s", json_quote_chararray (ctx, (char *) part_content->data, part_content->len));
685     }
686     else if (g_mime_content_type_is_type (content_type, "multipart", "*"))
687     {
688         printf (", \"content\": [");
689     }
690     else if (g_mime_content_type_is_type (content_type, "message", "rfc822"))
691     {
692         printf (", \"content\": [{");
693     }
694
695     talloc_free (ctx);
696     if (stream_memory)
697         g_object_unref (stream_memory);
698 }
699
700 static void
701 format_part_end_json (GMimeObject *part)
702 {
703     GMimeContentType *content_type = g_mime_object_get_content_type (GMIME_OBJECT (part));
704
705     if (g_mime_content_type_is_type (content_type, "multipart", "*"))
706         printf ("]");
707     else if (g_mime_content_type_is_type (content_type, "message", "rfc822"))
708         printf ("}]");
709
710     printf ("}");
711 }
712
713 static void
714 format_part_content_raw (GMimeObject *part)
715 {
716     if (! GMIME_IS_PART (part))
717         return;
718
719     GMimeStream *stream_stdout;
720     GMimeStream *stream_filter = NULL;
721     GMimeDataWrapper *wrapper;
722
723     stream_stdout = g_mime_stream_file_new (stdout);
724     g_mime_stream_file_set_owner (GMIME_STREAM_FILE (stream_stdout), FALSE);
725
726     stream_filter = g_mime_stream_filter_new (stream_stdout);
727
728     wrapper = g_mime_part_get_content_object (GMIME_PART (part));
729
730     if (wrapper && stream_filter)
731         g_mime_data_wrapper_write_to_stream (wrapper, stream_filter);
732
733     if (stream_filter)
734         g_object_unref (stream_filter);
735
736     if (stream_stdout)
737         g_object_unref(stream_stdout);
738 }
739
740 static void
741 show_message (void *ctx,
742               const notmuch_show_format_t *format,
743               notmuch_message_t *message,
744               int indent,
745               notmuch_show_params_t *params)
746 {
747     if (params->part <= 0) {
748         fputs (format->message_start, stdout);
749         if (format->message)
750             format->message(ctx, message, indent);
751
752         fputs (format->header_start, stdout);
753         if (format->header)
754             format->header(ctx, message);
755         fputs (format->header_end, stdout);
756
757         fputs (format->body_start, stdout);
758     }
759
760     if (format->part_content)
761         show_message_body (message, format, params);
762
763     if (params->part <= 0) {
764         fputs (format->body_end, stdout);
765
766         fputs (format->message_end, stdout);
767     }
768 }
769
770 static void
771 show_messages (void *ctx,
772                const notmuch_show_format_t *format,
773                notmuch_messages_t *messages,
774                int indent,
775                notmuch_show_params_t *params)
776 {
777     notmuch_message_t *message;
778     notmuch_bool_t match;
779     int first_set = 1;
780     int next_indent;
781
782     fputs (format->message_set_start, stdout);
783
784     for (;
785          notmuch_messages_valid (messages);
786          notmuch_messages_move_to_next (messages))
787     {
788         if (!first_set)
789             fputs (format->message_set_sep, stdout);
790         first_set = 0;
791
792         fputs (format->message_set_start, stdout);
793
794         message = notmuch_messages_get (messages);
795
796         match = notmuch_message_get_flag (message, NOTMUCH_MESSAGE_FLAG_MATCH);
797
798         next_indent = indent;
799
800         if (match || params->entire_thread) {
801             show_message (ctx, format, message, indent, params);
802             next_indent = indent + 1;
803
804             fputs (format->message_set_sep, stdout);
805         }
806
807         show_messages (ctx,
808                        format,
809                        notmuch_message_get_replies (message),
810                        next_indent,
811                        params);
812
813         notmuch_message_destroy (message);
814
815         fputs (format->message_set_end, stdout);
816     }
817
818     fputs (format->message_set_end, stdout);
819 }
820
821 /* Formatted output of single message */
822 static int
823 do_show_single (void *ctx,
824                 notmuch_query_t *query,
825                 const notmuch_show_format_t *format,
826                 notmuch_show_params_t *params)
827 {
828     notmuch_messages_t *messages;
829     notmuch_message_t *message;
830
831     if (notmuch_query_count_messages (query) != 1) {
832         fprintf (stderr, "Error: search term did not match precisely one message.\n");
833         return 1;
834     }
835
836     messages = notmuch_query_search_messages (query);
837     message = notmuch_messages_get (messages);
838
839     if (message == NULL) {
840         fprintf (stderr, "Error: Cannot find matching message.\n");
841         return 1;
842     }
843
844     notmuch_message_set_flag (message, NOTMUCH_MESSAGE_FLAG_MATCH, 1);
845
846     /* Special case for --format=raw of full single message, just cat out file */
847     if (params->raw && 0 == params->part) {
848
849         const char *filename;
850         FILE *file;
851         size_t size;
852         char buf[4096];
853
854         filename = notmuch_message_get_filename (message);
855         if (filename == NULL) {
856             fprintf (stderr, "Error: Cannot message filename.\n");
857             return 1;
858         }
859
860         file = fopen (filename, "r");
861         if (file == NULL) {
862             fprintf (stderr, "Error: Cannot open file %s: %s\n", filename, strerror (errno));
863             return 1;
864         }
865
866         while (!feof (file)) {
867             size = fread (buf, 1, sizeof (buf), file);
868             (void) fwrite (buf, size, 1, stdout);
869         }
870
871         fclose (file);
872
873     } else {
874
875         show_message (ctx, format, message, 0, params);
876
877     }
878
879     return 0;
880 }
881
882 /* Formatted output of threads */
883 static int
884 do_show (void *ctx,
885          notmuch_query_t *query,
886          const notmuch_show_format_t *format,
887          notmuch_show_params_t *params)
888 {
889     notmuch_threads_t *threads;
890     notmuch_thread_t *thread;
891     notmuch_messages_t *messages;
892     int first_toplevel = 1;
893
894     fputs (format->message_set_start, stdout);
895
896     for (threads = notmuch_query_search_threads (query);
897          notmuch_threads_valid (threads);
898          notmuch_threads_move_to_next (threads))
899     {
900         thread = notmuch_threads_get (threads);
901
902         messages = notmuch_thread_get_toplevel_messages (thread);
903
904         if (messages == NULL)
905             INTERNAL_ERROR ("Thread %s has no toplevel messages.\n",
906                             notmuch_thread_get_thread_id (thread));
907
908         if (!first_toplevel)
909             fputs (format->message_set_sep, stdout);
910         first_toplevel = 0;
911
912         show_messages (ctx, format, messages, 0, params);
913
914         notmuch_thread_destroy (thread);
915
916     }
917
918     fputs (format->message_set_end, stdout);
919
920     return 0;
921 }
922
923 int
924 notmuch_show_command (void *ctx, unused (int argc), unused (char *argv[]))
925 {
926     notmuch_config_t *config;
927     notmuch_database_t *notmuch;
928     notmuch_query_t *query;
929     char *query_string;
930     char *opt;
931     const notmuch_show_format_t *format = &format_text;
932     notmuch_show_params_t params;
933     int mbox = 0;
934     int format_specified = 0;
935     int i;
936
937     params.entire_thread = 0;
938     params.raw = 0;
939     params.part = -1;
940     params.cryptoctx = NULL;
941     params.decrypt = 0;
942
943     argc--; argv++; /* skip subcommand argument */
944
945     for (i = 0; i < argc && argv[i][0] == '-'; i++) {
946         if (strcmp (argv[i], "--") == 0) {
947             i++;
948             break;
949         }
950         if (STRNCMP_LITERAL (argv[i], "--format=") == 0) {
951             opt = argv[i] + sizeof ("--format=") - 1;
952             if (strcmp (opt, "text") == 0) {
953                 format = &format_text;
954             } else if (strcmp (opt, "json") == 0) {
955                 format = &format_json;
956                 params.entire_thread = 1;
957             } else if (strcmp (opt, "mbox") == 0) {
958                 format = &format_mbox;
959                 mbox = 1;
960             } else if (strcmp (opt, "raw") == 0) {
961                 format = &format_raw;
962                 params.raw = 1;
963             } else {
964                 fprintf (stderr, "Invalid value for --format: %s\n", opt);
965                 return 1;
966             }
967             format_specified = 1;
968         } else if (STRNCMP_LITERAL (argv[i], "--part=") == 0) {
969             params.part = atoi(argv[i] + sizeof ("--part=") - 1);
970         } else if (STRNCMP_LITERAL (argv[i], "--entire-thread") == 0) {
971             params.entire_thread = 1;
972         } else if ((STRNCMP_LITERAL (argv[i], "--verify") == 0) ||
973                    (STRNCMP_LITERAL (argv[i], "--decrypt") == 0)) {
974             if (params.cryptoctx == NULL) {
975                 GMimeSession* session = g_object_new(g_mime_session_get_type(), NULL);
976                 if (NULL == (params.cryptoctx = g_mime_gpg_context_new(session, "gpg")))
977                     fprintf (stderr, "Failed to construct gpg context.\n");
978                 else
979                     g_mime_gpg_context_set_always_trust((GMimeGpgContext*)params.cryptoctx, FALSE);
980                 g_object_unref (session);
981                 session = NULL;
982             }
983             if (STRNCMP_LITERAL (argv[i], "--decrypt") == 0)
984                 params.decrypt = 1;
985         } else {
986             fprintf (stderr, "Unrecognized option: %s\n", argv[i]);
987             return 1;
988         }
989     }
990
991     argc -= i;
992     argv += i;
993
994     config = notmuch_config_open (ctx, NULL, NULL);
995     if (config == NULL)
996         return 1;
997
998     query_string = query_string_from_args (ctx, argc, argv);
999     if (query_string == NULL) {
1000         fprintf (stderr, "Out of memory\n");
1001         return 1;
1002     }
1003
1004     if (mbox && params.part > 0) {
1005         fprintf (stderr, "Error: specifying parts is incompatible with mbox output format.\n");
1006         return 1;
1007     }
1008
1009     if (*query_string == '\0') {
1010         fprintf (stderr, "Error: notmuch show requires at least one search term.\n");
1011         return 1;
1012     }
1013
1014     notmuch = notmuch_database_open (notmuch_config_get_database_path (config),
1015                                      NOTMUCH_DATABASE_MODE_READ_ONLY);
1016     if (notmuch == NULL)
1017         return 1;
1018
1019     query = notmuch_query_create (notmuch, query_string);
1020     if (query == NULL) {
1021         fprintf (stderr, "Out of memory\n");
1022         return 1;
1023     }
1024
1025     /* if part was requested and format was not specified, use format=raw */
1026     if (params.part >= 0 && !format_specified)
1027         format = &format_raw;
1028
1029     /* If --format=raw specified without specifying part, we can only
1030      * output single message, so set part=0 */
1031     if (params.raw && params.part < 0)
1032         params.part = 0;
1033
1034     if (params.part >= 0)
1035         return do_show_single (ctx, query, format, &params);
1036     else
1037         return do_show (ctx, query, format, &params);
1038
1039     notmuch_query_destroy (query);
1040     notmuch_database_close (notmuch);
1041
1042     if (params.cryptoctx)
1043         g_object_unref(params.cryptoctx);
1044
1045     return 0;
1046 }