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