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