]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-show.el
9f045d7d2fdb26d5fdb9f4293d094c93644d5363
[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
30 (require 'notmuch-lib)
31 (require 'notmuch-query)
32 (require 'notmuch-wash)
33 (require 'notmuch-mua)
34
35 (declare-function notmuch-call-notmuch-process "notmuch" (&rest args))
36 (declare-function notmuch-fontify-headers "notmuch" nil)
37 (declare-function notmuch-select-tag-with-completion "notmuch" (prompt &rest search-terms))
38 (declare-function notmuch-search-show-thread "notmuch" nil)
39
40 (defcustom notmuch-message-headers '("Subject" "To" "Cc" "Date")
41   "Headers that should be shown in a message, in this order.
42
43 For an open message, all of these headers will be made visible
44 according to `notmuch-message-headers-visible' or can be toggled
45 with `notmuch-show-toggle-headers'. For a closed message, only
46 the first header in the list will be visible."
47   :group 'notmuch
48   :type '(repeat string))
49
50 (defcustom notmuch-message-headers-visible t
51   "Should the headers be visible by default?
52
53 If this value is non-nil, then all of the headers defined in
54 `notmuch-message-headers' will be visible by default in the display
55 of each message. Otherwise, these headers will be hidden and
56 `notmuch-show-toggle-headers' can be used to make the visible for
57 any given message."
58   :group 'notmuch
59   :type 'boolean)
60
61 (defcustom notmuch-show-relative-dates t
62   "Display relative dates in the message summary line."
63   :group 'notmuch
64   :type 'boolean)
65
66 (defvar notmuch-show-markup-headers-hook '(notmuch-show-colour-headers)
67   "A list of functions called to decorate the headers listed in
68 `notmuch-message-headers'.")
69
70 (defcustom notmuch-show-hook nil
71   "Functions called after populating a `notmuch-show' buffer."
72   :group 'notmuch
73   :type 'hook)
74
75 (defcustom notmuch-show-insert-text/plain-hook '(notmuch-wash-excerpt-citations)
76   "Functions used to improve the display of text/plain parts."
77   :group 'notmuch
78   :type 'hook
79   :options '(notmuch-wash-convert-inline-patch-to-part
80              notmuch-wash-wrap-long-lines
81              notmuch-wash-tidy-citations
82              notmuch-wash-elide-blank-lines
83              notmuch-wash-excerpt-citations))
84
85 (defmacro with-current-notmuch-show-message (&rest body)
86   "Evaluate body with current buffer set to the text of current message"
87   `(save-excursion
88      (let ((id (notmuch-show-get-message-id)))
89        (let ((buf (generate-new-buffer (concat "*notmuch-msg-" id "*"))))
90          (with-current-buffer buf
91             (call-process notmuch-command nil t nil "show" "--format=raw" id)
92            ,@body)
93          (kill-buffer buf)))))
94
95 (defun notmuch-show-view-all-mime-parts ()
96   "Use external viewers to view all attachments from the current message."
97   (interactive)
98   (with-current-notmuch-show-message
99    ; We ovverride the mm-inline-media-tests to indicate which message
100    ; parts are already sufficiently handled by the original
101    ; presentation of the message in notmuch-show mode. These parts
102    ; will be inserted directly into the temporary buffer of
103    ; with-current-notmuch-show-message and silently discarded.
104    ;
105    ; Any MIME part not explicitly mentioned here will be handled by an
106    ; external viewer as configured in the various mailcap files.
107    (let ((mm-inline-media-tests '(
108                                   ("text/.*" ignore identity)
109                                   ("application/pgp-signature" ignore identity)
110                                   ("multipart/alternative" ignore identity)
111                                   ("multipart/mixed" ignore identity)
112                                   ("multipart/related" ignore identity)
113                                  )))
114      (mm-display-parts (mm-dissect-buffer)))))
115
116 (defun notmuch-foreach-mime-part (function mm-handle)
117   (cond ((stringp (car mm-handle))
118          (dolist (part (cdr mm-handle))
119            (notmuch-foreach-mime-part function part)))
120         ((bufferp (car mm-handle))
121          (funcall function mm-handle))
122         (t (dolist (part mm-handle)
123              (notmuch-foreach-mime-part function part)))))
124
125 (defun notmuch-count-attachments (mm-handle)
126   (let ((count 0))
127     (notmuch-foreach-mime-part
128      (lambda (p)
129        (let ((disposition (mm-handle-disposition p)))
130          (and (listp disposition)
131               (or (equal (car disposition) "attachment")
132                   (and (equal (car disposition) "inline")
133                        (assq 'filename disposition)))
134               (incf count))))
135      mm-handle)
136     count))
137
138 (defun notmuch-save-attachments (mm-handle &optional queryp)
139   (notmuch-foreach-mime-part
140    (lambda (p)
141      (let ((disposition (mm-handle-disposition p)))
142        (and (listp disposition)
143             (or (equal (car disposition) "attachment")
144                 (and (equal (car disposition) "inline")
145                      (assq 'filename disposition)))
146             (or (not queryp)
147                 (y-or-n-p
148                  (concat "Save '" (cdr (assq 'filename disposition)) "' ")))
149             (mm-save-part p))))
150    mm-handle))
151
152 (defun notmuch-show-save-attachments ()
153   "Save all attachments from the current message."
154   (interactive)
155   (with-current-notmuch-show-message
156    (let ((mm-handle (mm-dissect-buffer)))
157      (notmuch-save-attachments
158       mm-handle (> (notmuch-count-attachments mm-handle) 1))))
159   (message "Done"))
160
161 (defun notmuch-show-fontify-header ()
162   (let ((face (cond
163                ((looking-at "[Tt]o:")
164                 'message-header-to)
165                ((looking-at "[Bb]?[Cc][Cc]:")
166                 'message-header-cc)
167                ((looking-at "[Ss]ubject:")
168                 'message-header-subject)
169                ((looking-at "[Ff]rom:")
170                 'message-header-from)
171                (t
172                 'message-header-other))))
173
174     (overlay-put (make-overlay (point) (re-search-forward ":"))
175                  'face 'message-header-name)
176     (overlay-put (make-overlay (point) (re-search-forward ".*$"))
177                  'face face)))
178
179 (defun notmuch-show-colour-headers ()
180   "Apply some colouring to the current headers."
181   (goto-char (point-min))
182   (while (looking-at "^[A-Za-z][-A-Za-z0-9]*:")
183     (notmuch-show-fontify-header)
184     (forward-line)))
185
186 (defun notmuch-show-spaces-n (n)
187   "Return a string comprised of `n' spaces."
188   (make-string n ? ))
189
190 (defun notmuch-show-update-tags (tags)
191   "Update the displayed tags of the current message."
192   (save-excursion
193     (goto-char (notmuch-show-message-top))
194     (if (re-search-forward "(\\([^()]*\\))$" (line-end-position) t)
195         (let ((inhibit-read-only t))
196           (replace-match (concat "("
197                                  (propertize (mapconcat 'identity tags " ")
198                                              'face 'notmuch-tag-face)
199                                  ")"))))))
200
201 (defun notmuch-show-insert-headerline (headers date tags depth)
202   "Insert a notmuch style headerline based on HEADERS for a
203 message at DEPTH in the current thread."
204   (let ((start (point)))
205     (insert (notmuch-show-spaces-n depth)
206             (plist-get headers :From)
207             " ("
208             date
209             ") ("
210             (propertize (mapconcat 'identity tags " ")
211                         'face 'notmuch-tag-face)
212             ")\n")
213     (overlay-put (make-overlay start (point)) 'face 'notmuch-message-summary-face)))
214
215 (defun notmuch-show-insert-header (header header-value)
216   "Insert a single header."
217   (insert header ": " header-value "\n"))
218
219 (defun notmuch-show-insert-headers (headers)
220   "Insert the headers of the current message."
221   (let ((start (point)))
222     (mapc '(lambda (header)
223              (let* ((header-symbol (intern (concat ":" header)))
224                     (header-value (plist-get headers header-symbol)))
225                (if (and header-value
226                         (not (string-equal "" header-value)))
227                    (notmuch-show-insert-header header header-value))))
228           notmuch-message-headers)
229     (save-excursion
230       (save-restriction
231         (narrow-to-region start (point-max))
232         (run-hooks 'notmuch-show-markup-headers-hook)))))
233
234 (define-button-type 'notmuch-show-part-button-type
235   'action 'notmuch-show-part-button-action
236   'follow-link t
237   'face 'message-mml)
238
239 (defun notmuch-show-insert-part-header (nth content-type declared-type &optional name)
240   (insert-button
241    (concat "[ "
242            (if name (concat name ": ") "")
243            declared-type
244            (if (not (string-equal declared-type content-type))
245                (concat " (as " content-type ")")
246              "")
247            " ]\n")
248    :type 'notmuch-show-part-button-type
249    :notmuch-part nth
250    :notmuch-filename name))
251
252 ;; Functions handling particular MIME parts.
253
254 (defun notmuch-show-save-part (message-id nth &optional filename)
255   (with-temp-buffer
256     ;; Always acquires the part via `notmuch part', even if it is
257     ;; available in the JSON output.
258     (insert (notmuch-show-get-bodypart-internal message-id nth))
259     (let ((file (read-file-name
260                  "Filename to save as: "
261                  (or mailcap-download-directory "~/")
262                  nil nil
263                  filename))
264           (require-final-newline nil)
265           (coding-system-for-write 'no-conversion))
266       (write-region (point-min) (point-max) file))))
267
268 (defun notmuch-show-mm-display-part-inline (msg part content-type content)
269   "Use the mm-decode/mm-view functions to display a part in the
270 current buffer, if possible."
271   (let ((display-buffer (current-buffer)))
272     (with-temp-buffer
273       (insert content)
274       (let ((handle (mm-make-handle (current-buffer) (list content-type))))
275         (set-buffer display-buffer)
276         (if (and (mm-inlinable-p handle)
277                  (mm-inlined-p handle))
278             (progn
279               (mm-display-part handle)
280               t)
281           nil)))))
282
283 (defun notmuch-show-insert-part-multipart/* (msg part content-type nth depth declared-type)
284   (let ((inner-parts (plist-get part :content)))
285     (notmuch-show-insert-part-header nth declared-type content-type nil)
286     ;; Show all of the parts.
287     (mapc (lambda (inner-part)
288             (notmuch-show-insert-bodypart msg inner-part depth))
289           inner-parts))
290   t)
291
292 (defun notmuch-show-insert-part-text/plain (msg part content-type nth depth declared-type)
293   (let ((start (point)))
294     ;; If this text/plain part is not the first part in the message,
295     ;; insert a header to make this clear.
296     (if (> nth 1)
297         (notmuch-show-insert-part-header nth declared-type content-type (plist-get part :filename)))
298     (insert (notmuch-show-get-bodypart-content msg part nth))
299     (save-excursion
300       (save-restriction
301         (narrow-to-region start (point-max))
302         (run-hook-with-args 'notmuch-show-insert-text/plain-hook depth))))
303   t)
304
305 (defun notmuch-show-insert-part-application/octet-stream (msg part content-type nth depth declared-type)
306   ;; If we can deduce a MIME type from the filename of the attachment,
307   ;; do so and pass it on to the handler for that type.
308   (if (plist-get part :filename)
309       (let ((extension (file-name-extension (plist-get part :filename)))
310             mime-type)
311         (if extension
312             (progn
313               (mailcap-parse-mimetypes)
314               (setq mime-type (mailcap-extension-to-mime extension))
315               (if (and mime-type
316                        (not (string-equal mime-type "application/octet-stream")))
317                   (notmuch-show-insert-bodypart-internal msg part mime-type nth depth content-type)
318                 nil))
319           nil))))
320
321 (defun notmuch-show-insert-part-*/* (msg part content-type nth depth declared-type)
322   ;; This handler _must_ succeed - it is the handler of last resort.
323   (notmuch-show-insert-part-header nth content-type declared-type (plist-get part :filename))
324   (let ((content (notmuch-show-get-bodypart-content msg part nth)))
325     (if content
326         (notmuch-show-mm-display-part-inline msg part content-type content)))
327   t)
328
329 ;; Functions for determining how to handle MIME parts.
330
331 (defun notmuch-show-split-content-type (content-type)
332   (split-string content-type "/"))
333
334 (defun notmuch-show-handlers-for (content-type)
335   "Return a list of content handlers for a part of type CONTENT-TYPE."
336   (let (result)
337     (mapc (lambda (func)
338             (if (functionp func)
339                 (push func result)))
340           ;; Reverse order of prefrence.
341           (list (intern (concat "notmuch-show-insert-part-*/*"))
342                 (intern (concat
343                          "notmuch-show-insert-part-"
344                          (car (notmuch-show-split-content-type content-type))
345                          "/*"))
346                 (intern (concat "notmuch-show-insert-part-" content-type))))
347     result))
348
349 ;; Helper for parts which are generally not included in the default
350 ;; JSON output.
351
352 (defun notmuch-show-get-bodypart-internal (message-id part-number)
353   (with-temp-buffer
354     (let ((coding-system-for-read 'no-conversion))
355       (call-process notmuch-command nil t nil
356                     "part" (format "--part=%s" part-number) message-id)
357       (buffer-string))))
358
359 (defun notmuch-show-get-bodypart-content (msg part nth)
360   (or (plist-get part :content)
361       (notmuch-show-get-bodypart-internal (concat "id:" (plist-get msg :id)) nth)))
362
363 ;; \f
364
365 (defun notmuch-show-insert-bodypart-internal (msg part content-type nth depth declared-type)
366   (let ((handlers (notmuch-show-handlers-for content-type)))
367     ;; Run the content handlers until one of them returns a non-nil
368     ;; value.
369     (while (and handlers
370                 (not (funcall (car handlers) msg part content-type nth depth declared-type)))
371       (setq handlers (cdr handlers))))
372   t)
373
374 (defun notmuch-show-insert-bodypart (msg part depth)
375   "Insert the body part PART at depth DEPTH in the current thread."
376   (let ((content-type (downcase (plist-get part :content-type)))
377         (nth (plist-get part :id)))
378     (notmuch-show-insert-bodypart-internal msg part content-type nth depth content-type))
379   ;; Some of the body part handlers leave point somewhere up in the
380   ;; part, so we make sure that we're down at the end.
381   (goto-char (point-max))
382   ;; Ensure that the part ends with a carriage return.
383   (if (not (bolp))
384       (insert "\n")))
385
386 (defun notmuch-show-insert-body (msg body depth)
387   "Insert the body BODY at depth DEPTH in the current thread."
388   (mapc '(lambda (part) (notmuch-show-insert-bodypart msg part depth)) body))
389
390 (defun notmuch-show-make-symbol (type)
391   (make-symbol (concat "notmuch-show-" type)))
392
393 (defun notmuch-show-strip-re (string)
394   (replace-regexp-in-string "\\([Rr]e: *\\)+" "" string))
395
396 (defvar notmuch-show-previous-subject "")
397 (make-variable-buffer-local 'notmuch-show-previous-subject)
398
399 (defun notmuch-show-insert-msg (msg depth)
400   "Insert the message MSG at depth DEPTH in the current thread."
401   (let* ((headers (plist-get msg :headers))
402          ;; Indentation causes the buffer offset of the start/end
403          ;; points to move, so we must use markers.
404          message-start message-end
405          content-start content-end
406          headers-start headers-end
407          body-start body-end
408          (headers-invis-spec (notmuch-show-make-symbol "header"))
409          (message-invis-spec (notmuch-show-make-symbol "message"))
410          (bare-subject (notmuch-show-strip-re (plist-get headers :Subject))))
411
412     ;; Set `buffer-invisibility-spec' to `nil' (a list), otherwise
413     ;; removing items from `buffer-invisibility-spec' (which is what
414     ;; `notmuch-show-headers-visible' and
415     ;; `notmuch-show-message-visible' do) is a no-op and has no
416     ;; effect. This caused threads with only matching messages to have
417     ;; those messages hidden initially because
418     ;; `buffer-invisibility-spec' stayed `t'.
419     ;;
420     ;; This needs to be set here (rather than just above the call to
421     ;; `notmuch-show-headers-visible') because some of the part
422     ;; rendering or body washing functions
423     ;; (e.g. `notmuch-wash-text/plain-citations') manipulate
424     ;; `buffer-invisibility-spec').
425     (when (eq buffer-invisibility-spec t)
426       (setq buffer-invisibility-spec nil))
427
428     (setq message-start (point-marker))
429
430     (notmuch-show-insert-headerline headers
431                                     (or (if notmuch-show-relative-dates
432                                             (plist-get msg :date_relative)
433                                           nil)
434                                         (plist-get headers :Date))
435                                     (plist-get msg :tags) depth)
436
437     (setq content-start (point-marker))
438
439     ;; Set `headers-start' to point after the 'Subject:' header to be
440     ;; compatible with the existing implementation. This just sets it
441     ;; to after the first header.
442     (notmuch-show-insert-headers headers)
443     ;; Headers should include a blank line (backwards compatibility).
444     (insert "\n")
445     (save-excursion
446       (goto-char content-start)
447       ;; If the subject of this message is the same as that of the
448       ;; previous message, don't display it when this message is
449       ;; collapsed.
450       (when (not (string= notmuch-show-previous-subject
451                           bare-subject))
452         (forward-line 1))
453       (setq headers-start (point-marker)))
454     (setq headers-end (point-marker))
455
456     (setq notmuch-show-previous-subject bare-subject)
457
458     (setq body-start (point-marker))
459     (notmuch-show-insert-body msg (plist-get msg :body) depth)
460     ;; Ensure that the body ends with a newline.
461     (if (not (bolp))
462         (insert "\n"))
463     (setq body-end (point-marker))
464     (setq content-end (point-marker))
465
466     ;; Indent according to the depth in the thread.
467     (indent-rigidly content-start content-end depth)
468
469     (setq message-end (point-max-marker))
470
471     ;; Save the extents of this message over the whole text of the
472     ;; message.
473     (put-text-property message-start message-end :notmuch-message-extent (cons message-start message-end))
474
475     (plist-put msg :headers-invis-spec headers-invis-spec)
476     (overlay-put (make-overlay headers-start headers-end) 'invisible headers-invis-spec)
477
478     (plist-put msg :message-invis-spec message-invis-spec)
479     (overlay-put (make-overlay body-start body-end) 'invisible message-invis-spec)
480
481     ;; Save the properties for this message. Currently this saves the
482     ;; entire message (augmented it with other stuff), which seems
483     ;; like overkill. We might save a reduced subset (for example, not
484     ;; the content).
485     (notmuch-show-set-message-properties msg)
486
487     ;; Set header visibility.
488     (notmuch-show-headers-visible msg notmuch-message-headers-visible)
489
490     ;; Message visibility depends on whether it matched the search
491     ;; criteria.
492     (notmuch-show-message-visible msg (plist-get msg :match))))
493
494 (defun notmuch-show-insert-tree (tree depth)
495   "Insert the message tree TREE at depth DEPTH in the current thread."
496   (let ((msg (car tree))
497         (replies (cadr tree)))
498     (notmuch-show-insert-msg msg depth)
499     (notmuch-show-insert-thread replies (1+ depth))))
500
501 (defun notmuch-show-insert-thread (thread depth)
502   "Insert the thread THREAD at depth DEPTH in the current forest."
503   (mapc '(lambda (tree) (notmuch-show-insert-tree tree depth)) thread))
504
505 (defun notmuch-show-insert-forest (forest)
506   "Insert the forest of threads FOREST."
507   (mapc '(lambda (thread) (notmuch-show-insert-thread thread 0)) forest))
508
509 (defvar notmuch-show-parent-buffer nil)
510
511 ;;;###autoload
512 (defun notmuch-show (thread-id &optional parent-buffer query-context buffer-name)
513   "Run \"notmuch show\" with the given thread ID and display results.
514
515 The optional PARENT-BUFFER is the notmuch-search buffer from
516 which this notmuch-show command was executed, (so that the
517 next thread from that buffer can be show when done with this
518 one).
519
520 The optional QUERY-CONTEXT is a notmuch search term. Only
521 messages from the thread matching this search term are shown if
522 non-nil.
523
524 The optional BUFFER-NAME provides the neame of the buffer in
525 which the message thread is shown. If it is nil (which occurs
526 when the command is called interactively) the argument to the
527 function is used. "
528   (interactive "sNotmuch show: ")
529   (let ((buffer (get-buffer-create (generate-new-buffer-name
530                                     (or buffer-name
531                                         (concat "*notmuch-" thread-id "*")))))
532         (inhibit-read-only t))
533     (switch-to-buffer buffer)
534     (notmuch-show-mode)
535     (set (make-local-variable 'notmuch-show-parent-buffer) parent-buffer)
536     (erase-buffer)
537     (goto-char (point-min))
538     (save-excursion
539       (let* ((basic-args (list thread-id))
540              (args (if query-context
541                        (append (list "\'") basic-args (list "and (" query-context ")\'"))
542                      (append (list "\'") basic-args (list "\'")))))
543         (notmuch-show-insert-forest (notmuch-query-get-threads args))
544         ;; If the query context reduced the results to nothing, run
545         ;; the basic query.
546         (when (and (eq (buffer-size) 0)
547                    query-context)
548           (notmuch-show-insert-forest
549            (notmuch-query-get-threads basic-args))))
550
551       ;; Enable buttonisation of URLs and email addresses in the
552       ;; buffer.
553       (goto-address-mode t)
554       ;; Act on visual lines rather than logical lines.
555       (visual-line-mode t)
556
557       (run-hooks 'notmuch-show-hook))
558
559     ;; Move straight to the first open message
560     (if (not (notmuch-show-message-visible-p))
561         (notmuch-show-next-open-message))
562
563     ;; Set the header line to the subject of the first open message.
564     (setq header-line-format (notmuch-show-strip-re (notmuch-show-get-subject)))
565
566     (notmuch-show-mark-read)))
567
568 (defvar notmuch-show-stash-map
569   (let ((map (make-sparse-keymap)))
570     (define-key map "c" 'notmuch-show-stash-cc)
571     (define-key map "d" 'notmuch-show-stash-date)
572     (define-key map "F" 'notmuch-show-stash-filename)
573     (define-key map "f" 'notmuch-show-stash-from)
574     (define-key map "i" 'notmuch-show-stash-message-id)
575     (define-key map "s" 'notmuch-show-stash-subject)
576     (define-key map "T" 'notmuch-show-stash-tags)
577     (define-key map "t" 'notmuch-show-stash-to)
578     map)
579   "Submap for stash commands")
580 (fset 'notmuch-show-stash-map notmuch-show-stash-map)
581
582 (defvar notmuch-show-mode-map
583       (let ((map (make-sparse-keymap)))
584         (define-key map "?" 'notmuch-help)
585         (define-key map "q" 'notmuch-kill-this-buffer)
586         (define-key map (kbd "<C-tab>") 'widget-backward)
587         (define-key map (kbd "M-TAB") 'notmuch-show-previous-button)
588         (define-key map (kbd "<backtab>") 'notmuch-show-previous-button)
589         (define-key map (kbd "TAB") 'notmuch-show-next-button)
590         (define-key map "s" 'notmuch-search)
591         (define-key map "m" 'notmuch-mua-mail)
592         (define-key map "f" 'notmuch-show-forward-message)
593         (define-key map "r" 'notmuch-show-reply)
594         (define-key map "|" 'notmuch-show-pipe-message)
595         (define-key map "w" 'notmuch-show-save-attachments)
596         (define-key map "V" 'notmuch-show-view-raw-message)
597         (define-key map "v" 'notmuch-show-view-all-mime-parts)
598         (define-key map "c" 'notmuch-show-stash-map)
599         (define-key map "h" 'notmuch-show-toggle-headers)
600         (define-key map "-" 'notmuch-show-remove-tag)
601         (define-key map "+" 'notmuch-show-add-tag)
602         (define-key map "x" 'notmuch-show-archive-thread-then-exit)
603         (define-key map "a" 'notmuch-show-archive-thread)
604         (define-key map "N" 'notmuch-show-next-message)
605         (define-key map "P" 'notmuch-show-previous-message)
606         (define-key map "n" 'notmuch-show-next-open-message)
607         (define-key map "p" 'notmuch-show-previous-open-message)
608         (define-key map (kbd "DEL") 'notmuch-show-rewind)
609         (define-key map " " 'notmuch-show-advance-and-archive)
610         (define-key map (kbd "M-RET") 'notmuch-show-open-or-close-all)
611         (define-key map (kbd "RET") 'notmuch-show-toggle-message)
612         map)
613       "Keymap for \"notmuch show\" buffers.")
614 (fset 'notmuch-show-mode-map notmuch-show-mode-map)
615
616 (defun notmuch-show-mode ()
617   "Major mode for viewing a thread with notmuch.
618
619 This buffer contains the results of the \"notmuch show\" command
620 for displaying a single thread of email from your email archives.
621
622 By default, various components of email messages, (citations,
623 signatures, already-read messages), are hidden. You can make
624 these parts visible by clicking with the mouse button or by
625 pressing RET after positioning the cursor on a hidden part, (for
626 which \\[notmuch-show-next-button] and \\[notmuch-show-previous-button] are helpful).
627
628 Reading the thread sequentially is well-supported by pressing
629 \\[notmuch-show-advance-and-archive]. This will scroll the current message (if necessary), advance
630 to the next message, or advance to the next thread (if already on
631 the last message of a thread).
632
633 Other commands are available to read or manipulate the thread
634 more selectively, (such as '\\[notmuch-show-next-message]' and '\\[notmuch-show-previous-message]' to advance to messages
635 without removing any tags, and '\\[notmuch-show-archive-thread]' to archive an entire thread
636 without scrolling through with \\[notmuch-show-advance-and-archive]).
637
638 You can add or remove arbitary tags from the current message with
639 '\\[notmuch-show-add-tag]' or '\\[notmuch-show-remove-tag]'.
640
641 All currently available key bindings:
642
643 \\{notmuch-show-mode-map}"
644   (interactive)
645   (kill-all-local-variables)
646   (use-local-map notmuch-show-mode-map)
647   (setq major-mode 'notmuch-show-mode
648         mode-name "notmuch-show")
649   (setq buffer-read-only t))
650
651 (defun notmuch-show-move-to-message-top ()
652   (goto-char (notmuch-show-message-top)))
653
654 (defun notmuch-show-move-to-message-bottom ()
655   (goto-char (notmuch-show-message-bottom)))
656
657 (defun notmuch-show-message-adjust ()
658   (recenter 0))
659
660 ;; Movement related functions.
661
662 ;; There's some strangeness here where a text property applied to a
663 ;; region a->b is not found when point is at b. We walk backwards
664 ;; until finding the property.
665 (defun notmuch-show-message-extent ()
666   (let (r)
667     (save-excursion
668       (while (not (setq r (get-text-property (point) :notmuch-message-extent)))
669         (backward-char)))
670     r))
671
672 (defun notmuch-show-message-top ()
673   (car (notmuch-show-message-extent)))
674
675 (defun notmuch-show-message-bottom ()
676   (cdr (notmuch-show-message-extent)))
677
678 (defun notmuch-show-goto-message-next ()
679   (let ((start (point)))
680     (notmuch-show-move-to-message-bottom)
681     (if (not (eobp))
682         t
683       (goto-char start)
684       nil)))
685
686 (defun notmuch-show-goto-message-previous ()
687   (notmuch-show-move-to-message-top)
688   (if (bobp)
689       nil
690     (backward-char)
691     (notmuch-show-move-to-message-top)
692     t))
693
694 (defun notmuch-show-move-past-invisible-forward ()
695   (while (point-invisible-p)
696     (forward-char)))
697
698 (defun notmuch-show-move-past-invisible-backward ()
699   (while (point-invisible-p)
700     (backward-char)))
701
702 ;; Functions relating to the visibility of messages and their
703 ;; components.
704
705 (defun notmuch-show-element-visible (props visible-p spec-property)
706   (let ((spec (plist-get props spec-property)))
707     (if visible-p
708         (remove-from-invisibility-spec spec)
709       (add-to-invisibility-spec spec))))
710
711 (defun notmuch-show-message-visible (props visible-p)
712   (if visible-p
713       ;; When making the message visible, the headers may or not be
714       ;; visible. So we check that property separately.
715       (let ((headers-visible (plist-get props :headers-visible)))
716         (notmuch-show-element-visible props headers-visible :headers-invis-spec)
717         (notmuch-show-element-visible props t :message-invis-spec))
718     (notmuch-show-element-visible props nil :headers-invis-spec)
719     (notmuch-show-element-visible props nil :message-invis-spec))
720
721   (notmuch-show-set-prop :message-visible visible-p props))
722
723 (defun notmuch-show-headers-visible (props visible-p)
724   (if (plist-get props :message-visible)
725       (notmuch-show-element-visible props visible-p :headers-invis-spec))
726   (notmuch-show-set-prop :headers-visible visible-p props))
727
728 ;; Functions for setting and getting attributes of the current
729 ;; message.
730
731 (defun notmuch-show-set-message-properties (props)
732   (save-excursion
733     (notmuch-show-move-to-message-top)
734     (put-text-property (point) (+ (point) 1) :notmuch-message-properties props)))
735
736 (defun notmuch-show-get-message-properties ()
737   (save-excursion
738     (notmuch-show-move-to-message-top)
739     (get-text-property (point) :notmuch-message-properties)))
740
741 (defun notmuch-show-set-prop (prop val &optional props)
742   (let ((inhibit-read-only t)
743         (props (or props
744                    (notmuch-show-get-message-properties))))
745     (plist-put props prop val)
746     (notmuch-show-set-message-properties props)))
747
748 (defun notmuch-show-get-prop (prop &optional props)
749   (let ((props (or props
750                    (notmuch-show-get-message-properties))))
751     (plist-get props prop)))
752
753 (defun notmuch-show-get-message-id ()
754   "Return the message id of the current message."
755   (concat "id:\"" (notmuch-show-get-prop :id) "\""))
756
757 ;; dme: Would it make sense to use a macro for many of these?
758
759 (defun notmuch-show-get-filename ()
760   "Return the filename of the current message."
761   (notmuch-show-get-prop :filename))
762
763 (defun notmuch-show-get-header (header)
764   "Return the named header of the current message, if any."
765   (plist-get (notmuch-show-get-prop :headers) header))
766
767 (defun notmuch-show-get-cc ()
768   (notmuch-show-get-header :Cc))
769
770 (defun notmuch-show-get-date ()
771   (notmuch-show-get-header :Date))
772
773 (defun notmuch-show-get-from ()
774   (notmuch-show-get-header :From))
775
776 (defun notmuch-show-get-subject ()
777   (notmuch-show-get-header :Subject))
778
779 (defun notmuch-show-get-to ()
780   (notmuch-show-get-header :To))
781
782 (defun notmuch-show-set-tags (tags)
783   "Set the tags of the current message."
784   (notmuch-show-set-prop :tags tags)
785   (notmuch-show-update-tags tags))
786
787 (defun notmuch-show-get-tags ()
788   "Return the tags of the current message."
789   (notmuch-show-get-prop :tags))
790
791 (defun notmuch-show-message-visible-p ()
792   "Is the current message visible?"
793   (notmuch-show-get-prop :message-visible))
794
795 (defun notmuch-show-headers-visible-p ()
796   "Are the headers of the current message visible?"
797   (notmuch-show-get-prop :headers-visible))
798
799 (defun notmuch-show-mark-read ()
800   "Mark the current message as read."
801   (notmuch-show-remove-tag "unread"))
802
803 ;; Functions for getting attributes of several messages in the current
804 ;; thread.
805
806 (defun notmuch-show-get-message-ids-for-open-messages ()
807   "Return a list of all message IDs for open messages in the current thread."
808   (save-excursion
809     (let (message-ids done)
810       (goto-char (point-min))
811       (while (not done)
812         (if (notmuch-show-message-visible-p)
813             (setq message-ids (append message-ids (list (notmuch-show-get-message-id)))))
814         (setq done (not (notmuch-show-goto-message-next)))
815         )
816       message-ids
817       )))
818
819 ;; Commands typically bound to keys.
820
821 (defun notmuch-show-advance-and-archive ()
822   "Advance through thread and archive.
823
824 This command is intended to be one of the simplest ways to
825 process a thread of email. It does the following:
826
827 If the current message in the thread is not yet fully visible,
828 scroll by a near screenful to read more of the message.
829
830 Otherwise, (the end of the current message is already within the
831 current window), advance to the next open message.
832
833 Finally, if there is no further message to advance to, and this
834 last message is already read, then archive the entire current
835 thread, (remove the \"inbox\" tag from each message). Also kill
836 this buffer, and display the next thread from the search from
837 which this thread was originally shown."
838   (interactive)
839   (let ((end-of-this-message (notmuch-show-message-bottom)))
840     (cond
841      ;; Ideally we would test `end-of-this-message' against the result
842      ;; of `window-end', but that doesn't account for the fact that
843      ;; the end of the message might be hidden, so we have to actually
844      ;; go to the end, walk back over invisible text and then see if
845      ;; point is visible.
846      ((save-excursion
847         (goto-char (- end-of-this-message 1))
848         (notmuch-show-move-past-invisible-backward)
849         (> (point) (window-end)))
850       ;; The bottom of this message is not visible - scroll.
851       (scroll-up nil))
852
853      ((not (= end-of-this-message (point-max)))
854       ;; This is not the last message - move to the next visible one.
855       (notmuch-show-next-open-message))
856
857      (t
858       ;; This is the last message - archive the thread.
859       (notmuch-show-archive-thread)))))
860
861 (defun notmuch-show-rewind ()
862   "Backup through the thread, (reverse scrolling compared to \\[notmuch-show-advance-and-archive]).
863
864 Specifically, if the beginning of the previous email is fewer
865 than `window-height' lines from the current point, move to it
866 just like `notmuch-show-previous-message'.
867
868 Otherwise, just scroll down a screenful of the current message.
869
870 This command does not modify any message tags, (it does not undo
871 any effects from previous calls to
872 `notmuch-show-advance-and-archive'."
873   (interactive)
874   (let ((start-of-message (notmuch-show-message-top))
875         (start-of-window (window-start)))
876     (cond
877       ;; Either this message is properly aligned with the start of the
878       ;; window or the start of this message is not visible on the
879       ;; screen - scroll.
880      ((or (= start-of-message start-of-window)
881           (< start-of-message start-of-window))
882       (scroll-down)
883       ;; If a small number of lines from the previous message are
884       ;; visible, realign so that the top of the current message is at
885       ;; the top of the screen.
886       (if (<= (count-screen-lines (window-start) start-of-message)
887               next-screen-context-lines)
888           (progn
889             (goto-char (notmuch-show-message-top))
890             (notmuch-show-message-adjust)))
891       ;; Move to the top left of the window.
892       (goto-char (window-start)))
893      (t
894       ;; Move to the previous message.
895       (notmuch-show-previous-message)))))
896
897 (defun notmuch-show-reply ()
898   "Reply to the current message."
899   (interactive)
900   (notmuch-mua-reply (notmuch-show-get-message-id)))
901
902 (defun notmuch-show-forward-message ()
903   "Forward the current message."
904   (interactive)
905   (with-current-notmuch-show-message
906    (notmuch-mua-forward-message)))
907
908 (defun notmuch-show-next-message ()
909   "Show the next message."
910   (interactive)
911   (if (notmuch-show-goto-message-next)
912       (progn
913         (notmuch-show-mark-read)
914         (notmuch-show-message-adjust))
915     (goto-char (point-max))))
916
917 (defun notmuch-show-previous-message ()
918   "Show the previous message."
919   (interactive)
920   (notmuch-show-goto-message-previous)
921   (notmuch-show-mark-read)
922   (notmuch-show-message-adjust))
923
924 (defun notmuch-show-next-open-message ()
925   "Show the next message."
926   (interactive)
927   (let (r)
928     (while (and (setq r (notmuch-show-goto-message-next))
929                 (not (notmuch-show-message-visible-p))))
930     (if r
931         (progn
932           (notmuch-show-mark-read)
933           (notmuch-show-message-adjust))
934       (goto-char (point-max)))))
935
936 (defun notmuch-show-previous-open-message ()
937   "Show the previous message."
938   (interactive)
939   (while (and (notmuch-show-goto-message-previous)
940               (not (notmuch-show-message-visible-p))))
941   (notmuch-show-mark-read)
942   (notmuch-show-message-adjust))
943
944 (defun notmuch-show-view-raw-message ()
945   "View the file holding the current message."
946   (interactive)
947   (let* ((id (notmuch-show-get-message-id))
948          (buf (get-buffer-create (concat "*notmuch-raw-" id "*"))))
949     (call-process notmuch-command nil buf nil "show" "--format=raw" id)
950     (switch-to-buffer buf)
951     (goto-char (point-min))
952     (set-buffer-modified-p nil)
953     (view-buffer buf 'kill-buffer-if-not-modified)))
954
955 (defun notmuch-show-pipe-message (entire-thread command)
956   "Pipe the contents of the current message (or thread) to the given command.
957
958 The given command will be executed with the raw contents of the
959 current email message as stdin. Anything printed by the command
960 to stdout or stderr will appear in the *notmuch-pipe* buffer.
961
962 When invoked with a prefix argument, the command will receive all
963 open messages in the current thread (formatted as an mbox) rather
964 than only the current message."
965   (interactive "P\nsPipe message to command: ")
966   (let (shell-command)
967     (if entire-thread
968         (setq shell-command 
969               (concat notmuch-command " show --format=mbox "
970                       (shell-quote-argument
971                        (mapconcat 'identity (notmuch-show-get-message-ids-for-open-messages) " OR "))
972                       " | " command))
973       (setq shell-command
974             (concat notmuch-command " show --format=raw "
975                     (shell-quote-argument (notmuch-show-get-message-id)) " | " command)))
976     (let ((buf (get-buffer-create (concat "*notmuch-pipe*"))))
977       (with-current-buffer buf
978         (setq buffer-read-only nil)
979         (erase-buffer)
980         (let ((exit-code (call-process-shell-command shell-command nil buf)))
981           (goto-char (point-max))
982           (set-buffer-modified-p nil)
983           (setq buffer-read-only t)
984           (unless (zerop exit-code)
985             (switch-to-buffer-other-window buf)
986             (message (format "Command '%s' exited abnormally with code %d"
987                              shell-command exit-code))))))))
988
989 (defun notmuch-show-add-tags-worker (current-tags add-tags)
990   "Add to `current-tags' with any tags from `add-tags' not
991 currently present and return the result."
992   (let ((result-tags (copy-sequence current-tags)))
993     (mapc (lambda (add-tag)
994             (unless (member add-tag current-tags)
995               (setq result-tags (push add-tag result-tags))))
996             add-tags)
997     (sort result-tags 'string<)))
998
999 (defun notmuch-show-del-tags-worker (current-tags del-tags)
1000   "Remove any tags in `del-tags' from `current-tags' and return
1001 the result."
1002   (let ((result-tags (copy-sequence current-tags)))
1003     (mapc (lambda (del-tag)
1004             (setq result-tags (delete del-tag result-tags)))
1005           del-tags)
1006     result-tags))
1007
1008 (defun notmuch-show-add-tag (&rest toadd)
1009   "Add a tag to the current message."
1010   (interactive
1011    (list (notmuch-select-tag-with-completion "Tag to add: ")))
1012
1013   (let* ((current-tags (notmuch-show-get-tags))
1014          (new-tags (notmuch-show-add-tags-worker current-tags toadd)))
1015
1016     (unless (equal current-tags new-tags)
1017       (apply 'notmuch-call-notmuch-process
1018              (append (cons "tag"
1019                            (mapcar (lambda (s) (concat "+" s)) toadd))
1020                      (cons (notmuch-show-get-message-id) nil)))
1021       (notmuch-show-set-tags new-tags))))
1022
1023 (defun notmuch-show-remove-tag (&rest toremove)
1024   "Remove a tag from the current message."
1025   (interactive
1026    (list (notmuch-select-tag-with-completion
1027           "Tag to remove: " (notmuch-show-get-message-id))))
1028
1029   (let* ((current-tags (notmuch-show-get-tags))
1030          (new-tags (notmuch-show-del-tags-worker current-tags toremove)))
1031
1032     (unless (equal current-tags new-tags)
1033       (apply 'notmuch-call-notmuch-process
1034              (append (cons "tag"
1035                            (mapcar (lambda (s) (concat "-" s)) toremove))
1036                      (cons (notmuch-show-get-message-id) nil)))
1037       (notmuch-show-set-tags new-tags))))
1038
1039 (defun notmuch-show-toggle-headers ()
1040   "Toggle the visibility of the current message headers."
1041   (interactive)
1042   (let ((props (notmuch-show-get-message-properties)))
1043     (notmuch-show-headers-visible
1044      props
1045      (not (plist-get props :headers-visible))))
1046   (force-window-update))
1047
1048 (defun notmuch-show-toggle-message ()
1049   "Toggle the visibility of the current message."
1050   (interactive)
1051   (let ((props (notmuch-show-get-message-properties)))
1052     (notmuch-show-message-visible
1053      props
1054      (not (plist-get props :message-visible))))
1055   (force-window-update))
1056
1057 (defun notmuch-show-open-or-close-all ()
1058   "Set the visibility all of the messages in the current thread.
1059 By default make all of the messages visible. With a prefix
1060 argument, hide all of the messages."
1061   (interactive)
1062   (save-excursion
1063     (goto-char (point-min))
1064     (loop do (notmuch-show-message-visible (notmuch-show-get-message-properties)
1065                                            (not current-prefix-arg))
1066           until (not (notmuch-show-goto-message-next))))
1067   (force-window-update))
1068
1069 (defun notmuch-show-next-button ()
1070   "Advance point to the next button in the buffer."
1071   (interactive)
1072   (forward-button 1))
1073
1074 (defun notmuch-show-previous-button ()
1075   "Move point back to the previous button in the buffer."
1076   (interactive)
1077   (backward-button 1))
1078
1079 (defun notmuch-show-archive-thread-internal (show-next)
1080   ;; Remove the tag from the current set of messages.
1081   (goto-char (point-min))
1082   (loop do (notmuch-show-remove-tag "inbox")
1083         until (not (notmuch-show-goto-message-next)))
1084   ;; Move to the next item in the search results, if any.
1085   (let ((parent-buffer notmuch-show-parent-buffer))
1086     (notmuch-kill-this-buffer)
1087     (if parent-buffer
1088         (progn
1089           (switch-to-buffer parent-buffer)
1090           (forward-line)
1091           (if show-next
1092               (notmuch-search-show-thread))))))
1093
1094 (defun notmuch-show-archive-thread ()
1095   "Archive each message in thread, then show next thread from search.
1096
1097 Archive each message currently shown by removing the \"inbox\"
1098 tag from each. Then kill this buffer and show the next thread
1099 from the search from which this thread was originally shown.
1100
1101 Note: This command is safe from any race condition of new messages
1102 being delivered to the same thread. It does not archive the
1103 entire thread, but only the messages shown in the current
1104 buffer."
1105   (interactive)
1106   (notmuch-show-archive-thread-internal t))
1107
1108 (defun notmuch-show-archive-thread-then-exit ()
1109   "Archive each message in thread, then exit back to search results."
1110   (interactive)
1111   (notmuch-show-archive-thread-internal nil))
1112
1113 (defun notmuch-show-stash-cc ()
1114   "Copy CC field of current message to kill-ring."
1115   (interactive)
1116   (notmuch-common-do-stash (notmuch-show-get-cc)))
1117
1118 (defun notmuch-show-stash-date ()
1119   "Copy date of current message to kill-ring."
1120   (interactive)
1121   (notmuch-common-do-stash (notmuch-show-get-date)))
1122
1123 (defun notmuch-show-stash-filename ()
1124   "Copy filename of current message to kill-ring."
1125   (interactive)
1126   (notmuch-common-do-stash (notmuch-show-get-filename)))
1127
1128 (defun notmuch-show-stash-from ()
1129   "Copy From address of current message to kill-ring."
1130   (interactive)
1131   (notmuch-common-do-stash (notmuch-show-get-from)))
1132
1133 (defun notmuch-show-stash-message-id ()
1134   "Copy message ID of current message to kill-ring."
1135   (interactive)
1136   (notmuch-common-do-stash (notmuch-show-get-message-id)))
1137
1138 (defun notmuch-show-stash-subject ()
1139   "Copy Subject field of current message to kill-ring."
1140   (interactive)
1141   (notmuch-common-do-stash (notmuch-show-get-subject)))
1142
1143 (defun notmuch-show-stash-tags ()
1144   "Copy tags of current message to kill-ring as a comma separated list."
1145   (interactive)
1146   (notmuch-common-do-stash (mapconcat 'identity (notmuch-show-get-tags) ",")))
1147
1148 (defun notmuch-show-stash-to ()
1149   "Copy To address of current message to kill-ring."
1150   (interactive)
1151   (notmuch-common-do-stash (notmuch-show-get-to)))
1152
1153 ;; Commands typically bound to buttons.
1154
1155 (defun notmuch-show-part-button-action (button)
1156   (let ((nth (button-get button :notmuch-part)))
1157     (if nth
1158         (notmuch-show-save-part (notmuch-show-get-message-id) nth
1159                                 (button-get button :notmuch-filename))
1160       (message "Not a valid part (is it a fake part?)."))))
1161
1162 ;;
1163
1164 (provide 'notmuch-show)