]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-show.el
emacs: add more part handling functions
[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/alternative (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     ;; In most cases, multipart/alternative is used to provide both
287     ;; text/plain and text/html (or multipart/related with text/html
288     ;; and image/*) parts. We might allow the user to express a
289     ;; preference about which part to show, but for the moment we just
290     ;; choose the first. This is usually the text/plain part.
291     (notmuch-show-insert-bodypart msg (car inner-parts) depth)
292     (mapc (lambda (inner-part)
293             (let ((inner-type (concat (plist-get inner-part :content-type) " (not shown)")))
294               (notmuch-show-insert-part-header (plist-get inner-part :id) inner-type inner-type nil)))
295           (cdr inner-parts)))
296   t)
297
298 (defun notmuch-show-insert-part-multipart/* (msg part content-type nth depth declared-type)
299   (let ((inner-parts (plist-get part :content)))
300     (notmuch-show-insert-part-header nth declared-type content-type nil)
301     ;; Show all of the parts.
302     (mapc (lambda (inner-part)
303             (notmuch-show-insert-bodypart msg inner-part depth))
304           inner-parts))
305   t)
306
307 (defun notmuch-show-insert-part-message/rfc822 (msg part content-type nth depth declared-type)
308   (let* ((message-part (plist-get part :content))
309          (inner-parts (plist-get message-part :content)))
310     (notmuch-show-insert-part-header nth declared-type content-type nil)
311     ;; Override `notmuch-message-headers' to force `From' to be
312     ;; displayed.
313     (let ((notmuch-message-headers '("From" "Subject" "To" "Cc" "Date")))
314       (notmuch-show-insert-headers (plist-get part :headers)))
315     ;; Blank line after headers to be compatible with the normal
316     ;; message display.
317     (insert "\n")
318
319     ;; Show all of the parts.
320     (mapc (lambda (inner-part)
321             (notmuch-show-insert-bodypart msg inner-part depth))
322           inner-parts))
323   t)
324
325 (defun notmuch-show-insert-part-text/plain (msg part content-type nth depth declared-type)
326   (let ((start (point)))
327     ;; If this text/plain part is not the first part in the message,
328     ;; insert a header to make this clear.
329     (if (> nth 1)
330         (notmuch-show-insert-part-header nth declared-type content-type (plist-get part :filename)))
331     (insert (notmuch-show-get-bodypart-content msg part nth))
332     (save-excursion
333       (save-restriction
334         (narrow-to-region start (point-max))
335         (run-hook-with-args 'notmuch-show-insert-text/plain-hook depth))))
336   t)
337
338 (defun notmuch-show-insert-part-application/octet-stream (msg part content-type nth depth declared-type)
339   ;; If we can deduce a MIME type from the filename of the attachment,
340   ;; do so and pass it on to the handler for that type.
341   (if (plist-get part :filename)
342       (let ((extension (file-name-extension (plist-get part :filename)))
343             mime-type)
344         (if extension
345             (progn
346               (mailcap-parse-mimetypes)
347               (setq mime-type (mailcap-extension-to-mime extension))
348               (if (and mime-type
349                        (not (string-equal mime-type "application/octet-stream")))
350                   (notmuch-show-insert-bodypart-internal msg part mime-type nth depth content-type)
351                 nil))
352           nil))))
353
354 (defun notmuch-show-insert-part-*/* (msg part content-type nth depth declared-type)
355   ;; This handler _must_ succeed - it is the handler of last resort.
356   (notmuch-show-insert-part-header nth content-type declared-type (plist-get part :filename))
357   (let ((content (notmuch-show-get-bodypart-content msg part nth)))
358     (if content
359         (notmuch-show-mm-display-part-inline msg part content-type content)))
360   t)
361
362 ;; Functions for determining how to handle MIME parts.
363
364 (defun notmuch-show-split-content-type (content-type)
365   (split-string content-type "/"))
366
367 (defun notmuch-show-handlers-for (content-type)
368   "Return a list of content handlers for a part of type CONTENT-TYPE."
369   (let (result)
370     (mapc (lambda (func)
371             (if (functionp func)
372                 (push func result)))
373           ;; Reverse order of prefrence.
374           (list (intern (concat "notmuch-show-insert-part-*/*"))
375                 (intern (concat
376                          "notmuch-show-insert-part-"
377                          (car (notmuch-show-split-content-type content-type))
378                          "/*"))
379                 (intern (concat "notmuch-show-insert-part-" content-type))))
380     result))
381
382 ;; Helper for parts which are generally not included in the default
383 ;; JSON output.
384
385 (defun notmuch-show-get-bodypart-internal (message-id part-number)
386   (with-temp-buffer
387     (let ((coding-system-for-read 'no-conversion))
388       (call-process notmuch-command nil t nil
389                     "part" (format "--part=%s" part-number) message-id)
390       (buffer-string))))
391
392 (defun notmuch-show-get-bodypart-content (msg part nth)
393   (or (plist-get part :content)
394       (notmuch-show-get-bodypart-internal (concat "id:" (plist-get msg :id)) nth)))
395
396 ;; \f
397
398 (defun notmuch-show-insert-bodypart-internal (msg part content-type nth depth declared-type)
399   (let ((handlers (notmuch-show-handlers-for content-type)))
400     ;; Run the content handlers until one of them returns a non-nil
401     ;; value.
402     (while (and handlers
403                 (not (funcall (car handlers) msg part content-type nth depth declared-type)))
404       (setq handlers (cdr handlers))))
405   t)
406
407 (defun notmuch-show-insert-bodypart (msg part depth)
408   "Insert the body part PART at depth DEPTH in the current thread."
409   (let ((content-type (downcase (plist-get part :content-type)))
410         (nth (plist-get part :id)))
411     (notmuch-show-insert-bodypart-internal msg part content-type nth depth content-type))
412   ;; Some of the body part handlers leave point somewhere up in the
413   ;; part, so we make sure that we're down at the end.
414   (goto-char (point-max))
415   ;; Ensure that the part ends with a carriage return.
416   (if (not (bolp))
417       (insert "\n")))
418
419 (defun notmuch-show-insert-body (msg body depth)
420   "Insert the body BODY at depth DEPTH in the current thread."
421   (mapc '(lambda (part) (notmuch-show-insert-bodypart msg part depth)) body))
422
423 (defun notmuch-show-make-symbol (type)
424   (make-symbol (concat "notmuch-show-" type)))
425
426 (defun notmuch-show-strip-re (string)
427   (replace-regexp-in-string "\\([Rr]e: *\\)+" "" string))
428
429 (defvar notmuch-show-previous-subject "")
430 (make-variable-buffer-local 'notmuch-show-previous-subject)
431
432 (defun notmuch-show-insert-msg (msg depth)
433   "Insert the message MSG at depth DEPTH in the current thread."
434   (let* ((headers (plist-get msg :headers))
435          ;; Indentation causes the buffer offset of the start/end
436          ;; points to move, so we must use markers.
437          message-start message-end
438          content-start content-end
439          headers-start headers-end
440          body-start body-end
441          (headers-invis-spec (notmuch-show-make-symbol "header"))
442          (message-invis-spec (notmuch-show-make-symbol "message"))
443          (bare-subject (notmuch-show-strip-re (plist-get headers :Subject))))
444
445     ;; Set `buffer-invisibility-spec' to `nil' (a list), otherwise
446     ;; removing items from `buffer-invisibility-spec' (which is what
447     ;; `notmuch-show-headers-visible' and
448     ;; `notmuch-show-message-visible' do) is a no-op and has no
449     ;; effect. This caused threads with only matching messages to have
450     ;; those messages hidden initially because
451     ;; `buffer-invisibility-spec' stayed `t'.
452     ;;
453     ;; This needs to be set here (rather than just above the call to
454     ;; `notmuch-show-headers-visible') because some of the part
455     ;; rendering or body washing functions
456     ;; (e.g. `notmuch-wash-text/plain-citations') manipulate
457     ;; `buffer-invisibility-spec').
458     (when (eq buffer-invisibility-spec t)
459       (setq buffer-invisibility-spec nil))
460
461     (setq message-start (point-marker))
462
463     (notmuch-show-insert-headerline headers
464                                     (or (if notmuch-show-relative-dates
465                                             (plist-get msg :date_relative)
466                                           nil)
467                                         (plist-get headers :Date))
468                                     (plist-get msg :tags) depth)
469
470     (setq content-start (point-marker))
471
472     ;; Set `headers-start' to point after the 'Subject:' header to be
473     ;; compatible with the existing implementation. This just sets it
474     ;; to after the first header.
475     (notmuch-show-insert-headers headers)
476     ;; Headers should include a blank line (backwards compatibility).
477     (insert "\n")
478     (save-excursion
479       (goto-char content-start)
480       ;; If the subject of this message is the same as that of the
481       ;; previous message, don't display it when this message is
482       ;; collapsed.
483       (when (not (string= notmuch-show-previous-subject
484                           bare-subject))
485         (forward-line 1))
486       (setq headers-start (point-marker)))
487     (setq headers-end (point-marker))
488
489     (setq notmuch-show-previous-subject bare-subject)
490
491     (setq body-start (point-marker))
492     (notmuch-show-insert-body msg (plist-get msg :body) depth)
493     ;; Ensure that the body ends with a newline.
494     (if (not (bolp))
495         (insert "\n"))
496     (setq body-end (point-marker))
497     (setq content-end (point-marker))
498
499     ;; Indent according to the depth in the thread.
500     (indent-rigidly content-start content-end depth)
501
502     (setq message-end (point-max-marker))
503
504     ;; Save the extents of this message over the whole text of the
505     ;; message.
506     (put-text-property message-start message-end :notmuch-message-extent (cons message-start message-end))
507
508     (plist-put msg :headers-invis-spec headers-invis-spec)
509     (overlay-put (make-overlay headers-start headers-end) 'invisible headers-invis-spec)
510
511     (plist-put msg :message-invis-spec message-invis-spec)
512     (overlay-put (make-overlay body-start body-end) 'invisible message-invis-spec)
513
514     ;; Save the properties for this message. Currently this saves the
515     ;; entire message (augmented it with other stuff), which seems
516     ;; like overkill. We might save a reduced subset (for example, not
517     ;; the content).
518     (notmuch-show-set-message-properties msg)
519
520     ;; Set header visibility.
521     (notmuch-show-headers-visible msg notmuch-message-headers-visible)
522
523     ;; Message visibility depends on whether it matched the search
524     ;; criteria.
525     (notmuch-show-message-visible msg (plist-get msg :match))))
526
527 (defun notmuch-show-insert-tree (tree depth)
528   "Insert the message tree TREE at depth DEPTH in the current thread."
529   (let ((msg (car tree))
530         (replies (cadr tree)))
531     (notmuch-show-insert-msg msg depth)
532     (notmuch-show-insert-thread replies (1+ depth))))
533
534 (defun notmuch-show-insert-thread (thread depth)
535   "Insert the thread THREAD at depth DEPTH in the current forest."
536   (mapc '(lambda (tree) (notmuch-show-insert-tree tree depth)) thread))
537
538 (defun notmuch-show-insert-forest (forest)
539   "Insert the forest of threads FOREST."
540   (mapc '(lambda (thread) (notmuch-show-insert-thread thread 0)) forest))
541
542 (defvar notmuch-show-parent-buffer nil)
543
544 ;;;###autoload
545 (defun notmuch-show (thread-id &optional parent-buffer query-context buffer-name)
546   "Run \"notmuch show\" with the given thread ID and display results.
547
548 The optional PARENT-BUFFER is the notmuch-search buffer from
549 which this notmuch-show command was executed, (so that the
550 next thread from that buffer can be show when done with this
551 one).
552
553 The optional QUERY-CONTEXT is a notmuch search term. Only
554 messages from the thread matching this search term are shown if
555 non-nil.
556
557 The optional BUFFER-NAME provides the neame of the buffer in
558 which the message thread is shown. If it is nil (which occurs
559 when the command is called interactively) the argument to the
560 function is used. "
561   (interactive "sNotmuch show: ")
562   (let ((buffer (get-buffer-create (generate-new-buffer-name
563                                     (or buffer-name
564                                         (concat "*notmuch-" thread-id "*")))))
565         (inhibit-read-only t))
566     (switch-to-buffer buffer)
567     (notmuch-show-mode)
568     (set (make-local-variable 'notmuch-show-parent-buffer) parent-buffer)
569     (erase-buffer)
570     (goto-char (point-min))
571     (save-excursion
572       (let* ((basic-args (list thread-id))
573              (args (if query-context
574                        (append (list "\'") basic-args (list "and (" query-context ")\'"))
575                      (append (list "\'") basic-args (list "\'")))))
576         (notmuch-show-insert-forest (notmuch-query-get-threads args))
577         ;; If the query context reduced the results to nothing, run
578         ;; the basic query.
579         (when (and (eq (buffer-size) 0)
580                    query-context)
581           (notmuch-show-insert-forest
582            (notmuch-query-get-threads basic-args))))
583
584       ;; Enable buttonisation of URLs and email addresses in the
585       ;; buffer.
586       (goto-address-mode t)
587       ;; Act on visual lines rather than logical lines.
588       (visual-line-mode t)
589
590       (run-hooks 'notmuch-show-hook))
591
592     ;; Move straight to the first open message
593     (if (not (notmuch-show-message-visible-p))
594         (notmuch-show-next-open-message))
595
596     ;; Set the header line to the subject of the first open message.
597     (setq header-line-format (notmuch-show-strip-re (notmuch-show-get-subject)))
598
599     (notmuch-show-mark-read)))
600
601 (defvar notmuch-show-stash-map
602   (let ((map (make-sparse-keymap)))
603     (define-key map "c" 'notmuch-show-stash-cc)
604     (define-key map "d" 'notmuch-show-stash-date)
605     (define-key map "F" 'notmuch-show-stash-filename)
606     (define-key map "f" 'notmuch-show-stash-from)
607     (define-key map "i" 'notmuch-show-stash-message-id)
608     (define-key map "s" 'notmuch-show-stash-subject)
609     (define-key map "T" 'notmuch-show-stash-tags)
610     (define-key map "t" 'notmuch-show-stash-to)
611     map)
612   "Submap for stash commands")
613 (fset 'notmuch-show-stash-map notmuch-show-stash-map)
614
615 (defvar notmuch-show-mode-map
616       (let ((map (make-sparse-keymap)))
617         (define-key map "?" 'notmuch-help)
618         (define-key map "q" 'notmuch-kill-this-buffer)
619         (define-key map (kbd "<C-tab>") 'widget-backward)
620         (define-key map (kbd "M-TAB") 'notmuch-show-previous-button)
621         (define-key map (kbd "<backtab>") 'notmuch-show-previous-button)
622         (define-key map (kbd "TAB") 'notmuch-show-next-button)
623         (define-key map "s" 'notmuch-search)
624         (define-key map "m" 'notmuch-mua-mail)
625         (define-key map "f" 'notmuch-show-forward-message)
626         (define-key map "r" 'notmuch-show-reply)
627         (define-key map "|" 'notmuch-show-pipe-message)
628         (define-key map "w" 'notmuch-show-save-attachments)
629         (define-key map "V" 'notmuch-show-view-raw-message)
630         (define-key map "v" 'notmuch-show-view-all-mime-parts)
631         (define-key map "c" 'notmuch-show-stash-map)
632         (define-key map "h" 'notmuch-show-toggle-headers)
633         (define-key map "-" 'notmuch-show-remove-tag)
634         (define-key map "+" 'notmuch-show-add-tag)
635         (define-key map "x" 'notmuch-show-archive-thread-then-exit)
636         (define-key map "a" 'notmuch-show-archive-thread)
637         (define-key map "N" 'notmuch-show-next-message)
638         (define-key map "P" 'notmuch-show-previous-message)
639         (define-key map "n" 'notmuch-show-next-open-message)
640         (define-key map "p" 'notmuch-show-previous-open-message)
641         (define-key map (kbd "DEL") 'notmuch-show-rewind)
642         (define-key map " " 'notmuch-show-advance-and-archive)
643         (define-key map (kbd "M-RET") 'notmuch-show-open-or-close-all)
644         (define-key map (kbd "RET") 'notmuch-show-toggle-message)
645         map)
646       "Keymap for \"notmuch show\" buffers.")
647 (fset 'notmuch-show-mode-map notmuch-show-mode-map)
648
649 (defun notmuch-show-mode ()
650   "Major mode for viewing a thread with notmuch.
651
652 This buffer contains the results of the \"notmuch show\" command
653 for displaying a single thread of email from your email archives.
654
655 By default, various components of email messages, (citations,
656 signatures, already-read messages), are hidden. You can make
657 these parts visible by clicking with the mouse button or by
658 pressing RET after positioning the cursor on a hidden part, (for
659 which \\[notmuch-show-next-button] and \\[notmuch-show-previous-button] are helpful).
660
661 Reading the thread sequentially is well-supported by pressing
662 \\[notmuch-show-advance-and-archive]. This will scroll the current message (if necessary), advance
663 to the next message, or advance to the next thread (if already on
664 the last message of a thread).
665
666 Other commands are available to read or manipulate the thread
667 more selectively, (such as '\\[notmuch-show-next-message]' and '\\[notmuch-show-previous-message]' to advance to messages
668 without removing any tags, and '\\[notmuch-show-archive-thread]' to archive an entire thread
669 without scrolling through with \\[notmuch-show-advance-and-archive]).
670
671 You can add or remove arbitary tags from the current message with
672 '\\[notmuch-show-add-tag]' or '\\[notmuch-show-remove-tag]'.
673
674 All currently available key bindings:
675
676 \\{notmuch-show-mode-map}"
677   (interactive)
678   (kill-all-local-variables)
679   (use-local-map notmuch-show-mode-map)
680   (setq major-mode 'notmuch-show-mode
681         mode-name "notmuch-show")
682   (setq buffer-read-only t))
683
684 (defun notmuch-show-move-to-message-top ()
685   (goto-char (notmuch-show-message-top)))
686
687 (defun notmuch-show-move-to-message-bottom ()
688   (goto-char (notmuch-show-message-bottom)))
689
690 (defun notmuch-show-message-adjust ()
691   (recenter 0))
692
693 ;; Movement related functions.
694
695 ;; There's some strangeness here where a text property applied to a
696 ;; region a->b is not found when point is at b. We walk backwards
697 ;; until finding the property.
698 (defun notmuch-show-message-extent ()
699   (let (r)
700     (save-excursion
701       (while (not (setq r (get-text-property (point) :notmuch-message-extent)))
702         (backward-char)))
703     r))
704
705 (defun notmuch-show-message-top ()
706   (car (notmuch-show-message-extent)))
707
708 (defun notmuch-show-message-bottom ()
709   (cdr (notmuch-show-message-extent)))
710
711 (defun notmuch-show-goto-message-next ()
712   (let ((start (point)))
713     (notmuch-show-move-to-message-bottom)
714     (if (not (eobp))
715         t
716       (goto-char start)
717       nil)))
718
719 (defun notmuch-show-goto-message-previous ()
720   (notmuch-show-move-to-message-top)
721   (if (bobp)
722       nil
723     (backward-char)
724     (notmuch-show-move-to-message-top)
725     t))
726
727 (defun notmuch-show-move-past-invisible-forward ()
728   (while (point-invisible-p)
729     (forward-char)))
730
731 (defun notmuch-show-move-past-invisible-backward ()
732   (while (point-invisible-p)
733     (backward-char)))
734
735 ;; Functions relating to the visibility of messages and their
736 ;; components.
737
738 (defun notmuch-show-element-visible (props visible-p spec-property)
739   (let ((spec (plist-get props spec-property)))
740     (if visible-p
741         (remove-from-invisibility-spec spec)
742       (add-to-invisibility-spec spec))))
743
744 (defun notmuch-show-message-visible (props visible-p)
745   (if visible-p
746       ;; When making the message visible, the headers may or not be
747       ;; visible. So we check that property separately.
748       (let ((headers-visible (plist-get props :headers-visible)))
749         (notmuch-show-element-visible props headers-visible :headers-invis-spec)
750         (notmuch-show-element-visible props t :message-invis-spec))
751     (notmuch-show-element-visible props nil :headers-invis-spec)
752     (notmuch-show-element-visible props nil :message-invis-spec))
753
754   (notmuch-show-set-prop :message-visible visible-p props))
755
756 (defun notmuch-show-headers-visible (props visible-p)
757   (if (plist-get props :message-visible)
758       (notmuch-show-element-visible props visible-p :headers-invis-spec))
759   (notmuch-show-set-prop :headers-visible visible-p props))
760
761 ;; Functions for setting and getting attributes of the current
762 ;; message.
763
764 (defun notmuch-show-set-message-properties (props)
765   (save-excursion
766     (notmuch-show-move-to-message-top)
767     (put-text-property (point) (+ (point) 1) :notmuch-message-properties props)))
768
769 (defun notmuch-show-get-message-properties ()
770   (save-excursion
771     (notmuch-show-move-to-message-top)
772     (get-text-property (point) :notmuch-message-properties)))
773
774 (defun notmuch-show-set-prop (prop val &optional props)
775   (let ((inhibit-read-only t)
776         (props (or props
777                    (notmuch-show-get-message-properties))))
778     (plist-put props prop val)
779     (notmuch-show-set-message-properties props)))
780
781 (defun notmuch-show-get-prop (prop &optional props)
782   (let ((props (or props
783                    (notmuch-show-get-message-properties))))
784     (plist-get props prop)))
785
786 (defun notmuch-show-get-message-id ()
787   "Return the message id of the current message."
788   (concat "id:\"" (notmuch-show-get-prop :id) "\""))
789
790 ;; dme: Would it make sense to use a macro for many of these?
791
792 (defun notmuch-show-get-filename ()
793   "Return the filename of the current message."
794   (notmuch-show-get-prop :filename))
795
796 (defun notmuch-show-get-header (header)
797   "Return the named header of the current message, if any."
798   (plist-get (notmuch-show-get-prop :headers) header))
799
800 (defun notmuch-show-get-cc ()
801   (notmuch-show-get-header :Cc))
802
803 (defun notmuch-show-get-date ()
804   (notmuch-show-get-header :Date))
805
806 (defun notmuch-show-get-from ()
807   (notmuch-show-get-header :From))
808
809 (defun notmuch-show-get-subject ()
810   (notmuch-show-get-header :Subject))
811
812 (defun notmuch-show-get-to ()
813   (notmuch-show-get-header :To))
814
815 (defun notmuch-show-set-tags (tags)
816   "Set the tags of the current message."
817   (notmuch-show-set-prop :tags tags)
818   (notmuch-show-update-tags tags))
819
820 (defun notmuch-show-get-tags ()
821   "Return the tags of the current message."
822   (notmuch-show-get-prop :tags))
823
824 (defun notmuch-show-message-visible-p ()
825   "Is the current message visible?"
826   (notmuch-show-get-prop :message-visible))
827
828 (defun notmuch-show-headers-visible-p ()
829   "Are the headers of the current message visible?"
830   (notmuch-show-get-prop :headers-visible))
831
832 (defun notmuch-show-mark-read ()
833   "Mark the current message as read."
834   (notmuch-show-remove-tag "unread"))
835
836 ;; Functions for getting attributes of several messages in the current
837 ;; thread.
838
839 (defun notmuch-show-get-message-ids-for-open-messages ()
840   "Return a list of all message IDs for open messages in the current thread."
841   (save-excursion
842     (let (message-ids done)
843       (goto-char (point-min))
844       (while (not done)
845         (if (notmuch-show-message-visible-p)
846             (setq message-ids (append message-ids (list (notmuch-show-get-message-id)))))
847         (setq done (not (notmuch-show-goto-message-next)))
848         )
849       message-ids
850       )))
851
852 ;; Commands typically bound to keys.
853
854 (defun notmuch-show-advance-and-archive ()
855   "Advance through thread and archive.
856
857 This command is intended to be one of the simplest ways to
858 process a thread of email. It does the following:
859
860 If the current message in the thread is not yet fully visible,
861 scroll by a near screenful to read more of the message.
862
863 Otherwise, (the end of the current message is already within the
864 current window), advance to the next open message.
865
866 Finally, if there is no further message to advance to, and this
867 last message is already read, then archive the entire current
868 thread, (remove the \"inbox\" tag from each message). Also kill
869 this buffer, and display the next thread from the search from
870 which this thread was originally shown."
871   (interactive)
872   (let ((end-of-this-message (notmuch-show-message-bottom)))
873     (cond
874      ;; Ideally we would test `end-of-this-message' against the result
875      ;; of `window-end', but that doesn't account for the fact that
876      ;; the end of the message might be hidden, so we have to actually
877      ;; go to the end, walk back over invisible text and then see if
878      ;; point is visible.
879      ((save-excursion
880         (goto-char (- end-of-this-message 1))
881         (notmuch-show-move-past-invisible-backward)
882         (> (point) (window-end)))
883       ;; The bottom of this message is not visible - scroll.
884       (scroll-up nil))
885
886      ((not (= end-of-this-message (point-max)))
887       ;; This is not the last message - move to the next visible one.
888       (notmuch-show-next-open-message))
889
890      (t
891       ;; This is the last message - archive the thread.
892       (notmuch-show-archive-thread)))))
893
894 (defun notmuch-show-rewind ()
895   "Backup through the thread, (reverse scrolling compared to \\[notmuch-show-advance-and-archive]).
896
897 Specifically, if the beginning of the previous email is fewer
898 than `window-height' lines from the current point, move to it
899 just like `notmuch-show-previous-message'.
900
901 Otherwise, just scroll down a screenful of the current message.
902
903 This command does not modify any message tags, (it does not undo
904 any effects from previous calls to
905 `notmuch-show-advance-and-archive'."
906   (interactive)
907   (let ((start-of-message (notmuch-show-message-top))
908         (start-of-window (window-start)))
909     (cond
910       ;; Either this message is properly aligned with the start of the
911       ;; window or the start of this message is not visible on the
912       ;; screen - scroll.
913      ((or (= start-of-message start-of-window)
914           (< start-of-message start-of-window))
915       (scroll-down)
916       ;; If a small number of lines from the previous message are
917       ;; visible, realign so that the top of the current message is at
918       ;; the top of the screen.
919       (if (<= (count-screen-lines (window-start) start-of-message)
920               next-screen-context-lines)
921           (progn
922             (goto-char (notmuch-show-message-top))
923             (notmuch-show-message-adjust)))
924       ;; Move to the top left of the window.
925       (goto-char (window-start)))
926      (t
927       ;; Move to the previous message.
928       (notmuch-show-previous-message)))))
929
930 (defun notmuch-show-reply ()
931   "Reply to the current message."
932   (interactive)
933   (notmuch-mua-reply (notmuch-show-get-message-id)))
934
935 (defun notmuch-show-forward-message ()
936   "Forward the current message."
937   (interactive)
938   (with-current-notmuch-show-message
939    (notmuch-mua-forward-message)))
940
941 (defun notmuch-show-next-message ()
942   "Show the next message."
943   (interactive)
944   (if (notmuch-show-goto-message-next)
945       (progn
946         (notmuch-show-mark-read)
947         (notmuch-show-message-adjust))
948     (goto-char (point-max))))
949
950 (defun notmuch-show-previous-message ()
951   "Show the previous message."
952   (interactive)
953   (notmuch-show-goto-message-previous)
954   (notmuch-show-mark-read)
955   (notmuch-show-message-adjust))
956
957 (defun notmuch-show-next-open-message ()
958   "Show the next message."
959   (interactive)
960   (let (r)
961     (while (and (setq r (notmuch-show-goto-message-next))
962                 (not (notmuch-show-message-visible-p))))
963     (if r
964         (progn
965           (notmuch-show-mark-read)
966           (notmuch-show-message-adjust))
967       (goto-char (point-max)))))
968
969 (defun notmuch-show-previous-open-message ()
970   "Show the previous message."
971   (interactive)
972   (while (and (notmuch-show-goto-message-previous)
973               (not (notmuch-show-message-visible-p))))
974   (notmuch-show-mark-read)
975   (notmuch-show-message-adjust))
976
977 (defun notmuch-show-view-raw-message ()
978   "View the file holding the current message."
979   (interactive)
980   (let* ((id (notmuch-show-get-message-id))
981          (buf (get-buffer-create (concat "*notmuch-raw-" id "*"))))
982     (call-process notmuch-command nil buf nil "show" "--format=raw" id)
983     (switch-to-buffer buf)
984     (goto-char (point-min))
985     (set-buffer-modified-p nil)
986     (view-buffer buf 'kill-buffer-if-not-modified)))
987
988 (defun notmuch-show-pipe-message (entire-thread command)
989   "Pipe the contents of the current message (or thread) to the given command.
990
991 The given command will be executed with the raw contents of the
992 current email message as stdin. Anything printed by the command
993 to stdout or stderr will appear in the *notmuch-pipe* buffer.
994
995 When invoked with a prefix argument, the command will receive all
996 open messages in the current thread (formatted as an mbox) rather
997 than only the current message."
998   (interactive "P\nsPipe message to command: ")
999   (let (shell-command)
1000     (if entire-thread
1001         (setq shell-command 
1002               (concat notmuch-command " show --format=mbox "
1003                       (shell-quote-argument
1004                        (mapconcat 'identity (notmuch-show-get-message-ids-for-open-messages) " OR "))
1005                       " | " command))
1006       (setq shell-command
1007             (concat notmuch-command " show --format=raw "
1008                     (shell-quote-argument (notmuch-show-get-message-id)) " | " command)))
1009     (let ((buf (get-buffer-create (concat "*notmuch-pipe*"))))
1010       (with-current-buffer buf
1011         (setq buffer-read-only nil)
1012         (erase-buffer)
1013         (let ((exit-code (call-process-shell-command shell-command nil buf)))
1014           (goto-char (point-max))
1015           (set-buffer-modified-p nil)
1016           (setq buffer-read-only t)
1017           (unless (zerop exit-code)
1018             (switch-to-buffer-other-window buf)
1019             (message (format "Command '%s' exited abnormally with code %d"
1020                              shell-command exit-code))))))))
1021
1022 (defun notmuch-show-add-tags-worker (current-tags add-tags)
1023   "Add to `current-tags' with any tags from `add-tags' not
1024 currently present and return the result."
1025   (let ((result-tags (copy-sequence current-tags)))
1026     (mapc (lambda (add-tag)
1027             (unless (member add-tag current-tags)
1028               (setq result-tags (push add-tag result-tags))))
1029             add-tags)
1030     (sort result-tags 'string<)))
1031
1032 (defun notmuch-show-del-tags-worker (current-tags del-tags)
1033   "Remove any tags in `del-tags' from `current-tags' and return
1034 the result."
1035   (let ((result-tags (copy-sequence current-tags)))
1036     (mapc (lambda (del-tag)
1037             (setq result-tags (delete del-tag result-tags)))
1038           del-tags)
1039     result-tags))
1040
1041 (defun notmuch-show-add-tag (&rest toadd)
1042   "Add a tag to the current message."
1043   (interactive
1044    (list (notmuch-select-tag-with-completion "Tag to add: ")))
1045
1046   (let* ((current-tags (notmuch-show-get-tags))
1047          (new-tags (notmuch-show-add-tags-worker current-tags toadd)))
1048
1049     (unless (equal current-tags new-tags)
1050       (apply 'notmuch-call-notmuch-process
1051              (append (cons "tag"
1052                            (mapcar (lambda (s) (concat "+" s)) toadd))
1053                      (cons (notmuch-show-get-message-id) nil)))
1054       (notmuch-show-set-tags new-tags))))
1055
1056 (defun notmuch-show-remove-tag (&rest toremove)
1057   "Remove a tag from the current message."
1058   (interactive
1059    (list (notmuch-select-tag-with-completion
1060           "Tag to remove: " (notmuch-show-get-message-id))))
1061
1062   (let* ((current-tags (notmuch-show-get-tags))
1063          (new-tags (notmuch-show-del-tags-worker current-tags toremove)))
1064
1065     (unless (equal current-tags new-tags)
1066       (apply 'notmuch-call-notmuch-process
1067              (append (cons "tag"
1068                            (mapcar (lambda (s) (concat "-" s)) toremove))
1069                      (cons (notmuch-show-get-message-id) nil)))
1070       (notmuch-show-set-tags new-tags))))
1071
1072 (defun notmuch-show-toggle-headers ()
1073   "Toggle the visibility of the current message headers."
1074   (interactive)
1075   (let ((props (notmuch-show-get-message-properties)))
1076     (notmuch-show-headers-visible
1077      props
1078      (not (plist-get props :headers-visible))))
1079   (force-window-update))
1080
1081 (defun notmuch-show-toggle-message ()
1082   "Toggle the visibility of the current message."
1083   (interactive)
1084   (let ((props (notmuch-show-get-message-properties)))
1085     (notmuch-show-message-visible
1086      props
1087      (not (plist-get props :message-visible))))
1088   (force-window-update))
1089
1090 (defun notmuch-show-open-or-close-all ()
1091   "Set the visibility all of the messages in the current thread.
1092 By default make all of the messages visible. With a prefix
1093 argument, hide all of the messages."
1094   (interactive)
1095   (save-excursion
1096     (goto-char (point-min))
1097     (loop do (notmuch-show-message-visible (notmuch-show-get-message-properties)
1098                                            (not current-prefix-arg))
1099           until (not (notmuch-show-goto-message-next))))
1100   (force-window-update))
1101
1102 (defun notmuch-show-next-button ()
1103   "Advance point to the next button in the buffer."
1104   (interactive)
1105   (forward-button 1))
1106
1107 (defun notmuch-show-previous-button ()
1108   "Move point back to the previous button in the buffer."
1109   (interactive)
1110   (backward-button 1))
1111
1112 (defun notmuch-show-archive-thread-internal (show-next)
1113   ;; Remove the tag from the current set of messages.
1114   (goto-char (point-min))
1115   (loop do (notmuch-show-remove-tag "inbox")
1116         until (not (notmuch-show-goto-message-next)))
1117   ;; Move to the next item in the search results, if any.
1118   (let ((parent-buffer notmuch-show-parent-buffer))
1119     (notmuch-kill-this-buffer)
1120     (if parent-buffer
1121         (progn
1122           (switch-to-buffer parent-buffer)
1123           (forward-line)
1124           (if show-next
1125               (notmuch-search-show-thread))))))
1126
1127 (defun notmuch-show-archive-thread ()
1128   "Archive each message in thread, then show next thread from search.
1129
1130 Archive each message currently shown by removing the \"inbox\"
1131 tag from each. Then kill this buffer and show the next thread
1132 from the search from which this thread was originally shown.
1133
1134 Note: This command is safe from any race condition of new messages
1135 being delivered to the same thread. It does not archive the
1136 entire thread, but only the messages shown in the current
1137 buffer."
1138   (interactive)
1139   (notmuch-show-archive-thread-internal t))
1140
1141 (defun notmuch-show-archive-thread-then-exit ()
1142   "Archive each message in thread, then exit back to search results."
1143   (interactive)
1144   (notmuch-show-archive-thread-internal nil))
1145
1146 (defun notmuch-show-stash-cc ()
1147   "Copy CC field of current message to kill-ring."
1148   (interactive)
1149   (notmuch-common-do-stash (notmuch-show-get-cc)))
1150
1151 (defun notmuch-show-stash-date ()
1152   "Copy date of current message to kill-ring."
1153   (interactive)
1154   (notmuch-common-do-stash (notmuch-show-get-date)))
1155
1156 (defun notmuch-show-stash-filename ()
1157   "Copy filename of current message to kill-ring."
1158   (interactive)
1159   (notmuch-common-do-stash (notmuch-show-get-filename)))
1160
1161 (defun notmuch-show-stash-from ()
1162   "Copy From address of current message to kill-ring."
1163   (interactive)
1164   (notmuch-common-do-stash (notmuch-show-get-from)))
1165
1166 (defun notmuch-show-stash-message-id ()
1167   "Copy message ID of current message to kill-ring."
1168   (interactive)
1169   (notmuch-common-do-stash (notmuch-show-get-message-id)))
1170
1171 (defun notmuch-show-stash-subject ()
1172   "Copy Subject field of current message to kill-ring."
1173   (interactive)
1174   (notmuch-common-do-stash (notmuch-show-get-subject)))
1175
1176 (defun notmuch-show-stash-tags ()
1177   "Copy tags of current message to kill-ring as a comma separated list."
1178   (interactive)
1179   (notmuch-common-do-stash (mapconcat 'identity (notmuch-show-get-tags) ",")))
1180
1181 (defun notmuch-show-stash-to ()
1182   "Copy To address of current message to kill-ring."
1183   (interactive)
1184   (notmuch-common-do-stash (notmuch-show-get-to)))
1185
1186 ;; Commands typically bound to buttons.
1187
1188 (defun notmuch-show-part-button-action (button)
1189   (let ((nth (button-get button :notmuch-part)))
1190     (if nth
1191         (notmuch-show-save-part (notmuch-show-get-message-id) nth
1192                                 (button-get button :notmuch-filename))
1193       (message "Not a valid part (is it a fake part?)."))))
1194
1195 ;;
1196
1197 (provide 'notmuch-show)