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