]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-show.el
Render all parts of multipart/encrypted when decrypting.
[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
31 (require 'notmuch-lib)
32 (require 'notmuch-query)
33 (require 'notmuch-wash)
34 (require 'notmuch-mua)
35 (require 'notmuch-crypto)
36
37 (declare-function notmuch-call-notmuch-process "notmuch" (&rest args))
38 (declare-function notmuch-fontify-headers "notmuch" nil)
39 (declare-function notmuch-select-tag-with-completion "notmuch" (prompt &rest search-terms))
40 (declare-function notmuch-search-show-thread "notmuch" nil)
41
42 (defcustom notmuch-message-headers '("Subject" "To" "Cc" "Date")
43   "Headers that should be shown in a message, in this order.
44
45 For an open message, all of these headers will be made visible
46 according to `notmuch-message-headers-visible' or can be toggled
47 with `notmuch-show-toggle-headers'. For a closed message, only
48 the first header in the list will be visible."
49   :group 'notmuch
50   :type '(repeat string))
51
52 (defcustom notmuch-message-headers-visible t
53   "Should the headers be visible by default?
54
55 If this value is non-nil, then all of the headers defined in
56 `notmuch-message-headers' will be visible by default in the display
57 of each message. Otherwise, these headers will be hidden and
58 `notmuch-show-toggle-headers' can be used to make the visible for
59 any given message."
60   :group 'notmuch
61   :type 'boolean)
62
63 (defcustom notmuch-show-relative-dates t
64   "Display relative dates in the message summary line."
65   :group 'notmuch
66   :type 'boolean)
67
68 (defcustom notmuch-show-elide-same-subject nil
69   "Do not show the subject of a collapsed message if it is the
70 same as that of the previous message."
71   :group 'notmuch
72   :type 'boolean)
73
74 (defcustom notmuch-show-always-show-subject t
75   "Should a collapsed message show the `Subject:' line?"
76   :group 'notmuch
77   :type 'boolean)
78
79 (defvar notmuch-show-markup-headers-hook '(notmuch-show-colour-headers)
80   "A list of functions called to decorate the headers listed in
81 `notmuch-message-headers'.")
82
83 (defcustom notmuch-show-hook nil
84   "Functions called after populating a `notmuch-show' buffer."
85   :group 'notmuch
86   :type 'hook)
87
88 (defcustom notmuch-show-insert-text/plain-hook '(notmuch-wash-excerpt-citations)
89   "Functions used to improve the display of text/plain parts."
90   :group 'notmuch
91   :type 'hook
92   :options '(notmuch-wash-convert-inline-patch-to-part
93              notmuch-wash-wrap-long-lines
94              notmuch-wash-tidy-citations
95              notmuch-wash-elide-blank-lines
96              notmuch-wash-excerpt-citations))
97
98 ;; Mostly useful for debugging.
99 (defcustom notmuch-show-all-multipart/alternative-parts nil
100   "Should all parts of multipart/alternative parts be shown?"
101   :group 'notmuch
102   :type 'boolean)
103
104 (defcustom notmuch-show-indent-multipart nil
105   "Should the sub-parts of a multipart/* part be indented?"
106   ;; dme: Not sure which is a good default.
107   :group 'notmuch
108   :type 'boolean)
109
110 (defmacro with-current-notmuch-show-message (&rest body)
111   "Evaluate body with current buffer set to the text of current message"
112   `(save-excursion
113      (let ((id (notmuch-show-get-message-id)))
114        (let ((buf (generate-new-buffer (concat "*notmuch-msg-" id "*"))))
115          (with-current-buffer buf
116             (call-process notmuch-command nil t nil "show" "--format=raw" id)
117            ,@body)
118          (kill-buffer buf)))))
119
120 (defun notmuch-show-view-all-mime-parts ()
121   "Use external viewers to view all attachments from the current message."
122   (interactive)
123   (with-current-notmuch-show-message
124    ; We ovverride the mm-inline-media-tests to indicate which message
125    ; parts are already sufficiently handled by the original
126    ; presentation of the message in notmuch-show mode. These parts
127    ; will be inserted directly into the temporary buffer of
128    ; with-current-notmuch-show-message and silently discarded.
129    ;
130    ; Any MIME part not explicitly mentioned here will be handled by an
131    ; external viewer as configured in the various mailcap files.
132    (let ((mm-inline-media-tests '(
133                                   ("text/.*" ignore identity)
134                                   ("application/pgp-signature" ignore identity)
135                                   ("multipart/alternative" ignore identity)
136                                   ("multipart/mixed" ignore identity)
137                                   ("multipart/related" ignore identity)
138                                  )))
139      (mm-display-parts (mm-dissect-buffer)))))
140
141 (defun notmuch-foreach-mime-part (function mm-handle)
142   (cond ((stringp (car mm-handle))
143          (dolist (part (cdr mm-handle))
144            (notmuch-foreach-mime-part function part)))
145         ((bufferp (car mm-handle))
146          (funcall function mm-handle))
147         (t (dolist (part mm-handle)
148              (notmuch-foreach-mime-part function part)))))
149
150 (defun notmuch-count-attachments (mm-handle)
151   (let ((count 0))
152     (notmuch-foreach-mime-part
153      (lambda (p)
154        (let ((disposition (mm-handle-disposition p)))
155          (and (listp disposition)
156               (or (equal (car disposition) "attachment")
157                   (and (equal (car disposition) "inline")
158                        (assq 'filename disposition)))
159               (incf count))))
160      mm-handle)
161     count))
162
163 (defun notmuch-save-attachments (mm-handle &optional queryp)
164   (notmuch-foreach-mime-part
165    (lambda (p)
166      (let ((disposition (mm-handle-disposition p)))
167        (and (listp disposition)
168             (or (equal (car disposition) "attachment")
169                 (and (equal (car disposition) "inline")
170                      (assq 'filename disposition)))
171             (or (not queryp)
172                 (y-or-n-p
173                  (concat "Save '" (cdr (assq 'filename disposition)) "' ")))
174             (mm-save-part p))))
175    mm-handle))
176
177 (defun notmuch-show-save-attachments ()
178   "Save all attachments from the current message."
179   (interactive)
180   (with-current-notmuch-show-message
181    (let ((mm-handle (mm-dissect-buffer)))
182      (notmuch-save-attachments
183       mm-handle (> (notmuch-count-attachments mm-handle) 1))))
184   (message "Done"))
185
186 (defun notmuch-show-fontify-header ()
187   (let ((face (cond
188                ((looking-at "[Tt]o:")
189                 'message-header-to)
190                ((looking-at "[Bb]?[Cc][Cc]:")
191                 'message-header-cc)
192                ((looking-at "[Ss]ubject:")
193                 'message-header-subject)
194                ((looking-at "[Ff]rom:")
195                 'message-header-from)
196                (t
197                 'message-header-other))))
198
199     (overlay-put (make-overlay (point) (re-search-forward ":"))
200                  'face 'message-header-name)
201     (overlay-put (make-overlay (point) (re-search-forward ".*$"))
202                  'face face)))
203
204 (defun notmuch-show-colour-headers ()
205   "Apply some colouring to the current headers."
206   (goto-char (point-min))
207   (while (looking-at "^[A-Za-z][-A-Za-z0-9]*:")
208     (notmuch-show-fontify-header)
209     (forward-line)))
210
211 (defun notmuch-show-spaces-n (n)
212   "Return a string comprised of `n' spaces."
213   (make-string n ? ))
214
215 (defun notmuch-show-update-tags (tags)
216   "Update the displayed tags of the current message."
217   (save-excursion
218     (goto-char (notmuch-show-message-top))
219     (if (re-search-forward "(\\([^()]*\\))$" (line-end-position) t)
220         (let ((inhibit-read-only t))
221           (replace-match (concat "("
222                                  (propertize (mapconcat 'identity tags " ")
223                                              'face 'notmuch-tag-face)
224                                  ")"))))))
225
226 (defun notmuch-show-clean-address (address)
227   "Clean a single email address for display."
228   (let* ((parsed (mail-header-parse-address address))
229          (address (car parsed))
230          (name (cdr parsed)))
231     ;; Remove double quotes. They might be required during transport,
232     ;; but we don't need to see them.
233     (when name
234       (setq name (replace-regexp-in-string "\"" "" name)))
235     ;; If the address is 'foo@bar.com <foo@bar.com>' then show just
236     ;; 'foo@bar.com'.
237     (when (string= name address)
238       (setq name nil))
239
240     (if (not name)
241         address
242       (concat name " <" address ">"))))
243
244 (defun notmuch-show-insert-headerline (headers date tags depth)
245   "Insert a notmuch style headerline based on HEADERS for a
246 message at DEPTH in the current thread."
247   (let ((start (point)))
248     (insert (notmuch-show-spaces-n depth)
249             (notmuch-show-clean-address (plist-get headers :From))
250             " ("
251             date
252             ") ("
253             (propertize (mapconcat 'identity tags " ")
254                         'face 'notmuch-tag-face)
255             ")\n")
256     (overlay-put (make-overlay start (point)) 'face 'notmuch-message-summary-face)))
257
258 (defun notmuch-show-insert-header (header header-value)
259   "Insert a single header."
260   (insert header ": " header-value "\n"))
261
262 (defun notmuch-show-insert-headers (headers)
263   "Insert the headers of the current message."
264   (let ((start (point)))
265     (mapc '(lambda (header)
266              (let* ((header-symbol (intern (concat ":" header)))
267                     (header-value (plist-get headers header-symbol)))
268                (if (and header-value
269                         (not (string-equal "" header-value)))
270                    (notmuch-show-insert-header header header-value))))
271           notmuch-message-headers)
272     (save-excursion
273       (save-restriction
274         (narrow-to-region start (point-max))
275         (run-hooks 'notmuch-show-markup-headers-hook)))))
276
277 (define-button-type 'notmuch-show-part-button-type
278   'action 'notmuch-show-part-button-action
279   'follow-link t
280   'face 'message-mml)
281
282 (defun notmuch-show-insert-part-header (nth content-type declared-type &optional name comment)
283   (insert-button
284    (concat "[ "
285            (if name (concat name ": ") "")
286            declared-type
287            (if (not (string-equal declared-type content-type))
288                (concat " (as " content-type ")")
289              "")
290            (or comment "")
291            " ]\n")
292    :type 'notmuch-show-part-button-type
293    :notmuch-part nth
294    :notmuch-filename name))
295
296 ;; Functions handling particular MIME parts.
297
298 (defun notmuch-show-save-part (message-id nth &optional filename)
299   (let ((process-crypto notmuch-show-process-crypto))
300     (with-temp-buffer
301       (setq notmuch-show-process-crypto process-crypto)
302       ;; Always acquires the part via `notmuch part', even if it is
303       ;; available in the JSON output.
304       (insert (notmuch-show-get-bodypart-internal message-id nth))
305       (let ((file (read-file-name
306                    "Filename to save as: "
307                    (or mailcap-download-directory "~/")
308                    nil nil
309                    filename))
310             (require-final-newline nil)
311             (coding-system-for-write 'no-conversion))
312         (write-region (point-min) (point-max) file)))))
313
314 (defun notmuch-show-mm-display-part-inline (msg part content-type content)
315   "Use the mm-decode/mm-view functions to display a part in the
316 current buffer, if possible."
317   (let ((display-buffer (current-buffer)))
318     (with-temp-buffer
319       (insert content)
320       (let ((handle (mm-make-handle (current-buffer) (list content-type))))
321         (set-buffer display-buffer)
322         (if (and (mm-inlinable-p handle)
323                  (mm-inlined-p handle))
324             (progn
325               (mm-display-part handle)
326               t)
327           nil)))))
328
329 (defvar notmuch-show-multipart/alternative-discouraged
330   '(
331     ;; Avoid HTML parts.
332     "text/html"
333     ;; multipart/related usually contain a text/html part and some associated graphics.
334     "multipart/related"
335     ))
336
337 (defun notmuch-show-multipart/*-to-list (part)
338   (mapcar '(lambda (inner-part) (plist-get inner-part :content-type))
339           (plist-get part :content)))
340
341 (defun notmuch-show-multipart/alternative-choose (types)
342   ;; Based on `mm-preferred-alternative-precedence'.
343   (let ((seq types))
344     (dolist (pref (reverse notmuch-show-multipart/alternative-discouraged))
345       (dolist (elem (copy-sequence seq))
346         (when (string-match pref elem)
347           (setq seq (nconc (delete elem seq) (list elem))))))
348     seq))
349
350 (defun notmuch-show-insert-part-multipart/alternative (msg part content-type nth depth declared-type)
351   (notmuch-show-insert-part-header nth declared-type content-type nil)
352   (let ((chosen-type (car (notmuch-show-multipart/alternative-choose (notmuch-show-multipart/*-to-list part))))
353         (inner-parts (plist-get part :content))
354         (start (point)))
355     ;; This inserts all parts of the chosen type rather than just one,
356     ;; but it's not clear that this is the wrong thing to do - which
357     ;; should be chosen if there are more than one that match?
358     (mapc (lambda (inner-part)
359             (let ((inner-type (plist-get inner-part :content-type)))
360               (if (or notmuch-show-all-multipart/alternative-parts
361                       (string= chosen-type inner-type))
362                   (notmuch-show-insert-bodypart msg inner-part depth)
363                 (notmuch-show-insert-part-header (plist-get inner-part :id) inner-type inner-type nil " (not shown)"))))
364           inner-parts)
365
366     (when notmuch-show-indent-multipart
367       (indent-rigidly start (point) 1)))
368   t)
369
370 (defun notmuch-show-setup-w3m ()
371   "Instruct w3m how to retrieve content from a \"related\" part of a message."
372   (interactive)
373   (if (boundp 'w3m-cid-retrieve-function-alist)
374     (unless (assq 'notmuch-show-mode w3m-cid-retrieve-function-alist)
375       (push (cons 'notmuch-show-mode 'notmuch-show-w3m-cid-retrieve)
376             w3m-cid-retrieve-function-alist)))
377   (setq mm-inline-text-html-with-images t))
378
379 (defvar w3m-current-buffer) ;; From `w3m.el'.
380 (defvar notmuch-show-w3m-cid-store nil)
381 (make-variable-buffer-local 'notmuch-show-w3m-cid-store)
382
383 (defun notmuch-show-w3m-cid-store-internal (content-id
384                                             message-id
385                                             part-number
386                                             content-type
387                                             content)
388   (push (list content-id
389               message-id
390               part-number
391               content-type
392               content)
393         notmuch-show-w3m-cid-store))
394
395 (defun notmuch-show-w3m-cid-store (msg part)
396   (let ((content-id (plist-get part :content-id)))
397     (when content-id
398       (notmuch-show-w3m-cid-store-internal (concat "cid:" content-id)
399                                            (plist-get msg :id)
400                                            (plist-get part :id)
401                                            (plist-get part :content-type)
402                                            nil))))
403
404 (defun notmuch-show-w3m-cid-retrieve (url &rest args)
405   (let ((matching-part (with-current-buffer w3m-current-buffer
406                          (assoc url notmuch-show-w3m-cid-store))))
407     (if matching-part
408         (let ((message-id (nth 1 matching-part))
409               (part-number (nth 2 matching-part))
410               (content-type (nth 3 matching-part))
411               (content (nth 4 matching-part)))
412           ;; If we don't already have the content, get it and cache
413           ;; it, as some messages reference the same cid: part many
414           ;; times (hundreds!), which results in many calls to
415           ;; `notmuch part'.
416           (unless content
417             (setq content (notmuch-show-get-bodypart-internal (concat "id:" message-id)
418                                                               part-number))
419             (with-current-buffer w3m-current-buffer
420               (notmuch-show-w3m-cid-store-internal url
421                                                    message-id
422                                                    part-number
423                                                    content-type
424                                                    content)))
425           (insert content)
426           content-type)
427       nil)))
428
429 (defun notmuch-show-insert-part-multipart/related (msg part content-type nth depth declared-type)
430   (notmuch-show-insert-part-header nth declared-type content-type nil)
431   (let ((inner-parts (plist-get part :content))
432         (start (point)))
433
434     ;; We assume that the first part is text/html and the remainder
435     ;; things that it references.
436
437     ;; Stash the non-primary parts.
438     (mapc (lambda (part)
439             (notmuch-show-w3m-cid-store msg part))
440           (cdr inner-parts))
441
442     ;; Render the primary part.
443     (notmuch-show-insert-bodypart msg (car inner-parts) depth)
444
445     (when notmuch-show-indent-multipart
446       (indent-rigidly start (point) 1)))
447   t)
448
449 (defun notmuch-show-insert-part-multipart/* (msg part content-type nth depth declared-type)
450   (notmuch-show-insert-part-header nth declared-type content-type nil)
451   (let ((inner-parts (plist-get part :content))
452         (start (point)))
453     ;; Show all of the parts.
454     (mapc (lambda (inner-part)
455             (notmuch-show-insert-bodypart msg inner-part depth))
456           inner-parts)
457
458     (when notmuch-show-indent-multipart
459       (indent-rigidly start (point) 1)))
460   t)
461
462 (defun notmuch-show-insert-part-message/rfc822 (msg part content-type nth depth declared-type)
463   (let* ((message-part (plist-get part :content))
464          (inner-parts (plist-get message-part :content)))
465     (notmuch-show-insert-part-header nth declared-type content-type nil)
466     ;; Override `notmuch-message-headers' to force `From' to be
467     ;; displayed.
468     (let ((notmuch-message-headers '("From" "Subject" "To" "Cc" "Date")))
469       (notmuch-show-insert-headers (plist-get part :headers)))
470     ;; Blank line after headers to be compatible with the normal
471     ;; message display.
472     (insert "\n")
473
474     ;; Show all of the parts.
475     (mapc (lambda (inner-part)
476             (notmuch-show-insert-bodypart msg inner-part depth))
477           inner-parts))
478   t)
479
480 (defun notmuch-show-insert-part-text/plain (msg part content-type nth depth declared-type)
481   (let ((start (point)))
482     ;; If this text/plain part is not the first part in the message,
483     ;; insert a header to make this clear.
484     (if (> nth 1)
485         (notmuch-show-insert-part-header nth declared-type content-type (plist-get part :filename)))
486     (insert (notmuch-show-get-bodypart-content msg part nth))
487     (save-excursion
488       (save-restriction
489         (narrow-to-region start (point-max))
490         (run-hook-with-args 'notmuch-show-insert-text/plain-hook depth))))
491   t)
492
493 (defun notmuch-show-insert-part-text/x-vcalendar (msg part content-type nth depth declared-type)
494   (notmuch-show-insert-part-header nth declared-type content-type (plist-get part :filename))
495   (insert (with-temp-buffer
496             (insert (notmuch-show-get-bodypart-content msg part nth))
497             (goto-char (point-min))
498             (let ((file (make-temp-file "notmuch-ical"))
499                   result)
500               (icalendar--convert-ical-to-diary
501                (icalendar--read-element nil nil)
502                file t)
503               (set-buffer (get-file-buffer file))
504               (setq result (buffer-substring (point-min) (point-max)))
505               (set-buffer-modified-p nil)
506               (kill-buffer (current-buffer))
507               (delete-file file)
508               result)))
509   t)
510
511 (defun notmuch-show-insert-part-application/octet-stream (msg part content-type nth depth declared-type)
512   ;; If we can deduce a MIME type from the filename of the attachment,
513   ;; do so and pass it on to the handler for that type.
514   (if (plist-get part :filename)
515       (let ((extension (file-name-extension (plist-get part :filename)))
516             mime-type)
517         (if extension
518             (progn
519               (mailcap-parse-mimetypes)
520               (setq mime-type (mailcap-extension-to-mime extension))
521               (if (and mime-type
522                        (not (string-equal mime-type "application/octet-stream")))
523                   (notmuch-show-insert-bodypart-internal msg part mime-type nth depth content-type)
524                 nil))
525           nil))))
526
527 (defun notmuch-show-insert-part-*/* (msg part content-type nth depth declared-type)
528   ;; This handler _must_ succeed - it is the handler of last resort.
529   (notmuch-show-insert-part-header nth content-type declared-type (plist-get part :filename))
530   (let ((content (notmuch-show-get-bodypart-content msg part nth)))
531     (if content
532         (notmuch-show-mm-display-part-inline msg part content-type content)))
533   t)
534
535 ;; Functions for determining how to handle MIME parts.
536
537 (defun notmuch-show-split-content-type (content-type)
538   (split-string content-type "/"))
539
540 (defun notmuch-show-handlers-for (content-type)
541   "Return a list of content handlers for a part of type CONTENT-TYPE."
542   (let (result)
543     (mapc (lambda (func)
544             (if (functionp func)
545                 (push func result)))
546           ;; Reverse order of prefrence.
547           (list (intern (concat "notmuch-show-insert-part-*/*"))
548                 (intern (concat
549                          "notmuch-show-insert-part-"
550                          (car (notmuch-show-split-content-type content-type))
551                          "/*"))
552                 (intern (concat "notmuch-show-insert-part-" content-type))))
553     result))
554
555 ;; Helper for parts which are generally not included in the default
556 ;; JSON output.
557 ;; Uses the buffer-local variable notmuch-show-process-crypto to
558 ;; determine if parts should be decrypted first.
559 (defun notmuch-show-get-bodypart-internal (message-id part-number)
560   (let ((args '("show" "--format=raw"))
561         (part-arg (format "--part=%s" part-number)))
562     (setq args (append args (list part-arg)))
563     (if notmuch-show-process-crypto
564         (setq args (append args '("--decrypt"))))
565     (setq args (append args (list message-id)))
566     (with-temp-buffer
567       (let ((coding-system-for-read 'no-conversion))
568         (progn
569           (apply 'call-process (append (list notmuch-command nil (list t nil) nil) args))
570           (buffer-string))))))
571
572 (defun notmuch-show-get-bodypart-content (msg part nth)
573   (or (plist-get part :content)
574       (notmuch-show-get-bodypart-internal (concat "id:" (plist-get msg :id)) nth)))
575
576 ;; \f
577
578 (defun notmuch-show-insert-bodypart-internal (msg part content-type nth depth declared-type)
579   (let ((handlers (notmuch-show-handlers-for content-type)))
580     ;; Run the content handlers until one of them returns a non-nil
581     ;; value.
582     (while (and handlers
583                 (not (funcall (car handlers) msg part content-type nth depth declared-type)))
584       (setq handlers (cdr handlers))))
585   t)
586
587 (defun notmuch-show-insert-bodypart (msg part depth)
588   "Insert the body part PART at depth DEPTH in the current thread."
589   (let ((content-type (downcase (plist-get part :content-type)))
590         (nth (plist-get part :id)))
591     ;; add encryption status button if encstatus specified
592     (if (plist-member part :encstatus)
593         (let* ((encstatus (car (plist-get part :encstatus))))
594           (notmuch-crypto-insert-encstatus-button encstatus)))
595     ;; add signature status button if sigstatus specified
596     (if (plist-member part :sigstatus)
597         (let* ((headers (plist-get msg :headers))
598                (from (plist-get headers :From))
599                (sigstatus (car (plist-get part :sigstatus))))
600           (notmuch-crypto-insert-sigstatus-button sigstatus from)))
601     (notmuch-show-insert-bodypart-internal msg part content-type nth depth content-type))
602   ;; Some of the body part handlers leave point somewhere up in the
603   ;; part, so we make sure that we're down at the end.
604   (goto-char (point-max))
605   ;; Ensure that the part ends with a carriage return.
606   (if (not (bolp))
607       (insert "\n")))
608
609 (defun notmuch-show-insert-body (msg body depth)
610   "Insert the body BODY at depth DEPTH in the current thread."
611   (mapc '(lambda (part) (notmuch-show-insert-bodypart msg part depth)) body))
612
613 (defun notmuch-show-make-symbol (type)
614   (make-symbol (concat "notmuch-show-" type)))
615
616 (defun notmuch-show-strip-re (string)
617   (replace-regexp-in-string "\\([Rr]e: *\\)+" "" string))
618
619 (defvar notmuch-show-previous-subject "")
620 (make-variable-buffer-local 'notmuch-show-previous-subject)
621
622 (defun notmuch-show-insert-msg (msg depth)
623   "Insert the message MSG at depth DEPTH in the current thread."
624   (let* ((headers (plist-get msg :headers))
625          ;; Indentation causes the buffer offset of the start/end
626          ;; points to move, so we must use markers.
627          message-start message-end
628          content-start content-end
629          headers-start headers-end
630          body-start body-end
631          (headers-invis-spec (notmuch-show-make-symbol "header"))
632          (message-invis-spec (notmuch-show-make-symbol "message"))
633          (bare-subject (notmuch-show-strip-re (plist-get headers :Subject))))
634
635     ;; Set `buffer-invisibility-spec' to `nil' (a list), otherwise
636     ;; removing items from `buffer-invisibility-spec' (which is what
637     ;; `notmuch-show-headers-visible' and
638     ;; `notmuch-show-message-visible' do) is a no-op and has no
639     ;; effect. This caused threads with only matching messages to have
640     ;; those messages hidden initially because
641     ;; `buffer-invisibility-spec' stayed `t'.
642     ;;
643     ;; This needs to be set here (rather than just above the call to
644     ;; `notmuch-show-headers-visible') because some of the part
645     ;; rendering or body washing functions
646     ;; (e.g. `notmuch-wash-text/plain-citations') manipulate
647     ;; `buffer-invisibility-spec').
648     (when (eq buffer-invisibility-spec t)
649       (setq buffer-invisibility-spec nil))
650
651     (setq message-start (point-marker))
652
653     (notmuch-show-insert-headerline headers
654                                     (or (if notmuch-show-relative-dates
655                                             (plist-get msg :date_relative)
656                                           nil)
657                                         (plist-get headers :Date))
658                                     (plist-get msg :tags) depth)
659
660     (setq content-start (point-marker))
661
662     ;; Set `headers-start' to point after the 'Subject:' header to be
663     ;; compatible with the existing implementation. This just sets it
664     ;; to after the first header.
665     (notmuch-show-insert-headers headers)
666     ;; Headers should include a blank line (backwards compatibility).
667     (insert "\n")
668     (save-excursion
669       (goto-char content-start)
670       ;; If the subject of this message is the same as that of the
671       ;; previous message, don't display it when this message is
672       ;; collapsed.
673       (when (and notmuch-show-elide-same-subject
674                  (not (string= notmuch-show-previous-subject
675                                bare-subject)))
676         (forward-line 1))
677       (setq headers-start (point-marker)))
678     (setq headers-end (point-marker))
679
680     (setq notmuch-show-previous-subject bare-subject)
681
682     (setq body-start (point-marker))
683     (notmuch-show-insert-body msg (plist-get msg :body) depth)
684     ;; Ensure that the body ends with a newline.
685     (if (not (bolp))
686         (insert "\n"))
687     (setq body-end (point-marker))
688     (setq content-end (point-marker))
689
690     ;; Indent according to the depth in the thread.
691     (indent-rigidly content-start content-end depth)
692
693     (setq message-end (point-max-marker))
694
695     ;; Save the extents of this message over the whole text of the
696     ;; message.
697     (put-text-property message-start message-end :notmuch-message-extent (cons message-start message-end))
698
699     (plist-put msg :headers-invis-spec headers-invis-spec)
700     (overlay-put (make-overlay headers-start headers-end) 'invisible headers-invis-spec)
701
702     (plist-put msg :message-invis-spec message-invis-spec)
703     (overlay-put (make-overlay body-start body-end) 'invisible message-invis-spec)
704
705     ;; Save the properties for this message. Currently this saves the
706     ;; entire message (augmented it with other stuff), which seems
707     ;; like overkill. We might save a reduced subset (for example, not
708     ;; the content).
709     (notmuch-show-set-message-properties msg)
710
711     ;; Set header visibility.
712     (notmuch-show-headers-visible msg notmuch-message-headers-visible)
713
714     ;; Message visibility depends on whether it matched the search
715     ;; criteria.
716     (notmuch-show-message-visible msg (plist-get msg :match))))
717
718 (defun notmuch-show-insert-tree (tree depth)
719   "Insert the message tree TREE at depth DEPTH in the current thread."
720   (let ((msg (car tree))
721         (replies (cadr tree)))
722     (notmuch-show-insert-msg msg depth)
723     (notmuch-show-insert-thread replies (1+ depth))))
724
725 (defun notmuch-show-insert-thread (thread depth)
726   "Insert the thread THREAD at depth DEPTH in the current forest."
727   (mapc '(lambda (tree) (notmuch-show-insert-tree tree depth)) thread))
728
729 (defun notmuch-show-insert-forest (forest)
730   "Insert the forest of threads FOREST."
731   (mapc '(lambda (thread) (notmuch-show-insert-thread thread 0)) forest))
732
733 (defvar notmuch-show-parent-buffer nil)
734 (make-variable-buffer-local 'notmuch-show-parent-buffer)
735
736 ;;;###autoload
737 (defun notmuch-show (thread-id &optional parent-buffer query-context buffer-name crypto-switch)
738   "Run \"notmuch show\" with the given thread ID and display results.
739
740 The optional PARENT-BUFFER is the notmuch-search buffer from
741 which this notmuch-show command was executed, (so that the
742 next thread from that buffer can be show when done with this
743 one).
744
745 The optional QUERY-CONTEXT is a notmuch search term. Only
746 messages from the thread matching this search term are shown if
747 non-nil.
748
749 The optional BUFFER-NAME provides the neame of the buffer in
750 which the message thread is shown. If it is nil (which occurs
751 when the command is called interactively) the argument to the
752 function is used. "
753   (interactive "sNotmuch show: ")
754   (let ((buffer (get-buffer-create (generate-new-buffer-name
755                                     (or buffer-name
756                                         (concat "*notmuch-" thread-id "*")))))
757         (process-crypto (if crypto-switch
758                             (not notmuch-crypto-process-mime)
759                           notmuch-crypto-process-mime))
760         (inhibit-read-only t))
761     (switch-to-buffer buffer)
762     (notmuch-show-mode)
763     (setq notmuch-show-parent-buffer parent-buffer)
764     (setq notmuch-show-process-crypto process-crypto)
765     (erase-buffer)
766     (goto-char (point-min))
767     (save-excursion
768       (let* ((basic-args (list thread-id))
769              (args (if query-context
770                        (append (list "\'") basic-args (list "and (" query-context ")\'"))
771                      (append (list "\'") basic-args (list "\'")))))
772         (notmuch-show-insert-forest (notmuch-query-get-threads args))
773         ;; If the query context reduced the results to nothing, run
774         ;; the basic query.
775         (when (and (eq (buffer-size) 0)
776                    query-context)
777           (notmuch-show-insert-forest
778            (notmuch-query-get-threads basic-args))))
779
780       ;; Enable buttonisation of URLs and email addresses in the
781       ;; buffer.
782       (goto-address-mode t)
783       ;; Act on visual lines rather than logical lines.
784       (visual-line-mode t)
785
786       (run-hooks 'notmuch-show-hook))
787
788     ;; Move straight to the first open message
789     (if (not (notmuch-show-message-visible-p))
790         (notmuch-show-next-open-message))
791
792     ;; Set the header line to the subject of the first open message.
793     (setq header-line-format (notmuch-show-strip-re (notmuch-show-get-subject)))
794
795     (notmuch-show-mark-read)))
796
797 (defvar notmuch-show-stash-map
798   (let ((map (make-sparse-keymap)))
799     (define-key map "c" 'notmuch-show-stash-cc)
800     (define-key map "d" 'notmuch-show-stash-date)
801     (define-key map "F" 'notmuch-show-stash-filename)
802     (define-key map "f" 'notmuch-show-stash-from)
803     (define-key map "i" 'notmuch-show-stash-message-id)
804     (define-key map "s" 'notmuch-show-stash-subject)
805     (define-key map "T" 'notmuch-show-stash-tags)
806     (define-key map "t" 'notmuch-show-stash-to)
807     map)
808   "Submap for stash commands")
809 (fset 'notmuch-show-stash-map notmuch-show-stash-map)
810
811 (defvar notmuch-show-mode-map
812       (let ((map (make-sparse-keymap)))
813         (define-key map "?" 'notmuch-help)
814         (define-key map "q" 'notmuch-kill-this-buffer)
815         (define-key map (kbd "<C-tab>") 'widget-backward)
816         (define-key map (kbd "M-TAB") 'notmuch-show-previous-button)
817         (define-key map (kbd "<backtab>") 'notmuch-show-previous-button)
818         (define-key map (kbd "TAB") 'notmuch-show-next-button)
819         (define-key map "s" 'notmuch-search)
820         (define-key map "m" 'notmuch-mua-new-mail)
821         (define-key map "f" 'notmuch-show-forward-message)
822         (define-key map "r" 'notmuch-show-reply)
823         (define-key map "|" 'notmuch-show-pipe-message)
824         (define-key map "w" 'notmuch-show-save-attachments)
825         (define-key map "V" 'notmuch-show-view-raw-message)
826         (define-key map "v" 'notmuch-show-view-all-mime-parts)
827         (define-key map "c" 'notmuch-show-stash-map)
828         (define-key map "h" 'notmuch-show-toggle-headers)
829         (define-key map "-" 'notmuch-show-remove-tag)
830         (define-key map "+" 'notmuch-show-add-tag)
831         (define-key map "x" 'notmuch-show-archive-thread-then-exit)
832         (define-key map "a" 'notmuch-show-archive-thread)
833         (define-key map "N" 'notmuch-show-next-message)
834         (define-key map "P" 'notmuch-show-previous-message)
835         (define-key map "n" 'notmuch-show-next-open-message)
836         (define-key map "p" 'notmuch-show-previous-open-message)
837         (define-key map (kbd "DEL") 'notmuch-show-rewind)
838         (define-key map " " 'notmuch-show-advance-and-archive)
839         (define-key map (kbd "M-RET") 'notmuch-show-open-or-close-all)
840         (define-key map (kbd "RET") 'notmuch-show-toggle-message)
841         map)
842       "Keymap for \"notmuch show\" buffers.")
843 (fset 'notmuch-show-mode-map notmuch-show-mode-map)
844
845 (defun notmuch-show-mode ()
846   "Major mode for viewing a thread with notmuch.
847
848 This buffer contains the results of the \"notmuch show\" command
849 for displaying a single thread of email from your email archives.
850
851 By default, various components of email messages, (citations,
852 signatures, already-read messages), are hidden. You can make
853 these parts visible by clicking with the mouse button or by
854 pressing RET after positioning the cursor on a hidden part, (for
855 which \\[notmuch-show-next-button] and \\[notmuch-show-previous-button] are helpful).
856
857 Reading the thread sequentially is well-supported by pressing
858 \\[notmuch-show-advance-and-archive]. This will scroll the current message (if necessary), advance
859 to the next message, or advance to the next thread (if already on
860 the last message of a thread).
861
862 Other commands are available to read or manipulate the thread
863 more selectively, (such as '\\[notmuch-show-next-message]' and '\\[notmuch-show-previous-message]' to advance to messages
864 without removing any tags, and '\\[notmuch-show-archive-thread]' to archive an entire thread
865 without scrolling through with \\[notmuch-show-advance-and-archive]).
866
867 You can add or remove arbitary tags from the current message with
868 '\\[notmuch-show-add-tag]' or '\\[notmuch-show-remove-tag]'.
869
870 All currently available key bindings:
871
872 \\{notmuch-show-mode-map}"
873   (interactive)
874   (kill-all-local-variables)
875   (use-local-map notmuch-show-mode-map)
876   (setq major-mode 'notmuch-show-mode
877         mode-name "notmuch-show")
878   (setq buffer-read-only t))
879
880 (defun notmuch-show-move-to-message-top ()
881   (goto-char (notmuch-show-message-top)))
882
883 (defun notmuch-show-move-to-message-bottom ()
884   (goto-char (notmuch-show-message-bottom)))
885
886 (defun notmuch-show-message-adjust ()
887   (recenter 0))
888
889 ;; Movement related functions.
890
891 ;; There's some strangeness here where a text property applied to a
892 ;; region a->b is not found when point is at b. We walk backwards
893 ;; until finding the property.
894 (defun notmuch-show-message-extent ()
895   (let (r)
896     (save-excursion
897       (while (not (setq r (get-text-property (point) :notmuch-message-extent)))
898         (backward-char)))
899     r))
900
901 (defun notmuch-show-message-top ()
902   (car (notmuch-show-message-extent)))
903
904 (defun notmuch-show-message-bottom ()
905   (cdr (notmuch-show-message-extent)))
906
907 (defun notmuch-show-goto-message-next ()
908   (let ((start (point)))
909     (notmuch-show-move-to-message-bottom)
910     (if (not (eobp))
911         t
912       (goto-char start)
913       nil)))
914
915 (defun notmuch-show-goto-message-previous ()
916   (notmuch-show-move-to-message-top)
917   (if (bobp)
918       nil
919     (backward-char)
920     (notmuch-show-move-to-message-top)
921     t))
922
923 (defun notmuch-show-move-past-invisible-forward ()
924   (while (point-invisible-p)
925     (forward-char)))
926
927 (defun notmuch-show-move-past-invisible-backward ()
928   (while (point-invisible-p)
929     (backward-char)))
930
931 ;; Functions relating to the visibility of messages and their
932 ;; components.
933
934 (defun notmuch-show-element-visible (props visible-p spec-property)
935   (let ((spec (plist-get props spec-property)))
936     (if visible-p
937         (remove-from-invisibility-spec spec)
938       (add-to-invisibility-spec spec))))
939
940 (defun notmuch-show-message-visible (props visible-p)
941   (if visible-p
942       ;; When making the message visible, the headers may or not be
943       ;; visible. So we check that property separately.
944       (let ((headers-visible (plist-get props :headers-visible)))
945         (notmuch-show-element-visible props headers-visible :headers-invis-spec)
946         (notmuch-show-element-visible props t :message-invis-spec))
947     (notmuch-show-element-visible props nil :headers-invis-spec)
948     (notmuch-show-element-visible props nil :message-invis-spec))
949
950   (notmuch-show-set-prop :message-visible visible-p props))
951
952 (defun notmuch-show-headers-visible (props visible-p)
953   (if (plist-get props :message-visible)
954       (notmuch-show-element-visible props visible-p :headers-invis-spec))
955   (notmuch-show-set-prop :headers-visible visible-p props))
956
957 ;; Functions for setting and getting attributes of the current
958 ;; message.
959
960 (defun notmuch-show-set-message-properties (props)
961   (save-excursion
962     (notmuch-show-move-to-message-top)
963     (put-text-property (point) (+ (point) 1) :notmuch-message-properties props)))
964
965 (defun notmuch-show-get-message-properties ()
966   (save-excursion
967     (notmuch-show-move-to-message-top)
968     (get-text-property (point) :notmuch-message-properties)))
969
970 (defun notmuch-show-set-prop (prop val &optional props)
971   (let ((inhibit-read-only t)
972         (props (or props
973                    (notmuch-show-get-message-properties))))
974     (plist-put props prop val)
975     (notmuch-show-set-message-properties props)))
976
977 (defun notmuch-show-get-prop (prop &optional props)
978   (let ((props (or props
979                    (notmuch-show-get-message-properties))))
980     (plist-get props prop)))
981
982 (defun notmuch-show-get-message-id ()
983   "Return the message id of the current message."
984   (concat "id:\"" (notmuch-show-get-prop :id) "\""))
985
986 ;; dme: Would it make sense to use a macro for many of these?
987
988 (defun notmuch-show-get-filename ()
989   "Return the filename of the current message."
990   (notmuch-show-get-prop :filename))
991
992 (defun notmuch-show-get-header (header)
993   "Return the named header of the current message, if any."
994   (plist-get (notmuch-show-get-prop :headers) header))
995
996 (defun notmuch-show-get-cc ()
997   (notmuch-show-get-header :Cc))
998
999 (defun notmuch-show-get-date ()
1000   (notmuch-show-get-header :Date))
1001
1002 (defun notmuch-show-get-from ()
1003   (notmuch-show-get-header :From))
1004
1005 (defun notmuch-show-get-subject ()
1006   (notmuch-show-get-header :Subject))
1007
1008 (defun notmuch-show-get-to ()
1009   (notmuch-show-get-header :To))
1010
1011 (defun notmuch-show-set-tags (tags)
1012   "Set the tags of the current message."
1013   (notmuch-show-set-prop :tags tags)
1014   (notmuch-show-update-tags tags))
1015
1016 (defun notmuch-show-get-tags ()
1017   "Return the tags of the current message."
1018   (notmuch-show-get-prop :tags))
1019
1020 (defun notmuch-show-message-visible-p ()
1021   "Is the current message visible?"
1022   (notmuch-show-get-prop :message-visible))
1023
1024 (defun notmuch-show-headers-visible-p ()
1025   "Are the headers of the current message visible?"
1026   (notmuch-show-get-prop :headers-visible))
1027
1028 (defun notmuch-show-mark-read ()
1029   "Mark the current message as read."
1030   (notmuch-show-remove-tag "unread"))
1031
1032 ;; Functions for getting attributes of several messages in the current
1033 ;; thread.
1034
1035 (defun notmuch-show-get-message-ids-for-open-messages ()
1036   "Return a list of all message IDs for open messages in the current thread."
1037   (save-excursion
1038     (let (message-ids done)
1039       (goto-char (point-min))
1040       (while (not done)
1041         (if (notmuch-show-message-visible-p)
1042             (setq message-ids (append message-ids (list (notmuch-show-get-message-id)))))
1043         (setq done (not (notmuch-show-goto-message-next)))
1044         )
1045       message-ids
1046       )))
1047
1048 ;; Commands typically bound to keys.
1049
1050 (defun notmuch-show-advance-and-archive ()
1051   "Advance through thread and archive.
1052
1053 This command is intended to be one of the simplest ways to
1054 process a thread of email. It does the following:
1055
1056 If the current message in the thread is not yet fully visible,
1057 scroll by a near screenful to read more of the message.
1058
1059 Otherwise, (the end of the current message is already within the
1060 current window), advance to the next open message.
1061
1062 Finally, if there is no further message to advance to, and this
1063 last message is already read, then archive the entire current
1064 thread, (remove the \"inbox\" tag from each message). Also kill
1065 this buffer, and display the next thread from the search from
1066 which this thread was originally shown."
1067   (interactive)
1068   (let ((end-of-this-message (notmuch-show-message-bottom)))
1069     (cond
1070      ;; Ideally we would test `end-of-this-message' against the result
1071      ;; of `window-end', but that doesn't account for the fact that
1072      ;; the end of the message might be hidden, so we have to actually
1073      ;; go to the end, walk back over invisible text and then see if
1074      ;; point is visible.
1075      ((save-excursion
1076         (goto-char (- end-of-this-message 1))
1077         (notmuch-show-move-past-invisible-backward)
1078         (> (point) (window-end)))
1079       ;; The bottom of this message is not visible - scroll.
1080       (scroll-up nil))
1081
1082      ((not (= end-of-this-message (point-max)))
1083       ;; This is not the last message - move to the next visible one.
1084       (notmuch-show-next-open-message))
1085
1086      (t
1087       ;; This is the last message - archive the thread.
1088       (notmuch-show-archive-thread)))))
1089
1090 (defun notmuch-show-rewind ()
1091   "Backup through the thread, (reverse scrolling compared to \\[notmuch-show-advance-and-archive]).
1092
1093 Specifically, if the beginning of the previous email is fewer
1094 than `window-height' lines from the current point, move to it
1095 just like `notmuch-show-previous-message'.
1096
1097 Otherwise, just scroll down a screenful of the current message.
1098
1099 This command does not modify any message tags, (it does not undo
1100 any effects from previous calls to
1101 `notmuch-show-advance-and-archive'."
1102   (interactive)
1103   (let ((start-of-message (notmuch-show-message-top))
1104         (start-of-window (window-start)))
1105     (cond
1106       ;; Either this message is properly aligned with the start of the
1107       ;; window or the start of this message is not visible on the
1108       ;; screen - scroll.
1109      ((or (= start-of-message start-of-window)
1110           (< start-of-message start-of-window))
1111       (scroll-down)
1112       ;; If a small number of lines from the previous message are
1113       ;; visible, realign so that the top of the current message is at
1114       ;; the top of the screen.
1115       (if (<= (count-screen-lines (window-start) start-of-message)
1116               next-screen-context-lines)
1117           (progn
1118             (goto-char (notmuch-show-message-top))
1119             (notmuch-show-message-adjust)))
1120       ;; Move to the top left of the window.
1121       (goto-char (window-start)))
1122      (t
1123       ;; Move to the previous message.
1124       (notmuch-show-previous-message)))))
1125
1126 (defun notmuch-show-reply (&optional prompt-for-sender)
1127   "Reply to the current message."
1128   (interactive "P")
1129   (notmuch-mua-new-reply (notmuch-show-get-message-id) prompt-for-sender))
1130
1131 (defun notmuch-show-forward-message (&optional prompt-for-sender)
1132   "Forward the current message."
1133   (interactive "P")
1134   (with-current-notmuch-show-message
1135    (notmuch-mua-new-forward-message prompt-for-sender)))
1136
1137 (defun notmuch-show-next-message ()
1138   "Show the next message."
1139   (interactive)
1140   (if (notmuch-show-goto-message-next)
1141       (progn
1142         (notmuch-show-mark-read)
1143         (notmuch-show-message-adjust))
1144     (goto-char (point-max))))
1145
1146 (defun notmuch-show-previous-message ()
1147   "Show the previous message."
1148   (interactive)
1149   (notmuch-show-goto-message-previous)
1150   (notmuch-show-mark-read)
1151   (notmuch-show-message-adjust))
1152
1153 (defun notmuch-show-next-open-message ()
1154   "Show the next message."
1155   (interactive)
1156   (let (r)
1157     (while (and (setq r (notmuch-show-goto-message-next))
1158                 (not (notmuch-show-message-visible-p))))
1159     (if r
1160         (progn
1161           (notmuch-show-mark-read)
1162           (notmuch-show-message-adjust))
1163       (goto-char (point-max)))))
1164
1165 (defun notmuch-show-previous-open-message ()
1166   "Show the previous message."
1167   (interactive)
1168   (while (and (notmuch-show-goto-message-previous)
1169               (not (notmuch-show-message-visible-p))))
1170   (notmuch-show-mark-read)
1171   (notmuch-show-message-adjust))
1172
1173 (defun notmuch-show-view-raw-message ()
1174   "View the file holding the current message."
1175   (interactive)
1176   (let* ((id (notmuch-show-get-message-id))
1177          (buf (get-buffer-create (concat "*notmuch-raw-" id "*"))))
1178     (call-process notmuch-command nil buf nil "show" "--format=raw" id)
1179     (switch-to-buffer buf)
1180     (goto-char (point-min))
1181     (set-buffer-modified-p nil)
1182     (view-buffer buf 'kill-buffer-if-not-modified)))
1183
1184 (defun notmuch-show-pipe-message (entire-thread command)
1185   "Pipe the contents of the current message (or thread) to the given command.
1186
1187 The given command will be executed with the raw contents of the
1188 current email message as stdin. Anything printed by the command
1189 to stdout or stderr will appear in the *notmuch-pipe* buffer.
1190
1191 When invoked with a prefix argument, the command will receive all
1192 open messages in the current thread (formatted as an mbox) rather
1193 than only the current message."
1194   (interactive "P\nsPipe message to command: ")
1195   (let (shell-command)
1196     (if entire-thread
1197         (setq shell-command 
1198               (concat notmuch-command " show --format=mbox "
1199                       (shell-quote-argument
1200                        (mapconcat 'identity (notmuch-show-get-message-ids-for-open-messages) " OR "))
1201                       " | " command))
1202       (setq shell-command
1203             (concat notmuch-command " show --format=raw "
1204                     (shell-quote-argument (notmuch-show-get-message-id)) " | " command)))
1205     (let ((buf (get-buffer-create (concat "*notmuch-pipe*"))))
1206       (with-current-buffer buf
1207         (setq buffer-read-only nil)
1208         (erase-buffer)
1209         (let ((exit-code (call-process-shell-command shell-command nil buf)))
1210           (goto-char (point-max))
1211           (set-buffer-modified-p nil)
1212           (setq buffer-read-only t)
1213           (unless (zerop exit-code)
1214             (switch-to-buffer-other-window buf)
1215             (message (format "Command '%s' exited abnormally with code %d"
1216                              shell-command exit-code))))))))
1217
1218 (defun notmuch-show-add-tags-worker (current-tags add-tags)
1219   "Add to `current-tags' with any tags from `add-tags' not
1220 currently present and return the result."
1221   (let ((result-tags (copy-sequence current-tags)))
1222     (mapc (lambda (add-tag)
1223             (unless (member add-tag current-tags)
1224               (setq result-tags (push add-tag result-tags))))
1225             add-tags)
1226     (sort result-tags 'string<)))
1227
1228 (defun notmuch-show-del-tags-worker (current-tags del-tags)
1229   "Remove any tags in `del-tags' from `current-tags' and return
1230 the result."
1231   (let ((result-tags (copy-sequence current-tags)))
1232     (mapc (lambda (del-tag)
1233             (setq result-tags (delete del-tag result-tags)))
1234           del-tags)
1235     result-tags))
1236
1237 (defun notmuch-show-add-tag (&rest toadd)
1238   "Add a tag to the current message."
1239   (interactive
1240    (list (notmuch-select-tag-with-completion "Tag to add: ")))
1241
1242   (let* ((current-tags (notmuch-show-get-tags))
1243          (new-tags (notmuch-show-add-tags-worker current-tags toadd)))
1244
1245     (unless (equal current-tags new-tags)
1246       (apply 'notmuch-tag (notmuch-show-get-message-id)
1247              (mapcar (lambda (s) (concat "+" s)) toadd))
1248       (notmuch-show-set-tags new-tags))))
1249
1250 (defun notmuch-show-remove-tag (&rest toremove)
1251   "Remove a tag from the current message."
1252   (interactive
1253    (list (notmuch-select-tag-with-completion
1254           "Tag to remove: " (notmuch-show-get-message-id))))
1255
1256   (let* ((current-tags (notmuch-show-get-tags))
1257          (new-tags (notmuch-show-del-tags-worker current-tags toremove)))
1258
1259     (unless (equal current-tags new-tags)
1260       (apply 'notmuch-tag (notmuch-show-get-message-id)
1261              (mapcar (lambda (s) (concat "-" s)) toremove))
1262       (notmuch-show-set-tags new-tags))))
1263
1264 (defun notmuch-show-toggle-headers ()
1265   "Toggle the visibility of the current message headers."
1266   (interactive)
1267   (let ((props (notmuch-show-get-message-properties)))
1268     (notmuch-show-headers-visible
1269      props
1270      (not (plist-get props :headers-visible))))
1271   (force-window-update))
1272
1273 (defun notmuch-show-toggle-message ()
1274   "Toggle the visibility of the current message."
1275   (interactive)
1276   (let ((props (notmuch-show-get-message-properties)))
1277     (notmuch-show-message-visible
1278      props
1279      (not (plist-get props :message-visible))))
1280   (force-window-update))
1281
1282 (defun notmuch-show-open-or-close-all ()
1283   "Set the visibility all of the messages in the current thread.
1284 By default make all of the messages visible. With a prefix
1285 argument, hide all of the messages."
1286   (interactive)
1287   (save-excursion
1288     (goto-char (point-min))
1289     (loop do (notmuch-show-message-visible (notmuch-show-get-message-properties)
1290                                            (not current-prefix-arg))
1291           until (not (notmuch-show-goto-message-next))))
1292   (force-window-update))
1293
1294 (defun notmuch-show-next-button ()
1295   "Advance point to the next button in the buffer."
1296   (interactive)
1297   (forward-button 1))
1298
1299 (defun notmuch-show-previous-button ()
1300   "Move point back to the previous button in the buffer."
1301   (interactive)
1302   (backward-button 1))
1303
1304 (defun notmuch-show-archive-thread-internal (show-next)
1305   ;; Remove the tag from the current set of messages.
1306   (goto-char (point-min))
1307   (loop do (notmuch-show-remove-tag "inbox")
1308         until (not (notmuch-show-goto-message-next)))
1309   ;; Move to the next item in the search results, if any.
1310   (let ((parent-buffer notmuch-show-parent-buffer))
1311     (notmuch-kill-this-buffer)
1312     (if parent-buffer
1313         (progn
1314           (switch-to-buffer parent-buffer)
1315           (forward-line)
1316           (if show-next
1317               (notmuch-search-show-thread))))))
1318
1319 (defun notmuch-show-archive-thread ()
1320   "Archive each message in thread, then show next thread from search.
1321
1322 Archive each message currently shown by removing the \"inbox\"
1323 tag from each. Then kill this buffer and show the next thread
1324 from the search from which this thread was originally shown.
1325
1326 Note: This command is safe from any race condition of new messages
1327 being delivered to the same thread. It does not archive the
1328 entire thread, but only the messages shown in the current
1329 buffer."
1330   (interactive)
1331   (notmuch-show-archive-thread-internal t))
1332
1333 (defun notmuch-show-archive-thread-then-exit ()
1334   "Archive each message in thread, then exit back to search results."
1335   (interactive)
1336   (notmuch-show-archive-thread-internal nil))
1337
1338 (defun notmuch-show-stash-cc ()
1339   "Copy CC field of current message to kill-ring."
1340   (interactive)
1341   (notmuch-common-do-stash (notmuch-show-get-cc)))
1342
1343 (defun notmuch-show-stash-date ()
1344   "Copy date of current message to kill-ring."
1345   (interactive)
1346   (notmuch-common-do-stash (notmuch-show-get-date)))
1347
1348 (defun notmuch-show-stash-filename ()
1349   "Copy filename of current message to kill-ring."
1350   (interactive)
1351   (notmuch-common-do-stash (notmuch-show-get-filename)))
1352
1353 (defun notmuch-show-stash-from ()
1354   "Copy From address of current message to kill-ring."
1355   (interactive)
1356   (notmuch-common-do-stash (notmuch-show-get-from)))
1357
1358 (defun notmuch-show-stash-message-id ()
1359   "Copy message ID of current message to kill-ring."
1360   (interactive)
1361   (notmuch-common-do-stash (notmuch-show-get-message-id)))
1362
1363 (defun notmuch-show-stash-subject ()
1364   "Copy Subject field of current message to kill-ring."
1365   (interactive)
1366   (notmuch-common-do-stash (notmuch-show-get-subject)))
1367
1368 (defun notmuch-show-stash-tags ()
1369   "Copy tags of current message to kill-ring as a comma separated list."
1370   (interactive)
1371   (notmuch-common-do-stash (mapconcat 'identity (notmuch-show-get-tags) ",")))
1372
1373 (defun notmuch-show-stash-to ()
1374   "Copy To address of current message to kill-ring."
1375   (interactive)
1376   (notmuch-common-do-stash (notmuch-show-get-to)))
1377
1378 ;; Commands typically bound to buttons.
1379
1380 (defun notmuch-show-part-button-action (button)
1381   (let ((nth (button-get button :notmuch-part)))
1382     (if nth
1383         (notmuch-show-save-part (notmuch-show-get-message-id) nth
1384                                 (button-get button :notmuch-filename))
1385       (message "Not a valid part (is it a fake part?)."))))
1386
1387 ;;
1388
1389 (provide 'notmuch-show)