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