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