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