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