]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-show.el
Don't re-compress .gz & al. in notmuch-show-save-part.
[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         ;; Don't re-compress .gz & al.  Arguably we should make
311         ;; `file-name-handler-alist' nil, but that would chop
312         ;; ange-ftp, which is reasonable to use here.
313         (mm-write-region (point-min) (point-max) file nil nil nil 'no-conversion t)))))
314
315 (defun notmuch-show-mm-display-part-inline (msg part content-type content)
316   "Use the mm-decode/mm-view functions to display a part in the
317 current buffer, if possible."
318   (let ((display-buffer (current-buffer)))
319     (with-temp-buffer
320       (insert content)
321       (let ((handle (mm-make-handle (current-buffer) (list content-type))))
322         (set-buffer display-buffer)
323         (if (and (mm-inlinable-p handle)
324                  (mm-inlined-p handle))
325             (progn
326               (mm-display-part handle)
327               t)
328           nil)))))
329
330 (defvar notmuch-show-multipart/alternative-discouraged
331   '(
332     ;; Avoid HTML parts.
333     "text/html"
334     ;; multipart/related usually contain a text/html part and some associated graphics.
335     "multipart/related"
336     ))
337
338 (defun notmuch-show-multipart/*-to-list (part)
339   (mapcar '(lambda (inner-part) (plist-get inner-part :content-type))
340           (plist-get part :content)))
341
342 (defun notmuch-show-multipart/alternative-choose (types)
343   ;; Based on `mm-preferred-alternative-precedence'.
344   (let ((seq types))
345     (dolist (pref (reverse notmuch-show-multipart/alternative-discouraged))
346       (dolist (elem (copy-sequence seq))
347         (when (string-match pref elem)
348           (setq seq (nconc (delete elem seq) (list elem))))))
349     seq))
350
351 (defun notmuch-show-insert-part-multipart/alternative (msg part content-type nth depth declared-type)
352   (notmuch-show-insert-part-header nth declared-type content-type nil)
353   (let ((chosen-type (car (notmuch-show-multipart/alternative-choose (notmuch-show-multipart/*-to-list part))))
354         (inner-parts (plist-get part :content))
355         (start (point)))
356     ;; This inserts all parts of the chosen type rather than just one,
357     ;; but it's not clear that this is the wrong thing to do - which
358     ;; should be chosen if there are more than one that match?
359     (mapc (lambda (inner-part)
360             (let ((inner-type (plist-get inner-part :content-type)))
361               (if (or notmuch-show-all-multipart/alternative-parts
362                       (string= chosen-type inner-type))
363                   (notmuch-show-insert-bodypart msg inner-part depth)
364                 (notmuch-show-insert-part-header (plist-get inner-part :id) inner-type inner-type nil " (not shown)"))))
365           inner-parts)
366
367     (when notmuch-show-indent-multipart
368       (indent-rigidly start (point) 1)))
369   t)
370
371 (defun notmuch-show-setup-w3m ()
372   "Instruct w3m how to retrieve content from a \"related\" part of a message."
373   (interactive)
374   (if (boundp 'w3m-cid-retrieve-function-alist)
375     (unless (assq 'notmuch-show-mode w3m-cid-retrieve-function-alist)
376       (push (cons 'notmuch-show-mode 'notmuch-show-w3m-cid-retrieve)
377             w3m-cid-retrieve-function-alist)))
378   (setq mm-inline-text-html-with-images t))
379
380 (defvar w3m-current-buffer) ;; From `w3m.el'.
381 (defvar notmuch-show-w3m-cid-store nil)
382 (make-variable-buffer-local 'notmuch-show-w3m-cid-store)
383
384 (defun notmuch-show-w3m-cid-store-internal (content-id
385                                             message-id
386                                             part-number
387                                             content-type
388                                             content)
389   (push (list content-id
390               message-id
391               part-number
392               content-type
393               content)
394         notmuch-show-w3m-cid-store))
395
396 (defun notmuch-show-w3m-cid-store (msg part)
397   (let ((content-id (plist-get part :content-id)))
398     (when content-id
399       (notmuch-show-w3m-cid-store-internal (concat "cid:" content-id)
400                                            (plist-get msg :id)
401                                            (plist-get part :id)
402                                            (plist-get part :content-type)
403                                            nil))))
404
405 (defun notmuch-show-w3m-cid-retrieve (url &rest args)
406   (let ((matching-part (with-current-buffer w3m-current-buffer
407                          (assoc url notmuch-show-w3m-cid-store))))
408     (if matching-part
409         (let ((message-id (nth 1 matching-part))
410               (part-number (nth 2 matching-part))
411               (content-type (nth 3 matching-part))
412               (content (nth 4 matching-part)))
413           ;; If we don't already have the content, get it and cache
414           ;; it, as some messages reference the same cid: part many
415           ;; times (hundreds!), which results in many calls to
416           ;; `notmuch part'.
417           (unless content
418             (setq content (notmuch-show-get-bodypart-internal (concat "id:" message-id)
419                                                               part-number))
420             (with-current-buffer w3m-current-buffer
421               (notmuch-show-w3m-cid-store-internal url
422                                                    message-id
423                                                    part-number
424                                                    content-type
425                                                    content)))
426           (insert content)
427           content-type)
428       nil)))
429
430 (defun notmuch-show-insert-part-multipart/related (msg part content-type nth depth declared-type)
431   (notmuch-show-insert-part-header nth declared-type content-type nil)
432   (let ((inner-parts (plist-get part :content))
433         (start (point)))
434
435     ;; We assume that the first part is text/html and the remainder
436     ;; things that it references.
437
438     ;; Stash the non-primary parts.
439     (mapc (lambda (part)
440             (notmuch-show-w3m-cid-store msg part))
441           (cdr inner-parts))
442
443     ;; Render the primary part.
444     (notmuch-show-insert-bodypart msg (car inner-parts) depth)
445
446     (when notmuch-show-indent-multipart
447       (indent-rigidly start (point) 1)))
448   t)
449
450 (defun notmuch-show-insert-part-multipart/signed (msg part content-type nth depth declared-type)
451   (let ((button (notmuch-show-insert-part-header nth declared-type content-type nil)))
452     (button-put button 'face '(:foreground "blue"))
453     ;; add signature status button if sigstatus provided
454     (if (plist-member part :sigstatus)
455         (let* ((headers (plist-get msg :headers))
456                (from (plist-get headers :From))
457                (sigstatus (car (plist-get part :sigstatus))))
458           (notmuch-crypto-insert-sigstatus-button sigstatus from))
459       ;; if we're not adding sigstatus, tell the user how they can get it
460       (button-put button 'help-echo "Set notmuch-crypto-process-mime to process cryptographic mime parts.")))
461
462   (let ((inner-parts (plist-get part :content))
463         (start (point)))
464     ;; Show all of the parts.
465     (mapc (lambda (inner-part)
466             (notmuch-show-insert-bodypart msg inner-part depth))
467           inner-parts)
468
469     (when notmuch-show-indent-multipart
470       (indent-rigidly start (point) 1)))
471   t)
472
473 (defun notmuch-show-insert-part-multipart/encrypted (msg part content-type nth depth declared-type)
474   (let ((button (notmuch-show-insert-part-header nth declared-type content-type nil)))
475     (button-put button 'face '(:foreground "blue"))
476     ;; add encryption status button if encstatus specified
477     (if (plist-member part :encstatus)
478         (let ((encstatus (car (plist-get part :encstatus))))
479           (notmuch-crypto-insert-encstatus-button encstatus)
480           ;; add signature status button if sigstatus specified
481           (if (plist-member part :sigstatus)
482               (let* ((headers (plist-get msg :headers))
483                      (from (plist-get headers :From))
484                      (sigstatus (car (plist-get part :sigstatus))))
485                 (notmuch-crypto-insert-sigstatus-button sigstatus from))))
486       ;; if we're not adding encstatus, tell the user how they can get it
487       (button-put button 'help-echo "Set notmuch-crypto-process-mime to process cryptographic mime parts.")))
488
489   (let ((inner-parts (plist-get part :content))
490         (start (point)))
491     ;; Show all of the parts.
492     (mapc (lambda (inner-part)
493             (notmuch-show-insert-bodypart msg inner-part depth))
494           inner-parts)
495
496     (when notmuch-show-indent-multipart
497       (indent-rigidly start (point) 1)))
498   t)
499
500 (defun notmuch-show-insert-part-multipart/* (msg part content-type nth depth declared-type)
501   (notmuch-show-insert-part-header nth declared-type content-type nil)
502   (let ((inner-parts (plist-get part :content))
503         (start (point)))
504     ;; Show all of the parts.
505     (mapc (lambda (inner-part)
506             (notmuch-show-insert-bodypart msg inner-part depth))
507           inner-parts)
508
509     (when notmuch-show-indent-multipart
510       (indent-rigidly start (point) 1)))
511   t)
512
513 (defun notmuch-show-insert-part-message/rfc822 (msg part content-type nth depth declared-type)
514   (let* ((message-part (plist-get part :content))
515          (inner-parts (plist-get message-part :content)))
516     (notmuch-show-insert-part-header nth declared-type content-type nil)
517     ;; Override `notmuch-message-headers' to force `From' to be
518     ;; displayed.
519     (let ((notmuch-message-headers '("From" "Subject" "To" "Cc" "Date")))
520       (notmuch-show-insert-headers (plist-get part :headers)))
521     ;; Blank line after headers to be compatible with the normal
522     ;; message display.
523     (insert "\n")
524
525     ;; Show all of the parts.
526     (mapc (lambda (inner-part)
527             (notmuch-show-insert-bodypart msg inner-part depth))
528           inner-parts))
529   t)
530
531 (defun notmuch-show-insert-part-text/plain (msg part content-type nth depth declared-type)
532   (let ((start (point)))
533     ;; If this text/plain part is not the first part in the message,
534     ;; insert a header to make this clear.
535     (if (> nth 1)
536         (notmuch-show-insert-part-header nth declared-type content-type (plist-get part :filename)))
537     (insert (notmuch-show-get-bodypart-content msg part nth))
538     (save-excursion
539       (save-restriction
540         (narrow-to-region start (point-max))
541         (run-hook-with-args 'notmuch-show-insert-text/plain-hook depth))))
542   t)
543
544 (defun notmuch-show-insert-part-text/x-vcalendar (msg part content-type nth depth declared-type)
545   (notmuch-show-insert-part-header nth declared-type content-type (plist-get part :filename))
546   (insert (with-temp-buffer
547             (insert (notmuch-show-get-bodypart-content msg part nth))
548             (goto-char (point-min))
549             (let ((file (make-temp-file "notmuch-ical"))
550                   result)
551               (icalendar--convert-ical-to-diary
552                (icalendar--read-element nil nil)
553                file t)
554               (set-buffer (get-file-buffer file))
555               (setq result (buffer-substring (point-min) (point-max)))
556               (set-buffer-modified-p nil)
557               (kill-buffer (current-buffer))
558               (delete-file file)
559               result)))
560   t)
561
562 (defun notmuch-show-insert-part-application/octet-stream (msg part content-type nth depth declared-type)
563   ;; If we can deduce a MIME type from the filename of the attachment,
564   ;; do so and pass it on to the handler for that type.
565   (if (plist-get part :filename)
566       (let ((extension (file-name-extension (plist-get part :filename)))
567             mime-type)
568         (if extension
569             (progn
570               (mailcap-parse-mimetypes)
571               (setq mime-type (mailcap-extension-to-mime extension))
572               (if (and mime-type
573                        (not (string-equal mime-type "application/octet-stream")))
574                   (notmuch-show-insert-bodypart-internal msg part mime-type nth depth content-type)
575                 nil))
576           nil))))
577
578 (defun notmuch-show-insert-part-application/* (msg part content-type nth depth declared-type
579 )
580   ;; do not render random "application" parts
581   (notmuch-show-insert-part-header nth content-type declared-type (plist-get part :filename)))
582
583 (defun notmuch-show-insert-part-*/* (msg part content-type nth depth declared-type)
584   ;; This handler _must_ succeed - it is the handler of last resort.
585   (notmuch-show-insert-part-header nth content-type declared-type (plist-get part :filename))
586   (let ((content (notmuch-show-get-bodypart-content msg part nth)))
587     (if content
588         (notmuch-show-mm-display-part-inline msg part content-type content)))
589   t)
590
591 ;; Functions for determining how to handle MIME parts.
592
593 (defun notmuch-show-split-content-type (content-type)
594   (split-string content-type "/"))
595
596 (defun notmuch-show-handlers-for (content-type)
597   "Return a list of content handlers for a part of type CONTENT-TYPE."
598   (let (result)
599     (mapc (lambda (func)
600             (if (functionp func)
601                 (push func result)))
602           ;; Reverse order of prefrence.
603           (list (intern (concat "notmuch-show-insert-part-*/*"))
604                 (intern (concat
605                          "notmuch-show-insert-part-"
606                          (car (notmuch-show-split-content-type content-type))
607                          "/*"))
608                 (intern (concat "notmuch-show-insert-part-" content-type))))
609     result))
610
611 ;; Helper for parts which are generally not included in the default
612 ;; JSON output.
613 ;; Uses the buffer-local variable notmuch-show-process-crypto to
614 ;; determine if parts should be decrypted first.
615 (defun notmuch-show-get-bodypart-internal (message-id part-number)
616   (let ((args '("show" "--format=raw"))
617         (part-arg (format "--part=%s" part-number)))
618     (setq args (append args (list part-arg)))
619     (if notmuch-show-process-crypto
620         (setq args (append args '("--decrypt"))))
621     (setq args (append args (list message-id)))
622     (with-temp-buffer
623       (let ((coding-system-for-read 'no-conversion))
624         (progn
625           (apply 'call-process (append (list notmuch-command nil (list t nil) nil) args))
626           (buffer-string))))))
627
628 (defun notmuch-show-get-bodypart-content (msg part nth)
629   (or (plist-get part :content)
630       (notmuch-show-get-bodypart-internal (concat "id:" (plist-get msg :id)) nth)))
631
632 ;; \f
633
634 (defun notmuch-show-insert-bodypart-internal (msg part content-type nth depth declared-type)
635   (let ((handlers (notmuch-show-handlers-for content-type)))
636     ;; Run the content handlers until one of them returns a non-nil
637     ;; value.
638     (while (and handlers
639                 (not (funcall (car handlers) msg part content-type nth depth declared-type)))
640       (setq handlers (cdr handlers))))
641   t)
642
643 (defun notmuch-show-insert-bodypart (msg part depth)
644   "Insert the body part PART at depth DEPTH in the current thread."
645   (let ((content-type (downcase (plist-get part :content-type)))
646         (nth (plist-get part :id)))
647     (notmuch-show-insert-bodypart-internal msg part content-type nth depth content-type))
648   ;; Some of the body part handlers leave point somewhere up in the
649   ;; part, so we make sure that we're down at the end.
650   (goto-char (point-max))
651   ;; Ensure that the part ends with a carriage return.
652   (if (not (bolp))
653       (insert "\n")))
654
655 (defun notmuch-show-insert-body (msg body depth)
656   "Insert the body BODY at depth DEPTH in the current thread."
657   (mapc '(lambda (part) (notmuch-show-insert-bodypart msg part depth)) body))
658
659 (defun notmuch-show-make-symbol (type)
660   (make-symbol (concat "notmuch-show-" type)))
661
662 (defun notmuch-show-strip-re (string)
663   (replace-regexp-in-string "\\([Rr]e: *\\)+" "" string))
664
665 (defvar notmuch-show-previous-subject "")
666 (make-variable-buffer-local 'notmuch-show-previous-subject)
667
668 (defun notmuch-show-insert-msg (msg depth)
669   "Insert the message MSG at depth DEPTH in the current thread."
670   (let* ((headers (plist-get msg :headers))
671          ;; Indentation causes the buffer offset of the start/end
672          ;; points to move, so we must use markers.
673          message-start message-end
674          content-start content-end
675          headers-start headers-end
676          body-start body-end
677          (headers-invis-spec (notmuch-show-make-symbol "header"))
678          (message-invis-spec (notmuch-show-make-symbol "message"))
679          (bare-subject (notmuch-show-strip-re (plist-get headers :Subject))))
680
681     ;; Set `buffer-invisibility-spec' to `nil' (a list), otherwise
682     ;; removing items from `buffer-invisibility-spec' (which is what
683     ;; `notmuch-show-headers-visible' and
684     ;; `notmuch-show-message-visible' do) is a no-op and has no
685     ;; effect. This caused threads with only matching messages to have
686     ;; those messages hidden initially because
687     ;; `buffer-invisibility-spec' stayed `t'.
688     ;;
689     ;; This needs to be set here (rather than just above the call to
690     ;; `notmuch-show-headers-visible') because some of the part
691     ;; rendering or body washing functions
692     ;; (e.g. `notmuch-wash-text/plain-citations') manipulate
693     ;; `buffer-invisibility-spec').
694     (when (eq buffer-invisibility-spec t)
695       (setq buffer-invisibility-spec nil))
696
697     (setq message-start (point-marker))
698
699     (notmuch-show-insert-headerline headers
700                                     (or (if notmuch-show-relative-dates
701                                             (plist-get msg :date_relative)
702                                           nil)
703                                         (plist-get headers :Date))
704                                     (plist-get msg :tags) depth)
705
706     (setq content-start (point-marker))
707
708     ;; Set `headers-start' to point after the 'Subject:' header to be
709     ;; compatible with the existing implementation. This just sets it
710     ;; to after the first header.
711     (notmuch-show-insert-headers headers)
712     ;; Headers should include a blank line (backwards compatibility).
713     (insert "\n")
714     (save-excursion
715       (goto-char content-start)
716       ;; If the subject of this message is the same as that of the
717       ;; previous message, don't display it when this message is
718       ;; collapsed.
719       (when (and notmuch-show-elide-same-subject
720                  (not (string= notmuch-show-previous-subject
721                                bare-subject)))
722         (forward-line 1))
723       (setq headers-start (point-marker)))
724     (setq headers-end (point-marker))
725
726     (setq notmuch-show-previous-subject bare-subject)
727
728     (setq body-start (point-marker))
729     (notmuch-show-insert-body msg (plist-get msg :body) depth)
730     ;; Ensure that the body ends with a newline.
731     (if (not (bolp))
732         (insert "\n"))
733     (setq body-end (point-marker))
734     (setq content-end (point-marker))
735
736     ;; Indent according to the depth in the thread.
737     (indent-rigidly content-start content-end depth)
738
739     (setq message-end (point-max-marker))
740
741     ;; Save the extents of this message over the whole text of the
742     ;; message.
743     (put-text-property message-start message-end :notmuch-message-extent (cons message-start message-end))
744
745     (plist-put msg :headers-invis-spec headers-invis-spec)
746     (overlay-put (make-overlay headers-start headers-end) 'invisible headers-invis-spec)
747
748     (plist-put msg :message-invis-spec message-invis-spec)
749     (overlay-put (make-overlay body-start body-end) 'invisible message-invis-spec)
750
751     ;; Save the properties for this message. Currently this saves the
752     ;; entire message (augmented it with other stuff), which seems
753     ;; like overkill. We might save a reduced subset (for example, not
754     ;; the content).
755     (notmuch-show-set-message-properties msg)
756
757     ;; Set header visibility.
758     (notmuch-show-headers-visible msg notmuch-message-headers-visible)
759
760     ;; Message visibility depends on whether it matched the search
761     ;; criteria.
762     (notmuch-show-message-visible msg (plist-get msg :match))))
763
764 (defun notmuch-show-insert-tree (tree depth)
765   "Insert the message tree TREE at depth DEPTH in the current thread."
766   (let ((msg (car tree))
767         (replies (cadr tree)))
768     (notmuch-show-insert-msg msg depth)
769     (notmuch-show-insert-thread replies (1+ depth))))
770
771 (defun notmuch-show-insert-thread (thread depth)
772   "Insert the thread THREAD at depth DEPTH in the current forest."
773   (mapc '(lambda (tree) (notmuch-show-insert-tree tree depth)) thread))
774
775 (defun notmuch-show-insert-forest (forest)
776   "Insert the forest of threads FOREST."
777   (mapc '(lambda (thread) (notmuch-show-insert-thread thread 0)) forest))
778
779 (defvar notmuch-show-parent-buffer nil)
780 (make-variable-buffer-local 'notmuch-show-parent-buffer)
781
782 ;;;###autoload
783 (defun notmuch-show (thread-id &optional parent-buffer query-context buffer-name crypto-switch)
784   "Run \"notmuch show\" with the given thread ID and display results.
785
786 The optional PARENT-BUFFER is the notmuch-search buffer from
787 which this notmuch-show command was executed, (so that the
788 next thread from that buffer can be show when done with this
789 one).
790
791 The optional QUERY-CONTEXT is a notmuch search term. Only
792 messages from the thread matching this search term are shown if
793 non-nil.
794
795 The optional BUFFER-NAME provides the neame of the buffer in
796 which the message thread is shown. If it is nil (which occurs
797 when the command is called interactively) the argument to the
798 function is used. "
799   (interactive "sNotmuch show: ")
800   (let ((buffer (get-buffer-create (generate-new-buffer-name
801                                     (or buffer-name
802                                         (concat "*notmuch-" thread-id "*")))))
803         (process-crypto (if crypto-switch
804                             (not notmuch-crypto-process-mime)
805                           notmuch-crypto-process-mime))
806         (inhibit-read-only t))
807     (switch-to-buffer buffer)
808     (notmuch-show-mode)
809     (setq notmuch-show-parent-buffer parent-buffer)
810     (setq notmuch-show-process-crypto process-crypto)
811     (erase-buffer)
812     (goto-char (point-min))
813     (save-excursion
814       (let* ((basic-args (list thread-id))
815              (args (if query-context
816                        (append (list "\'") basic-args (list "and (" query-context ")\'"))
817                      (append (list "\'") basic-args (list "\'")))))
818         (notmuch-show-insert-forest (notmuch-query-get-threads args))
819         ;; If the query context reduced the results to nothing, run
820         ;; the basic query.
821         (when (and (eq (buffer-size) 0)
822                    query-context)
823           (notmuch-show-insert-forest
824            (notmuch-query-get-threads basic-args))))
825
826       ;; Enable buttonisation of URLs and email addresses in the
827       ;; buffer.
828       (goto-address-mode t)
829       ;; Act on visual lines rather than logical lines.
830       (visual-line-mode t)
831
832       (run-hooks 'notmuch-show-hook))
833
834     ;; Move straight to the first open message
835     (if (not (notmuch-show-message-visible-p))
836         (notmuch-show-next-open-message))
837
838     ;; Set the header line to the subject of the first open message.
839     (setq header-line-format (notmuch-show-strip-re (notmuch-show-get-subject)))
840
841     (notmuch-show-mark-read)))
842
843 (defvar notmuch-show-stash-map
844   (let ((map (make-sparse-keymap)))
845     (define-key map "c" 'notmuch-show-stash-cc)
846     (define-key map "d" 'notmuch-show-stash-date)
847     (define-key map "F" 'notmuch-show-stash-filename)
848     (define-key map "f" 'notmuch-show-stash-from)
849     (define-key map "i" 'notmuch-show-stash-message-id)
850     (define-key map "s" 'notmuch-show-stash-subject)
851     (define-key map "T" 'notmuch-show-stash-tags)
852     (define-key map "t" 'notmuch-show-stash-to)
853     map)
854   "Submap for stash commands")
855 (fset 'notmuch-show-stash-map notmuch-show-stash-map)
856
857 (defvar notmuch-show-mode-map
858       (let ((map (make-sparse-keymap)))
859         (define-key map "?" 'notmuch-help)
860         (define-key map "q" 'notmuch-kill-this-buffer)
861         (define-key map (kbd "<C-tab>") 'widget-backward)
862         (define-key map (kbd "M-TAB") 'notmuch-show-previous-button)
863         (define-key map (kbd "<backtab>") 'notmuch-show-previous-button)
864         (define-key map (kbd "TAB") 'notmuch-show-next-button)
865         (define-key map "s" 'notmuch-search)
866         (define-key map "m" 'notmuch-mua-new-mail)
867         (define-key map "f" 'notmuch-show-forward-message)
868         (define-key map "r" 'notmuch-show-reply)
869         (define-key map "|" 'notmuch-show-pipe-message)
870         (define-key map "w" 'notmuch-show-save-attachments)
871         (define-key map "V" 'notmuch-show-view-raw-message)
872         (define-key map "v" 'notmuch-show-view-all-mime-parts)
873         (define-key map "c" 'notmuch-show-stash-map)
874         (define-key map "h" 'notmuch-show-toggle-headers)
875         (define-key map "-" 'notmuch-show-remove-tag)
876         (define-key map "+" 'notmuch-show-add-tag)
877         (define-key map "x" 'notmuch-show-archive-thread-then-exit)
878         (define-key map "a" 'notmuch-show-archive-thread)
879         (define-key map "N" 'notmuch-show-next-message)
880         (define-key map "P" 'notmuch-show-previous-message)
881         (define-key map "n" 'notmuch-show-next-open-message)
882         (define-key map "p" 'notmuch-show-previous-open-message)
883         (define-key map (kbd "DEL") 'notmuch-show-rewind)
884         (define-key map " " 'notmuch-show-advance-and-archive)
885         (define-key map (kbd "M-RET") 'notmuch-show-open-or-close-all)
886         (define-key map (kbd "RET") 'notmuch-show-toggle-message)
887         map)
888       "Keymap for \"notmuch show\" buffers.")
889 (fset 'notmuch-show-mode-map notmuch-show-mode-map)
890
891 (defun notmuch-show-mode ()
892   "Major mode for viewing a thread with notmuch.
893
894 This buffer contains the results of the \"notmuch show\" command
895 for displaying a single thread of email from your email archives.
896
897 By default, various components of email messages, (citations,
898 signatures, already-read messages), are hidden. You can make
899 these parts visible by clicking with the mouse button or by
900 pressing RET after positioning the cursor on a hidden part, (for
901 which \\[notmuch-show-next-button] and \\[notmuch-show-previous-button] are helpful).
902
903 Reading the thread sequentially is well-supported by pressing
904 \\[notmuch-show-advance-and-archive]. This will scroll the current message (if necessary), advance
905 to the next message, or advance to the next thread (if already on
906 the last message of a thread).
907
908 Other commands are available to read or manipulate the thread
909 more selectively, (such as '\\[notmuch-show-next-message]' and '\\[notmuch-show-previous-message]' to advance to messages
910 without removing any tags, and '\\[notmuch-show-archive-thread]' to archive an entire thread
911 without scrolling through with \\[notmuch-show-advance-and-archive]).
912
913 You can add or remove arbitary tags from the current message with
914 '\\[notmuch-show-add-tag]' or '\\[notmuch-show-remove-tag]'.
915
916 All currently available key bindings:
917
918 \\{notmuch-show-mode-map}"
919   (interactive)
920   (kill-all-local-variables)
921   (use-local-map notmuch-show-mode-map)
922   (setq major-mode 'notmuch-show-mode
923         mode-name "notmuch-show")
924   (setq buffer-read-only t))
925
926 (defun notmuch-show-move-to-message-top ()
927   (goto-char (notmuch-show-message-top)))
928
929 (defun notmuch-show-move-to-message-bottom ()
930   (goto-char (notmuch-show-message-bottom)))
931
932 (defun notmuch-show-message-adjust ()
933   (recenter 0))
934
935 ;; Movement related functions.
936
937 ;; There's some strangeness here where a text property applied to a
938 ;; region a->b is not found when point is at b. We walk backwards
939 ;; until finding the property.
940 (defun notmuch-show-message-extent ()
941   (let (r)
942     (save-excursion
943       (while (not (setq r (get-text-property (point) :notmuch-message-extent)))
944         (backward-char)))
945     r))
946
947 (defun notmuch-show-message-top ()
948   (car (notmuch-show-message-extent)))
949
950 (defun notmuch-show-message-bottom ()
951   (cdr (notmuch-show-message-extent)))
952
953 (defun notmuch-show-goto-message-next ()
954   (let ((start (point)))
955     (notmuch-show-move-to-message-bottom)
956     (if (not (eobp))
957         t
958       (goto-char start)
959       nil)))
960
961 (defun notmuch-show-goto-message-previous ()
962   (notmuch-show-move-to-message-top)
963   (if (bobp)
964       nil
965     (backward-char)
966     (notmuch-show-move-to-message-top)
967     t))
968
969 (defun notmuch-show-move-past-invisible-forward ()
970   (while (point-invisible-p)
971     (forward-char)))
972
973 (defun notmuch-show-move-past-invisible-backward ()
974   (while (point-invisible-p)
975     (backward-char)))
976
977 ;; Functions relating to the visibility of messages and their
978 ;; components.
979
980 (defun notmuch-show-element-visible (props visible-p spec-property)
981   (let ((spec (plist-get props spec-property)))
982     (if visible-p
983         (remove-from-invisibility-spec spec)
984       (add-to-invisibility-spec spec))))
985
986 (defun notmuch-show-message-visible (props visible-p)
987   (if visible-p
988       ;; When making the message visible, the headers may or not be
989       ;; visible. So we check that property separately.
990       (let ((headers-visible (plist-get props :headers-visible)))
991         (notmuch-show-element-visible props headers-visible :headers-invis-spec)
992         (notmuch-show-element-visible props t :message-invis-spec))
993     (notmuch-show-element-visible props nil :headers-invis-spec)
994     (notmuch-show-element-visible props nil :message-invis-spec))
995
996   (notmuch-show-set-prop :message-visible visible-p props))
997
998 (defun notmuch-show-headers-visible (props visible-p)
999   (if (plist-get props :message-visible)
1000       (notmuch-show-element-visible props visible-p :headers-invis-spec))
1001   (notmuch-show-set-prop :headers-visible visible-p props))
1002
1003 ;; Functions for setting and getting attributes of the current
1004 ;; message.
1005
1006 (defun notmuch-show-set-message-properties (props)
1007   (save-excursion
1008     (notmuch-show-move-to-message-top)
1009     (put-text-property (point) (+ (point) 1) :notmuch-message-properties props)))
1010
1011 (defun notmuch-show-get-message-properties ()
1012   (save-excursion
1013     (notmuch-show-move-to-message-top)
1014     (get-text-property (point) :notmuch-message-properties)))
1015
1016 (defun notmuch-show-set-prop (prop val &optional props)
1017   (let ((inhibit-read-only t)
1018         (props (or props
1019                    (notmuch-show-get-message-properties))))
1020     (plist-put props prop val)
1021     (notmuch-show-set-message-properties props)))
1022
1023 (defun notmuch-show-get-prop (prop &optional props)
1024   (let ((props (or props
1025                    (notmuch-show-get-message-properties))))
1026     (plist-get props prop)))
1027
1028 (defun notmuch-show-get-message-id ()
1029   "Return the message id of the current message."
1030   (concat "id:\"" (notmuch-show-get-prop :id) "\""))
1031
1032 ;; dme: Would it make sense to use a macro for many of these?
1033
1034 (defun notmuch-show-get-filename ()
1035   "Return the filename of the current message."
1036   (notmuch-show-get-prop :filename))
1037
1038 (defun notmuch-show-get-header (header)
1039   "Return the named header of the current message, if any."
1040   (plist-get (notmuch-show-get-prop :headers) header))
1041
1042 (defun notmuch-show-get-cc ()
1043   (notmuch-show-get-header :Cc))
1044
1045 (defun notmuch-show-get-date ()
1046   (notmuch-show-get-header :Date))
1047
1048 (defun notmuch-show-get-from ()
1049   (notmuch-show-get-header :From))
1050
1051 (defun notmuch-show-get-subject ()
1052   (notmuch-show-get-header :Subject))
1053
1054 (defun notmuch-show-get-to ()
1055   (notmuch-show-get-header :To))
1056
1057 (defun notmuch-show-set-tags (tags)
1058   "Set the tags of the current message."
1059   (notmuch-show-set-prop :tags tags)
1060   (notmuch-show-update-tags tags))
1061
1062 (defun notmuch-show-get-tags ()
1063   "Return the tags of the current message."
1064   (notmuch-show-get-prop :tags))
1065
1066 (defun notmuch-show-message-visible-p ()
1067   "Is the current message visible?"
1068   (notmuch-show-get-prop :message-visible))
1069
1070 (defun notmuch-show-headers-visible-p ()
1071   "Are the headers of the current message visible?"
1072   (notmuch-show-get-prop :headers-visible))
1073
1074 (defun notmuch-show-mark-read ()
1075   "Mark the current message as read."
1076   (notmuch-show-remove-tag "unread"))
1077
1078 ;; Functions for getting attributes of several messages in the current
1079 ;; thread.
1080
1081 (defun notmuch-show-get-message-ids-for-open-messages ()
1082   "Return a list of all message IDs for open messages in the current thread."
1083   (save-excursion
1084     (let (message-ids done)
1085       (goto-char (point-min))
1086       (while (not done)
1087         (if (notmuch-show-message-visible-p)
1088             (setq message-ids (append message-ids (list (notmuch-show-get-message-id)))))
1089         (setq done (not (notmuch-show-goto-message-next)))
1090         )
1091       message-ids
1092       )))
1093
1094 ;; Commands typically bound to keys.
1095
1096 (defun notmuch-show-advance-and-archive ()
1097   "Advance through thread and archive.
1098
1099 This command is intended to be one of the simplest ways to
1100 process a thread of email. It does the following:
1101
1102 If the current message in the thread is not yet fully visible,
1103 scroll by a near screenful to read more of the message.
1104
1105 Otherwise, (the end of the current message is already within the
1106 current window), advance to the next open message.
1107
1108 Finally, if there is no further message to advance to, and this
1109 last message is already read, then archive the entire current
1110 thread, (remove the \"inbox\" tag from each message). Also kill
1111 this buffer, and display the next thread from the search from
1112 which this thread was originally shown."
1113   (interactive)
1114   (let ((end-of-this-message (notmuch-show-message-bottom)))
1115     (cond
1116      ;; Ideally we would test `end-of-this-message' against the result
1117      ;; of `window-end', but that doesn't account for the fact that
1118      ;; the end of the message might be hidden, so we have to actually
1119      ;; go to the end, walk back over invisible text and then see if
1120      ;; point is visible.
1121      ((save-excursion
1122         (goto-char (- end-of-this-message 1))
1123         (notmuch-show-move-past-invisible-backward)
1124         (> (point) (window-end)))
1125       ;; The bottom of this message is not visible - scroll.
1126       (scroll-up nil))
1127
1128      ((not (= end-of-this-message (point-max)))
1129       ;; This is not the last message - move to the next visible one.
1130       (notmuch-show-next-open-message))
1131
1132      (t
1133       ;; This is the last message - archive the thread.
1134       (notmuch-show-archive-thread)))))
1135
1136 (defun notmuch-show-rewind ()
1137   "Backup through the thread, (reverse scrolling compared to \\[notmuch-show-advance-and-archive]).
1138
1139 Specifically, if the beginning of the previous email is fewer
1140 than `window-height' lines from the current point, move to it
1141 just like `notmuch-show-previous-message'.
1142
1143 Otherwise, just scroll down a screenful of the current message.
1144
1145 This command does not modify any message tags, (it does not undo
1146 any effects from previous calls to
1147 `notmuch-show-advance-and-archive'."
1148   (interactive)
1149   (let ((start-of-message (notmuch-show-message-top))
1150         (start-of-window (window-start)))
1151     (cond
1152       ;; Either this message is properly aligned with the start of the
1153       ;; window or the start of this message is not visible on the
1154       ;; screen - scroll.
1155      ((or (= start-of-message start-of-window)
1156           (< start-of-message start-of-window))
1157       (scroll-down)
1158       ;; If a small number of lines from the previous message are
1159       ;; visible, realign so that the top of the current message is at
1160       ;; the top of the screen.
1161       (if (<= (count-screen-lines (window-start) start-of-message)
1162               next-screen-context-lines)
1163           (progn
1164             (goto-char (notmuch-show-message-top))
1165             (notmuch-show-message-adjust)))
1166       ;; Move to the top left of the window.
1167       (goto-char (window-start)))
1168      (t
1169       ;; Move to the previous message.
1170       (notmuch-show-previous-message)))))
1171
1172 (defun notmuch-show-reply (&optional prompt-for-sender)
1173   "Reply to the current message."
1174   (interactive "P")
1175   (notmuch-mua-new-reply (notmuch-show-get-message-id) prompt-for-sender))
1176
1177 (defun notmuch-show-forward-message (&optional prompt-for-sender)
1178   "Forward the current message."
1179   (interactive "P")
1180   (with-current-notmuch-show-message
1181    (notmuch-mua-new-forward-message prompt-for-sender)))
1182
1183 (defun notmuch-show-next-message ()
1184   "Show the next message."
1185   (interactive)
1186   (if (notmuch-show-goto-message-next)
1187       (progn
1188         (notmuch-show-mark-read)
1189         (notmuch-show-message-adjust))
1190     (goto-char (point-max))))
1191
1192 (defun notmuch-show-previous-message ()
1193   "Show the previous message."
1194   (interactive)
1195   (notmuch-show-goto-message-previous)
1196   (notmuch-show-mark-read)
1197   (notmuch-show-message-adjust))
1198
1199 (defun notmuch-show-next-open-message ()
1200   "Show the next message."
1201   (interactive)
1202   (let (r)
1203     (while (and (setq r (notmuch-show-goto-message-next))
1204                 (not (notmuch-show-message-visible-p))))
1205     (if r
1206         (progn
1207           (notmuch-show-mark-read)
1208           (notmuch-show-message-adjust))
1209       (goto-char (point-max)))))
1210
1211 (defun notmuch-show-previous-open-message ()
1212   "Show the previous message."
1213   (interactive)
1214   (while (and (notmuch-show-goto-message-previous)
1215               (not (notmuch-show-message-visible-p))))
1216   (notmuch-show-mark-read)
1217   (notmuch-show-message-adjust))
1218
1219 (defun notmuch-show-view-raw-message ()
1220   "View the file holding the current message."
1221   (interactive)
1222   (let* ((id (notmuch-show-get-message-id))
1223          (buf (get-buffer-create (concat "*notmuch-raw-" id "*"))))
1224     (call-process notmuch-command nil buf nil "show" "--format=raw" id)
1225     (switch-to-buffer buf)
1226     (goto-char (point-min))
1227     (set-buffer-modified-p nil)
1228     (view-buffer buf 'kill-buffer-if-not-modified)))
1229
1230 (defun notmuch-show-pipe-message (entire-thread command)
1231   "Pipe the contents of the current message (or thread) to the given command.
1232
1233 The given command will be executed with the raw contents of the
1234 current email message as stdin. Anything printed by the command
1235 to stdout or stderr will appear in the *notmuch-pipe* buffer.
1236
1237 When invoked with a prefix argument, the command will receive all
1238 open messages in the current thread (formatted as an mbox) rather
1239 than only the current message."
1240   (interactive "P\nsPipe message to command: ")
1241   (let (shell-command)
1242     (if entire-thread
1243         (setq shell-command 
1244               (concat notmuch-command " show --format=mbox "
1245                       (shell-quote-argument
1246                        (mapconcat 'identity (notmuch-show-get-message-ids-for-open-messages) " OR "))
1247                       " | " command))
1248       (setq shell-command
1249             (concat notmuch-command " show --format=raw "
1250                     (shell-quote-argument (notmuch-show-get-message-id)) " | " command)))
1251     (let ((buf (get-buffer-create (concat "*notmuch-pipe*"))))
1252       (with-current-buffer buf
1253         (setq buffer-read-only nil)
1254         (erase-buffer)
1255         (let ((exit-code (call-process-shell-command shell-command nil buf)))
1256           (goto-char (point-max))
1257           (set-buffer-modified-p nil)
1258           (setq buffer-read-only t)
1259           (unless (zerop exit-code)
1260             (switch-to-buffer-other-window buf)
1261             (message (format "Command '%s' exited abnormally with code %d"
1262                              shell-command exit-code))))))))
1263
1264 (defun notmuch-show-add-tags-worker (current-tags add-tags)
1265   "Add to `current-tags' with any tags from `add-tags' not
1266 currently present and return the result."
1267   (let ((result-tags (copy-sequence current-tags)))
1268     (mapc (lambda (add-tag)
1269             (unless (member add-tag current-tags)
1270               (setq result-tags (push add-tag result-tags))))
1271             add-tags)
1272     (sort result-tags 'string<)))
1273
1274 (defun notmuch-show-del-tags-worker (current-tags del-tags)
1275   "Remove any tags in `del-tags' from `current-tags' and return
1276 the result."
1277   (let ((result-tags (copy-sequence current-tags)))
1278     (mapc (lambda (del-tag)
1279             (setq result-tags (delete del-tag result-tags)))
1280           del-tags)
1281     result-tags))
1282
1283 (defun notmuch-show-add-tag (&rest toadd)
1284   "Add a tag to the current message."
1285   (interactive
1286    (list (notmuch-select-tag-with-completion "Tag to add: ")))
1287
1288   (let* ((current-tags (notmuch-show-get-tags))
1289          (new-tags (notmuch-show-add-tags-worker current-tags toadd)))
1290
1291     (unless (equal current-tags new-tags)
1292       (apply 'notmuch-tag (notmuch-show-get-message-id)
1293              (mapcar (lambda (s) (concat "+" s)) toadd))
1294       (notmuch-show-set-tags new-tags))))
1295
1296 (defun notmuch-show-remove-tag (&rest toremove)
1297   "Remove a tag from the current message."
1298   (interactive
1299    (list (notmuch-select-tag-with-completion
1300           "Tag to remove: " (notmuch-show-get-message-id))))
1301
1302   (let* ((current-tags (notmuch-show-get-tags))
1303          (new-tags (notmuch-show-del-tags-worker current-tags toremove)))
1304
1305     (unless (equal current-tags new-tags)
1306       (apply 'notmuch-tag (notmuch-show-get-message-id)
1307              (mapcar (lambda (s) (concat "-" s)) toremove))
1308       (notmuch-show-set-tags new-tags))))
1309
1310 (defun notmuch-show-toggle-headers ()
1311   "Toggle the visibility of the current message headers."
1312   (interactive)
1313   (let ((props (notmuch-show-get-message-properties)))
1314     (notmuch-show-headers-visible
1315      props
1316      (not (plist-get props :headers-visible))))
1317   (force-window-update))
1318
1319 (defun notmuch-show-toggle-message ()
1320   "Toggle the visibility of the current message."
1321   (interactive)
1322   (let ((props (notmuch-show-get-message-properties)))
1323     (notmuch-show-message-visible
1324      props
1325      (not (plist-get props :message-visible))))
1326   (force-window-update))
1327
1328 (defun notmuch-show-open-or-close-all ()
1329   "Set the visibility all of the messages in the current thread.
1330 By default make all of the messages visible. With a prefix
1331 argument, hide all of the messages."
1332   (interactive)
1333   (save-excursion
1334     (goto-char (point-min))
1335     (loop do (notmuch-show-message-visible (notmuch-show-get-message-properties)
1336                                            (not current-prefix-arg))
1337           until (not (notmuch-show-goto-message-next))))
1338   (force-window-update))
1339
1340 (defun notmuch-show-next-button ()
1341   "Advance point to the next button in the buffer."
1342   (interactive)
1343   (forward-button 1))
1344
1345 (defun notmuch-show-previous-button ()
1346   "Move point back to the previous button in the buffer."
1347   (interactive)
1348   (backward-button 1))
1349
1350 (defun notmuch-show-archive-thread-internal (show-next)
1351   ;; Remove the tag from the current set of messages.
1352   (goto-char (point-min))
1353   (loop do (notmuch-show-remove-tag "inbox")
1354         until (not (notmuch-show-goto-message-next)))
1355   ;; Move to the next item in the search results, if any.
1356   (let ((parent-buffer notmuch-show-parent-buffer))
1357     (notmuch-kill-this-buffer)
1358     (if parent-buffer
1359         (progn
1360           (switch-to-buffer parent-buffer)
1361           (forward-line)
1362           (if show-next
1363               (notmuch-search-show-thread))))))
1364
1365 (defun notmuch-show-archive-thread ()
1366   "Archive each message in thread, then show next thread from search.
1367
1368 Archive each message currently shown by removing the \"inbox\"
1369 tag from each. Then kill this buffer and show the next thread
1370 from the search from which this thread was originally shown.
1371
1372 Note: This command is safe from any race condition of new messages
1373 being delivered to the same thread. It does not archive the
1374 entire thread, but only the messages shown in the current
1375 buffer."
1376   (interactive)
1377   (notmuch-show-archive-thread-internal t))
1378
1379 (defun notmuch-show-archive-thread-then-exit ()
1380   "Archive each message in thread, then exit back to search results."
1381   (interactive)
1382   (notmuch-show-archive-thread-internal nil))
1383
1384 (defun notmuch-show-stash-cc ()
1385   "Copy CC field of current message to kill-ring."
1386   (interactive)
1387   (notmuch-common-do-stash (notmuch-show-get-cc)))
1388
1389 (defun notmuch-show-stash-date ()
1390   "Copy date of current message to kill-ring."
1391   (interactive)
1392   (notmuch-common-do-stash (notmuch-show-get-date)))
1393
1394 (defun notmuch-show-stash-filename ()
1395   "Copy filename of current message to kill-ring."
1396   (interactive)
1397   (notmuch-common-do-stash (notmuch-show-get-filename)))
1398
1399 (defun notmuch-show-stash-from ()
1400   "Copy From address of current message to kill-ring."
1401   (interactive)
1402   (notmuch-common-do-stash (notmuch-show-get-from)))
1403
1404 (defun notmuch-show-stash-message-id ()
1405   "Copy message ID of current message to kill-ring."
1406   (interactive)
1407   (notmuch-common-do-stash (notmuch-show-get-message-id)))
1408
1409 (defun notmuch-show-stash-subject ()
1410   "Copy Subject field of current message to kill-ring."
1411   (interactive)
1412   (notmuch-common-do-stash (notmuch-show-get-subject)))
1413
1414 (defun notmuch-show-stash-tags ()
1415   "Copy tags of current message to kill-ring as a comma separated list."
1416   (interactive)
1417   (notmuch-common-do-stash (mapconcat 'identity (notmuch-show-get-tags) ",")))
1418
1419 (defun notmuch-show-stash-to ()
1420   "Copy To address of current message to kill-ring."
1421   (interactive)
1422   (notmuch-common-do-stash (notmuch-show-get-to)))
1423
1424 ;; Commands typically bound to buttons.
1425
1426 (defun notmuch-show-part-button-action (button)
1427   (let ((nth (button-get button :notmuch-part)))
1428     (if nth
1429         (notmuch-show-save-part (notmuch-show-get-message-id) nth
1430                                 (button-get button :notmuch-filename))
1431       (message "Not a valid part (is it a fake part?)."))))
1432
1433 ;;
1434
1435 (provide 'notmuch-show)