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