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