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