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