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