]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-show.el
emacs: Remove v command
[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-tag)
34 (require 'notmuch-query)
35 (require 'notmuch-wash)
36 (require 'notmuch-mua)
37 (require 'notmuch-crypto)
38 (require 'notmuch-print)
39
40 (declare-function notmuch-call-notmuch-process "notmuch" (&rest args))
41 (declare-function notmuch-search-next-thread "notmuch" nil)
42 (declare-function notmuch-search-previous-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-visibility-headers'. For a closed message,
51 only 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-visibility-headers' can be used to make them
62 visible for 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 nil
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 (defcustom notmuch-show-only-matching-messages nil
129   "Only matching messages are shown by default."
130   :type 'boolean
131   :group 'notmuch-show)
132
133 (defvar notmuch-show-thread-id nil)
134 (make-variable-buffer-local 'notmuch-show-thread-id)
135 (put 'notmuch-show-thread-id 'permanent-local t)
136
137 (defvar notmuch-show-parent-buffer nil)
138 (make-variable-buffer-local 'notmuch-show-parent-buffer)
139 (put 'notmuch-show-parent-buffer 'permanent-local t)
140
141 (defvar notmuch-show-query-context nil)
142 (make-variable-buffer-local 'notmuch-show-query-context)
143 (put 'notmuch-show-query-context 'permanent-local t)
144
145 (defvar notmuch-show-process-crypto nil)
146 (make-variable-buffer-local 'notmuch-show-process-crypto)
147 (put 'notmuch-show-process-crypto 'permanent-local t)
148
149 (defvar notmuch-show-elide-non-matching-messages nil)
150 (make-variable-buffer-local 'notmuch-show-elide-non-matching-messages)
151 (put 'notmuch-show-elide-non-matching-messages 'permanent-local t)
152
153 (defvar notmuch-show-indent-content t)
154 (make-variable-buffer-local 'notmuch-show-indent-content)
155 (put 'notmuch-show-indent-content 'permanent-local t)
156
157 (defcustom notmuch-show-stash-mlarchive-link-alist
158   '(("Gmane" . "http://mid.gmane.org/")
159     ("MARC" . "http://marc.info/?i=")
160     ("Mail Archive, The" . "http://mail-archive.com/search?l=mid&q=")
161     ("LKML" . "http://lkml.kernel.org/r/")
162     ;; FIXME: can these services be searched by `Message-Id' ?
163     ;; ("MarkMail" . "http://markmail.org/")
164     ;; ("Nabble" . "http://nabble.com/")
165     ;; ("opensubscriber" . "http://opensubscriber.com/")
166     )
167   "List of Mailing List Archives to use when stashing links.
168
169 These URIs are concatenated with the current message's
170 Message-Id in `notmuch-show-stash-mlarchive-link'."
171   :type '(alist :key-type (string :tag "Name")
172                 :value-type (string :tag "URL"))
173   :group 'notmuch-show)
174
175 (defcustom notmuch-show-stash-mlarchive-link-default "Gmane"
176   "Default Mailing List Archive to use when stashing links.
177
178 This is used when `notmuch-show-stash-mlarchive-link' isn't
179 provided with an MLA argument nor `completing-read' input."
180   :type `(choice
181           ,@(mapcar
182              (lambda (mla)
183                (list 'const :tag (car mla) :value (car mla)))
184              notmuch-show-stash-mlarchive-link-alist))
185   :group 'notmuch-show)
186
187 (defcustom notmuch-show-mark-read-tags '("-unread")
188   "List of tag changes to apply to a message when it is marked as read.
189
190 Tags starting with \"+\" (or not starting with either \"+\" or
191 \"-\") in the list will be added, and tags starting with \"-\"
192 will be removed from the message being marked as read.
193
194 For example, if you wanted to remove an \"unread\" tag and add a
195 \"read\" tag (which would make little sense), you would set:
196     (\"-unread\" \"+read\")"
197   :type '(repeat string)
198   :group 'notmuch-show)
199
200
201 (defmacro with-current-notmuch-show-message (&rest body)
202   "Evaluate body with current buffer set to the text of current message"
203   `(save-excursion
204      (let ((id (notmuch-show-get-message-id)))
205        (let ((buf (generate-new-buffer (concat "*notmuch-msg-" id "*"))))
206          (with-current-buffer buf
207            (let ((coding-system-for-read 'no-conversion))
208              (call-process notmuch-command nil t nil "show" "--format=raw" id)
209              ,@body)
210            (kill-buffer buf))))))
211
212 (defun notmuch-show-turn-on-visual-line-mode ()
213   "Enable Visual Line mode."
214   (visual-line-mode t))
215
216 ;; DEPRECATED in Notmuch 0.16 since we now have convenient part
217 ;; commands.  We'll keep the command around for a version or two in
218 ;; case people want to bind it themselves.
219 (defun notmuch-show-view-all-mime-parts ()
220   "Use external viewers to view all attachments from the current message."
221   (interactive)
222   (with-current-notmuch-show-message
223    ;; We override the mm-inline-media-tests to indicate which message
224    ;; parts are already sufficiently handled by the original
225    ;; presentation of the message in notmuch-show mode. These parts
226    ;; will be inserted directly into the temporary buffer of
227    ;; with-current-notmuch-show-message and silently discarded.
228    ;;
229    ;; Any MIME part not explicitly mentioned here will be handled by an
230    ;; external viewer as configured in the various mailcap files.
231    (let ((mm-inline-media-tests '(
232                                   ("text/.*" ignore identity)
233                                   ("application/pgp-signature" ignore identity)
234                                   ("multipart/alternative" ignore identity)
235                                   ("multipart/mixed" ignore identity)
236                                   ("multipart/related" ignore identity)
237                                  )))
238      (mm-display-parts (mm-dissect-buffer)))))
239
240 (defun notmuch-foreach-mime-part (function mm-handle)
241   (cond ((stringp (car mm-handle))
242          (dolist (part (cdr mm-handle))
243            (notmuch-foreach-mime-part function part)))
244         ((bufferp (car mm-handle))
245          (funcall function mm-handle))
246         (t (dolist (part mm-handle)
247              (notmuch-foreach-mime-part function part)))))
248
249 (defun notmuch-count-attachments (mm-handle)
250   (let ((count 0))
251     (notmuch-foreach-mime-part
252      (lambda (p)
253        (let ((disposition (mm-handle-disposition p)))
254          (and (listp disposition)
255               (or (equal (car disposition) "attachment")
256                   (and (equal (car disposition) "inline")
257                        (assq 'filename disposition)))
258               (incf count))))
259      mm-handle)
260     count))
261
262 (defun notmuch-save-attachments (mm-handle &optional queryp)
263   (notmuch-foreach-mime-part
264    (lambda (p)
265      (let ((disposition (mm-handle-disposition p)))
266        (and (listp disposition)
267             (or (equal (car disposition) "attachment")
268                 (and (equal (car disposition) "inline")
269                      (assq 'filename disposition)))
270             (or (not queryp)
271                 (y-or-n-p
272                  (concat "Save '" (cdr (assq 'filename disposition)) "' ")))
273             (mm-save-part p))))
274    mm-handle))
275
276 (defun notmuch-show-save-attachments ()
277   "Save all attachments from the current message."
278   (interactive)
279   (with-current-notmuch-show-message
280    (let ((mm-handle (mm-dissect-buffer)))
281      (notmuch-save-attachments
282       mm-handle (> (notmuch-count-attachments mm-handle) 1))))
283   (message "Done"))
284
285 (defun notmuch-show-with-message-as-text (fn)
286   "Apply FN to a text representation of the current message.
287
288 FN is called with one argument, the message properties. It should
289 operation on the contents of the current buffer."
290
291   ;; Remake the header to ensure that all information is available.
292   (let* ((to (notmuch-show-get-to))
293          (cc (notmuch-show-get-cc))
294          (from (notmuch-show-get-from))
295          (subject (notmuch-show-get-subject))
296          (date (notmuch-show-get-date))
297          (tags (notmuch-show-get-tags))
298          (depth (notmuch-show-get-depth))
299
300          (header (concat
301                   "Subject: " subject "\n"
302                   "To: " to "\n"
303                   (if (not (string= cc ""))
304                       (concat "Cc: " cc "\n")
305                     "")
306                   "From: " from "\n"
307                   "Date: " date "\n"
308                   (if tags
309                       (concat "Tags: "
310                               (mapconcat #'identity tags ", ") "\n")
311                     "")))
312          (all (buffer-substring (notmuch-show-message-top)
313                                 (notmuch-show-message-bottom)))
314
315          (props (notmuch-show-get-message-properties))
316          (indenting notmuch-show-indent-content))
317     (with-temp-buffer
318       (insert all)
319       (if indenting
320           (indent-rigidly (point-min) (point-max) (- depth)))
321       ;; Remove the original header.
322       (goto-char (point-min))
323       (re-search-forward "^$" (point-max) nil)
324       (delete-region (point-min) (point))
325       (insert header)
326       (funcall fn props))))
327
328 (defun notmuch-show-print-message ()
329   "Print the current message."
330   (interactive)
331   (notmuch-show-with-message-as-text 'notmuch-print-message))
332
333 (defun notmuch-show-fontify-header ()
334   (let ((face (cond
335                ((looking-at "[Tt]o:")
336                 'message-header-to)
337                ((looking-at "[Bb]?[Cc][Cc]:")
338                 'message-header-cc)
339                ((looking-at "[Ss]ubject:")
340                 'message-header-subject)
341                ((looking-at "[Ff]rom:")
342                 'message-header-from)
343                (t
344                 'message-header-other))))
345
346     (overlay-put (make-overlay (point) (re-search-forward ":"))
347                  'face 'message-header-name)
348     (overlay-put (make-overlay (point) (re-search-forward ".*$"))
349                  'face face)))
350
351 (defun notmuch-show-colour-headers ()
352   "Apply some colouring to the current headers."
353   (goto-char (point-min))
354   (while (looking-at "^[A-Za-z][-A-Za-z0-9]*:")
355     (notmuch-show-fontify-header)
356     (forward-line)))
357
358 (defun notmuch-show-spaces-n (n)
359   "Return a string comprised of `n' spaces."
360   (make-string n ? ))
361
362 (defun notmuch-show-update-tags (tags)
363   "Update the displayed tags of the current message."
364   (save-excursion
365     (goto-char (notmuch-show-message-top))
366     (if (re-search-forward "(\\([^()]*\\))$" (line-end-position) t)
367         (let ((inhibit-read-only t))
368           (replace-match (concat "("
369                                  (notmuch-tag-format-tags tags)
370                                  ")"))))))
371
372 (defun notmuch-clean-address (address)
373   "Try to clean a single email ADDRESS for display. Return a cons
374 cell of (AUTHOR_EMAIL AUTHOR_NAME). Return (ADDRESS nil) if
375 parsing fails."
376   (condition-case nil
377     (let (p-name p-address)
378       ;; It would be convenient to use `mail-header-parse-address',
379       ;; but that expects un-decoded mailbox parts, whereas our
380       ;; mailbox parts are already decoded (and hence may contain
381       ;; UTF-8). Given that notmuch should handle most of the awkward
382       ;; cases, some simple string deconstruction should be sufficient
383       ;; here.
384       (cond
385        ;; "User <user@dom.ain>" style.
386        ((string-match "\\(.*\\) <\\(.*\\)>" address)
387         (setq p-name (match-string 1 address)
388               p-address (match-string 2 address)))
389
390        ;; "<user@dom.ain>" style.
391        ((string-match "<\\(.*\\)>" address)
392         (setq p-address (match-string 1 address)))
393
394        ;; Everything else.
395        (t
396         (setq p-address address)))
397
398       (when p-name
399         ;; Remove elements of the mailbox part that are not relevant for
400         ;; display, even if they are required during transport:
401         ;;
402         ;; Backslashes.
403         (setq p-name (replace-regexp-in-string "\\\\" "" p-name))
404
405         ;; Outer single and double quotes, which might be nested.
406         (loop
407          with start-of-loop
408          do (setq start-of-loop p-name)
409
410          when (string-match "^\"\\(.*\\)\"$" p-name)
411          do (setq p-name (match-string 1 p-name))
412
413          when (string-match "^'\\(.*\\)'$" p-name)
414          do (setq p-name (match-string 1 p-name))
415
416          until (string= start-of-loop p-name)))
417
418       ;; If the address is 'foo@bar.com <foo@bar.com>' then show just
419       ;; 'foo@bar.com'.
420       (when (string= p-name p-address)
421         (setq p-name nil))
422
423       (cons p-address p-name))
424     (error (cons address nil))))
425
426 (defun notmuch-show-clean-address (address)
427   "Try to clean a single email ADDRESS for display.  Return
428 unchanged ADDRESS if parsing fails."
429   (let* ((clean-address (notmuch-clean-address address))
430          (p-address (car clean-address))
431          (p-name (cdr clean-address)))
432     ;; If no name, return just the address.
433     (if (not p-name)
434         p-address
435       ;; Otherwise format the name and address together.
436       (concat p-name " <" p-address ">"))))
437
438 (defun notmuch-show-insert-headerline (headers date tags depth)
439   "Insert a notmuch style headerline based on HEADERS for a
440 message at DEPTH in the current thread."
441   (let ((start (point)))
442     (insert (notmuch-show-spaces-n (* notmuch-show-indent-messages-width depth))
443             (notmuch-show-clean-address (plist-get headers :From))
444             " ("
445             date
446             ") ("
447             (notmuch-tag-format-tags tags)
448             ")\n")
449     (overlay-put (make-overlay start (point)) 'face 'notmuch-message-summary-face)))
450
451 (defun notmuch-show-insert-header (header header-value)
452   "Insert a single header."
453   (insert header ": " header-value "\n"))
454
455 (defun notmuch-show-insert-headers (headers)
456   "Insert the headers of the current message."
457   (let ((start (point)))
458     (mapc (lambda (header)
459             (let* ((header-symbol (intern (concat ":" header)))
460                    (header-value (plist-get headers header-symbol)))
461               (if (and header-value
462                        (not (string-equal "" header-value)))
463                   (notmuch-show-insert-header header header-value))))
464           notmuch-message-headers)
465     (save-excursion
466       (save-restriction
467         (narrow-to-region start (point-max))
468         (run-hooks 'notmuch-show-markup-headers-hook)))))
469
470 (define-button-type 'notmuch-show-part-button-type
471   'action 'notmuch-show-part-button-default
472   'follow-link t
473   'face 'message-mml
474   :supertype 'notmuch-button-type)
475
476 (defun notmuch-show-insert-part-header (nth content-type declared-type &optional name comment)
477   (let ((button)
478         (base-label (concat (when name (concat name ": "))
479                             declared-type
480                             (unless (string-equal declared-type content-type)
481                               (concat " (as " content-type ")"))
482                             comment)))
483
484     (setq button
485           (insert-button
486            (concat "[ " base-label " ]")
487            :base-label base-label
488            :type 'notmuch-show-part-button-type
489            :notmuch-part-hidden nil))
490     (insert "\n")
491     ;; return button
492     button))
493
494 (defun notmuch-show-toggle-part-invisibility (&optional button)
495   (interactive)
496   (let* ((button (or button (button-at (point))))
497          (overlay (button-get button 'overlay))
498          (lazy-part (button-get button :notmuch-lazy-part)))
499     ;; We have a part to toggle if there is an overlay or if there is a lazy part.
500     ;; If neither is present we cannot toggle the part so we just return nil.
501     (when (or overlay lazy-part)
502       (let* ((show (button-get button :notmuch-part-hidden))
503              (new-start (button-start button))
504              (button-label (button-get button :base-label))
505              (old-point (point))
506              (properties (text-properties-at (point)))
507              (inhibit-read-only t))
508         ;; Toggle the button itself.
509         (button-put button :notmuch-part-hidden (not show))
510         (goto-char new-start)
511         (insert "[ " button-label (if show " ]" " (hidden) ]"))
512         (set-text-properties new-start (point) properties)
513         (let ((old-end (button-end button)))
514           (move-overlay button new-start (point))
515           (delete-region (point) old-end))
516         (goto-char (min old-point (1- (button-end button))))
517         ;; Return nil if there is a lazy-part, it is empty, and we are
518         ;; trying to show it.  In all other cases return t.
519         (if lazy-part
520             (when show
521               (button-put button :notmuch-lazy-part nil)
522               (notmuch-show-lazy-part lazy-part button))
523           ;; else there must be an overlay.
524           (overlay-put overlay 'invisible (not show))
525           t)))))
526
527 ;; MIME part renderers
528
529 (defun notmuch-show-multipart/*-to-list (part)
530   (mapcar (lambda (inner-part) (plist-get inner-part :content-type))
531           (plist-get part :content)))
532
533 (defun notmuch-show-insert-part-multipart/alternative (msg part content-type nth depth button)
534   (let ((chosen-type (car (notmuch-multipart/alternative-choose (notmuch-show-multipart/*-to-list part))))
535         (inner-parts (plist-get part :content))
536         (start (point)))
537     ;; This inserts all parts of the chosen type rather than just one,
538     ;; but it's not clear that this is the wrong thing to do - which
539     ;; should be chosen if there are more than one that match?
540     (mapc (lambda (inner-part)
541             (let* ((inner-type (plist-get inner-part :content-type))
542                   (hide (not (or notmuch-show-all-multipart/alternative-parts
543                            (string= chosen-type inner-type)))))
544               (notmuch-show-insert-bodypart msg inner-part depth hide)))
545           inner-parts)
546
547     (when notmuch-show-indent-multipart
548       (indent-rigidly start (point) 1)))
549   t)
550
551 (defun notmuch-show-setup-w3m ()
552   "Instruct w3m how to retrieve content from a \"related\" part of a message."
553   (interactive)
554   (if (boundp 'w3m-cid-retrieve-function-alist)
555     (unless (assq 'notmuch-show-mode w3m-cid-retrieve-function-alist)
556       (push (cons 'notmuch-show-mode 'notmuch-show-w3m-cid-retrieve)
557             w3m-cid-retrieve-function-alist)))
558   (setq mm-inline-text-html-with-images t))
559
560 (defvar w3m-current-buffer) ;; From `w3m.el'.
561 (defvar notmuch-show-w3m-cid-store nil)
562 (make-variable-buffer-local 'notmuch-show-w3m-cid-store)
563
564 (defun notmuch-show-w3m-cid-store-internal (content-id
565                                             message-id
566                                             part-number
567                                             content-type
568                                             content)
569   (push (list content-id
570               message-id
571               part-number
572               content-type
573               content)
574         notmuch-show-w3m-cid-store))
575
576 (defun notmuch-show-w3m-cid-store (msg part)
577   (let ((content-id (plist-get part :content-id)))
578     (when content-id
579       (notmuch-show-w3m-cid-store-internal (concat "cid:" content-id)
580                                            (plist-get msg :id)
581                                            (plist-get part :id)
582                                            (plist-get part :content-type)
583                                            nil))))
584
585 (defun notmuch-show-w3m-cid-retrieve (url &rest args)
586   (let ((matching-part (with-current-buffer w3m-current-buffer
587                          (assoc url notmuch-show-w3m-cid-store))))
588     (if matching-part
589         (let ((message-id (nth 1 matching-part))
590               (part-number (nth 2 matching-part))
591               (content-type (nth 3 matching-part))
592               (content (nth 4 matching-part)))
593           ;; If we don't already have the content, get it and cache
594           ;; it, as some messages reference the same cid: part many
595           ;; times (hundreds!), which results in many calls to
596           ;; `notmuch part'.
597           (unless content
598             (setq content (notmuch-get-bodypart-internal (notmuch-id-to-query message-id)
599                                                               part-number notmuch-show-process-crypto))
600             (with-current-buffer w3m-current-buffer
601               (notmuch-show-w3m-cid-store-internal url
602                                                    message-id
603                                                    part-number
604                                                    content-type
605                                                    content)))
606           (insert content)
607           content-type)
608       nil)))
609
610 (defun notmuch-show-insert-part-multipart/related (msg part content-type nth depth button)
611   (let ((inner-parts (plist-get part :content))
612         (start (point)))
613
614     ;; We assume that the first part is text/html and the remainder
615     ;; things that it references.
616
617     ;; Stash the non-primary parts.
618     (mapc (lambda (part)
619             (notmuch-show-w3m-cid-store msg part))
620           (cdr inner-parts))
621
622     ;; Render the primary part.
623     (notmuch-show-insert-bodypart msg (car inner-parts) depth)
624
625     (when notmuch-show-indent-multipart
626       (indent-rigidly start (point) 1)))
627   t)
628
629 (defun notmuch-show-insert-part-multipart/signed (msg part content-type nth depth button)
630   (button-put button 'face 'notmuch-crypto-part-header)
631   ;; add signature status button if sigstatus provided
632   (if (plist-member part :sigstatus)
633       (let* ((from (notmuch-show-get-header :From msg))
634              (sigstatus (car (plist-get part :sigstatus))))
635         (notmuch-crypto-insert-sigstatus-button sigstatus from))
636     ;; if we're not adding sigstatus, tell the user how they can get it
637     (button-put button 'help-echo "Set notmuch-crypto-process-mime to process cryptographic MIME parts."))
638
639   (let ((inner-parts (plist-get part :content))
640         (start (point)))
641     ;; Show all of the parts.
642     (mapc (lambda (inner-part)
643             (notmuch-show-insert-bodypart msg inner-part depth))
644           inner-parts)
645
646     (when notmuch-show-indent-multipart
647       (indent-rigidly start (point) 1)))
648   t)
649
650 (defun notmuch-show-insert-part-multipart/encrypted (msg part content-type nth depth button)
651   (button-put button 'face 'notmuch-crypto-part-header)
652   ;; add encryption status button if encstatus specified
653   (if (plist-member part :encstatus)
654       (let ((encstatus (car (plist-get part :encstatus))))
655         (notmuch-crypto-insert-encstatus-button encstatus)
656         ;; add signature status button if sigstatus specified
657         (if (plist-member part :sigstatus)
658             (let* ((from (notmuch-show-get-header :From msg))
659                    (sigstatus (car (plist-get part :sigstatus))))
660               (notmuch-crypto-insert-sigstatus-button sigstatus from))))
661     ;; if we're not adding encstatus, tell the user how they can get it
662     (button-put button 'help-echo "Set notmuch-crypto-process-mime to process cryptographic MIME parts."))
663
664   (let ((inner-parts (plist-get part :content))
665         (start (point)))
666     ;; Show all of the parts.
667     (mapc (lambda (inner-part)
668             (notmuch-show-insert-bodypart msg inner-part depth))
669           inner-parts)
670
671     (when notmuch-show-indent-multipart
672       (indent-rigidly start (point) 1)))
673   t)
674
675 (defun notmuch-show-insert-part-multipart/* (msg part content-type nth depth button)
676   (let ((inner-parts (plist-get part :content))
677         (start (point)))
678     ;; Show all of the parts.
679     (mapc (lambda (inner-part)
680             (notmuch-show-insert-bodypart msg inner-part depth))
681           inner-parts)
682
683     (when notmuch-show-indent-multipart
684       (indent-rigidly start (point) 1)))
685   t)
686
687 (defun notmuch-show-insert-part-message/rfc822 (msg part content-type nth depth button)
688   (let* ((message (car (plist-get part :content)))
689          (body (car (plist-get message :body)))
690          (start (point)))
691
692     ;; Override `notmuch-message-headers' to force `From' to be
693     ;; displayed.
694     (let ((notmuch-message-headers '("From" "Subject" "To" "Cc" "Date")))
695       (notmuch-show-insert-headers (plist-get message :headers)))
696
697     ;; Blank line after headers to be compatible with the normal
698     ;; message display.
699     (insert "\n")
700
701     ;; Show the body
702     (notmuch-show-insert-bodypart msg body depth)
703
704     (when notmuch-show-indent-multipart
705       (indent-rigidly start (point) 1)))
706   t)
707
708 (defun notmuch-show-insert-part-text/plain (msg part content-type nth depth button)
709   ;; For backward compatibility we want to apply the text/plain hook
710   ;; to the whole of the part including the part button if there is
711   ;; one.
712   (let ((start (if button
713                    (button-start button)
714                  (point))))
715     (insert (notmuch-get-bodypart-content msg part nth notmuch-show-process-crypto))
716     (save-excursion
717       (save-restriction
718         (narrow-to-region start (point-max))
719         (run-hook-with-args 'notmuch-show-insert-text/plain-hook msg depth))))
720   t)
721
722 (defun notmuch-show-insert-part-text/calendar (msg part content-type nth depth button)
723   (insert (with-temp-buffer
724             (insert (notmuch-get-bodypart-content msg part nth notmuch-show-process-crypto))
725             ;; notmuch-get-bodypart-content provides "raw", non-converted
726             ;; data. Replace CRLF with LF before icalendar can use it.
727             (goto-char (point-min))
728             (while (re-search-forward "\r\n" nil t)
729               (replace-match "\n" nil nil))
730             (let ((file (make-temp-file "notmuch-ical"))
731                   result)
732               (unwind-protect
733                   (progn
734                     (unless (icalendar-import-buffer file t)
735                       (error "Icalendar import error. See *icalendar-errors* for more information"))
736                     (set-buffer (get-file-buffer file))
737                     (setq result (buffer-substring (point-min) (point-max)))
738                     (set-buffer-modified-p nil)
739                     (kill-buffer (current-buffer)))
740                 (delete-file file))
741               result)))
742   t)
743
744 ;; For backwards compatibility.
745 (defun notmuch-show-insert-part-text/x-vcalendar (msg part content-type nth depth button)
746   (notmuch-show-insert-part-text/calendar msg part content-type nth depth button))
747
748 (defun notmuch-show-get-mime-type-of-application/octet-stream (part)
749   ;; If we can deduce a MIME type from the filename of the attachment,
750   ;; we return that.
751   (if (plist-get part :filename)
752       (let ((extension (file-name-extension (plist-get part :filename)))
753             mime-type)
754         (if extension
755             (progn
756               (mailcap-parse-mimetypes)
757               (setq mime-type (mailcap-extension-to-mime extension))
758               (if (and mime-type
759                        (not (string-equal mime-type "application/octet-stream")))
760                   mime-type
761                 nil))
762           nil))))
763
764 (defun notmuch-show-insert-part-text/html (msg part content-type nth depth button)
765   ;; text/html handler to work around bugs in renderers and our
766   ;; invisibile parts code. In particular w3m sets up a keymap which
767   ;; "leaks" outside the invisible region and causes strange effects
768   ;; in notmuch. We set mm-inline-text-html-with-w3m-keymap to nil to
769   ;; tell w3m not to set a keymap (so the normal notmuch-show-mode-map
770   ;; remains).
771   (let ((mm-inline-text-html-with-w3m-keymap nil))
772     (notmuch-show-insert-part-*/* msg part content-type nth depth button)))
773
774 (defun notmuch-show-insert-part-*/* (msg part content-type nth depth button)
775   ;; This handler _must_ succeed - it is the handler of last resort.
776   (notmuch-mm-display-part-inline msg part nth content-type notmuch-show-process-crypto)
777   t)
778
779 ;; Functions for determining how to handle MIME parts.
780
781 (defun notmuch-show-handlers-for (content-type)
782   "Return a list of content handlers for a part of type CONTENT-TYPE."
783   (let (result)
784     (mapc (lambda (func)
785             (if (functionp func)
786                 (push func result)))
787           ;; Reverse order of prefrence.
788           (list (intern (concat "notmuch-show-insert-part-*/*"))
789                 (intern (concat
790                          "notmuch-show-insert-part-"
791                          (car (notmuch-split-content-type content-type))
792                          "/*"))
793                 (intern (concat "notmuch-show-insert-part-" content-type))))
794     result))
795
796 ;; \f
797
798 (defun notmuch-show-insert-bodypart-internal (msg part content-type nth depth button)
799   (let ((handlers (notmuch-show-handlers-for content-type)))
800     ;; Run the content handlers until one of them returns a non-nil
801     ;; value.
802     (while (and handlers
803                 (not (condition-case err
804                          (funcall (car handlers) msg part content-type nth depth button)
805                        (error (progn
806                                 (insert "!!! Bodypart insert error: ")
807                                 (insert (error-message-string err))
808                                 (insert " !!!\n") nil)))))
809       (setq handlers (cdr handlers))))
810   t)
811
812 (defun notmuch-show-create-part-overlays (button beg end)
813   "Add an overlay to the part between BEG and END"
814
815   ;; If there is no button (i.e., the part is text/plain and the first
816   ;; part) or if the part has no content then we don't make the part
817   ;; toggleable.
818   (when (and button (/= beg end))
819     (button-put button 'overlay (make-overlay beg end))
820     ;; Return true if we created an overlay.
821     t))
822
823 (defun notmuch-show-record-part-information (part beg end)
824   "Store PART as a text property from BEG to END"
825
826   ;; Record part information.  Since we already inserted subparts,
827   ;; don't override existing :notmuch-part properties.
828   (notmuch-map-text-property beg end :notmuch-part
829                              (lambda (v) (or v part)))
830   ;; Make :notmuch-part front sticky and rear non-sticky so it stays
831   ;; applied to the beginning of each line when we indent the
832   ;; message.  Since we're operating on arbitrary renderer output,
833   ;; watch out for sticky specs of t, which means all properties are
834   ;; front-sticky/rear-nonsticky.
835   (notmuch-map-text-property beg end 'front-sticky
836                              (lambda (v) (if (listp v)
837                                              (pushnew :notmuch-part v)
838                                            v)))
839   (notmuch-map-text-property beg end 'rear-nonsticky
840                              (lambda (v) (if (listp v)
841                                              (pushnew :notmuch-part v)
842                                            v))))
843
844 (defun notmuch-show-lazy-part (part-args button)
845   ;; Insert the lazy part after the button for the part. We would just
846   ;; move to the start of the new line following the button and insert
847   ;; the part but that point might have text properties (eg colours
848   ;; from a message header etc) so instead we start from the last
849   ;; character of the button by adding a newline and finish by
850   ;; removing the extra newline from the end of the part.
851   (save-excursion
852     (goto-char (button-end button))
853     (insert "\n")
854     (let* ((inhibit-read-only t)
855            ;; We need to use markers for the start and end of the part
856            ;; because the part insertion functions do not guarantee
857            ;; to leave point at the end of the part.
858            (part-beg (copy-marker (point) nil))
859            (part-end (copy-marker (point) t))
860            ;; We have to save the depth as we can't find the depth
861            ;; when narrowed.
862            (depth (notmuch-show-get-depth)))
863       (save-restriction
864         (narrow-to-region part-beg part-end)
865         (delete-region part-beg part-end)
866         (apply #'notmuch-show-insert-bodypart-internal part-args)
867         (indent-rigidly part-beg part-end depth))
868       (goto-char part-end)
869       (delete-char 1)
870       (notmuch-show-record-part-information (second part-args)
871                                             (button-start button)
872                                             part-end)
873       ;; Create the overlay. If the lazy-part turned out to be empty/not
874       ;; showable this returns nil.
875       (notmuch-show-create-part-overlays button part-beg part-end))))
876
877 (defun notmuch-show-insert-bodypart (msg part depth &optional hide)
878   "Insert the body part PART at depth DEPTH in the current thread.
879
880 If HIDE is non-nil then initially hide this part."
881
882   (let* ((content-type (downcase (plist-get part :content-type)))
883          (mime-type (or (and (string= content-type "application/octet-stream")
884                              (notmuch-show-get-mime-type-of-application/octet-stream part))
885                         (and (string= content-type "inline patch")
886                              "text/x-diff")
887                         content-type))
888          (nth (plist-get part :id))
889          (beg (point))
890          ;; We omit the part button for the first (or only) part if this is text/plain.
891          (button (unless (and (string= mime-type "text/plain") (<= nth 1))
892                    (notmuch-show-insert-part-header nth mime-type content-type (plist-get part :filename))))
893          (content-beg (point)))
894
895     (if (not hide)
896         (notmuch-show-insert-bodypart-internal msg part mime-type nth depth button)
897       (button-put button :notmuch-lazy-part
898                   (list msg part mime-type nth depth button)))
899
900     ;; Some of the body part handlers leave point somewhere up in the
901     ;; part, so we make sure that we're down at the end.
902     (goto-char (point-max))
903     ;; Ensure that the part ends with a carriage return.
904     (unless (bolp)
905       (insert "\n"))
906     ;; We do not create the overlay for hidden (lazy) parts until
907     ;; they are inserted.
908     (if (not hide)
909         (notmuch-show-create-part-overlays button content-beg (point))
910       (save-excursion
911         (notmuch-show-toggle-part-invisibility button)))
912     (notmuch-show-record-part-information part beg (point))))
913
914 (defun notmuch-show-insert-body (msg body depth)
915   "Insert the body BODY at depth DEPTH in the current thread."
916   (mapc (lambda (part) (notmuch-show-insert-bodypart msg part depth)) body))
917
918 (defun notmuch-show-make-symbol (type)
919   (make-symbol (concat "notmuch-show-" type)))
920
921 (defun notmuch-show-strip-re (string)
922   (replace-regexp-in-string "^\\([Rr]e: *\\)+" "" string))
923
924 (defvar notmuch-show-previous-subject "")
925 (make-variable-buffer-local 'notmuch-show-previous-subject)
926
927 (defun notmuch-show-insert-msg (msg depth)
928   "Insert the message MSG at depth DEPTH in the current thread."
929   (let* ((headers (plist-get msg :headers))
930          ;; Indentation causes the buffer offset of the start/end
931          ;; points to move, so we must use markers.
932          message-start message-end
933          content-start content-end
934          headers-start headers-end
935          (bare-subject (notmuch-show-strip-re (plist-get headers :Subject))))
936
937     (setq message-start (point-marker))
938
939     (notmuch-show-insert-headerline headers
940                                     (or (if notmuch-show-relative-dates
941                                             (plist-get msg :date_relative)
942                                           nil)
943                                         (plist-get headers :Date))
944                                     (plist-get msg :tags) depth)
945
946     (setq content-start (point-marker))
947
948     ;; Set `headers-start' to point after the 'Subject:' header to be
949     ;; compatible with the existing implementation. This just sets it
950     ;; to after the first header.
951     (notmuch-show-insert-headers headers)
952     (save-excursion
953       (goto-char content-start)
954       ;; If the subject of this message is the same as that of the
955       ;; previous message, don't display it when this message is
956       ;; collapsed.
957       (when (not (string= notmuch-show-previous-subject
958                           bare-subject))
959         (forward-line 1))
960       (setq headers-start (point-marker)))
961     (setq headers-end (point-marker))
962
963     (setq notmuch-show-previous-subject bare-subject)
964
965     ;; A blank line between the headers and the body.
966     (insert "\n")
967     (notmuch-show-insert-body msg (plist-get msg :body)
968                               (if notmuch-show-indent-content depth 0))
969     ;; Ensure that the body ends with a newline.
970     (unless (bolp)
971       (insert "\n"))
972     (setq content-end (point-marker))
973
974     ;; Indent according to the depth in the thread.
975     (if notmuch-show-indent-content
976         (indent-rigidly content-start content-end (* notmuch-show-indent-messages-width depth)))
977
978     (setq message-end (point-max-marker))
979
980     ;; Save the extents of this message over the whole text of the
981     ;; message.
982     (put-text-property message-start message-end :notmuch-message-extent (cons message-start message-end))
983
984     ;; Create overlays used to control visibility
985     (plist-put msg :headers-overlay (make-overlay headers-start headers-end))
986     (plist-put msg :message-overlay (make-overlay headers-start content-end))
987
988     (plist-put msg :depth depth)
989
990     ;; Save the properties for this message. Currently this saves the
991     ;; entire message (augmented it with other stuff), which seems
992     ;; like overkill. We might save a reduced subset (for example, not
993     ;; the content).
994     (notmuch-show-set-message-properties msg)
995
996     ;; Set header visibility.
997     (notmuch-show-headers-visible msg notmuch-message-headers-visible)
998
999     ;; Message visibility depends on whether it matched the search
1000     ;; criteria.
1001     (notmuch-show-message-visible msg (and (plist-get msg :match)
1002                                            (not (plist-get msg :excluded))))))
1003
1004 (defun notmuch-show-toggle-process-crypto ()
1005   "Toggle the processing of cryptographic MIME parts."
1006   (interactive)
1007   (setq notmuch-show-process-crypto (not notmuch-show-process-crypto))
1008   (message (if notmuch-show-process-crypto
1009                "Processing cryptographic MIME parts."
1010              "Not processing cryptographic MIME parts."))
1011   (notmuch-show-refresh-view))
1012
1013 (defun notmuch-show-toggle-elide-non-matching ()
1014   "Toggle the display of non-matching messages."
1015   (interactive)
1016   (setq notmuch-show-elide-non-matching-messages (not notmuch-show-elide-non-matching-messages))
1017   (message (if notmuch-show-elide-non-matching-messages
1018                "Showing matching messages only."
1019              "Showing all messages."))
1020   (notmuch-show-refresh-view))
1021
1022 (defun notmuch-show-toggle-thread-indentation ()
1023   "Toggle the indentation of threads."
1024   (interactive)
1025   (setq notmuch-show-indent-content (not notmuch-show-indent-content))
1026   (message (if notmuch-show-indent-content
1027                "Content is indented."
1028              "Content is not indented."))
1029   (notmuch-show-refresh-view))
1030
1031 (defun notmuch-show-insert-tree (tree depth)
1032   "Insert the message tree TREE at depth DEPTH in the current thread."
1033   (let ((msg (car tree))
1034         (replies (cadr tree)))
1035     ;; We test whether there is a message or just some replies.
1036     (when msg
1037       (notmuch-show-insert-msg msg depth))
1038     (notmuch-show-insert-thread replies (1+ depth))))
1039
1040 (defun notmuch-show-insert-thread (thread depth)
1041   "Insert the thread THREAD at depth DEPTH in the current forest."
1042   (mapc (lambda (tree) (notmuch-show-insert-tree tree depth)) thread))
1043
1044 (defun notmuch-show-insert-forest (forest)
1045   "Insert the forest of threads FOREST."
1046   (mapc (lambda (thread) (notmuch-show-insert-thread thread 0)) forest))
1047
1048 (defvar notmuch-id-regexp
1049   (concat
1050    ;; Match the id: prefix only if it begins a word (to disallow, for
1051    ;; example, matching cid:).
1052    "\\<id:\\("
1053    ;; If the term starts with a ", then parse Xapian's quoted boolean
1054    ;; term syntax, which allows for anything as long as embedded
1055    ;; double quotes escaped by doubling them.  We also disallow
1056    ;; newlines (which Xapian allows) to prevent runaway terms.
1057    "\"\\([^\"\n]\\|\"\"\\)*\""
1058    ;; Otherwise, parse Xapian's unquoted syntax, which goes up to the
1059    ;; next space or ).  We disallow [.,;] as the last character
1060    ;; because these are probably part of the surrounding text, and not
1061    ;; part of the id.  This doesn't match single character ids; meh.
1062    "\\|[^\"[:space:])][^[:space:])]*[^])[:space:].,:;?!]"
1063    "\\)")
1064   "The regexp used to match id: links in messages.")
1065
1066 (defvar notmuch-mid-regexp
1067   ;; goto-address-url-regexp matched cid: links, which have the same
1068   ;; grammar as the message ID part of a mid: link.  Construct the
1069   ;; regexp using the same technique as goto-address-url-regexp.
1070   (concat "\\<mid:\\(" thing-at-point-url-path-regexp "\\)")
1071   "The regexp used to match mid: links in messages.
1072
1073 See RFC 2392.")
1074
1075 (defun notmuch-show-buttonise-links (start end)
1076   "Buttonise URLs and mail addresses between START and END.
1077
1078 This also turns id:\"<message id>\"-parts and mid: links into
1079 buttons for a corresponding notmuch search."
1080   (goto-address-fontify-region start end)
1081   (save-excursion
1082     (let (links)
1083       (goto-char start)
1084       (while (re-search-forward notmuch-id-regexp end t)
1085         (push (list (match-beginning 0) (match-end 0)
1086                     (match-string-no-properties 0)) links))
1087       (goto-char start)
1088       (while (re-search-forward notmuch-mid-regexp end t)
1089         (let* ((mid-cid (match-string-no-properties 1))
1090                (mid (save-match-data
1091                       (string-match "^[^/]*" mid-cid)
1092                       (url-unhex-string (match-string 0 mid-cid)))))
1093           (push (list (match-beginning 0) (match-end 0)
1094                       (notmuch-id-to-query mid)) links)))
1095       (dolist (link links)
1096         ;; Remove the overlay created by goto-address-mode
1097         (remove-overlays (first link) (second link) 'goto-address t)
1098         (make-text-button (first link) (second link)
1099                           :type 'notmuch-button-type
1100                           'action `(lambda (arg)
1101                                      (notmuch-show ,(third link)))
1102                           'follow-link t
1103                           'help-echo "Mouse-1, RET: search for this message"
1104                           'face goto-address-mail-face)))))
1105
1106 ;;;###autoload
1107 (defun notmuch-show (thread-id &optional parent-buffer query-context buffer-name)
1108   "Run \"notmuch show\" with the given thread ID and display results.
1109
1110 The optional PARENT-BUFFER is the notmuch-search buffer from
1111 which this notmuch-show command was executed, (so that the
1112 next thread from that buffer can be show when done with this
1113 one).
1114
1115 The optional QUERY-CONTEXT is a notmuch search term. Only
1116 messages from the thread matching this search term are shown if
1117 non-nil.
1118
1119 The optional BUFFER-NAME provides the name of the buffer in
1120 which the message thread is shown. If it is nil (which occurs
1121 when the command is called interactively) the argument to the
1122 function is used."
1123   (interactive "sNotmuch show: ")
1124   (let ((buffer-name (generate-new-buffer-name
1125                       (or buffer-name
1126                           (concat "*notmuch-" thread-id "*")))))
1127     (switch-to-buffer (get-buffer-create buffer-name))
1128     ;; Set the default value for `notmuch-show-process-crypto' in this
1129     ;; buffer.
1130     (setq notmuch-show-process-crypto notmuch-crypto-process-mime)
1131     ;; Set the default value for
1132     ;; `notmuch-show-elide-non-matching-messages' in this buffer. If
1133     ;; there is a prefix argument, invert the default.
1134     (setq notmuch-show-elide-non-matching-messages notmuch-show-only-matching-messages)
1135     (if current-prefix-arg
1136         (setq notmuch-show-elide-non-matching-messages (not notmuch-show-elide-non-matching-messages)))
1137
1138     (setq notmuch-show-thread-id thread-id
1139           notmuch-show-parent-buffer parent-buffer
1140           notmuch-show-query-context query-context)
1141     (notmuch-show-build-buffer)
1142     (notmuch-show-goto-first-wanted-message)
1143     (current-buffer)))
1144
1145 (defun notmuch-show-build-buffer ()
1146   (let ((inhibit-read-only t))
1147
1148     (notmuch-show-mode)
1149     ;; Don't track undo information for this buffer
1150     (set 'buffer-undo-list t)
1151
1152     (erase-buffer)
1153     (goto-char (point-min))
1154     (save-excursion
1155       (let* ((basic-args (list notmuch-show-thread-id))
1156              (args (if notmuch-show-query-context
1157                        (append (list "\'") basic-args
1158                                (list "and (" notmuch-show-query-context ")\'"))
1159                      (append (list "\'") basic-args (list "\'"))))
1160              (cli-args (cons "--exclude=false"
1161                              (when notmuch-show-elide-non-matching-messages
1162                                (list "--entire-thread=false")))))
1163
1164         (notmuch-show-insert-forest (notmuch-query-get-threads (append cli-args args)))
1165         ;; If the query context reduced the results to nothing, run
1166         ;; the basic query.
1167         (when (and (eq (buffer-size) 0)
1168                    notmuch-show-query-context)
1169           (notmuch-show-insert-forest
1170            (notmuch-query-get-threads (append cli-args basic-args)))))
1171
1172       (jit-lock-register #'notmuch-show-buttonise-links)
1173
1174       ;; Set the header line to the subject of the first message.
1175       (setq header-line-format (notmuch-show-strip-re (notmuch-show-get-subject)))
1176
1177       (run-hooks 'notmuch-show-hook))))
1178
1179 (defun notmuch-show-capture-state ()
1180   "Capture the state of the current buffer.
1181
1182 This includes:
1183  - the list of open messages,
1184  - the current message."
1185   (list (notmuch-show-get-message-id) (notmuch-show-get-message-ids-for-open-messages)))
1186
1187 (defun notmuch-show-apply-state (state)
1188   "Apply STATE to the current buffer.
1189
1190 This includes:
1191  - opening the messages previously opened,
1192  - closing all other messages,
1193  - moving to the correct current message."
1194   (let ((current (car state))
1195         (open (cadr state)))
1196
1197     ;; Open those that were open.
1198     (goto-char (point-min))
1199     (loop do (notmuch-show-message-visible (notmuch-show-get-message-properties)
1200                                            (member (notmuch-show-get-message-id) open))
1201           until (not (notmuch-show-goto-message-next)))
1202
1203     ;; Go to the previously open message.
1204     (goto-char (point-min))
1205     (unless (loop if (string= current (notmuch-show-get-message-id))
1206                   return t
1207                   until (not (notmuch-show-goto-message-next)))
1208       (goto-char (point-min))
1209       (message "Previously current message not found."))
1210     (notmuch-show-message-adjust)))
1211
1212 (defun notmuch-show-refresh-view (&optional reset-state)
1213   "Refresh the current view.
1214
1215 Refreshes the current view, observing changes in display
1216 preferences. If invoked with a prefix argument (or RESET-STATE is
1217 non-nil) then the state of the buffer (open/closed messages) is
1218 reset based on the original query."
1219   (interactive "P")
1220   (let ((inhibit-read-only t)
1221         (state (unless reset-state
1222                  (notmuch-show-capture-state))))
1223     ;; erase-buffer does not seem to remove overlays, which can lead
1224     ;; to weird effects such as remaining images, so remove them
1225     ;; manually.
1226     (remove-overlays)
1227     (erase-buffer)
1228     (notmuch-show-build-buffer)
1229     (if state
1230         (notmuch-show-apply-state state)
1231       ;; We're resetting state, so navigate to the first open message
1232       ;; and mark it read, just like opening a new show buffer.
1233       (notmuch-show-goto-first-wanted-message))))
1234
1235 (defvar notmuch-show-stash-map
1236   (let ((map (make-sparse-keymap)))
1237     (define-key map "c" 'notmuch-show-stash-cc)
1238     (define-key map "d" 'notmuch-show-stash-date)
1239     (define-key map "F" 'notmuch-show-stash-filename)
1240     (define-key map "f" 'notmuch-show-stash-from)
1241     (define-key map "i" 'notmuch-show-stash-message-id)
1242     (define-key map "I" 'notmuch-show-stash-message-id-stripped)
1243     (define-key map "s" 'notmuch-show-stash-subject)
1244     (define-key map "T" 'notmuch-show-stash-tags)
1245     (define-key map "t" 'notmuch-show-stash-to)
1246     (define-key map "l" 'notmuch-show-stash-mlarchive-link)
1247     (define-key map "L" 'notmuch-show-stash-mlarchive-link-and-go)
1248     map)
1249   "Submap for stash commands")
1250 (fset 'notmuch-show-stash-map notmuch-show-stash-map)
1251
1252 (defvar notmuch-show-part-map
1253   (let ((map (make-sparse-keymap)))
1254     (define-key map "s" 'notmuch-show-save-part)
1255     (define-key map "v" 'notmuch-show-view-part)
1256     (define-key map "o" 'notmuch-show-interactively-view-part)
1257     (define-key map "|" 'notmuch-show-pipe-part)
1258     map)
1259   "Submap for part commands")
1260 (fset 'notmuch-show-part-map notmuch-show-part-map)
1261
1262 (defvar notmuch-show-mode-map
1263       (let ((map (make-sparse-keymap)))
1264         (define-key map "?" 'notmuch-help)
1265         (define-key map "q" 'notmuch-kill-this-buffer)
1266         (define-key map (kbd "<C-tab>") 'widget-backward)
1267         (define-key map (kbd "M-TAB") 'notmuch-show-previous-button)
1268         (define-key map (kbd "<backtab>") 'notmuch-show-previous-button)
1269         (define-key map (kbd "TAB") 'notmuch-show-next-button)
1270         (define-key map "s" 'notmuch-search)
1271         (define-key map "m" 'notmuch-mua-new-mail)
1272         (define-key map "f" 'notmuch-show-forward-message)
1273         (define-key map "r" 'notmuch-show-reply-sender)
1274         (define-key map "R" 'notmuch-show-reply)
1275         (define-key map "|" 'notmuch-show-pipe-message)
1276         (define-key map "w" 'notmuch-show-save-attachments)
1277         (define-key map "V" 'notmuch-show-view-raw-message)
1278         (define-key map "c" 'notmuch-show-stash-map)
1279         (define-key map "=" 'notmuch-show-refresh-view)
1280         (define-key map "h" 'notmuch-show-toggle-visibility-headers)
1281         (define-key map "*" 'notmuch-show-tag-all)
1282         (define-key map "-" 'notmuch-show-remove-tag)
1283         (define-key map "+" 'notmuch-show-add-tag)
1284         (define-key map "X" 'notmuch-show-archive-thread-then-exit)
1285         (define-key map "x" 'notmuch-show-archive-message-then-next-or-exit)
1286         (define-key map "A" 'notmuch-show-archive-thread-then-next)
1287         (define-key map "a" 'notmuch-show-archive-message-then-next-or-next-thread)
1288         (define-key map "N" 'notmuch-show-next-message)
1289         (define-key map "P" 'notmuch-show-previous-message)
1290         (define-key map "n" 'notmuch-show-next-open-message)
1291         (define-key map "p" 'notmuch-show-previous-open-message)
1292         (define-key map (kbd "M-n") 'notmuch-show-next-thread-show)
1293         (define-key map (kbd "M-p") 'notmuch-show-previous-thread-show)
1294         (define-key map (kbd "DEL") 'notmuch-show-rewind)
1295         (define-key map " " 'notmuch-show-advance-and-archive)
1296         (define-key map (kbd "M-RET") 'notmuch-show-open-or-close-all)
1297         (define-key map (kbd "RET") 'notmuch-show-toggle-message)
1298         (define-key map "#" 'notmuch-show-print-message)
1299         (define-key map "!" 'notmuch-show-toggle-elide-non-matching)
1300         (define-key map "$" 'notmuch-show-toggle-process-crypto)
1301         (define-key map "<" 'notmuch-show-toggle-thread-indentation)
1302         (define-key map "t" 'toggle-truncate-lines)
1303         (define-key map "." 'notmuch-show-part-map)
1304         map)
1305       "Keymap for \"notmuch show\" buffers.")
1306 (fset 'notmuch-show-mode-map notmuch-show-mode-map)
1307
1308 (defun notmuch-show-mode ()
1309   "Major mode for viewing a thread with notmuch.
1310
1311 This buffer contains the results of the \"notmuch show\" command
1312 for displaying a single thread of email from your email archives.
1313
1314 By default, various components of email messages, (citations,
1315 signatures, already-read messages), are hidden. You can make
1316 these parts visible by clicking with the mouse button or by
1317 pressing RET after positioning the cursor on a hidden part, (for
1318 which \\[notmuch-show-next-button] and \\[notmuch-show-previous-button] are helpful).
1319
1320 Reading the thread sequentially is well-supported by pressing
1321 \\[notmuch-show-advance-and-archive]. This will scroll the current message (if necessary), advance
1322 to the next message, or advance to the next thread (if already on
1323 the last message of a thread).
1324
1325 Other commands are available to read or manipulate the thread
1326 more selectively, (such as '\\[notmuch-show-next-message]' and '\\[notmuch-show-previous-message]' to advance to messages
1327 without removing any tags, and '\\[notmuch-show-archive-thread]' to archive an entire thread
1328 without scrolling through with \\[notmuch-show-advance-and-archive]).
1329
1330 You can add or remove arbitrary tags from the current message with
1331 '\\[notmuch-show-add-tag]' or '\\[notmuch-show-remove-tag]'.
1332
1333 All currently available key bindings:
1334
1335 \\{notmuch-show-mode-map}"
1336   (interactive)
1337   (kill-all-local-variables)
1338   (use-local-map notmuch-show-mode-map)
1339   (setq major-mode 'notmuch-show-mode
1340         mode-name "notmuch-show")
1341   (setq buffer-read-only t
1342         truncate-lines t))
1343
1344 (defun notmuch-show-move-to-message-top ()
1345   (goto-char (notmuch-show-message-top)))
1346
1347 (defun notmuch-show-move-to-message-bottom ()
1348   (goto-char (notmuch-show-message-bottom)))
1349
1350 (defun notmuch-show-message-adjust ()
1351   (recenter 0))
1352
1353 ;; Movement related functions.
1354
1355 ;; There's some strangeness here where a text property applied to a
1356 ;; region a->b is not found when point is at b. We walk backwards
1357 ;; until finding the property.
1358 (defun notmuch-show-message-extent ()
1359   (let (r)
1360     (save-excursion
1361       (while (not (setq r (get-text-property (point) :notmuch-message-extent)))
1362         (backward-char)))
1363     r))
1364
1365 (defun notmuch-show-message-top ()
1366   (car (notmuch-show-message-extent)))
1367
1368 (defun notmuch-show-message-bottom ()
1369   (cdr (notmuch-show-message-extent)))
1370
1371 (defun notmuch-show-goto-message-next ()
1372   (let ((start (point)))
1373     (notmuch-show-move-to-message-bottom)
1374     (if (not (eobp))
1375         t
1376       (goto-char start)
1377       nil)))
1378
1379 (defun notmuch-show-goto-message-previous ()
1380   (notmuch-show-move-to-message-top)
1381   (if (bobp)
1382       nil
1383     (backward-char)
1384     (notmuch-show-move-to-message-top)
1385     t))
1386
1387 (defun notmuch-show-mapc (function)
1388   "Iterate through all messages in the current thread with
1389 `notmuch-show-goto-message-next' and call FUNCTION for side
1390 effects."
1391   (save-excursion
1392     (goto-char (point-min))
1393     (loop do (funcall function)
1394           while (notmuch-show-goto-message-next))))
1395
1396 ;; Functions relating to the visibility of messages and their
1397 ;; components.
1398
1399 (defun notmuch-show-message-visible (props visible-p)
1400   (overlay-put (plist-get props :message-overlay) 'invisible (not visible-p))
1401   (notmuch-show-set-prop :message-visible visible-p props))
1402
1403 (defun notmuch-show-headers-visible (props visible-p)
1404   (overlay-put (plist-get props :headers-overlay) 'invisible (not visible-p))
1405   (notmuch-show-set-prop :headers-visible visible-p props))
1406
1407 ;; Functions for setting and getting attributes of the current
1408 ;; message.
1409
1410 (defun notmuch-show-set-message-properties (props)
1411   (save-excursion
1412     (notmuch-show-move-to-message-top)
1413     (put-text-property (point) (+ (point) 1) :notmuch-message-properties props)))
1414
1415 (defun notmuch-show-get-message-properties ()
1416   "Return the properties of the current message as a plist.
1417
1418 Some useful entries are:
1419 :headers - Property list containing the headers :Date, :Subject, :From, etc.
1420 :body - Body of the message
1421 :tags - Tags for this message"
1422   (save-excursion
1423     (notmuch-show-move-to-message-top)
1424     (get-text-property (point) :notmuch-message-properties)))
1425
1426 (defun notmuch-show-get-part-properties ()
1427   "Return the properties of the innermost part containing point.
1428
1429 This is the part property list retrieved from the CLI.  Signals
1430 an error if there is no part containing point."
1431   (or (get-text-property (point) :notmuch-part)
1432       (error "No message part here")))
1433
1434 (defun notmuch-show-set-prop (prop val &optional props)
1435   (let ((inhibit-read-only t)
1436         (props (or props
1437                    (notmuch-show-get-message-properties))))
1438     (plist-put props prop val)
1439     (notmuch-show-set-message-properties props)))
1440
1441 (defun notmuch-show-get-prop (prop &optional props)
1442   (let ((props (or props
1443                    (notmuch-show-get-message-properties))))
1444     (plist-get props prop)))
1445
1446 (defun notmuch-show-get-message-id (&optional bare)
1447   "Return an id: query for the Message-Id of the current message.
1448
1449 If optional argument BARE is non-nil, return
1450 the Message-Id without id: prefix and escaping."
1451   (if bare
1452       (notmuch-show-get-prop :id)
1453     (notmuch-id-to-query (notmuch-show-get-prop :id))))
1454
1455 (defun notmuch-show-get-messages-ids ()
1456   "Return all id: queries of messages in the current thread."
1457   (let ((message-ids))
1458     (notmuch-show-mapc
1459      (lambda () (push (notmuch-show-get-message-id) message-ids)))
1460     message-ids))
1461
1462 (defun notmuch-show-get-messages-ids-search ()
1463   "Return a search string for all message ids of messages in the
1464 current thread."
1465   (mapconcat 'identity (notmuch-show-get-messages-ids) " or "))
1466
1467 ;; dme: Would it make sense to use a macro for many of these?
1468
1469 (defun notmuch-show-get-filename ()
1470   "Return the filename of the current message."
1471   (notmuch-show-get-prop :filename))
1472
1473 (defun notmuch-show-get-header (header &optional props)
1474   "Return the named header of the current message, if any."
1475   (plist-get (notmuch-show-get-prop :headers props) header))
1476
1477 (defun notmuch-show-get-cc ()
1478   (notmuch-show-get-header :Cc))
1479
1480 (defun notmuch-show-get-date ()
1481   (notmuch-show-get-header :Date))
1482
1483 (defun notmuch-show-get-from ()
1484   (notmuch-show-get-header :From))
1485
1486 (defun notmuch-show-get-subject ()
1487   (notmuch-show-get-header :Subject))
1488
1489 (defun notmuch-show-get-to ()
1490   (notmuch-show-get-header :To))
1491
1492 (defun notmuch-show-get-depth ()
1493   (notmuch-show-get-prop :depth))
1494
1495 (defun notmuch-show-set-tags (tags)
1496   "Set the tags of the current message."
1497   (notmuch-show-set-prop :tags tags)
1498   (notmuch-show-update-tags tags))
1499
1500 (defun notmuch-show-get-tags ()
1501   "Return the tags of the current message."
1502   (notmuch-show-get-prop :tags))
1503
1504 (defun notmuch-show-message-visible-p ()
1505   "Is the current message visible?"
1506   (notmuch-show-get-prop :message-visible))
1507
1508 (defun notmuch-show-headers-visible-p ()
1509   "Are the headers of the current message visible?"
1510   (notmuch-show-get-prop :headers-visible))
1511
1512 (defun notmuch-show-mark-read (&optional unread)
1513   "Mark the current message as read.
1514
1515 Mark the current message as read by applying the tag changes in
1516 `notmuch-show-mark-read-tags' to it (remove the \"unread\" tag by
1517 default). If a prefix argument is given, the message will be
1518 marked as unread, i.e. the tag changes in
1519 `notmuch-show-mark-read-tags' will be reversed."
1520   (interactive "P")
1521   (when notmuch-show-mark-read-tags
1522     (apply 'notmuch-show-tag-message
1523            (notmuch-tag-change-list notmuch-show-mark-read-tags unread))))
1524
1525 ;; Functions for getting attributes of several messages in the current
1526 ;; thread.
1527
1528 (defun notmuch-show-get-message-ids-for-open-messages ()
1529   "Return a list of all id: queries for open messages in the current thread."
1530   (save-excursion
1531     (let (message-ids done)
1532       (goto-char (point-min))
1533       (while (not done)
1534         (if (notmuch-show-message-visible-p)
1535             (setq message-ids (append message-ids (list (notmuch-show-get-message-id)))))
1536         (setq done (not (notmuch-show-goto-message-next)))
1537         )
1538       message-ids
1539       )))
1540
1541 ;; Commands typically bound to keys.
1542
1543 (defun notmuch-show-advance ()
1544   "Advance through thread.
1545
1546 If the current message in the thread is not yet fully visible,
1547 scroll by a near screenful to read more of the message.
1548
1549 Otherwise, (the end of the current message is already within the
1550 current window), advance to the next open message."
1551   (interactive)
1552   (let* ((end-of-this-message (notmuch-show-message-bottom))
1553          (visible-end-of-this-message (1- end-of-this-message))
1554          (ret nil))
1555     (while (invisible-p visible-end-of-this-message)
1556       (setq visible-end-of-this-message
1557             (max (point-min)
1558                  (1- (previous-single-char-property-change
1559                       visible-end-of-this-message 'invisible)))))
1560     (cond
1561      ;; Ideally we would test `end-of-this-message' against the result
1562      ;; of `window-end', but that doesn't account for the fact that
1563      ;; the end of the message might be hidden.
1564      ((and visible-end-of-this-message
1565            (> visible-end-of-this-message (window-end)))
1566       ;; The bottom of this message is not visible - scroll.
1567       (scroll-up nil))
1568
1569      ((not (= end-of-this-message (point-max)))
1570       ;; This is not the last message - move to the next visible one.
1571       (notmuch-show-next-open-message))
1572
1573      ((not (= (point) (point-max)))
1574       ;; This is the last message, but the cursor is not at the end of
1575       ;; the buffer. Move it there.
1576       (goto-char (point-max)))
1577
1578      (t
1579       ;; This is the last message - change the return value
1580       (setq ret t)))
1581     ret))
1582
1583 (defun notmuch-show-advance-and-archive ()
1584   "Advance through thread and archive.
1585
1586 This command is intended to be one of the simplest ways to
1587 process a thread of email. It works exactly like
1588 notmuch-show-advance, in that it scrolls through messages in a
1589 show buffer, except that when it gets to the end of the buffer it
1590 archives the entire current thread, (apply changes in
1591 `notmuch-archive-tags'), kills the buffer, and displays the next
1592 thread from the search from which this thread was originally
1593 shown."
1594   (interactive)
1595   (if (notmuch-show-advance)
1596       (notmuch-show-archive-thread-then-next)))
1597
1598 (defun notmuch-show-rewind ()
1599   "Backup through the thread, (reverse scrolling compared to \\[notmuch-show-advance-and-archive]).
1600
1601 Specifically, if the beginning of the previous email is fewer
1602 than `window-height' lines from the current point, move to it
1603 just like `notmuch-show-previous-message'.
1604
1605 Otherwise, just scroll down a screenful of the current message.
1606
1607 This command does not modify any message tags, (it does not undo
1608 any effects from previous calls to
1609 `notmuch-show-advance-and-archive'."
1610   (interactive)
1611   (let ((start-of-message (notmuch-show-message-top))
1612         (start-of-window (window-start)))
1613     (cond
1614       ;; Either this message is properly aligned with the start of the
1615       ;; window or the start of this message is not visible on the
1616       ;; screen - scroll.
1617      ((or (= start-of-message start-of-window)
1618           (< start-of-message start-of-window))
1619       (scroll-down)
1620       ;; If a small number of lines from the previous message are
1621       ;; visible, realign so that the top of the current message is at
1622       ;; the top of the screen.
1623       (when (<= (count-screen-lines (window-start) start-of-message)
1624                 next-screen-context-lines)
1625         (goto-char (notmuch-show-message-top))
1626         (notmuch-show-message-adjust))
1627       ;; Move to the top left of the window.
1628       (goto-char (window-start)))
1629      (t
1630       ;; Move to the previous message.
1631       (notmuch-show-previous-message)))))
1632
1633 (defun notmuch-show-reply (&optional prompt-for-sender)
1634   "Reply to the sender and all recipients of the current message."
1635   (interactive "P")
1636   (notmuch-mua-new-reply (notmuch-show-get-message-id) prompt-for-sender t))
1637
1638 (defun notmuch-show-reply-sender (&optional prompt-for-sender)
1639   "Reply to the sender of the current message."
1640   (interactive "P")
1641   (notmuch-mua-new-reply (notmuch-show-get-message-id) prompt-for-sender nil))
1642
1643 (defun notmuch-show-forward-message (&optional prompt-for-sender)
1644   "Forward the current message."
1645   (interactive "P")
1646   (with-current-notmuch-show-message
1647    (notmuch-mua-new-forward-message prompt-for-sender)))
1648
1649 (defun notmuch-show-next-message (&optional pop-at-end)
1650   "Show the next message.
1651
1652 If a prefix argument is given and this is the last message in the
1653 thread, navigate to the next thread in the parent search buffer."
1654   (interactive "P")
1655   (if (notmuch-show-goto-message-next)
1656       (progn
1657         (notmuch-show-mark-read)
1658         (notmuch-show-message-adjust))
1659     (if pop-at-end
1660         (notmuch-show-next-thread)
1661       (goto-char (point-max)))))
1662
1663 (defun notmuch-show-previous-message ()
1664   "Show the previous message or the start of the current message."
1665   (interactive)
1666   (if (= (point) (notmuch-show-message-top))
1667       (notmuch-show-goto-message-previous)
1668     (notmuch-show-move-to-message-top))
1669   (notmuch-show-mark-read)
1670   (notmuch-show-message-adjust))
1671
1672 (defun notmuch-show-next-open-message (&optional pop-at-end)
1673   "Show the next open message.
1674
1675 If a prefix argument is given and this is the last open message
1676 in the thread, navigate to the next thread in the parent search
1677 buffer. Return t if there was a next open message in the thread
1678 to show, nil otherwise."
1679   (interactive "P")
1680   (let (r)
1681     (while (and (setq r (notmuch-show-goto-message-next))
1682                 (not (notmuch-show-message-visible-p))))
1683     (if r
1684         (progn
1685           (notmuch-show-mark-read)
1686           (notmuch-show-message-adjust))
1687       (if pop-at-end
1688           (notmuch-show-next-thread)
1689         (goto-char (point-max))))
1690     r))
1691
1692 (defun notmuch-show-next-matching-message ()
1693   "Show the next matching message."
1694   (interactive)
1695   (let (r)
1696     (while (and (setq r (notmuch-show-goto-message-next))
1697                 (not (notmuch-show-get-prop :match))))
1698     (if r
1699         (progn
1700           (notmuch-show-mark-read)
1701           (notmuch-show-message-adjust))
1702       (goto-char (point-max)))))
1703
1704 (defun notmuch-show-open-if-matched ()
1705   "Open a message if it is matched (whether or not excluded)."
1706   (let ((props (notmuch-show-get-message-properties)))
1707     (notmuch-show-message-visible props (plist-get props :match))))
1708
1709 (defun notmuch-show-goto-first-wanted-message ()
1710   "Move to the first open message and mark it read"
1711   (goto-char (point-min))
1712   (if (notmuch-show-message-visible-p)
1713       (notmuch-show-mark-read)
1714     (notmuch-show-next-open-message))
1715   (when (eobp)
1716     ;; There are no matched non-excluded messages so open all matched
1717     ;; (necessarily excluded) messages and go to the first.
1718     (notmuch-show-mapc 'notmuch-show-open-if-matched)
1719     (force-window-update)
1720     (goto-char (point-min))
1721     (if (notmuch-show-message-visible-p)
1722         (notmuch-show-mark-read)
1723       (notmuch-show-next-open-message))))
1724
1725 (defun notmuch-show-previous-open-message ()
1726   "Show the previous open message."
1727   (interactive)
1728   (while (and (if (= (point) (notmuch-show-message-top))
1729                   (notmuch-show-goto-message-previous)
1730                 (notmuch-show-move-to-message-top))
1731               (not (notmuch-show-message-visible-p))))
1732   (notmuch-show-mark-read)
1733   (notmuch-show-message-adjust))
1734
1735 (defun notmuch-show-view-raw-message ()
1736   "View the file holding the current message."
1737   (interactive)
1738   (let* ((id (notmuch-show-get-message-id))
1739          (buf (get-buffer-create (concat "*notmuch-raw-" id "*"))))
1740     (call-process notmuch-command nil buf nil "show" "--format=raw" id)
1741     (switch-to-buffer buf)
1742     (goto-char (point-min))
1743     (set-buffer-modified-p nil)
1744     (view-buffer buf 'kill-buffer-if-not-modified)))
1745
1746 (defun notmuch-show-pipe-message (entire-thread command)
1747   "Pipe the contents of the current message (or thread) to the given command.
1748
1749 The given command will be executed with the raw contents of the
1750 current email message as stdin. Anything printed by the command
1751 to stdout or stderr will appear in the *notmuch-pipe* buffer.
1752
1753 When invoked with a prefix argument, the command will receive all
1754 open messages in the current thread (formatted as an mbox) rather
1755 than only the current message."
1756   (interactive (let ((query-string (if current-prefix-arg
1757                                        "Pipe all open messages to command: "
1758                                      "Pipe message to command: ")))
1759                  (list current-prefix-arg (read-string query-string))))
1760   (let (shell-command)
1761     (if entire-thread
1762         (setq shell-command
1763               (concat notmuch-command " show --format=mbox --exclude=false "
1764                       (shell-quote-argument
1765                        (mapconcat 'identity (notmuch-show-get-message-ids-for-open-messages) " OR "))
1766                       " | " command))
1767       (setq shell-command
1768             (concat notmuch-command " show --format=raw "
1769                     (shell-quote-argument (notmuch-show-get-message-id)) " | " command)))
1770     (let ((buf (get-buffer-create (concat "*notmuch-pipe*"))))
1771       (with-current-buffer buf
1772         (setq buffer-read-only nil)
1773         (erase-buffer)
1774         (let ((exit-code (call-process-shell-command shell-command nil buf)))
1775           (goto-char (point-max))
1776           (set-buffer-modified-p nil)
1777           (setq buffer-read-only t)
1778           (unless (zerop exit-code)
1779             (switch-to-buffer-other-window buf)
1780             (message (format "Command '%s' exited abnormally with code %d"
1781                              shell-command exit-code))))))))
1782
1783 (defun notmuch-show-tag-message (&rest tag-changes)
1784   "Change tags for the current message.
1785
1786 TAG-CHANGES is a list of tag operations for `notmuch-tag'."
1787   (let* ((current-tags (notmuch-show-get-tags))
1788          (new-tags (notmuch-update-tags current-tags tag-changes)))
1789     (unless (equal current-tags new-tags)
1790       (notmuch-tag (notmuch-show-get-message-id) tag-changes)
1791       (notmuch-show-set-tags new-tags))))
1792
1793 (defun notmuch-show-tag (&optional tag-changes)
1794   "Change tags for the current message.
1795
1796 See `notmuch-tag' for information on the format of TAG-CHANGES."
1797   (interactive)
1798   (let* ((tag-changes (notmuch-tag (notmuch-show-get-message-id) tag-changes))
1799          (current-tags (notmuch-show-get-tags))
1800          (new-tags (notmuch-update-tags current-tags tag-changes)))
1801     (unless (equal current-tags new-tags)
1802       (notmuch-show-set-tags new-tags))))
1803
1804 (defun notmuch-show-tag-all (&optional tag-changes)
1805   "Change tags for all messages in the current show buffer.
1806
1807 See `notmuch-tag' for information on the format of TAG-CHANGES."
1808   (interactive)
1809   (setq tag-changes (notmuch-tag (notmuch-show-get-messages-ids-search) tag-changes))
1810   (notmuch-show-mapc
1811    (lambda ()
1812      (let* ((current-tags (notmuch-show-get-tags))
1813             (new-tags (notmuch-update-tags current-tags tag-changes)))
1814        (unless (equal current-tags new-tags)
1815          (notmuch-show-set-tags new-tags))))))
1816
1817 (defun notmuch-show-add-tag ()
1818   "Same as `notmuch-show-tag' but sets initial input to '+'."
1819   (interactive)
1820   (notmuch-show-tag "+"))
1821
1822 (defun notmuch-show-remove-tag ()
1823   "Same as `notmuch-show-tag' but sets initial input to '-'."
1824   (interactive)
1825   (notmuch-show-tag "-"))
1826
1827 (defun notmuch-show-toggle-visibility-headers ()
1828   "Toggle the visibility of the current message headers."
1829   (interactive)
1830   (let ((props (notmuch-show-get-message-properties)))
1831     (notmuch-show-headers-visible
1832      props
1833      (not (plist-get props :headers-visible))))
1834   (force-window-update))
1835
1836 (defun notmuch-show-toggle-message ()
1837   "Toggle the visibility of the current message."
1838   (interactive)
1839   (let ((props (notmuch-show-get-message-properties)))
1840     (notmuch-show-message-visible
1841      props
1842      (not (plist-get props :message-visible))))
1843   (force-window-update))
1844
1845 (defun notmuch-show-open-or-close-all ()
1846   "Set the visibility all of the messages in the current thread.
1847 By default make all of the messages visible. With a prefix
1848 argument, hide all of the messages."
1849   (interactive)
1850   (save-excursion
1851     (goto-char (point-min))
1852     (loop do (notmuch-show-message-visible (notmuch-show-get-message-properties)
1853                                            (not current-prefix-arg))
1854           until (not (notmuch-show-goto-message-next))))
1855   (force-window-update))
1856
1857 (defun notmuch-show-next-button ()
1858   "Advance point to the next button in the buffer."
1859   (interactive)
1860   (forward-button 1))
1861
1862 (defun notmuch-show-previous-button ()
1863   "Move point back to the previous button in the buffer."
1864   (interactive)
1865   (backward-button 1))
1866
1867 (defun notmuch-show-next-thread (&optional show previous)
1868   "Move to the next item in the search results, if any.
1869
1870 If SHOW is non-nil, open the next item in a show
1871 buffer. Otherwise just highlight the next item in the search
1872 buffer. If PREVIOUS is non-nil, move to the previous item in the
1873 search results instead."
1874   (interactive "P")
1875   (let ((parent-buffer notmuch-show-parent-buffer))
1876     (notmuch-kill-this-buffer)
1877     (when (buffer-live-p parent-buffer)
1878       (switch-to-buffer parent-buffer)
1879       (and (if previous
1880                (notmuch-search-previous-thread)
1881              (notmuch-search-next-thread))
1882            show
1883            (notmuch-search-show-thread)))))
1884
1885 (defun notmuch-show-next-thread-show ()
1886   "Show the next thread in the search results, if any."
1887   (interactive)
1888   (notmuch-show-next-thread t))
1889
1890 (defun notmuch-show-previous-thread-show ()
1891   "Show the previous thread in the search results, if any."
1892   (interactive)
1893   (notmuch-show-next-thread t t))
1894
1895 (defun notmuch-show-archive-thread (&optional unarchive)
1896   "Archive each message in thread.
1897
1898 Archive each message currently shown by applying the tag changes
1899 in `notmuch-archive-tags' to each. If a prefix argument is given,
1900 the messages will be \"unarchived\", i.e. the tag changes in
1901 `notmuch-archive-tags' will be reversed.
1902
1903 Note: This command is safe from any race condition of new messages
1904 being delivered to the same thread. It does not archive the
1905 entire thread, but only the messages shown in the current
1906 buffer."
1907   (interactive "P")
1908   (when notmuch-archive-tags
1909     (notmuch-show-tag-all
1910      (notmuch-tag-change-list notmuch-archive-tags unarchive))))
1911
1912 (defun notmuch-show-archive-thread-then-next ()
1913   "Archive all messages in the current buffer, then show next thread from search."
1914   (interactive)
1915   (notmuch-show-archive-thread)
1916   (notmuch-show-next-thread t))
1917
1918 (defun notmuch-show-archive-thread-then-exit ()
1919   "Archive all messages in the current buffer, then exit back to search results."
1920   (interactive)
1921   (notmuch-show-archive-thread)
1922   (notmuch-show-next-thread))
1923
1924 (defun notmuch-show-archive-message (&optional unarchive)
1925   "Archive the current message.
1926
1927 Archive the current message by applying the tag changes in
1928 `notmuch-archive-tags' to it. If a prefix argument is given, the
1929 message will be \"unarchived\", i.e. the tag changes in
1930 `notmuch-archive-tags' will be reversed."
1931   (interactive "P")
1932   (when notmuch-archive-tags
1933     (apply 'notmuch-show-tag-message
1934            (notmuch-tag-change-list notmuch-archive-tags unarchive))))
1935
1936 (defun notmuch-show-archive-message-then-next-or-exit ()
1937   "Archive the current message, then show the next open message in the current thread.
1938
1939 If at the last open message in the current thread, then exit back
1940 to search results."
1941   (interactive)
1942   (notmuch-show-archive-message)
1943   (notmuch-show-next-open-message t))
1944
1945 (defun notmuch-show-archive-message-then-next-or-next-thread ()
1946   "Archive the current message, then show the next open message in the current thread.
1947
1948 If at the last open message in the current thread, then show next
1949 thread from search."
1950   (interactive)
1951   (notmuch-show-archive-message)
1952   (unless (notmuch-show-next-open-message)
1953     (notmuch-show-next-thread t)))
1954
1955 (defun notmuch-show-stash-cc ()
1956   "Copy CC field of current message to kill-ring."
1957   (interactive)
1958   (notmuch-common-do-stash (notmuch-show-get-cc)))
1959
1960 (defun notmuch-show-stash-date ()
1961   "Copy date of current message to kill-ring."
1962   (interactive)
1963   (notmuch-common-do-stash (notmuch-show-get-date)))
1964
1965 (defun notmuch-show-stash-filename ()
1966   "Copy filename of current message to kill-ring."
1967   (interactive)
1968   (notmuch-common-do-stash (notmuch-show-get-filename)))
1969
1970 (defun notmuch-show-stash-from ()
1971   "Copy From address of current message to kill-ring."
1972   (interactive)
1973   (notmuch-common-do-stash (notmuch-show-get-from)))
1974
1975 (defun notmuch-show-stash-message-id (&optional stash-thread-id)
1976   "Copy id: query matching the current message to kill-ring.
1977
1978 If invoked with a prefix argument (or STASH-THREAD-ID is
1979 non-nil), copy thread: query matching the current thread to
1980 kill-ring."
1981   (interactive "P")
1982   (if stash-thread-id
1983       (notmuch-common-do-stash notmuch-show-thread-id)
1984     (notmuch-common-do-stash (notmuch-show-get-message-id))))
1985
1986 (defun notmuch-show-stash-message-id-stripped ()
1987   "Copy message ID of current message (sans `id:' prefix) to kill-ring."
1988   (interactive)
1989   (notmuch-common-do-stash (notmuch-show-get-message-id t)))
1990
1991 (defun notmuch-show-stash-subject ()
1992   "Copy Subject field of current message to kill-ring."
1993   (interactive)
1994   (notmuch-common-do-stash (notmuch-show-get-subject)))
1995
1996 (defun notmuch-show-stash-tags ()
1997   "Copy tags of current message to kill-ring as a comma separated list."
1998   (interactive)
1999   (notmuch-common-do-stash (mapconcat 'identity (notmuch-show-get-tags) ",")))
2000
2001 (defun notmuch-show-stash-to ()
2002   "Copy To address of current message to kill-ring."
2003   (interactive)
2004   (notmuch-common-do-stash (notmuch-show-get-to)))
2005
2006 (defun notmuch-show-stash-mlarchive-link (&optional mla)
2007   "Copy an ML Archive URI for the current message to the kill-ring.
2008
2009 This presumes that the message is available at the selected Mailing List Archive.
2010
2011 If optional argument MLA is non-nil, use the provided key instead of prompting
2012 the user (see `notmuch-show-stash-mlarchive-link-alist')."
2013   (interactive)
2014   (notmuch-common-do-stash
2015    (concat (cdr (assoc
2016                  (or mla
2017                      (let ((completion-ignore-case t))
2018                        (completing-read
2019                         "Mailing List Archive: "
2020                         notmuch-show-stash-mlarchive-link-alist
2021                         nil t nil nil notmuch-show-stash-mlarchive-link-default)))
2022                  notmuch-show-stash-mlarchive-link-alist))
2023            (notmuch-show-get-message-id t))))
2024
2025 (defun notmuch-show-stash-mlarchive-link-and-go (&optional mla)
2026   "Copy an ML Archive URI for the current message to the kill-ring and visit it.
2027
2028 This presumes that the message is available at the selected Mailing List Archive.
2029
2030 If optional argument MLA is non-nil, use the provided key instead of prompting
2031 the user (see `notmuch-show-stash-mlarchive-link-alist')."
2032   (interactive)
2033   (notmuch-show-stash-mlarchive-link mla)
2034   (browse-url (current-kill 0 t)))
2035
2036 ;; Interactive part functions and their helpers
2037
2038 (defun notmuch-show-generate-part-buffer (message-id nth)
2039   "Return a temporary buffer containing the specified part's content."
2040   (let ((buf (generate-new-buffer " *notmuch-part*"))
2041         (process-crypto notmuch-show-process-crypto))
2042     (with-current-buffer buf
2043       (setq notmuch-show-process-crypto process-crypto)
2044       ;; Always acquires the part via `notmuch part', even if it is
2045       ;; available in the JSON output.
2046       (insert (notmuch-get-bodypart-internal message-id nth notmuch-show-process-crypto)))
2047     buf))
2048
2049 (defun notmuch-show-current-part-handle ()
2050   "Return an mm-handle for the part containing point.
2051
2052 This creates a temporary buffer for the part's content; the
2053 caller is responsible for killing this buffer as appropriate."
2054   (let* ((part (notmuch-show-get-part-properties))
2055          (message-id (notmuch-show-get-message-id))
2056          (nth (plist-get part :id))
2057          (buf (notmuch-show-generate-part-buffer message-id nth))
2058          (content-type (plist-get part :content-type))
2059          (filename (plist-get part :filename))
2060          (disposition (if filename `(attachment (filename . ,filename)))))
2061     (mm-make-handle buf (list content-type) nil nil disposition)))
2062
2063 (defun notmuch-show-apply-to-current-part-handle (fn)
2064   "Apply FN to an mm-handle for the part containing point.
2065
2066 This ensures that the temporary buffer created for the mm-handle
2067 is destroyed when FN returns."
2068   (let ((handle (notmuch-show-current-part-handle)))
2069     (unwind-protect
2070         (funcall fn handle)
2071       (kill-buffer (mm-handle-buffer handle)))))
2072
2073 (defun notmuch-show-part-button-default (&optional button)
2074   (interactive)
2075   (let ((button (or button (button-at (point)))))
2076     ;; Try to toggle the part, if that fails then call the default
2077     ;; action. The toggle fails if the part has no emacs renderable
2078     ;; content.
2079     (unless (notmuch-show-toggle-part-invisibility button)
2080       (call-interactively notmuch-show-part-button-default-action))))
2081
2082 (defun notmuch-show-save-part ()
2083   "Save the MIME part containing point to a file."
2084   (interactive)
2085   (notmuch-show-apply-to-current-part-handle #'mm-save-part))
2086
2087 (defun notmuch-show-view-part ()
2088   "View the MIME part containing point in an external viewer."
2089   (interactive)
2090   ;; Set mm-inlined-types to nil to force an external viewer
2091   (let ((mm-inlined-types nil))
2092     (notmuch-show-apply-to-current-part-handle #'mm-display-part)))
2093
2094 (defun notmuch-show-interactively-view-part ()
2095   "View the MIME part containing point, prompting for a viewer."
2096   (interactive)
2097   (notmuch-show-apply-to-current-part-handle #'mm-interactively-view-part))
2098
2099 (defun notmuch-show-pipe-part ()
2100   "Pipe the MIME part containing point to an external command."
2101   (interactive)
2102   (notmuch-show-apply-to-current-part-handle #'mm-pipe-part))
2103
2104
2105 (provide 'notmuch-show)