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