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