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