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