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