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