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