]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-show.el
emacs: Prefer '[No Subject]' to blank subjects.
[notmuch] / emacs / notmuch-show.el
1 ;; notmuch-show.el --- displaying notmuch forests.
2 ;;
3 ;; Copyright © Carl Worth
4 ;; Copyright © David Edmondson
5 ;;
6 ;; This file is part of Notmuch.
7 ;;
8 ;; Notmuch is free software: you can redistribute it and/or modify it
9 ;; under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation, either version 3 of the License, or
11 ;; (at your option) any later version.
12 ;;
13 ;; Notmuch is distributed in the hope that it will be useful, but
14 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 ;; General Public License for more details.
17 ;;
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with Notmuch.  If not, see <http://www.gnu.org/licenses/>.
20 ;;
21 ;; Authors: Carl Worth <cworth@cworth.org>
22 ;;          David Edmondson <dme@dme.org>
23
24 (eval-when-compile (require 'cl))
25 (require 'mm-view)
26 (require 'message)
27 (require 'mm-decode)
28 (require 'mailcap)
29 (require 'icalendar)
30 (require 'goto-addr)
31
32 (require 'notmuch-lib)
33 (require 'notmuch-query)
34 (require 'notmuch-wash)
35 (require 'notmuch-mua)
36 (require 'notmuch-crypto)
37 (require 'notmuch-print)
38
39 (declare-function notmuch-call-notmuch-process "notmuch" (&rest args))
40 (declare-function notmuch-fontify-headers "notmuch" nil)
41 (declare-function notmuch-select-tag-with-completion "notmuch" (prompt &rest search-terms))
42 (declare-function notmuch-search-next-thread "notmuch" nil)
43 (declare-function notmuch-search-show-thread "notmuch" nil)
44
45 (defcustom notmuch-message-headers '("Subject" "To" "Cc" "Date")
46   "Headers that should be shown in a message, in this order.
47
48 For an open message, all of these headers will be made visible
49 according to `notmuch-message-headers-visible' or can be toggled
50 with `notmuch-show-toggle-headers'. For a closed message, only
51 the first header in the list will be visible."
52   :type '(repeat string)
53   :group 'notmuch-show)
54
55 (defcustom notmuch-message-headers-visible t
56   "Should the headers be visible by default?
57
58 If this value is non-nil, then all of the headers defined in
59 `notmuch-message-headers' will be visible by default in the display
60 of each message. Otherwise, these headers will be hidden and
61 `notmuch-show-toggle-headers' can be used to make the visible for
62 any given message."
63   :type 'boolean
64   :group 'notmuch-show)
65
66 (defcustom notmuch-show-relative-dates t
67   "Display relative dates in the message summary line."
68   :type 'boolean
69   :group 'notmuch-show)
70
71 (defvar notmuch-show-markup-headers-hook '(notmuch-show-colour-headers)
72   "A list of functions called to decorate the headers listed in
73 `notmuch-message-headers'.")
74
75 (defcustom notmuch-show-hook '(notmuch-show-turn-on-visual-line-mode)
76   "Functions called after populating a `notmuch-show' buffer."
77   :type 'hook
78   :options '(notmuch-show-turn-on-visual-line-mode)
79   :group 'notmuch-show
80   :group 'notmuch-hooks)
81
82 (defcustom notmuch-show-insert-text/plain-hook '(notmuch-wash-wrap-long-lines
83                                                  notmuch-wash-tidy-citations
84                                                  notmuch-wash-elide-blank-lines
85                                                  notmuch-wash-excerpt-citations)
86   "Functions used to improve the display of text/plain parts."
87   :type 'hook
88   :options '(notmuch-wash-convert-inline-patch-to-part
89              notmuch-wash-wrap-long-lines
90              notmuch-wash-tidy-citations
91              notmuch-wash-elide-blank-lines
92              notmuch-wash-excerpt-citations)
93   :group 'notmuch-show
94   :group 'notmuch-hooks)
95
96 ;; Mostly useful for debugging.
97 (defcustom notmuch-show-all-multipart/alternative-parts t
98   "Should all parts of multipart/alternative parts be shown?"
99   :type 'boolean
100   :group 'notmuch-show)
101
102 (defcustom notmuch-show-indent-messages-width 1
103   "Width of message indentation in threads.
104
105 Messages are shown indented according to their depth in a thread.
106 This variable determines the width of this indentation measured
107 in number of blanks.  Defaults to `1', choose `0' to disable
108 indentation."
109   :type 'integer
110   :group 'notmuch-show)
111
112 (defcustom notmuch-show-indent-multipart nil
113   "Should the sub-parts of a multipart/* part be indented?"
114   ;; dme: Not sure which is a good default.
115   :type 'boolean
116   :group 'notmuch-show)
117
118 (defcustom notmuch-show-part-button-default-action 'notmuch-show-save-part
119   "Default part header button action (on ENTER or mouse click)."
120   :group 'notmuch-show
121   :type '(choice (const :tag "Save part"
122                         notmuch-show-save-part)
123                  (const :tag "View part"
124                         notmuch-show-view-part)
125                  (const :tag "View interactively"
126                         notmuch-show-interactively-view-part)))
127
128 (defmacro with-current-notmuch-show-message (&rest body)
129   "Evaluate body with current buffer set to the text of current message"
130   `(save-excursion
131      (let ((id (notmuch-show-get-message-id)))
132        (let ((buf (generate-new-buffer (concat "*notmuch-msg-" id "*"))))
133          (with-current-buffer buf
134             (call-process notmuch-command nil t nil "show" "--format=raw" id)
135            ,@body)
136          (kill-buffer buf)))))
137
138 (defun notmuch-show-turn-on-visual-line-mode ()
139   "Enable Visual Line mode."
140   (visual-line-mode t))
141
142 (defun notmuch-show-view-all-mime-parts ()
143   "Use external viewers to view all attachments from the current message."
144   (interactive)
145   (with-current-notmuch-show-message
146    ;; We override the mm-inline-media-tests to indicate which message
147    ;; parts are already sufficiently handled by the original
148    ;; presentation of the message in notmuch-show mode. These parts
149    ;; will be inserted directly into the temporary buffer of
150    ;; with-current-notmuch-show-message and silently discarded.
151    ;;
152    ;; Any MIME part not explicitly mentioned here will be handled by an
153    ;; external viewer as configured in the various mailcap files.
154    (let ((mm-inline-media-tests '(
155                                   ("text/.*" ignore identity)
156                                   ("application/pgp-signature" ignore identity)
157                                   ("multipart/alternative" ignore identity)
158                                   ("multipart/mixed" ignore identity)
159                                   ("multipart/related" ignore identity)
160                                  )))
161      (mm-display-parts (mm-dissect-buffer)))))
162
163 (defun notmuch-foreach-mime-part (function mm-handle)
164   (cond ((stringp (car mm-handle))
165          (dolist (part (cdr mm-handle))
166            (notmuch-foreach-mime-part function part)))
167         ((bufferp (car mm-handle))
168          (funcall function mm-handle))
169         (t (dolist (part mm-handle)
170              (notmuch-foreach-mime-part function part)))))
171
172 (defun notmuch-count-attachments (mm-handle)
173   (let ((count 0))
174     (notmuch-foreach-mime-part
175      (lambda (p)
176        (let ((disposition (mm-handle-disposition p)))
177          (and (listp disposition)
178               (or (equal (car disposition) "attachment")
179                   (and (equal (car disposition) "inline")
180                        (assq 'filename disposition)))
181               (incf count))))
182      mm-handle)
183     count))
184
185 (defun notmuch-save-attachments (mm-handle &optional queryp)
186   (notmuch-foreach-mime-part
187    (lambda (p)
188      (let ((disposition (mm-handle-disposition p)))
189        (and (listp disposition)
190             (or (equal (car disposition) "attachment")
191                 (and (equal (car disposition) "inline")
192                      (assq 'filename disposition)))
193             (or (not queryp)
194                 (y-or-n-p
195                  (concat "Save '" (cdr (assq 'filename disposition)) "' ")))
196             (mm-save-part p))))
197    mm-handle))
198
199 (defun notmuch-show-save-attachments ()
200   "Save all attachments from the current message."
201   (interactive)
202   (with-current-notmuch-show-message
203    (let ((mm-handle (mm-dissect-buffer)))
204      (notmuch-save-attachments
205       mm-handle (> (notmuch-count-attachments mm-handle) 1))))
206   (message "Done"))
207
208 (defun notmuch-show-with-message-as-text (fn)
209   "Apply FN to a text representation of the current message.
210
211 FN is called with one argument, the message properties. It should
212 operation on the contents of the current buffer."
213
214   ;; Remake the header to ensure that all information is available.
215   (let* ((to (notmuch-show-get-to))
216          (cc (notmuch-show-get-cc))
217          (from (notmuch-show-get-from))
218          (subject (notmuch-show-get-subject))
219          (date (notmuch-show-get-date))
220          (tags (notmuch-show-get-tags))
221          (depth (notmuch-show-get-depth))
222
223          (header (concat
224                   "Subject: " subject "\n"
225                   "To: " to "\n"
226                   (if (not (string= cc ""))
227                       (concat "Cc: " cc "\n")
228                     "")
229                   "From: " from "\n"
230                   "Date: " date "\n"
231                   (if tags
232                       (concat "Tags: "
233                               (mapconcat #'identity tags ", ") "\n")
234                     "")))
235          (all (buffer-substring (notmuch-show-message-top)
236                                 (notmuch-show-message-bottom)))
237
238          (props (notmuch-show-get-message-properties)))
239     (with-temp-buffer
240       (insert all)
241       (indent-rigidly (point-min) (point-max) (- depth))
242       ;; Remove the original header.
243       (goto-char (point-min))
244       (re-search-forward "^$" (point-max) nil)
245       (delete-region (point-min) (point))
246       (insert header)
247       (funcall fn props))))
248
249 (defun notmuch-show-print-message ()
250   "Print the current message."
251   (interactive)
252   (notmuch-show-with-message-as-text 'notmuch-print-message))
253
254 (defun notmuch-show-fontify-header ()
255   (let ((face (cond
256                ((looking-at "[Tt]o:")
257                 'message-header-to)
258                ((looking-at "[Bb]?[Cc][Cc]:")
259                 'message-header-cc)
260                ((looking-at "[Ss]ubject:")
261                 'message-header-subject)
262                ((looking-at "[Ff]rom:")
263                 'message-header-from)
264                (t
265                 'message-header-other))))
266
267     (overlay-put (make-overlay (point) (re-search-forward ":"))
268                  'face 'message-header-name)
269     (overlay-put (make-overlay (point) (re-search-forward ".*$"))
270                  'face face)))
271
272 (defun notmuch-show-colour-headers ()
273   "Apply some colouring to the current headers."
274   (goto-char (point-min))
275   (while (looking-at "^[A-Za-z][-A-Za-z0-9]*:")
276     (notmuch-show-fontify-header)
277     (forward-line)))
278
279 (defun notmuch-show-spaces-n (n)
280   "Return a string comprised of `n' spaces."
281   (make-string n ? ))
282
283 (defun notmuch-show-update-tags (tags)
284   "Update the displayed tags of the current message."
285   (save-excursion
286     (goto-char (notmuch-show-message-top))
287     (if (re-search-forward "(\\([^()]*\\))$" (line-end-position) t)
288         (let ((inhibit-read-only t))
289           (replace-match (concat "("
290                                  (propertize (mapconcat 'identity tags " ")
291                                              'face 'notmuch-tag-face)
292                                  ")"))))))
293
294 (defun notmuch-show-clean-address (address)
295   "Try to clean a single email ADDRESS for display.  Return
296 unchanged ADDRESS if parsing fails."
297   (condition-case nil
298     (let (p-name p-address)
299       ;; It would be convenient to use `mail-header-parse-address',
300       ;; but that expects un-decoded mailbox parts, whereas our
301       ;; mailbox parts are already decoded (and hence may contain
302       ;; UTF-8). Given that notmuch should handle most of the awkward
303       ;; cases, some simple string deconstruction should be sufficient
304       ;; here.
305       (cond
306        ;; "User <user@dom.ain>" style.
307        ((string-match "\\(.*\\) <\\(.*\\)>" address)
308         (setq p-name (match-string 1 address)
309               p-address (match-string 2 address)))
310
311        ;; "<user@dom.ain>" style.
312        ((string-match "<\\(.*\\)>" address)
313         (setq p-address (match-string 1 address)))
314
315        ;; Everything else.
316        (t
317         (setq p-address address)))
318
319       ;; Remove elements of the mailbox part that are not relevant for
320       ;; display, even if they are required during transport.
321       (when p-name
322         ;; Outer double quotes.
323         (when (string-match "^\"\\(.*\\)\"$" p-name)
324           (setq p-name (match-string 1 p-name)))
325
326         ;; Backslashes.
327         (setq p-name (replace-regexp-in-string "\\\\" "" p-name)))
328
329       ;; If the address is 'foo@bar.com <foo@bar.com>' then show just
330       ;; 'foo@bar.com'.
331       (when (string= p-name p-address)
332         (setq p-name nil))
333
334       ;; If no name results, return just the address.
335       (if (not p-name)
336           p-address
337         ;; Otherwise format the name and address together.
338         (concat p-name " <" p-address ">")))
339     (error address)))
340
341 (defun notmuch-show-insert-headerline (headers date tags depth)
342   "Insert a notmuch style headerline based on HEADERS for a
343 message at DEPTH in the current thread."
344   (let ((start (point)))
345     (insert (notmuch-show-spaces-n (* notmuch-show-indent-messages-width depth))
346             (notmuch-show-clean-address (plist-get headers :From))
347             " ("
348             date
349             ") ("
350             (propertize (mapconcat 'identity tags " ")
351                         'face 'notmuch-tag-face)
352             ")\n")
353     (overlay-put (make-overlay start (point)) 'face 'notmuch-message-summary-face)))
354
355 (defun notmuch-show-insert-header (header header-value)
356   "Insert a single header."
357   (insert header ": " header-value "\n"))
358
359 (defun notmuch-show-insert-headers (headers)
360   "Insert the headers of the current message."
361   (let ((start (point)))
362     (mapc (lambda (header)
363             (let* ((header-symbol (intern (concat ":" header)))
364                    (header-value (plist-get headers header-symbol)))
365               (if (and header-value
366                        (not (string-equal "" header-value)))
367                   (notmuch-show-insert-header header header-value))))
368           notmuch-message-headers)
369     (save-excursion
370       (save-restriction
371         (narrow-to-region start (point-max))
372         (run-hooks 'notmuch-show-markup-headers-hook)))))
373
374 (define-button-type 'notmuch-show-part-button-type
375   'action 'notmuch-show-part-button-default
376   'keymap 'notmuch-show-part-button-map
377   'follow-link t
378   'face 'message-mml)
379
380 (defvar notmuch-show-part-button-map
381   (let ((map (make-sparse-keymap)))
382     (set-keymap-parent map button-map)
383     (define-key map "s" 'notmuch-show-part-button-save)
384     (define-key map "v" 'notmuch-show-part-button-view)
385     (define-key map "o" 'notmuch-show-part-button-interactively-view)
386     map)
387   "Submap for button commands")
388 (fset 'notmuch-show-part-button-map notmuch-show-part-button-map)
389
390 (defun notmuch-show-insert-part-header (nth content-type declared-type &optional name comment)
391   (let ((button))
392     (setq button
393           (insert-button
394            (concat "[ "
395                    (if name (concat name ": ") "")
396                    declared-type
397                    (if (not (string-equal declared-type content-type))
398                        (concat " (as " content-type ")")
399                      "")
400                    (or comment "")
401                    " ]")
402            :type 'notmuch-show-part-button-type
403            :notmuch-part nth
404            :notmuch-filename name
405            :notmuch-content-type content-type))
406     (insert "\n")
407     ;; return button
408     button))
409
410 ;; Functions handling particular MIME parts.
411
412 (defmacro notmuch-with-temp-part-buffer (message-id nth &rest body)
413   (declare (indent 2))
414   (let ((process-crypto (make-symbol "process-crypto")))
415     `(let ((,process-crypto notmuch-show-process-crypto))
416        (with-temp-buffer
417          (setq notmuch-show-process-crypto ,process-crypto)
418          ;; Always acquires the part via `notmuch part', even if it is
419          ;; available in the JSON output.
420          (insert (notmuch-show-get-bodypart-internal ,message-id ,nth))
421          ,@body))))
422
423 (defun notmuch-show-save-part (message-id nth &optional filename content-type)
424   (notmuch-with-temp-part-buffer message-id nth
425     (let ((file (read-file-name
426                  "Filename to save as: "
427                  (or mailcap-download-directory "~/")
428                  nil nil
429                  filename)))
430       ;; Don't re-compress .gz & al.  Arguably we should make
431       ;; `file-name-handler-alist' nil, but that would chop
432       ;; ange-ftp, which is reasonable to use here.
433       (mm-write-region (point-min) (point-max) file nil nil nil 'no-conversion t))))
434
435 (defun notmuch-show-view-part (message-id nth &optional filename content-type )
436   (notmuch-with-temp-part-buffer message-id nth
437     ;; set mm-inlined-types to nil to force an external viewer
438     (let ((handle (mm-make-handle (current-buffer) (list content-type)))
439           (mm-inlined-types nil))
440       ;; We override mm-save-part as notmuch-show-save-part is better
441       ;; since it offers the filename. We need to lexically bind
442       ;; everything we need for notmuch-show-save-part to prevent
443       ;; potential dynamic shadowing.
444       (lexical-let ((message-id message-id)
445                     (nth nth)
446                     (filename filename)
447                     (content-type content-type))
448         (flet ((mm-save-part (&rest args) (notmuch-show-save-part
449                                            message-id nth filename content-type)))
450           (mm-display-part handle))))))
451
452 (defun notmuch-show-interactively-view-part (message-id nth &optional filename content-type)
453   (notmuch-with-temp-part-buffer message-id nth
454     (let ((handle (mm-make-handle (current-buffer) (list content-type))))
455       (mm-interactively-view-part handle))))
456
457 (defun notmuch-show-mm-display-part-inline (msg part nth content-type)
458   "Use the mm-decode/mm-view functions to display a part in the
459 current buffer, if possible."
460   (let ((display-buffer (current-buffer)))
461     (with-temp-buffer
462       (let* ((charset (plist-get part :content-charset))
463              (handle (mm-make-handle (current-buffer) `(,content-type (charset . ,charset)))))
464         ;; If the user wants the part inlined, insert the content and
465         ;; test whether we are able to inline it (which includes both
466         ;; capability and suitability tests).
467         (when (mm-inlined-p handle)
468           (insert (notmuch-show-get-bodypart-content msg part nth))
469           (when (mm-inlinable-p handle)
470             (set-buffer display-buffer)
471             (mm-display-part handle)
472             t))))))
473
474 (defvar notmuch-show-multipart/alternative-discouraged
475   '(
476     ;; Avoid HTML parts.
477     "text/html"
478     ;; multipart/related usually contain a text/html part and some associated graphics.
479     "multipart/related"
480     ))
481
482 (defun notmuch-show-multipart/*-to-list (part)
483   (mapcar (lambda (inner-part) (plist-get inner-part :content-type))
484           (plist-get part :content)))
485
486 (defun notmuch-show-multipart/alternative-choose (types)
487   ;; Based on `mm-preferred-alternative-precedence'.
488   (let ((seq types))
489     (dolist (pref (reverse notmuch-show-multipart/alternative-discouraged))
490       (dolist (elem (copy-sequence seq))
491         (when (string-match pref elem)
492           (setq seq (nconc (delete elem seq) (list elem))))))
493     seq))
494
495 (defun notmuch-show-insert-part-multipart/alternative (msg part content-type nth depth declared-type)
496   (notmuch-show-insert-part-header nth declared-type content-type nil)
497   (let ((chosen-type (car (notmuch-show-multipart/alternative-choose (notmuch-show-multipart/*-to-list part))))
498         (inner-parts (plist-get part :content))
499         (start (point)))
500     ;; This inserts all parts of the chosen type rather than just one,
501     ;; but it's not clear that this is the wrong thing to do - which
502     ;; should be chosen if there are more than one that match?
503     (mapc (lambda (inner-part)
504             (let ((inner-type (plist-get inner-part :content-type)))
505               (if (or notmuch-show-all-multipart/alternative-parts
506                       (string= chosen-type inner-type))
507                   (notmuch-show-insert-bodypart msg inner-part depth)
508                 (notmuch-show-insert-part-header (plist-get inner-part :id) inner-type inner-type nil " (not shown)"))))
509           inner-parts)
510
511     (when notmuch-show-indent-multipart
512       (indent-rigidly start (point) 1)))
513   t)
514
515 (defun notmuch-show-setup-w3m ()
516   "Instruct w3m how to retrieve content from a \"related\" part of a message."
517   (interactive)
518   (if (boundp 'w3m-cid-retrieve-function-alist)
519     (unless (assq 'notmuch-show-mode w3m-cid-retrieve-function-alist)
520       (push (cons 'notmuch-show-mode 'notmuch-show-w3m-cid-retrieve)
521             w3m-cid-retrieve-function-alist)))
522   (setq mm-inline-text-html-with-images t))
523
524 (defvar w3m-current-buffer) ;; From `w3m.el'.
525 (defvar notmuch-show-w3m-cid-store nil)
526 (make-variable-buffer-local 'notmuch-show-w3m-cid-store)
527
528 (defun notmuch-show-w3m-cid-store-internal (content-id
529                                             message-id
530                                             part-number
531                                             content-type
532                                             content)
533   (push (list content-id
534               message-id
535               part-number
536               content-type
537               content)
538         notmuch-show-w3m-cid-store))
539
540 (defun notmuch-show-w3m-cid-store (msg part)
541   (let ((content-id (plist-get part :content-id)))
542     (when content-id
543       (notmuch-show-w3m-cid-store-internal (concat "cid:" content-id)
544                                            (plist-get msg :id)
545                                            (plist-get part :id)
546                                            (plist-get part :content-type)
547                                            nil))))
548
549 (defun notmuch-show-w3m-cid-retrieve (url &rest args)
550   (let ((matching-part (with-current-buffer w3m-current-buffer
551                          (assoc url notmuch-show-w3m-cid-store))))
552     (if matching-part
553         (let ((message-id (nth 1 matching-part))
554               (part-number (nth 2 matching-part))
555               (content-type (nth 3 matching-part))
556               (content (nth 4 matching-part)))
557           ;; If we don't already have the content, get it and cache
558           ;; it, as some messages reference the same cid: part many
559           ;; times (hundreds!), which results in many calls to
560           ;; `notmuch part'.
561           (unless content
562             (setq content (notmuch-show-get-bodypart-internal (concat "id:" message-id)
563                                                               part-number))
564             (with-current-buffer w3m-current-buffer
565               (notmuch-show-w3m-cid-store-internal url
566                                                    message-id
567                                                    part-number
568                                                    content-type
569                                                    content)))
570           (insert content)
571           content-type)
572       nil)))
573
574 (defun notmuch-show-insert-part-multipart/related (msg part content-type nth depth declared-type)
575   (notmuch-show-insert-part-header nth declared-type content-type nil)
576   (let ((inner-parts (plist-get part :content))
577         (start (point)))
578
579     ;; We assume that the first part is text/html and the remainder
580     ;; things that it references.
581
582     ;; Stash the non-primary parts.
583     (mapc (lambda (part)
584             (notmuch-show-w3m-cid-store msg part))
585           (cdr inner-parts))
586
587     ;; Render the primary part.
588     (notmuch-show-insert-bodypart msg (car inner-parts) depth)
589
590     (when notmuch-show-indent-multipart
591       (indent-rigidly start (point) 1)))
592   t)
593
594 (defun notmuch-show-insert-part-multipart/signed (msg part content-type nth depth declared-type)
595   (let ((button (notmuch-show-insert-part-header nth declared-type content-type nil)))
596     (button-put button 'face 'notmuch-crypto-part-header)
597     ;; add signature status button if sigstatus provided
598     (if (plist-member part :sigstatus)
599         (let* ((from (notmuch-show-get-header :From msg))
600                (sigstatus (car (plist-get part :sigstatus))))
601           (notmuch-crypto-insert-sigstatus-button sigstatus from))
602       ;; if we're not adding sigstatus, tell the user how they can get it
603       (button-put button 'help-echo "Set notmuch-crypto-process-mime to process cryptographic mime parts.")))
604
605   (let ((inner-parts (plist-get part :content))
606         (start (point)))
607     ;; Show all of the parts.
608     (mapc (lambda (inner-part)
609             (notmuch-show-insert-bodypart msg inner-part depth))
610           inner-parts)
611
612     (when notmuch-show-indent-multipart
613       (indent-rigidly start (point) 1)))
614   t)
615
616 (defun notmuch-show-insert-part-multipart/encrypted (msg part content-type nth depth declared-type)
617   (let ((button (notmuch-show-insert-part-header nth declared-type content-type nil)))
618     (button-put button 'face 'notmuch-crypto-part-header)
619     ;; add encryption status button if encstatus specified
620     (if (plist-member part :encstatus)
621         (let ((encstatus (car (plist-get part :encstatus))))
622           (notmuch-crypto-insert-encstatus-button encstatus)
623           ;; add signature status button if sigstatus specified
624           (if (plist-member part :sigstatus)
625               (let* ((from (notmuch-show-get-header :From msg))
626                      (sigstatus (car (plist-get part :sigstatus))))
627                 (notmuch-crypto-insert-sigstatus-button sigstatus from))))
628       ;; if we're not adding encstatus, tell the user how they can get it
629       (button-put button 'help-echo "Set notmuch-crypto-process-mime to process cryptographic mime parts.")))
630
631   (let ((inner-parts (plist-get part :content))
632         (start (point)))
633     ;; Show all of the parts.
634     (mapc (lambda (inner-part)
635             (notmuch-show-insert-bodypart msg inner-part depth))
636           inner-parts)
637
638     (when notmuch-show-indent-multipart
639       (indent-rigidly start (point) 1)))
640   t)
641
642 (defun notmuch-show-insert-part-multipart/* (msg part content-type nth depth declared-type)
643   (notmuch-show-insert-part-header nth declared-type content-type nil)
644   (let ((inner-parts (plist-get part :content))
645         (start (point)))
646     ;; Show all of the parts.
647     (mapc (lambda (inner-part)
648             (notmuch-show-insert-bodypart msg inner-part depth))
649           inner-parts)
650
651     (when notmuch-show-indent-multipart
652       (indent-rigidly start (point) 1)))
653   t)
654
655 (defun notmuch-show-insert-part-message/rfc822 (msg part content-type nth depth declared-type)
656   (notmuch-show-insert-part-header nth declared-type content-type nil)
657   (let* ((message (car (plist-get part :content)))
658          (body (car (plist-get message :body)))
659          (start (point)))
660
661     ;; Override `notmuch-message-headers' to force `From' to be
662     ;; displayed.
663     (let ((notmuch-message-headers '("From" "Subject" "To" "Cc" "Date")))
664       (notmuch-show-insert-headers (plist-get message :headers)))
665
666     ;; Blank line after headers to be compatible with the normal
667     ;; message display.
668     (insert "\n")
669
670     ;; Show the body
671     (notmuch-show-insert-bodypart msg body depth)
672
673     (when notmuch-show-indent-multipart
674       (indent-rigidly start (point) 1)))
675   t)
676
677 (defun notmuch-show-insert-part-text/plain (msg part content-type nth depth declared-type)
678   (let ((start (point)))
679     ;; If this text/plain part is not the first part in the message,
680     ;; insert a header to make this clear.
681     (if (> nth 1)
682         (notmuch-show-insert-part-header nth declared-type content-type (plist-get part :filename)))
683     (insert (notmuch-show-get-bodypart-content msg part nth))
684     (save-excursion
685       (save-restriction
686         (narrow-to-region start (point-max))
687         (run-hook-with-args 'notmuch-show-insert-text/plain-hook msg depth))))
688   t)
689
690 (defun notmuch-show-insert-part-text/x-vcalendar (msg part content-type nth depth declared-type)
691   (notmuch-show-insert-part-header nth declared-type content-type (plist-get part :filename))
692   (insert (with-temp-buffer
693             (insert (notmuch-show-get-bodypart-content msg part nth))
694             (goto-char (point-min))
695             (let ((file (make-temp-file "notmuch-ical"))
696                   result)
697               (icalendar--convert-ical-to-diary
698                (icalendar--read-element nil nil)
699                file t)
700               (set-buffer (get-file-buffer file))
701               (setq result (buffer-substring (point-min) (point-max)))
702               (set-buffer-modified-p nil)
703               (kill-buffer (current-buffer))
704               (delete-file file)
705               result)))
706   t)
707
708 (defun notmuch-show-insert-part-application/octet-stream (msg part content-type nth depth declared-type)
709   ;; If we can deduce a MIME type from the filename of the attachment,
710   ;; do so and pass it on to the handler for that type.
711   (if (plist-get part :filename)
712       (let ((extension (file-name-extension (plist-get part :filename)))
713             mime-type)
714         (if extension
715             (progn
716               (mailcap-parse-mimetypes)
717               (setq mime-type (mailcap-extension-to-mime extension))
718               (if (and mime-type
719                        (not (string-equal mime-type "application/octet-stream")))
720                   (notmuch-show-insert-bodypart-internal msg part mime-type nth depth content-type)
721                 nil))
722           nil))))
723
724 ;; Handler for wash generated inline patch fake parts.
725 (defun notmuch-show-insert-part-inline-patch-fake-part (msg part content-type nth depth declared-type)
726   (notmuch-show-insert-part-*/* msg part "text/x-diff" nth depth "inline patch"))
727
728 (defun notmuch-show-insert-part-*/* (msg part content-type nth depth declared-type)
729   ;; This handler _must_ succeed - it is the handler of last resort.
730   (notmuch-show-insert-part-header nth content-type declared-type (plist-get part :filename))
731   (notmuch-show-mm-display-part-inline msg part nth content-type)
732   t)
733
734 ;; Functions for determining how to handle MIME parts.
735
736 (defun notmuch-show-split-content-type (content-type)
737   (split-string content-type "/"))
738
739 (defun notmuch-show-handlers-for (content-type)
740   "Return a list of content handlers for a part of type CONTENT-TYPE."
741   (let (result)
742     (mapc (lambda (func)
743             (if (functionp func)
744                 (push func result)))
745           ;; Reverse order of prefrence.
746           (list (intern (concat "notmuch-show-insert-part-*/*"))
747                 (intern (concat
748                          "notmuch-show-insert-part-"
749                          (car (notmuch-show-split-content-type content-type))
750                          "/*"))
751                 (intern (concat "notmuch-show-insert-part-" content-type))))
752     result))
753
754 ;; Helper for parts which are generally not included in the default
755 ;; JSON output.
756 ;; Uses the buffer-local variable notmuch-show-process-crypto to
757 ;; determine if parts should be decrypted first.
758 (defun notmuch-show-get-bodypart-internal (message-id part-number)
759   (let ((args '("show" "--format=raw"))
760         (part-arg (format "--part=%s" part-number)))
761     (setq args (append args (list part-arg)))
762     (if notmuch-show-process-crypto
763         (setq args (append args '("--decrypt"))))
764     (setq args (append args (list message-id)))
765     (with-temp-buffer
766       (let ((coding-system-for-read 'no-conversion))
767         (progn
768           (apply 'call-process (append (list notmuch-command nil (list t nil) nil) args))
769           (buffer-string))))))
770
771 (defun notmuch-show-get-bodypart-content (msg part nth)
772   (or (plist-get part :content)
773       (notmuch-show-get-bodypart-internal (concat "id:" (plist-get msg :id)) nth)))
774
775 ;; \f
776
777 (defun notmuch-show-insert-bodypart-internal (msg part content-type nth depth declared-type)
778   (let ((handlers (notmuch-show-handlers-for content-type)))
779     ;; Run the content handlers until one of them returns a non-nil
780     ;; value.
781     (while (and handlers
782                 (not (funcall (car handlers) msg part content-type nth depth declared-type)))
783       (setq handlers (cdr handlers))))
784   t)
785
786 (defun notmuch-show-insert-bodypart (msg part depth)
787   "Insert the body part PART at depth DEPTH in the current thread."
788   (let ((content-type (downcase (plist-get part :content-type)))
789         (nth (plist-get part :id)))
790     (notmuch-show-insert-bodypart-internal msg part content-type nth depth content-type))
791   ;; Some of the body part handlers leave point somewhere up in the
792   ;; part, so we make sure that we're down at the end.
793   (goto-char (point-max))
794   ;; Ensure that the part ends with a carriage return.
795   (unless (bolp)
796     (insert "\n")))
797
798 (defun notmuch-show-insert-body (msg body depth)
799   "Insert the body BODY at depth DEPTH in the current thread."
800   (mapc (lambda (part) (notmuch-show-insert-bodypart msg part depth)) body))
801
802 (defun notmuch-show-make-symbol (type)
803   (make-symbol (concat "notmuch-show-" type)))
804
805 (defun notmuch-show-strip-re (string)
806   (replace-regexp-in-string "\\([Rr]e: *\\)+" "" string))
807
808 (defvar notmuch-show-previous-subject "")
809 (make-variable-buffer-local 'notmuch-show-previous-subject)
810
811 (defun notmuch-show-insert-msg (msg depth)
812   "Insert the message MSG at depth DEPTH in the current thread."
813   (let* ((headers (plist-get msg :headers))
814          ;; Indentation causes the buffer offset of the start/end
815          ;; points to move, so we must use markers.
816          message-start message-end
817          content-start content-end
818          headers-start headers-end
819          body-start body-end
820          (headers-invis-spec (notmuch-show-make-symbol "header"))
821          (message-invis-spec (notmuch-show-make-symbol "message"))
822          (bare-subject (notmuch-show-strip-re (plist-get headers :Subject))))
823
824     ;; Set `buffer-invisibility-spec' to `nil' (a list), otherwise
825     ;; removing items from `buffer-invisibility-spec' (which is what
826     ;; `notmuch-show-headers-visible' and
827     ;; `notmuch-show-message-visible' do) is a no-op and has no
828     ;; effect. This caused threads with only matching messages to have
829     ;; those messages hidden initially because
830     ;; `buffer-invisibility-spec' stayed `t'.
831     ;;
832     ;; This needs to be set here (rather than just above the call to
833     ;; `notmuch-show-headers-visible') because some of the part
834     ;; rendering or body washing functions
835     ;; (e.g. `notmuch-wash-text/plain-citations') manipulate
836     ;; `buffer-invisibility-spec').
837     (when (eq buffer-invisibility-spec t)
838       (setq buffer-invisibility-spec nil))
839
840     (setq message-start (point-marker))
841
842     (notmuch-show-insert-headerline headers
843                                     (or (if notmuch-show-relative-dates
844                                             (plist-get msg :date_relative)
845                                           nil)
846                                         (plist-get headers :Date))
847                                     (plist-get msg :tags) depth)
848
849     (setq content-start (point-marker))
850
851     (plist-put msg :headers-invis-spec headers-invis-spec)
852     (plist-put msg :message-invis-spec message-invis-spec)
853
854     ;; Set `headers-start' to point after the 'Subject:' header to be
855     ;; compatible with the existing implementation. This just sets it
856     ;; to after the first header.
857     (notmuch-show-insert-headers headers)
858     ;; Headers should include a blank line (backwards compatibility).
859     (insert "\n")
860     (save-excursion
861       (goto-char content-start)
862       ;; If the subject of this message is the same as that of the
863       ;; previous message, don't display it when this message is
864       ;; collapsed.
865       (when (not (string= notmuch-show-previous-subject
866                           bare-subject))
867         (forward-line 1))
868       (setq headers-start (point-marker)))
869     (setq headers-end (point-marker))
870
871     (setq notmuch-show-previous-subject bare-subject)
872
873     (setq body-start (point-marker))
874     (notmuch-show-insert-body msg (plist-get msg :body) depth)
875     ;; Ensure that the body ends with a newline.
876     (unless (bolp)
877       (insert "\n"))
878     (setq body-end (point-marker))
879     (setq content-end (point-marker))
880
881     ;; Indent according to the depth in the thread.
882     (indent-rigidly content-start content-end (* notmuch-show-indent-messages-width depth))
883
884     (setq message-end (point-max-marker))
885
886     ;; Save the extents of this message over the whole text of the
887     ;; message.
888     (put-text-property message-start message-end :notmuch-message-extent (cons message-start message-end))
889
890     (let ((headers-overlay (make-overlay headers-start headers-end))
891           (invis-specs (list headers-invis-spec message-invis-spec)))
892       (overlay-put headers-overlay 'invisible invis-specs)
893       (overlay-put headers-overlay 'priority 10))
894     (overlay-put (make-overlay body-start body-end) 'invisible message-invis-spec)
895
896     (plist-put msg :depth depth)
897
898     ;; Save the properties for this message. Currently this saves the
899     ;; entire message (augmented it with other stuff), which seems
900     ;; like overkill. We might save a reduced subset (for example, not
901     ;; the content).
902     (notmuch-show-set-message-properties msg)
903
904     ;; Set header visibility.
905     (notmuch-show-headers-visible msg notmuch-message-headers-visible)
906
907     ;; Message visibility depends on whether it matched the search
908     ;; criteria.
909     (notmuch-show-message-visible msg (plist-get msg :match))))
910
911 (defun notmuch-show-insert-tree (tree depth)
912   "Insert the message tree TREE at depth DEPTH in the current thread."
913   (let ((msg (car tree))
914         (replies (cadr tree)))
915     (notmuch-show-insert-msg msg depth)
916     (notmuch-show-insert-thread replies (1+ depth))))
917
918 (defun notmuch-show-insert-thread (thread depth)
919   "Insert the thread THREAD at depth DEPTH in the current forest."
920   (mapc (lambda (tree) (notmuch-show-insert-tree tree depth)) thread))
921
922 (defun notmuch-show-insert-forest (forest)
923   "Insert the forest of threads FOREST."
924   (mapc (lambda (thread) (notmuch-show-insert-thread thread 0)) forest))
925
926 (defvar notmuch-show-thread-id nil)
927 (make-variable-buffer-local 'notmuch-show-thread-id)
928 (defvar notmuch-show-parent-buffer nil)
929 (make-variable-buffer-local 'notmuch-show-parent-buffer)
930 (defvar notmuch-show-query-context nil)
931 (make-variable-buffer-local 'notmuch-show-query-context)
932 (defvar notmuch-show-buffer-name nil)
933 (make-variable-buffer-local 'notmuch-show-buffer-name)
934
935 (defun notmuch-show-buttonise-links (start end)
936   "Buttonise URLs and mail addresses between START and END.
937
938 This also turns id:\"<message id>\"-parts into buttons for
939 a corresponding notmuch search."
940   (goto-address-fontify-region start end)
941   (save-excursion
942     (goto-char start)
943     (while (re-search-forward "id:\\(\"?\\)[^[:space:]\"]+\\1" end t)
944       ;; remove the overlay created by goto-address-mode
945       (remove-overlays (match-beginning 0) (match-end 0) 'goto-address t)
946       (make-text-button (match-beginning 0) (match-end 0)
947                         'action `(lambda (arg)
948                                    (notmuch-show ,(match-string-no-properties 0)))
949                         'follow-link t
950                         'help-echo "Mouse-1, RET: search for this message"
951                         'face goto-address-mail-face))))
952
953 ;;;###autoload
954 (defun notmuch-show (thread-id &optional parent-buffer query-context buffer-name crypto-switch)
955   "Run \"notmuch show\" with the given thread ID and display results.
956
957 The optional PARENT-BUFFER is the notmuch-search buffer from
958 which this notmuch-show command was executed, (so that the
959 next thread from that buffer can be show when done with this
960 one).
961
962 The optional QUERY-CONTEXT is a notmuch search term. Only
963 messages from the thread matching this search term are shown if
964 non-nil.
965
966 The optional BUFFER-NAME provides the name of the buffer in
967 which the message thread is shown. If it is nil (which occurs
968 when the command is called interactively) the argument to the
969 function is used.
970
971 The optional CRYPTO-SWITCH toggles the value of the
972 notmuch-crypto-process-mime customization variable for this show
973 buffer."
974   (interactive "sNotmuch show: ")
975   (let* ((process-crypto (if crypto-switch
976                              (not notmuch-crypto-process-mime)
977                            notmuch-crypto-process-mime)))
978     (notmuch-show-worker thread-id parent-buffer query-context buffer-name process-crypto)))
979
980 (defun notmuch-show-worker (thread-id parent-buffer query-context buffer-name process-crypto)
981   (let* ((buffer-name (generate-new-buffer-name
982                        (or buffer-name
983                            (concat "*notmuch-" thread-id "*"))))
984          (buffer (get-buffer-create buffer-name))
985          (inhibit-read-only t))
986     (switch-to-buffer buffer)
987     (notmuch-show-mode)
988     ;; Don't track undo information for this buffer
989     (set 'buffer-undo-list t)
990
991     (setq notmuch-show-thread-id thread-id)
992     (setq notmuch-show-parent-buffer parent-buffer)
993     (setq notmuch-show-query-context query-context)
994     (setq notmuch-show-buffer-name buffer-name)
995     (setq notmuch-show-process-crypto process-crypto)
996
997     (erase-buffer)
998     (goto-char (point-min))
999     (save-excursion
1000       (let* ((basic-args (list thread-id))
1001              (args (if query-context
1002                        (append (list "\'") basic-args (list "and (" query-context ")\'"))
1003                      (append (list "\'") basic-args (list "\'")))))
1004         (notmuch-show-insert-forest (notmuch-query-get-threads args))
1005         ;; If the query context reduced the results to nothing, run
1006         ;; the basic query.
1007         (when (and (eq (buffer-size) 0)
1008                    query-context)
1009           (notmuch-show-insert-forest
1010            (notmuch-query-get-threads basic-args))))
1011
1012       (jit-lock-register #'notmuch-show-buttonise-links)
1013
1014       (run-hooks 'notmuch-show-hook))
1015
1016     ;; Move straight to the first open message
1017     (unless (notmuch-show-message-visible-p)
1018       (notmuch-show-next-open-message))
1019
1020     ;; Set the header line to the subject of the first open message.
1021     (setq header-line-format (notmuch-show-strip-re (notmuch-show-get-pretty-subject)))
1022
1023     (notmuch-show-mark-read)))
1024
1025 (defun notmuch-show-refresh-view (&optional crypto-switch)
1026   "Refresh the current view (with crypto switch if prefix given).
1027
1028 Kills the current buffer and reruns notmuch show with the same
1029 thread id.  If a prefix is given, crypto processing is toggled."
1030   (interactive "P")
1031   (let ((thread-id notmuch-show-thread-id)
1032         (parent-buffer notmuch-show-parent-buffer)
1033         (query-context notmuch-show-query-context)
1034         (buffer-name notmuch-show-buffer-name)
1035         (process-crypto (if crypto-switch
1036                             (not notmuch-show-process-crypto)
1037                           notmuch-show-process-crypto)))
1038     (notmuch-kill-this-buffer)
1039     (notmuch-show-worker thread-id parent-buffer query-context buffer-name process-crypto)))
1040
1041 (defvar notmuch-show-stash-map
1042   (let ((map (make-sparse-keymap)))
1043     (define-key map "c" 'notmuch-show-stash-cc)
1044     (define-key map "d" 'notmuch-show-stash-date)
1045     (define-key map "F" 'notmuch-show-stash-filename)
1046     (define-key map "f" 'notmuch-show-stash-from)
1047     (define-key map "i" 'notmuch-show-stash-message-id)
1048     (define-key map "I" 'notmuch-show-stash-message-id-stripped)
1049     (define-key map "s" 'notmuch-show-stash-subject)
1050     (define-key map "T" 'notmuch-show-stash-tags)
1051     (define-key map "t" 'notmuch-show-stash-to)
1052     map)
1053   "Submap for stash commands")
1054 (fset 'notmuch-show-stash-map notmuch-show-stash-map)
1055
1056 (defvar notmuch-show-mode-map
1057       (let ((map (make-sparse-keymap)))
1058         (define-key map "?" 'notmuch-help)
1059         (define-key map "q" 'notmuch-kill-this-buffer)
1060         (define-key map (kbd "<C-tab>") 'widget-backward)
1061         (define-key map (kbd "M-TAB") 'notmuch-show-previous-button)
1062         (define-key map (kbd "<backtab>") 'notmuch-show-previous-button)
1063         (define-key map (kbd "TAB") 'notmuch-show-next-button)
1064         (define-key map "s" 'notmuch-search)
1065         (define-key map "m" 'notmuch-mua-new-mail)
1066         (define-key map "f" 'notmuch-show-forward-message)
1067         (define-key map "r" 'notmuch-show-reply-sender)
1068         (define-key map "R" 'notmuch-show-reply)
1069         (define-key map "|" 'notmuch-show-pipe-message)
1070         (define-key map "w" 'notmuch-show-save-attachments)
1071         (define-key map "V" 'notmuch-show-view-raw-message)
1072         (define-key map "v" 'notmuch-show-view-all-mime-parts)
1073         (define-key map "c" 'notmuch-show-stash-map)
1074         (define-key map "=" 'notmuch-show-refresh-view)
1075         (define-key map "h" 'notmuch-show-toggle-headers)
1076         (define-key map "-" 'notmuch-show-remove-tag)
1077         (define-key map "+" 'notmuch-show-add-tag)
1078         (define-key map "x" 'notmuch-show-archive-thread-then-exit)
1079         (define-key map "a" 'notmuch-show-archive-message-then-next)
1080         (define-key map "A" 'notmuch-show-archive-thread-then-next)
1081         (define-key map "N" 'notmuch-show-next-message)
1082         (define-key map "P" 'notmuch-show-previous-message)
1083         (define-key map "n" 'notmuch-show-next-open-message)
1084         (define-key map "p" 'notmuch-show-previous-open-message)
1085         (define-key map (kbd "DEL") 'notmuch-show-rewind)
1086         (define-key map " " 'notmuch-show-advance-and-archive)
1087         (define-key map (kbd "M-RET") 'notmuch-show-open-or-close-all)
1088         (define-key map (kbd "RET") 'notmuch-show-toggle-message)
1089         (define-key map "#" 'notmuch-show-print-message)
1090         map)
1091       "Keymap for \"notmuch show\" buffers.")
1092 (fset 'notmuch-show-mode-map notmuch-show-mode-map)
1093
1094 (defun notmuch-show-mode ()
1095   "Major mode for viewing a thread with notmuch.
1096
1097 This buffer contains the results of the \"notmuch show\" command
1098 for displaying a single thread of email from your email archives.
1099
1100 By default, various components of email messages, (citations,
1101 signatures, already-read messages), are hidden. You can make
1102 these parts visible by clicking with the mouse button or by
1103 pressing RET after positioning the cursor on a hidden part, (for
1104 which \\[notmuch-show-next-button] and \\[notmuch-show-previous-button] are helpful).
1105
1106 Reading the thread sequentially is well-supported by pressing
1107 \\[notmuch-show-advance-and-archive]. This will scroll the current message (if necessary), advance
1108 to the next message, or advance to the next thread (if already on
1109 the last message of a thread).
1110
1111 Other commands are available to read or manipulate the thread
1112 more selectively, (such as '\\[notmuch-show-next-message]' and '\\[notmuch-show-previous-message]' to advance to messages
1113 without removing any tags, and '\\[notmuch-show-archive-thread]' to archive an entire thread
1114 without scrolling through with \\[notmuch-show-advance-and-archive]).
1115
1116 You can add or remove arbitrary tags from the current message with
1117 '\\[notmuch-show-add-tag]' or '\\[notmuch-show-remove-tag]'.
1118
1119 All currently available key bindings:
1120
1121 \\{notmuch-show-mode-map}"
1122   (interactive)
1123   (kill-all-local-variables)
1124   (use-local-map notmuch-show-mode-map)
1125   (setq major-mode 'notmuch-show-mode
1126         mode-name "notmuch-show")
1127   (setq buffer-read-only t
1128         truncate-lines t))
1129
1130 (defun notmuch-show-move-to-message-top ()
1131   (goto-char (notmuch-show-message-top)))
1132
1133 (defun notmuch-show-move-to-message-bottom ()
1134   (goto-char (notmuch-show-message-bottom)))
1135
1136 (defun notmuch-show-message-adjust ()
1137   (recenter 0))
1138
1139 ;; Movement related functions.
1140
1141 ;; There's some strangeness here where a text property applied to a
1142 ;; region a->b is not found when point is at b. We walk backwards
1143 ;; until finding the property.
1144 (defun notmuch-show-message-extent ()
1145   (let (r)
1146     (save-excursion
1147       (while (not (setq r (get-text-property (point) :notmuch-message-extent)))
1148         (backward-char)))
1149     r))
1150
1151 (defun notmuch-show-message-top ()
1152   (car (notmuch-show-message-extent)))
1153
1154 (defun notmuch-show-message-bottom ()
1155   (cdr (notmuch-show-message-extent)))
1156
1157 (defun notmuch-show-goto-message-next ()
1158   (let ((start (point)))
1159     (notmuch-show-move-to-message-bottom)
1160     (if (not (eobp))
1161         t
1162       (goto-char start)
1163       nil)))
1164
1165 (defun notmuch-show-goto-message-previous ()
1166   (notmuch-show-move-to-message-top)
1167   (if (bobp)
1168       nil
1169     (backward-char)
1170     (notmuch-show-move-to-message-top)
1171     t))
1172
1173 ;; Functions relating to the visibility of messages and their
1174 ;; components.
1175
1176 (defun notmuch-show-element-visible (props visible-p spec-property)
1177   (let ((spec (plist-get props spec-property)))
1178     (if visible-p
1179         (remove-from-invisibility-spec spec)
1180       (add-to-invisibility-spec spec))))
1181
1182 (defun notmuch-show-message-visible (props visible-p)
1183   (notmuch-show-element-visible props visible-p :message-invis-spec)
1184   (notmuch-show-set-prop :message-visible visible-p props))
1185
1186 (defun notmuch-show-headers-visible (props visible-p)
1187   (notmuch-show-element-visible props visible-p :headers-invis-spec)
1188   (notmuch-show-set-prop :headers-visible visible-p props))
1189
1190 ;; Functions for setting and getting attributes of the current
1191 ;; message.
1192
1193 (defun notmuch-show-set-message-properties (props)
1194   (save-excursion
1195     (notmuch-show-move-to-message-top)
1196     (put-text-property (point) (+ (point) 1) :notmuch-message-properties props)))
1197
1198 (defun notmuch-show-get-message-properties ()
1199   "Return the properties of the current message as a plist.
1200
1201 Some useful entries are:
1202 :headers - Property list containing the headers :Date, :Subject, :From, etc.
1203 :body - Body of the message
1204 :tags - Tags for this message"
1205   (save-excursion
1206     (notmuch-show-move-to-message-top)
1207     (get-text-property (point) :notmuch-message-properties)))
1208
1209 (defun notmuch-show-set-prop (prop val &optional props)
1210   (let ((inhibit-read-only t)
1211         (props (or props
1212                    (notmuch-show-get-message-properties))))
1213     (plist-put props prop val)
1214     (notmuch-show-set-message-properties props)))
1215
1216 (defun notmuch-show-get-prop (prop &optional props)
1217   (let ((props (or props
1218                    (notmuch-show-get-message-properties))))
1219     (plist-get props prop)))
1220
1221 (defun notmuch-show-get-message-id ()
1222   "Return the message id of the current message."
1223   (concat "id:\"" (notmuch-show-get-prop :id) "\""))
1224
1225 ;; dme: Would it make sense to use a macro for many of these?
1226
1227 (defun notmuch-show-get-filename ()
1228   "Return the filename of the current message."
1229   (notmuch-show-get-prop :filename))
1230
1231 (defun notmuch-show-get-header (header &optional props)
1232   "Return the named header of the current message, if any."
1233   (plist-get (notmuch-show-get-prop :headers props) header))
1234
1235 (defun notmuch-show-get-cc ()
1236   (notmuch-show-get-header :Cc))
1237
1238 (defun notmuch-show-get-date ()
1239   (notmuch-show-get-header :Date))
1240
1241 (defun notmuch-show-get-from ()
1242   (notmuch-show-get-header :From))
1243
1244 (defun notmuch-show-get-subject ()
1245   (notmuch-show-get-header :Subject))
1246
1247 (defun notmuch-show-get-to ()
1248   (notmuch-show-get-header :To))
1249
1250 (defun notmuch-show-get-depth ()
1251   (notmuch-show-get-prop :depth))
1252
1253 (defun notmuch-show-get-pretty-subject ()
1254   (notmuch-prettify-subject (notmuch-show-get-subject)))
1255
1256 (defun notmuch-show-set-tags (tags)
1257   "Set the tags of the current message."
1258   (notmuch-show-set-prop :tags tags)
1259   (notmuch-show-update-tags tags))
1260
1261 (defun notmuch-show-get-tags ()
1262   "Return the tags of the current message."
1263   (notmuch-show-get-prop :tags))
1264
1265 (defun notmuch-show-message-visible-p ()
1266   "Is the current message visible?"
1267   (notmuch-show-get-prop :message-visible))
1268
1269 (defun notmuch-show-headers-visible-p ()
1270   "Are the headers of the current message visible?"
1271   (notmuch-show-get-prop :headers-visible))
1272
1273 (defun notmuch-show-mark-read ()
1274   "Mark the current message as read."
1275   (notmuch-show-remove-tag "unread"))
1276
1277 ;; Functions for getting attributes of several messages in the current
1278 ;; thread.
1279
1280 (defun notmuch-show-get-message-ids-for-open-messages ()
1281   "Return a list of all message IDs for open messages in the current thread."
1282   (save-excursion
1283     (let (message-ids done)
1284       (goto-char (point-min))
1285       (while (not done)
1286         (if (notmuch-show-message-visible-p)
1287             (setq message-ids (append message-ids (list (notmuch-show-get-message-id)))))
1288         (setq done (not (notmuch-show-goto-message-next)))
1289         )
1290       message-ids
1291       )))
1292
1293 ;; Commands typically bound to keys.
1294
1295 (defun notmuch-show-advance ()
1296   "Advance through thread.
1297
1298 If the current message in the thread is not yet fully visible,
1299 scroll by a near screenful to read more of the message.
1300
1301 Otherwise, (the end of the current message is already within the
1302 current window), advance to the next open message."
1303   (interactive)
1304   (let* ((end-of-this-message (notmuch-show-message-bottom))
1305          (visible-end-of-this-message (1- end-of-this-message))
1306          (ret nil))
1307     (while (invisible-p visible-end-of-this-message)
1308       (setq visible-end-of-this-message
1309             (max (point-min)
1310                  (1- (previous-single-char-property-change
1311                       visible-end-of-this-message 'invisible)))))
1312     (cond
1313      ;; Ideally we would test `end-of-this-message' against the result
1314      ;; of `window-end', but that doesn't account for the fact that
1315      ;; the end of the message might be hidden.
1316      ((and visible-end-of-this-message
1317            (> visible-end-of-this-message (window-end)))
1318       ;; The bottom of this message is not visible - scroll.
1319       (scroll-up nil))
1320
1321      ((not (= end-of-this-message (point-max)))
1322       ;; This is not the last message - move to the next visible one.
1323       (notmuch-show-next-open-message))
1324
1325      (t
1326       ;; This is the last message - change the return value
1327       (setq ret t)))
1328     ret))
1329
1330 (defun notmuch-show-advance-and-archive ()
1331   "Advance through thread and archive.
1332
1333 This command is intended to be one of the simplest ways to
1334 process a thread of email. It works exactly like
1335 notmuch-show-advance, in that it scrolls through messages in a
1336 show buffer, except that when it gets to the end of the buffer it
1337 archives the entire current thread, (remove the \"inbox\" tag
1338 from each message), kills the buffer, and displays the next
1339 thread from the search from which this thread was originally
1340 shown."
1341   (interactive)
1342   (if (notmuch-show-advance)
1343       (notmuch-show-archive-thread-then-next)))
1344
1345 (defun notmuch-show-rewind ()
1346   "Backup through the thread, (reverse scrolling compared to \\[notmuch-show-advance-and-archive]).
1347
1348 Specifically, if the beginning of the previous email is fewer
1349 than `window-height' lines from the current point, move to it
1350 just like `notmuch-show-previous-message'.
1351
1352 Otherwise, just scroll down a screenful of the current message.
1353
1354 This command does not modify any message tags, (it does not undo
1355 any effects from previous calls to
1356 `notmuch-show-advance-and-archive'."
1357   (interactive)
1358   (let ((start-of-message (notmuch-show-message-top))
1359         (start-of-window (window-start)))
1360     (cond
1361       ;; Either this message is properly aligned with the start of the
1362       ;; window or the start of this message is not visible on the
1363       ;; screen - scroll.
1364      ((or (= start-of-message start-of-window)
1365           (< start-of-message start-of-window))
1366       (scroll-down)
1367       ;; If a small number of lines from the previous message are
1368       ;; visible, realign so that the top of the current message is at
1369       ;; the top of the screen.
1370       (when (<= (count-screen-lines (window-start) start-of-message)
1371                 next-screen-context-lines)
1372         (goto-char (notmuch-show-message-top))
1373         (notmuch-show-message-adjust))
1374       ;; Move to the top left of the window.
1375       (goto-char (window-start)))
1376      (t
1377       ;; Move to the previous message.
1378       (notmuch-show-previous-message)))))
1379
1380 (defun notmuch-show-reply (&optional prompt-for-sender)
1381   "Reply to the sender and all recipients of the current message."
1382   (interactive "P")
1383   (notmuch-mua-new-reply (notmuch-show-get-message-id) prompt-for-sender t))
1384
1385 (defun notmuch-show-reply-sender (&optional prompt-for-sender)
1386   "Reply to the sender of the current message."
1387   (interactive "P")
1388   (notmuch-mua-new-reply (notmuch-show-get-message-id) prompt-for-sender nil))
1389
1390 (defun notmuch-show-forward-message (&optional prompt-for-sender)
1391   "Forward the current message."
1392   (interactive "P")
1393   (with-current-notmuch-show-message
1394    (notmuch-mua-new-forward-message prompt-for-sender)))
1395
1396 (defun notmuch-show-next-message (&optional pop-at-end)
1397   "Show the next message.
1398
1399 If a prefix argument is given and this is the last message in the
1400 thread, navigate to the next thread in the parent search buffer."
1401   (interactive "P")
1402   (if (notmuch-show-goto-message-next)
1403       (progn
1404         (notmuch-show-mark-read)
1405         (notmuch-show-message-adjust))
1406     (if pop-at-end
1407         (notmuch-show-next-thread)
1408       (goto-char (point-max)))))
1409
1410 (defun notmuch-show-previous-message ()
1411   "Show the previous message."
1412   (interactive)
1413   (notmuch-show-goto-message-previous)
1414   (notmuch-show-mark-read)
1415   (notmuch-show-message-adjust))
1416
1417 (defun notmuch-show-next-open-message (&optional pop-at-end)
1418   "Show the next open message.
1419
1420 If a prefix argument is given and this is the last open message
1421 in the thread, navigate to the next thread in the parent search
1422 buffer."
1423   (interactive "P")
1424   (let (r)
1425     (while (and (setq r (notmuch-show-goto-message-next))
1426                 (not (notmuch-show-message-visible-p))))
1427     (if r
1428         (progn
1429           (notmuch-show-mark-read)
1430           (notmuch-show-message-adjust))
1431       (if pop-at-end
1432           (notmuch-show-next-thread)
1433         (goto-char (point-max))))))
1434
1435 (defun notmuch-show-previous-open-message ()
1436   "Show the previous open message."
1437   (interactive)
1438   (while (and (notmuch-show-goto-message-previous)
1439               (not (notmuch-show-message-visible-p))))
1440   (notmuch-show-mark-read)
1441   (notmuch-show-message-adjust))
1442
1443 (defun notmuch-show-view-raw-message ()
1444   "View the file holding the current message."
1445   (interactive)
1446   (let* ((id (notmuch-show-get-message-id))
1447          (buf (get-buffer-create (concat "*notmuch-raw-" id "*"))))
1448     (call-process notmuch-command nil buf nil "show" "--format=raw" id)
1449     (switch-to-buffer buf)
1450     (goto-char (point-min))
1451     (set-buffer-modified-p nil)
1452     (view-buffer buf 'kill-buffer-if-not-modified)))
1453
1454 (defun notmuch-show-pipe-message (entire-thread command)
1455   "Pipe the contents of the current message (or thread) to the given command.
1456
1457 The given command will be executed with the raw contents of the
1458 current email message as stdin. Anything printed by the command
1459 to stdout or stderr will appear in the *notmuch-pipe* buffer.
1460
1461 When invoked with a prefix argument, the command will receive all
1462 open messages in the current thread (formatted as an mbox) rather
1463 than only the current message."
1464   (interactive "P\nsPipe message to command: ")
1465   (let (shell-command)
1466     (if entire-thread
1467         (setq shell-command
1468               (concat notmuch-command " show --format=mbox "
1469                       (shell-quote-argument
1470                        (mapconcat 'identity (notmuch-show-get-message-ids-for-open-messages) " OR "))
1471                       " | " command))
1472       (setq shell-command
1473             (concat notmuch-command " show --format=raw "
1474                     (shell-quote-argument (notmuch-show-get-message-id)) " | " command)))
1475     (let ((buf (get-buffer-create (concat "*notmuch-pipe*"))))
1476       (with-current-buffer buf
1477         (setq buffer-read-only nil)
1478         (erase-buffer)
1479         (let ((exit-code (call-process-shell-command shell-command nil buf)))
1480           (goto-char (point-max))
1481           (set-buffer-modified-p nil)
1482           (setq buffer-read-only t)
1483           (unless (zerop exit-code)
1484             (switch-to-buffer-other-window buf)
1485             (message (format "Command '%s' exited abnormally with code %d"
1486                              shell-command exit-code))))))))
1487
1488 (defun notmuch-show-add-tags-worker (current-tags add-tags)
1489   "Add to `current-tags' with any tags from `add-tags' not
1490 currently present and return the result."
1491   (let ((result-tags (copy-sequence current-tags)))
1492     (mapc (lambda (add-tag)
1493             (unless (member add-tag current-tags)
1494               (setq result-tags (push add-tag result-tags))))
1495             add-tags)
1496     (sort result-tags 'string<)))
1497
1498 (defun notmuch-show-del-tags-worker (current-tags del-tags)
1499   "Remove any tags in `del-tags' from `current-tags' and return
1500 the result."
1501   (let ((result-tags (copy-sequence current-tags)))
1502     (mapc (lambda (del-tag)
1503             (setq result-tags (delete del-tag result-tags)))
1504           del-tags)
1505     result-tags))
1506
1507 (defun notmuch-show-add-tag (&rest toadd)
1508   "Add a tag to the current message."
1509   (interactive
1510    (list (notmuch-select-tag-with-completion "Tag to add: ")))
1511
1512   (let* ((current-tags (notmuch-show-get-tags))
1513          (new-tags (notmuch-show-add-tags-worker current-tags toadd)))
1514
1515     (unless (equal current-tags new-tags)
1516       (apply 'notmuch-tag (notmuch-show-get-message-id)
1517              (mapcar (lambda (s) (concat "+" s)) toadd))
1518       (notmuch-show-set-tags new-tags))))
1519
1520 (defun notmuch-show-remove-tag (&rest toremove)
1521   "Remove a tag from the current message."
1522   (interactive
1523    (list (notmuch-select-tag-with-completion
1524           "Tag to remove: " (notmuch-show-get-message-id))))
1525
1526   (let* ((current-tags (notmuch-show-get-tags))
1527          (new-tags (notmuch-show-del-tags-worker current-tags toremove)))
1528
1529     (unless (equal current-tags new-tags)
1530       (apply 'notmuch-tag (notmuch-show-get-message-id)
1531              (mapcar (lambda (s) (concat "-" s)) toremove))
1532       (notmuch-show-set-tags new-tags))))
1533
1534 (defun notmuch-show-toggle-headers ()
1535   "Toggle the visibility of the current message headers."
1536   (interactive)
1537   (let ((props (notmuch-show-get-message-properties)))
1538     (notmuch-show-headers-visible
1539      props
1540      (not (plist-get props :headers-visible))))
1541   (force-window-update))
1542
1543 (defun notmuch-show-toggle-message ()
1544   "Toggle the visibility of the current message."
1545   (interactive)
1546   (let ((props (notmuch-show-get-message-properties)))
1547     (notmuch-show-message-visible
1548      props
1549      (not (plist-get props :message-visible))))
1550   (force-window-update))
1551
1552 (defun notmuch-show-open-or-close-all ()
1553   "Set the visibility all of the messages in the current thread.
1554 By default make all of the messages visible. With a prefix
1555 argument, hide all of the messages."
1556   (interactive)
1557   (save-excursion
1558     (goto-char (point-min))
1559     (loop do (notmuch-show-message-visible (notmuch-show-get-message-properties)
1560                                            (not current-prefix-arg))
1561           until (not (notmuch-show-goto-message-next))))
1562   (force-window-update))
1563
1564 (defun notmuch-show-next-button ()
1565   "Advance point to the next button in the buffer."
1566   (interactive)
1567   (forward-button 1))
1568
1569 (defun notmuch-show-previous-button ()
1570   "Move point back to the previous button in the buffer."
1571   (interactive)
1572   (backward-button 1))
1573
1574 (defun notmuch-show-tag-thread-internal (tag &optional remove)
1575   "Add tag to the current set of messages.
1576
1577 If the remove switch is given, tags will be removed instead of
1578 added."
1579   (goto-char (point-min))
1580   (let ((tag-function (if remove
1581                           'notmuch-show-remove-tag
1582                         'notmuch-show-add-tag)))
1583     (loop do (funcall tag-function tag)
1584           until (not (notmuch-show-goto-message-next)))))
1585
1586 (defun notmuch-show-add-tag-thread (tag)
1587   "Add tag to all messages in the current thread."
1588   (interactive)
1589   (notmuch-show-tag-thread-internal tag))
1590
1591 (defun notmuch-show-remove-tag-thread (tag)
1592   "Remove tag from all messages in the current thread."
1593   (interactive)
1594   (notmuch-show-tag-thread-internal tag t))
1595
1596 (defun notmuch-show-next-thread (&optional show-next)
1597   "Move to the next item in the search results, if any."
1598   (interactive "P")
1599   (let ((parent-buffer notmuch-show-parent-buffer))
1600     (notmuch-kill-this-buffer)
1601     (when parent-buffer
1602       (switch-to-buffer parent-buffer)
1603       (notmuch-search-next-thread)
1604       (if show-next
1605           (notmuch-search-show-thread)))))
1606
1607 (defun notmuch-show-archive-thread (&optional unarchive)
1608   "Archive each message in thread.
1609
1610 If a prefix argument is given, the messages will be
1611 \"unarchived\" (ie. the \"inbox\" tag will be added instead of
1612 removed).
1613
1614 Archive each message currently shown by removing the \"inbox\"
1615 tag from each. Then kill this buffer and show the next thread
1616 from the search from which this thread was originally shown.
1617
1618 Note: This command is safe from any race condition of new messages
1619 being delivered to the same thread. It does not archive the
1620 entire thread, but only the messages shown in the current
1621 buffer."
1622   (interactive "P")
1623   (if unarchive
1624       (notmuch-show-add-tag-thread "inbox")
1625     (notmuch-show-remove-tag-thread "inbox")))
1626
1627 (defun notmuch-show-archive-thread-then-next ()
1628   "Archive each message in thread, then show next thread from search."
1629   (interactive)
1630   (notmuch-show-archive-thread)
1631   (notmuch-show-next-thread t))
1632
1633 (defun notmuch-show-archive-thread-then-exit ()
1634   "Archive each message in thread, then exit back to search results."
1635   (interactive)
1636   (notmuch-show-archive-thread)
1637   (notmuch-show-next-thread))
1638
1639 (defun notmuch-show-archive-message (&optional unarchive)
1640   "Archive the current message.
1641
1642 If a prefix argument is given, the message will be
1643 \"unarchived\" (ie. the \"inbox\" tag will be added instead of
1644 removed)."
1645   (interactive "P")
1646   (if unarchive
1647       (notmuch-show-add-tag "inbox")
1648     (notmuch-show-remove-tag "inbox")))
1649
1650 (defun notmuch-show-archive-message-then-next ()
1651   "Archive the current message, then show the next open message in the current thread."
1652   (interactive)
1653   (notmuch-show-archive-message)
1654   (notmuch-show-next-open-message t))
1655
1656 (defun notmuch-show-stash-cc ()
1657   "Copy CC field of current message to kill-ring."
1658   (interactive)
1659   (notmuch-common-do-stash (notmuch-show-get-cc)))
1660
1661 (defun notmuch-show-stash-date ()
1662   "Copy date of current message to kill-ring."
1663   (interactive)
1664   (notmuch-common-do-stash (notmuch-show-get-date)))
1665
1666 (defun notmuch-show-stash-filename ()
1667   "Copy filename of current message to kill-ring."
1668   (interactive)
1669   (notmuch-common-do-stash (notmuch-show-get-filename)))
1670
1671 (defun notmuch-show-stash-from ()
1672   "Copy From address of current message to kill-ring."
1673   (interactive)
1674   (notmuch-common-do-stash (notmuch-show-get-from)))
1675
1676 (defun notmuch-show-stash-message-id ()
1677   "Copy message ID of current message to kill-ring."
1678   (interactive)
1679   (notmuch-common-do-stash (notmuch-show-get-message-id)))
1680
1681 (defun notmuch-show-stash-message-id-stripped ()
1682   "Copy message ID of current message (sans `id:' prefix) to kill-ring."
1683   (interactive)
1684   (notmuch-common-do-stash (substring (notmuch-show-get-message-id) 4 -1)))
1685
1686 (defun notmuch-show-stash-subject ()
1687   "Copy Subject field of current message to kill-ring."
1688   (interactive)
1689   (notmuch-common-do-stash (notmuch-show-get-subject)))
1690
1691 (defun notmuch-show-stash-tags ()
1692   "Copy tags of current message to kill-ring as a comma separated list."
1693   (interactive)
1694   (notmuch-common-do-stash (mapconcat 'identity (notmuch-show-get-tags) ",")))
1695
1696 (defun notmuch-show-stash-to ()
1697   "Copy To address of current message to kill-ring."
1698   (interactive)
1699   (notmuch-common-do-stash (notmuch-show-get-to)))
1700
1701 ;; Commands typically bound to buttons.
1702
1703 (defun notmuch-show-part-button-default (&optional button)
1704   (interactive)
1705   (notmuch-show-part-button-internal button notmuch-show-part-button-default-action))
1706
1707 (defun notmuch-show-part-button-save (&optional button)
1708   (interactive)
1709   (notmuch-show-part-button-internal button #'notmuch-show-save-part))
1710
1711 (defun notmuch-show-part-button-view (&optional button)
1712   (interactive)
1713   (notmuch-show-part-button-internal button #'notmuch-show-view-part))
1714
1715 (defun notmuch-show-part-button-interactively-view (&optional button)
1716   (interactive)
1717   (notmuch-show-part-button-internal button #'notmuch-show-interactively-view-part))
1718
1719 (defun notmuch-show-part-button-internal (button handler)
1720   (let ((button (or button (button-at (point)))))
1721     (if button
1722         (let ((nth (button-get button :notmuch-part)))
1723           (if nth
1724               (funcall handler (notmuch-show-get-message-id) nth
1725                        (button-get button :notmuch-filename)
1726                        (button-get button :notmuch-content-type)))))))
1727
1728 ;;
1729
1730 (provide 'notmuch-show)