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