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