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