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