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