]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-show.el
emacs: add "*" binding for notmuch-show view
[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 "a" 'notmuch-show-archive-message-then-next)
1092         (define-key map "A" 'notmuch-show-archive-thread-then-next)
1093         (define-key map "N" 'notmuch-show-next-message)
1094         (define-key map "P" 'notmuch-show-previous-message)
1095         (define-key map "n" 'notmuch-show-next-open-message)
1096         (define-key map "p" 'notmuch-show-previous-open-message)
1097         (define-key map (kbd "DEL") 'notmuch-show-rewind)
1098         (define-key map " " 'notmuch-show-advance-and-archive)
1099         (define-key map (kbd "M-RET") 'notmuch-show-open-or-close-all)
1100         (define-key map (kbd "RET") 'notmuch-show-toggle-message)
1101         (define-key map "#" 'notmuch-show-print-message)
1102         map)
1103       "Keymap for \"notmuch show\" buffers.")
1104 (fset 'notmuch-show-mode-map notmuch-show-mode-map)
1105
1106 (defun notmuch-show-mode ()
1107   "Major mode for viewing a thread with notmuch.
1108
1109 This buffer contains the results of the \"notmuch show\" command
1110 for displaying a single thread of email from your email archives.
1111
1112 By default, various components of email messages, (citations,
1113 signatures, already-read messages), are hidden. You can make
1114 these parts visible by clicking with the mouse button or by
1115 pressing RET after positioning the cursor on a hidden part, (for
1116 which \\[notmuch-show-next-button] and \\[notmuch-show-previous-button] are helpful).
1117
1118 Reading the thread sequentially is well-supported by pressing
1119 \\[notmuch-show-advance-and-archive]. This will scroll the current message (if necessary), advance
1120 to the next message, or advance to the next thread (if already on
1121 the last message of a thread).
1122
1123 Other commands are available to read or manipulate the thread
1124 more selectively, (such as '\\[notmuch-show-next-message]' and '\\[notmuch-show-previous-message]' to advance to messages
1125 without removing any tags, and '\\[notmuch-show-archive-thread]' to archive an entire thread
1126 without scrolling through with \\[notmuch-show-advance-and-archive]).
1127
1128 You can add or remove arbitrary tags from the current message with
1129 '\\[notmuch-show-add-tag]' or '\\[notmuch-show-remove-tag]'.
1130
1131 All currently available key bindings:
1132
1133 \\{notmuch-show-mode-map}"
1134   (interactive)
1135   (kill-all-local-variables)
1136   (use-local-map notmuch-show-mode-map)
1137   (setq major-mode 'notmuch-show-mode
1138         mode-name "notmuch-show")
1139   (setq buffer-read-only t
1140         truncate-lines t))
1141
1142 (defun notmuch-show-move-to-message-top ()
1143   (goto-char (notmuch-show-message-top)))
1144
1145 (defun notmuch-show-move-to-message-bottom ()
1146   (goto-char (notmuch-show-message-bottom)))
1147
1148 (defun notmuch-show-message-adjust ()
1149   (recenter 0))
1150
1151 ;; Movement related functions.
1152
1153 ;; There's some strangeness here where a text property applied to a
1154 ;; region a->b is not found when point is at b. We walk backwards
1155 ;; until finding the property.
1156 (defun notmuch-show-message-extent ()
1157   (let (r)
1158     (save-excursion
1159       (while (not (setq r (get-text-property (point) :notmuch-message-extent)))
1160         (backward-char)))
1161     r))
1162
1163 (defun notmuch-show-message-top ()
1164   (car (notmuch-show-message-extent)))
1165
1166 (defun notmuch-show-message-bottom ()
1167   (cdr (notmuch-show-message-extent)))
1168
1169 (defun notmuch-show-goto-message-next ()
1170   (let ((start (point)))
1171     (notmuch-show-move-to-message-bottom)
1172     (if (not (eobp))
1173         t
1174       (goto-char start)
1175       nil)))
1176
1177 (defun notmuch-show-goto-message-previous ()
1178   (notmuch-show-move-to-message-top)
1179   (if (bobp)
1180       nil
1181     (backward-char)
1182     (notmuch-show-move-to-message-top)
1183     t))
1184
1185 (defun notmuch-show-mapc (function)
1186   "Iterate through all messages in the current thread with
1187 `notmuch-show-goto-message-next' and call FUNCTION for side
1188 effects."
1189   (save-excursion
1190     (goto-char (point-min))
1191     (loop do (funcall function)
1192           while (notmuch-show-goto-message-next))))
1193
1194 ;; Functions relating to the visibility of messages and their
1195 ;; components.
1196
1197 (defun notmuch-show-element-visible (props visible-p spec-property)
1198   (let ((spec (plist-get props spec-property)))
1199     (if visible-p
1200         (remove-from-invisibility-spec spec)
1201       (add-to-invisibility-spec spec))))
1202
1203 (defun notmuch-show-message-visible (props visible-p)
1204   (notmuch-show-element-visible props visible-p :message-invis-spec)
1205   (notmuch-show-set-prop :message-visible visible-p props))
1206
1207 (defun notmuch-show-headers-visible (props visible-p)
1208   (notmuch-show-element-visible props visible-p :headers-invis-spec)
1209   (notmuch-show-set-prop :headers-visible visible-p props))
1210
1211 ;; Functions for setting and getting attributes of the current
1212 ;; message.
1213
1214 (defun notmuch-show-set-message-properties (props)
1215   (save-excursion
1216     (notmuch-show-move-to-message-top)
1217     (put-text-property (point) (+ (point) 1) :notmuch-message-properties props)))
1218
1219 (defun notmuch-show-get-message-properties ()
1220   "Return the properties of the current message as a plist.
1221
1222 Some useful entries are:
1223 :headers - Property list containing the headers :Date, :Subject, :From, etc.
1224 :body - Body of the message
1225 :tags - Tags for this message"
1226   (save-excursion
1227     (notmuch-show-move-to-message-top)
1228     (get-text-property (point) :notmuch-message-properties)))
1229
1230 (defun notmuch-show-set-prop (prop val &optional props)
1231   (let ((inhibit-read-only t)
1232         (props (or props
1233                    (notmuch-show-get-message-properties))))
1234     (plist-put props prop val)
1235     (notmuch-show-set-message-properties props)))
1236
1237 (defun notmuch-show-get-prop (prop &optional props)
1238   (let ((props (or props
1239                    (notmuch-show-get-message-properties))))
1240     (plist-get props prop)))
1241
1242 (defun notmuch-show-get-message-id ()
1243   "Return the message id of the current message."
1244   (concat "id:\"" (notmuch-show-get-prop :id) "\""))
1245
1246 (defun notmuch-show-get-messages-ids ()
1247   "Return all message ids of messages in the current thread."
1248   (let ((message-ids))
1249     (notmuch-show-mapc
1250      (lambda () (push (notmuch-show-get-message-id) message-ids)))
1251     message-ids))
1252
1253 (defun notmuch-show-get-messages-ids-search ()
1254   "Return a search string for all message ids of messages in the
1255 current thread."
1256   (mapconcat 'identity (notmuch-show-get-messages-ids) " or "))
1257
1258 ;; dme: Would it make sense to use a macro for many of these?
1259
1260 (defun notmuch-show-get-filename ()
1261   "Return the filename of the current message."
1262   (notmuch-show-get-prop :filename))
1263
1264 (defun notmuch-show-get-header (header &optional props)
1265   "Return the named header of the current message, if any."
1266   (plist-get (notmuch-show-get-prop :headers props) header))
1267
1268 (defun notmuch-show-get-cc ()
1269   (notmuch-show-get-header :Cc))
1270
1271 (defun notmuch-show-get-date ()
1272   (notmuch-show-get-header :Date))
1273
1274 (defun notmuch-show-get-from ()
1275   (notmuch-show-get-header :From))
1276
1277 (defun notmuch-show-get-subject ()
1278   (notmuch-show-get-header :Subject))
1279
1280 (defun notmuch-show-get-to ()
1281   (notmuch-show-get-header :To))
1282
1283 (defun notmuch-show-get-depth ()
1284   (notmuch-show-get-prop :depth))
1285
1286 (defun notmuch-show-get-pretty-subject ()
1287   (notmuch-prettify-subject (notmuch-show-get-subject)))
1288
1289 (defun notmuch-show-set-tags (tags)
1290   "Set the tags of the current message."
1291   (notmuch-show-set-prop :tags tags)
1292   (notmuch-show-update-tags tags))
1293
1294 (defun notmuch-show-get-tags ()
1295   "Return the tags of the current message."
1296   (notmuch-show-get-prop :tags))
1297
1298 (defun notmuch-show-message-visible-p ()
1299   "Is the current message visible?"
1300   (notmuch-show-get-prop :message-visible))
1301
1302 (defun notmuch-show-headers-visible-p ()
1303   "Are the headers of the current message visible?"
1304   (notmuch-show-get-prop :headers-visible))
1305
1306 (defun notmuch-show-mark-read ()
1307   "Mark the current message as read."
1308   (notmuch-show-tag-message "-unread"))
1309
1310 ;; Functions for getting attributes of several messages in the current
1311 ;; thread.
1312
1313 (defun notmuch-show-get-message-ids-for-open-messages ()
1314   "Return a list of all message IDs for open messages in the current thread."
1315   (save-excursion
1316     (let (message-ids done)
1317       (goto-char (point-min))
1318       (while (not done)
1319         (if (notmuch-show-message-visible-p)
1320             (setq message-ids (append message-ids (list (notmuch-show-get-message-id)))))
1321         (setq done (not (notmuch-show-goto-message-next)))
1322         )
1323       message-ids
1324       )))
1325
1326 ;; Commands typically bound to keys.
1327
1328 (defun notmuch-show-advance ()
1329   "Advance through thread.
1330
1331 If the current message in the thread is not yet fully visible,
1332 scroll by a near screenful to read more of the message.
1333
1334 Otherwise, (the end of the current message is already within the
1335 current window), advance to the next open message."
1336   (interactive)
1337   (let* ((end-of-this-message (notmuch-show-message-bottom))
1338          (visible-end-of-this-message (1- end-of-this-message))
1339          (ret nil))
1340     (while (invisible-p visible-end-of-this-message)
1341       (setq visible-end-of-this-message
1342             (max (point-min)
1343                  (1- (previous-single-char-property-change
1344                       visible-end-of-this-message 'invisible)))))
1345     (cond
1346      ;; Ideally we would test `end-of-this-message' against the result
1347      ;; of `window-end', but that doesn't account for the fact that
1348      ;; the end of the message might be hidden.
1349      ((and visible-end-of-this-message
1350            (> visible-end-of-this-message (window-end)))
1351       ;; The bottom of this message is not visible - scroll.
1352       (scroll-up nil))
1353
1354      ((not (= end-of-this-message (point-max)))
1355       ;; This is not the last message - move to the next visible one.
1356       (notmuch-show-next-open-message))
1357
1358      (t
1359       ;; This is the last message - change the return value
1360       (setq ret t)))
1361     ret))
1362
1363 (defun notmuch-show-advance-and-archive ()
1364   "Advance through thread and archive.
1365
1366 This command is intended to be one of the simplest ways to
1367 process a thread of email. It works exactly like
1368 notmuch-show-advance, in that it scrolls through messages in a
1369 show buffer, except that when it gets to the end of the buffer it
1370 archives the entire current thread, (remove the \"inbox\" tag
1371 from each message), kills the buffer, and displays the next
1372 thread from the search from which this thread was originally
1373 shown."
1374   (interactive)
1375   (if (notmuch-show-advance)
1376       (notmuch-show-archive-thread-then-next)))
1377
1378 (defun notmuch-show-rewind ()
1379   "Backup through the thread, (reverse scrolling compared to \\[notmuch-show-advance-and-archive]).
1380
1381 Specifically, if the beginning of the previous email is fewer
1382 than `window-height' lines from the current point, move to it
1383 just like `notmuch-show-previous-message'.
1384
1385 Otherwise, just scroll down a screenful of the current message.
1386
1387 This command does not modify any message tags, (it does not undo
1388 any effects from previous calls to
1389 `notmuch-show-advance-and-archive'."
1390   (interactive)
1391   (let ((start-of-message (notmuch-show-message-top))
1392         (start-of-window (window-start)))
1393     (cond
1394       ;; Either this message is properly aligned with the start of the
1395       ;; window or the start of this message is not visible on the
1396       ;; screen - scroll.
1397      ((or (= start-of-message start-of-window)
1398           (< start-of-message start-of-window))
1399       (scroll-down)
1400       ;; If a small number of lines from the previous message are
1401       ;; visible, realign so that the top of the current message is at
1402       ;; the top of the screen.
1403       (when (<= (count-screen-lines (window-start) start-of-message)
1404                 next-screen-context-lines)
1405         (goto-char (notmuch-show-message-top))
1406         (notmuch-show-message-adjust))
1407       ;; Move to the top left of the window.
1408       (goto-char (window-start)))
1409      (t
1410       ;; Move to the previous message.
1411       (notmuch-show-previous-message)))))
1412
1413 (defun notmuch-show-reply (&optional prompt-for-sender)
1414   "Reply to the sender and all recipients of the current message."
1415   (interactive "P")
1416   (notmuch-mua-new-reply (notmuch-show-get-message-id) prompt-for-sender t))
1417
1418 (defun notmuch-show-reply-sender (&optional prompt-for-sender)
1419   "Reply to the sender of the current message."
1420   (interactive "P")
1421   (notmuch-mua-new-reply (notmuch-show-get-message-id) prompt-for-sender nil))
1422
1423 (defun notmuch-show-forward-message (&optional prompt-for-sender)
1424   "Forward the current message."
1425   (interactive "P")
1426   (with-current-notmuch-show-message
1427    (notmuch-mua-new-forward-message prompt-for-sender)))
1428
1429 (defun notmuch-show-next-message (&optional pop-at-end)
1430   "Show the next message.
1431
1432 If a prefix argument is given and this is the last message in the
1433 thread, navigate to the next thread in the parent search buffer."
1434   (interactive "P")
1435   (if (notmuch-show-goto-message-next)
1436       (progn
1437         (notmuch-show-mark-read)
1438         (notmuch-show-message-adjust))
1439     (if pop-at-end
1440         (notmuch-show-next-thread)
1441       (goto-char (point-max)))))
1442
1443 (defun notmuch-show-previous-message ()
1444   "Show the previous message."
1445   (interactive)
1446   (notmuch-show-goto-message-previous)
1447   (notmuch-show-mark-read)
1448   (notmuch-show-message-adjust))
1449
1450 (defun notmuch-show-next-open-message (&optional pop-at-end)
1451   "Show the next open message.
1452
1453 If a prefix argument is given and this is the last open message
1454 in the thread, navigate to the next thread in the parent search
1455 buffer."
1456   (interactive "P")
1457   (let (r)
1458     (while (and (setq r (notmuch-show-goto-message-next))
1459                 (not (notmuch-show-message-visible-p))))
1460     (if r
1461         (progn
1462           (notmuch-show-mark-read)
1463           (notmuch-show-message-adjust))
1464       (if pop-at-end
1465           (notmuch-show-next-thread)
1466         (goto-char (point-max))))))
1467
1468 (defun notmuch-show-previous-open-message ()
1469   "Show the previous open message."
1470   (interactive)
1471   (while (and (notmuch-show-goto-message-previous)
1472               (not (notmuch-show-message-visible-p))))
1473   (notmuch-show-mark-read)
1474   (notmuch-show-message-adjust))
1475
1476 (defun notmuch-show-view-raw-message ()
1477   "View the file holding the current message."
1478   (interactive)
1479   (let* ((id (notmuch-show-get-message-id))
1480          (buf (get-buffer-create (concat "*notmuch-raw-" id "*"))))
1481     (call-process notmuch-command nil buf nil "show" "--format=raw" id)
1482     (switch-to-buffer buf)
1483     (goto-char (point-min))
1484     (set-buffer-modified-p nil)
1485     (view-buffer buf 'kill-buffer-if-not-modified)))
1486
1487 (defun notmuch-show-pipe-message (entire-thread command)
1488   "Pipe the contents of the current message (or thread) to the given command.
1489
1490 The given command will be executed with the raw contents of the
1491 current email message as stdin. Anything printed by the command
1492 to stdout or stderr will appear in the *notmuch-pipe* buffer.
1493
1494 When invoked with a prefix argument, the command will receive all
1495 open messages in the current thread (formatted as an mbox) rather
1496 than only the current message."
1497   (interactive "P\nsPipe message to command: ")
1498   (let (shell-command)
1499     (if entire-thread
1500         (setq shell-command
1501               (concat notmuch-command " show --format=mbox "
1502                       (shell-quote-argument
1503                        (mapconcat 'identity (notmuch-show-get-message-ids-for-open-messages) " OR "))
1504                       " | " command))
1505       (setq shell-command
1506             (concat notmuch-command " show --format=raw "
1507                     (shell-quote-argument (notmuch-show-get-message-id)) " | " command)))
1508     (let ((buf (get-buffer-create (concat "*notmuch-pipe*"))))
1509       (with-current-buffer buf
1510         (setq buffer-read-only nil)
1511         (erase-buffer)
1512         (let ((exit-code (call-process-shell-command shell-command nil buf)))
1513           (goto-char (point-max))
1514           (set-buffer-modified-p nil)
1515           (setq buffer-read-only t)
1516           (unless (zerop exit-code)
1517             (switch-to-buffer-other-window buf)
1518             (message (format "Command '%s' exited abnormally with code %d"
1519                              shell-command exit-code))))))))
1520
1521 (defun notmuch-show-tag-message (&rest tag-changes)
1522   "Change tags for the current message.
1523
1524 TAG-CHANGES is a list of tag operations for `notmuch-tag'."
1525   (let* ((current-tags (notmuch-show-get-tags))
1526          (new-tags (notmuch-update-tags current-tags tag-changes)))
1527     (unless (equal current-tags new-tags)
1528       (apply 'notmuch-tag (notmuch-show-get-message-id) tag-changes)
1529       (notmuch-show-set-tags new-tags))))
1530
1531 (defun notmuch-show-tag (&optional initial-input)
1532   "Change tags for the current message, read input from the minibuffer."
1533   (interactive)
1534   (let ((tag-changes (notmuch-read-tag-changes
1535                       initial-input (notmuch-show-get-message-id))))
1536     (apply 'notmuch-show-tag-message tag-changes)))
1537
1538 (defun notmuch-show-tag-all (&rest tag-changes)
1539   "Change tags for all messages in the current thread.
1540
1541 TAG-CHANGES is a list of tag operations for `notmuch-tag'."
1542   (interactive (notmuch-read-tag-changes nil notmuch-show-thread-id))
1543   (apply 'notmuch-tag (notmuch-show-get-messages-ids-search) tag-changes)
1544   (notmuch-show-mapc
1545    (lambda ()
1546      (let* ((current-tags (notmuch-show-get-tags))
1547             (new-tags (notmuch-update-tags current-tags tag-changes)))
1548        (unless (equal current-tags new-tags)
1549          (notmuch-show-set-tags new-tags))))))
1550
1551 (defun notmuch-show-add-tag ()
1552   "Same as `notmuch-show-tag' but sets initial input to '+'."
1553   (interactive)
1554   (notmuch-show-tag "+"))
1555
1556 (defun notmuch-show-remove-tag ()
1557   "Same as `notmuch-show-tag' but sets initial input to '-'."
1558   (interactive)
1559   (notmuch-show-tag "-"))
1560
1561 (defun notmuch-show-toggle-headers ()
1562   "Toggle the visibility of the current message headers."
1563   (interactive)
1564   (let ((props (notmuch-show-get-message-properties)))
1565     (notmuch-show-headers-visible
1566      props
1567      (not (plist-get props :headers-visible))))
1568   (force-window-update))
1569
1570 (defun notmuch-show-toggle-message ()
1571   "Toggle the visibility of the current message."
1572   (interactive)
1573   (let ((props (notmuch-show-get-message-properties)))
1574     (notmuch-show-message-visible
1575      props
1576      (not (plist-get props :message-visible))))
1577   (force-window-update))
1578
1579 (defun notmuch-show-open-or-close-all ()
1580   "Set the visibility all of the messages in the current thread.
1581 By default make all of the messages visible. With a prefix
1582 argument, hide all of the messages."
1583   (interactive)
1584   (save-excursion
1585     (goto-char (point-min))
1586     (loop do (notmuch-show-message-visible (notmuch-show-get-message-properties)
1587                                            (not current-prefix-arg))
1588           until (not (notmuch-show-goto-message-next))))
1589   (force-window-update))
1590
1591 (defun notmuch-show-next-button ()
1592   "Advance point to the next button in the buffer."
1593   (interactive)
1594   (forward-button 1))
1595
1596 (defun notmuch-show-previous-button ()
1597   "Move point back to the previous button in the buffer."
1598   (interactive)
1599   (backward-button 1))
1600
1601 (defun notmuch-show-tag-thread-internal (tag &optional remove)
1602   "Add tag to the current set of messages.
1603
1604 If the remove switch is given, tags will be removed instead of
1605 added."
1606   (goto-char (point-min))
1607   (let ((op (if remove "-" "+")))
1608     (loop do (notmuch-show-tag-message (concat op tag))
1609           until (not (notmuch-show-goto-message-next)))))
1610
1611 (defun notmuch-show-add-tag-thread (tag)
1612   "Add tag to all messages in the current thread."
1613   (interactive)
1614   (notmuch-show-tag-thread-internal tag))
1615
1616 (defun notmuch-show-remove-tag-thread (tag)
1617   "Remove tag from all messages in the current thread."
1618   (interactive)
1619   (notmuch-show-tag-thread-internal tag t))
1620
1621 (defun notmuch-show-next-thread (&optional show-next)
1622   "Move to the next item in the search results, if any."
1623   (interactive "P")
1624   (let ((parent-buffer notmuch-show-parent-buffer))
1625     (notmuch-kill-this-buffer)
1626     (when parent-buffer
1627       (switch-to-buffer parent-buffer)
1628       (notmuch-search-next-thread)
1629       (if show-next
1630           (notmuch-search-show-thread)))))
1631
1632 (defun notmuch-show-archive-thread (&optional unarchive)
1633   "Archive each message in thread.
1634
1635 If a prefix argument is given, the messages will be
1636 \"unarchived\" (ie. the \"inbox\" tag will be added instead of
1637 removed).
1638
1639 Archive each message currently shown by removing the \"inbox\"
1640 tag from each. Then kill this buffer and show the next thread
1641 from the search from which this thread was originally shown.
1642
1643 Note: This command is safe from any race condition of new messages
1644 being delivered to the same thread. It does not archive the
1645 entire thread, but only the messages shown in the current
1646 buffer."
1647   (interactive "P")
1648   (if unarchive
1649       (notmuch-show-add-tag-thread "inbox")
1650     (notmuch-show-remove-tag-thread "inbox")))
1651
1652 (defun notmuch-show-archive-thread-then-next ()
1653   "Archive each message in thread, then show next thread from search."
1654   (interactive)
1655   (notmuch-show-archive-thread)
1656   (notmuch-show-next-thread t))
1657
1658 (defun notmuch-show-archive-thread-then-exit ()
1659   "Archive each message in thread, then exit back to search results."
1660   (interactive)
1661   (notmuch-show-archive-thread)
1662   (notmuch-show-next-thread))
1663
1664 (defun notmuch-show-archive-message (&optional unarchive)
1665   "Archive the current message.
1666
1667 If a prefix argument is given, the message will be
1668 \"unarchived\" (ie. the \"inbox\" tag will be added instead of
1669 removed)."
1670   (interactive "P")
1671   (let ((op (if unarchive "+" "-")))
1672     (notmuch-show-tag-message (concat op "inbox"))))
1673
1674 (defun notmuch-show-archive-message-then-next ()
1675   "Archive the current message, then show the next open message in the current thread."
1676   (interactive)
1677   (notmuch-show-archive-message)
1678   (notmuch-show-next-open-message t))
1679
1680 (defun notmuch-show-stash-cc ()
1681   "Copy CC field of current message to kill-ring."
1682   (interactive)
1683   (notmuch-common-do-stash (notmuch-show-get-cc)))
1684
1685 (defun notmuch-show-stash-date ()
1686   "Copy date of current message to kill-ring."
1687   (interactive)
1688   (notmuch-common-do-stash (notmuch-show-get-date)))
1689
1690 (defun notmuch-show-stash-filename ()
1691   "Copy filename of current message to kill-ring."
1692   (interactive)
1693   (notmuch-common-do-stash (notmuch-show-get-filename)))
1694
1695 (defun notmuch-show-stash-from ()
1696   "Copy From address of current message to kill-ring."
1697   (interactive)
1698   (notmuch-common-do-stash (notmuch-show-get-from)))
1699
1700 (defun notmuch-show-stash-message-id ()
1701   "Copy message ID of current message to kill-ring."
1702   (interactive)
1703   (notmuch-common-do-stash (notmuch-show-get-message-id)))
1704
1705 (defun notmuch-show-stash-message-id-stripped ()
1706   "Copy message ID of current message (sans `id:' prefix) to kill-ring."
1707   (interactive)
1708   (notmuch-common-do-stash (substring (notmuch-show-get-message-id) 4 -1)))
1709
1710 (defun notmuch-show-stash-subject ()
1711   "Copy Subject field of current message to kill-ring."
1712   (interactive)
1713   (notmuch-common-do-stash (notmuch-show-get-subject)))
1714
1715 (defun notmuch-show-stash-tags ()
1716   "Copy tags of current message to kill-ring as a comma separated list."
1717   (interactive)
1718   (notmuch-common-do-stash (mapconcat 'identity (notmuch-show-get-tags) ",")))
1719
1720 (defun notmuch-show-stash-to ()
1721   "Copy To address of current message to kill-ring."
1722   (interactive)
1723   (notmuch-common-do-stash (notmuch-show-get-to)))
1724
1725 ;; Commands typically bound to buttons.
1726
1727 (defun notmuch-show-part-button-default (&optional button)
1728   (interactive)
1729   (notmuch-show-part-button-internal button notmuch-show-part-button-default-action))
1730
1731 (defun notmuch-show-part-button-save (&optional button)
1732   (interactive)
1733   (notmuch-show-part-button-internal button #'notmuch-show-save-part))
1734
1735 (defun notmuch-show-part-button-view (&optional button)
1736   (interactive)
1737   (notmuch-show-part-button-internal button #'notmuch-show-view-part))
1738
1739 (defun notmuch-show-part-button-interactively-view (&optional button)
1740   (interactive)
1741   (notmuch-show-part-button-internal button #'notmuch-show-interactively-view-part))
1742
1743 (defun notmuch-show-part-button-internal (button handler)
1744   (let ((button (or button (button-at (point)))))
1745     (if button
1746         (let ((nth (button-get button :notmuch-part)))
1747           (if nth
1748               (funcall handler (notmuch-show-get-message-id) nth
1749                        (button-get button :notmuch-filename)
1750                        (button-get button :notmuch-content-type)))))))
1751
1752 ;;
1753
1754 (provide 'notmuch-show)