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