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