]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-show.el
debian: bump standards version to 3.9.4
[notmuch] / emacs / notmuch-show.el
1 ;; notmuch-show.el --- displaying notmuch forests.
2 ;;
3 ;; Copyright © Carl Worth
4 ;; Copyright © David Edmondson
5 ;;
6 ;; This file is part of Notmuch.
7 ;;
8 ;; Notmuch is free software: you can redistribute it and/or modify it
9 ;; under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation, either version 3 of the License, or
11 ;; (at your option) any later version.
12 ;;
13 ;; Notmuch is distributed in the hope that it will be useful, but
14 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 ;; General Public License for more details.
17 ;;
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with Notmuch.  If not, see <http://www.gnu.org/licenses/>.
20 ;;
21 ;; Authors: Carl Worth <cworth@cworth.org>
22 ;;          David Edmondson <dme@dme.org>
23
24 (eval-when-compile (require 'cl))
25 (require 'mm-view)
26 (require 'message)
27 (require 'mm-decode)
28 (require 'mailcap)
29 (require 'icalendar)
30 (require 'goto-addr)
31
32 (require 'notmuch-lib)
33 (require 'notmuch-tag)
34 (require 'notmuch-query)
35 (require 'notmuch-wash)
36 (require 'notmuch-mua)
37 (require 'notmuch-crypto)
38 (require 'notmuch-print)
39
40 (declare-function notmuch-call-notmuch-process "notmuch" (&rest args))
41 (declare-function notmuch-fontify-headers "notmuch" nil)
42 (declare-function notmuch-search-next-thread "notmuch" nil)
43 (declare-function notmuch-search-show-thread "notmuch" nil)
44
45 (defcustom notmuch-message-headers '("Subject" "To" "Cc" "Date")
46   "Headers that should be shown in a message, in this order.
47
48 For an open message, all of these headers will be made visible
49 according to `notmuch-message-headers-visible' or can be toggled
50 with `notmuch-show-toggle-visibility-headers'. For a closed message,
51 only the first header in the list will be visible."
52   :type '(repeat string)
53   :group 'notmuch-show)
54
55 (defcustom notmuch-message-headers-visible t
56   "Should the headers be visible by default?
57
58 If this value is non-nil, then all of the headers defined in
59 `notmuch-message-headers' will be visible by default in the display
60 of each message. Otherwise, these headers will be hidden and
61 `notmuch-show-toggle-visibility-headers' can be used to make them
62 visible for any given message."
63   :type 'boolean
64   :group 'notmuch-show)
65
66 (defcustom notmuch-show-relative-dates t
67   "Display relative dates in the message summary line."
68   :type 'boolean
69   :group 'notmuch-show)
70
71 (defvar notmuch-show-markup-headers-hook '(notmuch-show-colour-headers)
72   "A list of functions called to decorate the headers listed in
73 `notmuch-message-headers'.")
74
75 (defcustom notmuch-show-hook '(notmuch-show-turn-on-visual-line-mode)
76   "Functions called after populating a `notmuch-show' buffer."
77   :type 'hook
78   :options '(notmuch-show-turn-on-visual-line-mode)
79   :group 'notmuch-show
80   :group 'notmuch-hooks)
81
82 (defcustom notmuch-show-insert-text/plain-hook '(notmuch-wash-wrap-long-lines
83                                                  notmuch-wash-tidy-citations
84                                                  notmuch-wash-elide-blank-lines
85                                                  notmuch-wash-excerpt-citations)
86   "Functions used to improve the display of text/plain parts."
87   :type 'hook
88   :options '(notmuch-wash-convert-inline-patch-to-part
89              notmuch-wash-wrap-long-lines
90              notmuch-wash-tidy-citations
91              notmuch-wash-elide-blank-lines
92              notmuch-wash-excerpt-citations)
93   :group 'notmuch-show
94   :group 'notmuch-hooks)
95
96 ;; Mostly useful for debugging.
97 (defcustom notmuch-show-all-multipart/alternative-parts nil
98   "Should all parts of multipart/alternative parts be shown?"
99   :type 'boolean
100   :group 'notmuch-show)
101
102 (defcustom notmuch-show-indent-messages-width 1
103   "Width of message indentation in threads.
104
105 Messages are shown indented according to their depth in a thread.
106 This variable determines the width of this indentation measured
107 in number of blanks.  Defaults to `1', choose `0' to disable
108 indentation."
109   :type 'integer
110   :group 'notmuch-show)
111
112 (defcustom notmuch-show-indent-multipart nil
113   "Should the sub-parts of a multipart/* part be indented?"
114   ;; dme: Not sure which is a good default.
115   :type 'boolean
116   :group 'notmuch-show)
117
118 (defcustom notmuch-show-part-button-default-action 'notmuch-show-save-part
119   "Default part header button action (on ENTER or mouse click)."
120   :group 'notmuch-show
121   :type '(choice (const :tag "Save part"
122                         notmuch-show-save-part)
123                  (const :tag "View part"
124                         notmuch-show-view-part)
125                  (const :tag "View interactively"
126                         notmuch-show-interactively-view-part)))
127
128 (defcustom notmuch-show-only-matching-messages nil
129   "Only matching messages are shown by default."
130   :type 'boolean
131   :group 'notmuch-show)
132
133 (defvar notmuch-show-thread-id nil)
134 (make-variable-buffer-local 'notmuch-show-thread-id)
135 (put 'notmuch-show-thread-id 'permanent-local t)
136
137 (defvar notmuch-show-parent-buffer nil)
138 (make-variable-buffer-local 'notmuch-show-parent-buffer)
139 (put 'notmuch-show-parent-buffer 'permanent-local t)
140
141 (defvar notmuch-show-query-context nil)
142 (make-variable-buffer-local 'notmuch-show-query-context)
143 (put 'notmuch-show-query-context 'permanent-local t)
144
145 (defvar notmuch-show-process-crypto nil)
146 (make-variable-buffer-local 'notmuch-show-process-crypto)
147 (put 'notmuch-show-process-crypto 'permanent-local t)
148
149 (defvar notmuch-show-elide-non-matching-messages nil)
150 (make-variable-buffer-local 'notmuch-show-elide-non-matching-messages)
151 (put 'notmuch-show-elide-non-matching-messages 'permanent-local t)
152
153 (defvar notmuch-show-indent-content t)
154 (make-variable-buffer-local 'notmuch-show-indent-content)
155 (put 'notmuch-show-indent-content 'permanent-local t)
156
157 (defcustom notmuch-show-stash-mlarchive-link-alist
158   '(("Gmane" . "http://mid.gmane.org/")
159     ("MARC" . "http://marc.info/?i=")
160     ("Mail Archive, The" . "http://mail-archive.com/search?l=mid&q=")
161     ;; FIXME: can these services be searched by `Message-Id' ?
162     ;; ("MarkMail" . "http://markmail.org/")
163     ;; ("Nabble" . "http://nabble.com/")
164     ;; ("opensubscriber" . "http://opensubscriber.com/")
165     )
166   "List of Mailing List Archives to use when stashing links.
167
168 These URIs are concatenated with the current message's
169 Message-Id in `notmuch-show-stash-mlarchive-link'."
170   :type '(alist :key-type (string :tag "Name")
171                 :value-type (string :tag "URL"))
172   :group 'notmuch-show)
173
174 (defcustom notmuch-show-stash-mlarchive-link-default "Gmane"
175   "Default Mailing List Archive to use when stashing links.
176
177 This is used when `notmuch-show-stash-mlarchive-link' isn't
178 provided with an MLA argument nor `completing-read' input."
179   :type `(choice
180           ,@(mapcar
181              (lambda (mla)
182                (list 'const :tag (car mla) :value (car mla)))
183              notmuch-show-stash-mlarchive-link-alist))
184   :group 'notmuch-show)
185
186 (defcustom notmuch-show-mark-read-tags '("-unread")
187   "List of tag changes to apply to a message when it is marked as read.
188
189 Tags starting with \"+\" (or not starting with either \"+\" or
190 \"-\") in the list will be added, and tags starting with \"-\"
191 will be removed from the message being marked as read.
192
193 For example, if you wanted to remove an \"unread\" tag and add a
194 \"read\" tag (which would make little sense), you would set:
195     (\"-unread\" \"+read\")"
196   :type '(repeat string)
197   :group 'notmuch-show)
198
199
200 (defmacro with-current-notmuch-show-message (&rest body)
201   "Evaluate body with current buffer set to the text of current message"
202   `(save-excursion
203      (let ((id (notmuch-show-get-message-id)))
204        (let ((buf (generate-new-buffer (concat "*notmuch-msg-" id "*"))))
205          (with-current-buffer buf
206            (let ((coding-system-for-read 'no-conversion))
207              (call-process notmuch-command nil t nil "show" "--format=raw" id)
208              ,@body)
209            (kill-buffer buf))))))
210
211 (defun notmuch-show-turn-on-visual-line-mode ()
212   "Enable Visual Line mode."
213   (visual-line-mode t))
214
215 (defun notmuch-show-view-all-mime-parts ()
216   "Use external viewers to view all attachments from the current message."
217   (interactive)
218   (with-current-notmuch-show-message
219    ;; We override the mm-inline-media-tests to indicate which message
220    ;; parts are already sufficiently handled by the original
221    ;; presentation of the message in notmuch-show mode. These parts
222    ;; will be inserted directly into the temporary buffer of
223    ;; with-current-notmuch-show-message and silently discarded.
224    ;;
225    ;; Any MIME part not explicitly mentioned here will be handled by an
226    ;; external viewer as configured in the various mailcap files.
227    (let ((mm-inline-media-tests '(
228                                   ("text/.*" ignore identity)
229                                   ("application/pgp-signature" ignore identity)
230                                   ("multipart/alternative" ignore identity)
231                                   ("multipart/mixed" ignore identity)
232                                   ("multipart/related" ignore identity)
233                                  )))
234      (mm-display-parts (mm-dissect-buffer)))))
235
236 (defun notmuch-foreach-mime-part (function mm-handle)
237   (cond ((stringp (car mm-handle))
238          (dolist (part (cdr mm-handle))
239            (notmuch-foreach-mime-part function part)))
240         ((bufferp (car mm-handle))
241          (funcall function mm-handle))
242         (t (dolist (part mm-handle)
243              (notmuch-foreach-mime-part function part)))))
244
245 (defun notmuch-count-attachments (mm-handle)
246   (let ((count 0))
247     (notmuch-foreach-mime-part
248      (lambda (p)
249        (let ((disposition (mm-handle-disposition p)))
250          (and (listp disposition)
251               (or (equal (car disposition) "attachment")
252                   (and (equal (car disposition) "inline")
253                        (assq 'filename disposition)))
254               (incf count))))
255      mm-handle)
256     count))
257
258 (defun notmuch-save-attachments (mm-handle &optional queryp)
259   (notmuch-foreach-mime-part
260    (lambda (p)
261      (let ((disposition (mm-handle-disposition p)))
262        (and (listp disposition)
263             (or (equal (car disposition) "attachment")
264                 (and (equal (car disposition) "inline")
265                      (assq 'filename disposition)))
266             (or (not queryp)
267                 (y-or-n-p
268                  (concat "Save '" (cdr (assq 'filename disposition)) "' ")))
269             (mm-save-part p))))
270    mm-handle))
271
272 (defun notmuch-show-save-attachments ()
273   "Save all attachments from the current message."
274   (interactive)
275   (with-current-notmuch-show-message
276    (let ((mm-handle (mm-dissect-buffer)))
277      (notmuch-save-attachments
278       mm-handle (> (notmuch-count-attachments mm-handle) 1))))
279   (message "Done"))
280
281 (defun notmuch-show-with-message-as-text (fn)
282   "Apply FN to a text representation of the current message.
283
284 FN is called with one argument, the message properties. It should
285 operation on the contents of the current buffer."
286
287   ;; Remake the header to ensure that all information is available.
288   (let* ((to (notmuch-show-get-to))
289          (cc (notmuch-show-get-cc))
290          (from (notmuch-show-get-from))
291          (subject (notmuch-show-get-subject))
292          (date (notmuch-show-get-date))
293          (tags (notmuch-show-get-tags))
294          (depth (notmuch-show-get-depth))
295
296          (header (concat
297                   "Subject: " subject "\n"
298                   "To: " to "\n"
299                   (if (not (string= cc ""))
300                       (concat "Cc: " cc "\n")
301                     "")
302                   "From: " from "\n"
303                   "Date: " date "\n"
304                   (if tags
305                       (concat "Tags: "
306                               (mapconcat #'identity tags ", ") "\n")
307                     "")))
308          (all (buffer-substring (notmuch-show-message-top)
309                                 (notmuch-show-message-bottom)))
310
311          (props (notmuch-show-get-message-properties))
312          (indenting notmuch-show-indent-content))
313     (with-temp-buffer
314       (insert all)
315       (if indenting
316           (indent-rigidly (point-min) (point-max) (- depth)))
317       ;; Remove the original header.
318       (goto-char (point-min))
319       (re-search-forward "^$" (point-max) nil)
320       (delete-region (point-min) (point))
321       (insert header)
322       (funcall fn props))))
323
324 (defun notmuch-show-print-message ()
325   "Print the current message."
326   (interactive)
327   (notmuch-show-with-message-as-text 'notmuch-print-message))
328
329 (defun notmuch-show-fontify-header ()
330   (let ((face (cond
331                ((looking-at "[Tt]o:")
332                 'message-header-to)
333                ((looking-at "[Bb]?[Cc][Cc]:")
334                 'message-header-cc)
335                ((looking-at "[Ss]ubject:")
336                 'message-header-subject)
337                ((looking-at "[Ff]rom:")
338                 'message-header-from)
339                (t
340                 'message-header-other))))
341
342     (overlay-put (make-overlay (point) (re-search-forward ":"))
343                  'face 'message-header-name)
344     (overlay-put (make-overlay (point) (re-search-forward ".*$"))
345                  'face face)))
346
347 (defun notmuch-show-colour-headers ()
348   "Apply some colouring to the current headers."
349   (goto-char (point-min))
350   (while (looking-at "^[A-Za-z][-A-Za-z0-9]*:")
351     (notmuch-show-fontify-header)
352     (forward-line)))
353
354 (defun notmuch-show-spaces-n (n)
355   "Return a string comprised of `n' spaces."
356   (make-string n ? ))
357
358 (defun notmuch-show-update-tags (tags)
359   "Update the displayed tags of the current message."
360   (save-excursion
361     (goto-char (notmuch-show-message-top))
362     (if (re-search-forward "(\\([^()]*\\))$" (line-end-position) t)
363         (let ((inhibit-read-only t))
364           (replace-match (concat "("
365                                  (propertize (mapconcat 'identity tags " ")
366                                              'face 'notmuch-tag-face)
367                                  ")"))))))
368
369 (defun notmuch-clean-address (address)
370   "Try to clean a single email ADDRESS for display. Return a cons
371 cell of (AUTHOR_EMAIL AUTHOR_NAME). Return (ADDRESS nil) if
372 parsing fails."
373   (condition-case nil
374     (let (p-name p-address)
375       ;; It would be convenient to use `mail-header-parse-address',
376       ;; but that expects un-decoded mailbox parts, whereas our
377       ;; mailbox parts are already decoded (and hence may contain
378       ;; UTF-8). Given that notmuch should handle most of the awkward
379       ;; cases, some simple string deconstruction should be sufficient
380       ;; here.
381       (cond
382        ;; "User <user@dom.ain>" style.
383        ((string-match "\\(.*\\) <\\(.*\\)>" address)
384         (setq p-name (match-string 1 address)
385               p-address (match-string 2 address)))
386
387        ;; "<user@dom.ain>" style.
388        ((string-match "<\\(.*\\)>" address)
389         (setq p-address (match-string 1 address)))
390
391        ;; Everything else.
392        (t
393         (setq p-address address)))
394
395       (when p-name
396         ;; Remove elements of the mailbox part that are not relevant for
397         ;; display, even if they are required during transport:
398         ;;
399         ;; Backslashes.
400         (setq p-name (replace-regexp-in-string "\\\\" "" p-name))
401
402         ;; Outer single and double quotes, which might be nested.
403         (loop
404          with start-of-loop
405          do (setq start-of-loop p-name)
406
407          when (string-match "^\"\\(.*\\)\"$" p-name)
408          do (setq p-name (match-string 1 p-name))
409
410          when (string-match "^'\\(.*\\)'$" p-name)
411          do (setq p-name (match-string 1 p-name))
412
413          until (string= start-of-loop p-name)))
414
415       ;; If the address is 'foo@bar.com <foo@bar.com>' then show just
416       ;; 'foo@bar.com'.
417       (when (string= p-name p-address)
418         (setq p-name nil))
419
420       (cons p-address p-name))
421     (error (cons address nil))))
422
423 (defun notmuch-show-clean-address (address)
424   "Try to clean a single email ADDRESS for display.  Return
425 unchanged ADDRESS if parsing fails."
426   (let* ((clean-address (notmuch-clean-address address))
427          (p-address (car clean-address))
428          (p-name (cdr clean-address)))
429     ;; If no name, return just the address.
430     (if (not p-name)
431         p-address
432       ;; Otherwise format the name and address together.
433       (concat p-name " <" p-address ">"))))
434
435 (defun notmuch-show-insert-headerline (headers date tags depth)
436   "Insert a notmuch style headerline based on HEADERS for a
437 message at DEPTH in the current thread."
438   (let ((start (point)))
439     (insert (notmuch-show-spaces-n (* notmuch-show-indent-messages-width depth))
440             (notmuch-show-clean-address (plist-get headers :From))
441             " ("
442             date
443             ") ("
444             (propertize (mapconcat 'identity tags " ")
445                         'face 'notmuch-tag-face)
446             ")\n")
447     (overlay-put (make-overlay start (point)) 'face 'notmuch-message-summary-face)))
448
449 (defun notmuch-show-insert-header (header header-value)
450   "Insert a single header."
451   (insert header ": " header-value "\n"))
452
453 (defun notmuch-show-insert-headers (headers)
454   "Insert the headers of the current message."
455   (let ((start (point)))
456     (mapc (lambda (header)
457             (let* ((header-symbol (intern (concat ":" header)))
458                    (header-value (plist-get headers header-symbol)))
459               (if (and header-value
460                        (not (string-equal "" header-value)))
461                   (notmuch-show-insert-header header header-value))))
462           notmuch-message-headers)
463     (save-excursion
464       (save-restriction
465         (narrow-to-region start (point-max))
466         (run-hooks 'notmuch-show-markup-headers-hook)))))
467
468 (define-button-type 'notmuch-show-part-button-type
469   'action 'notmuch-show-part-button-default
470   'keymap 'notmuch-show-part-button-map
471   'follow-link t
472   'face 'message-mml)
473
474 (defvar notmuch-show-part-button-map
475   (let ((map (make-sparse-keymap)))
476     (set-keymap-parent map button-map)
477     (define-key map "s" 'notmuch-show-part-button-save)
478     (define-key map "v" 'notmuch-show-part-button-view)
479     (define-key map "o" 'notmuch-show-part-button-interactively-view)
480     (define-key map "|" 'notmuch-show-part-button-pipe)
481     map)
482   "Submap for button commands")
483 (fset 'notmuch-show-part-button-map notmuch-show-part-button-map)
484
485 (defun notmuch-show-insert-part-header (nth content-type declared-type &optional name comment)
486   (let ((button)
487         (base-label (concat (when name (concat name ": "))
488                             declared-type
489                             (unless (string-equal declared-type content-type)
490                               (concat " (as " content-type ")"))
491                             comment)))
492
493     (setq button
494           (insert-button
495            (concat "[ " base-label " ]")
496            :base-label base-label
497            :type 'notmuch-show-part-button-type
498            :notmuch-part nth
499            :notmuch-filename name
500            :notmuch-content-type content-type))
501     (insert "\n")
502     ;; return button
503     button))
504
505 ;; Functions handling particular MIME parts.
506
507 (defmacro notmuch-with-temp-part-buffer (message-id nth &rest body)
508   (declare (indent 2))
509   (let ((process-crypto (make-symbol "process-crypto")))
510     `(let ((,process-crypto notmuch-show-process-crypto))
511        (with-temp-buffer
512          (setq notmuch-show-process-crypto ,process-crypto)
513          ;; Always acquires the part via `notmuch part', even if it is
514          ;; available in the JSON output.
515          (insert (notmuch-get-bodypart-internal ,message-id ,nth notmuch-show-process-crypto))
516          ,@body))))
517
518 (defun notmuch-show-save-part (message-id nth &optional filename content-type)
519   (notmuch-with-temp-part-buffer message-id nth
520     (let ((file (read-file-name
521                  "Filename to save as: "
522                  (or mailcap-download-directory "~/")
523                  nil nil
524                  filename)))
525       ;; Don't re-compress .gz & al.  Arguably we should make
526       ;; `file-name-handler-alist' nil, but that would chop
527       ;; ange-ftp, which is reasonable to use here.
528       (mm-write-region (point-min) (point-max) file nil nil nil 'no-conversion t))))
529
530 (defun notmuch-show-view-part (message-id nth &optional filename content-type )
531   (notmuch-with-temp-part-buffer message-id nth
532     ;; set mm-inlined-types to nil to force an external viewer
533     (let ((handle (mm-make-handle (current-buffer) (list content-type)))
534           (mm-inlined-types nil))
535       ;; We override mm-save-part as notmuch-show-save-part is better
536       ;; since it offers the filename. We need to lexically bind
537       ;; everything we need for notmuch-show-save-part to prevent
538       ;; potential dynamic shadowing.
539       (lexical-let ((message-id message-id)
540                     (nth nth)
541                     (filename filename)
542                     (content-type content-type))
543         (flet ((mm-save-part (&rest args) (notmuch-show-save-part
544                                            message-id nth filename content-type)))
545           (mm-display-part handle))))))
546
547 (defun notmuch-show-interactively-view-part (message-id nth &optional filename content-type)
548   (notmuch-with-temp-part-buffer message-id nth
549     (let ((handle (mm-make-handle (current-buffer) (list content-type))))
550       (mm-interactively-view-part handle))))
551
552 (defun notmuch-show-pipe-part (message-id nth &optional filename content-type)
553   (notmuch-with-temp-part-buffer message-id nth
554     (let ((handle (mm-make-handle (current-buffer) (list content-type))))
555       (mm-pipe-part handle))))
556
557 ;; This is taken from notmuch-wash: maybe it should be unified?
558 (defun notmuch-show-toggle-part-invisibility (&optional button)
559   (interactive)
560   (let* ((button (or button (button-at (point))))
561          (overlay (button-get button 'overlay)))
562     (when overlay
563       (let* ((show (overlay-get overlay 'invisible))
564              (new-start (button-start button))
565              (button-label (button-get button :base-label))
566              (old-point (point))
567              (inhibit-read-only t))
568         (overlay-put overlay 'invisible (not show))
569         (goto-char new-start)
570         (insert "[ " button-label (if show " ]" " (hidden) ]"))
571         (let ((old-end (button-end button)))
572           (move-overlay button new-start (point))
573           (delete-region (point) old-end))
574         (goto-char (min old-point (1- (button-end button))))))))
575
576 (defun notmuch-show-multipart/*-to-list (part)
577   (mapcar (lambda (inner-part) (plist-get inner-part :content-type))
578           (plist-get part :content)))
579
580 (defun notmuch-show-insert-part-multipart/alternative (msg part content-type nth depth declared-type)
581   (notmuch-show-insert-part-header nth declared-type content-type nil)
582   (let ((chosen-type (car (notmuch-multipart/alternative-choose (notmuch-show-multipart/*-to-list part))))
583         (inner-parts (plist-get part :content))
584         (start (point)))
585     ;; This inserts all parts of the chosen type rather than just one,
586     ;; but it's not clear that this is the wrong thing to do - which
587     ;; should be chosen if there are more than one that match?
588     (mapc (lambda (inner-part)
589             (let* ((inner-type (plist-get inner-part :content-type))
590                   (hide (not (or notmuch-show-all-multipart/alternative-parts
591                            (string= chosen-type inner-type)))))
592               (notmuch-show-insert-bodypart msg inner-part depth hide)))
593           inner-parts)
594
595     (when notmuch-show-indent-multipart
596       (indent-rigidly start (point) 1)))
597   t)
598
599 (defun notmuch-show-setup-w3m ()
600   "Instruct w3m how to retrieve content from a \"related\" part of a message."
601   (interactive)
602   (if (boundp 'w3m-cid-retrieve-function-alist)
603     (unless (assq 'notmuch-show-mode w3m-cid-retrieve-function-alist)
604       (push (cons 'notmuch-show-mode 'notmuch-show-w3m-cid-retrieve)
605             w3m-cid-retrieve-function-alist)))
606   (setq mm-inline-text-html-with-images t))
607
608 (defvar w3m-current-buffer) ;; From `w3m.el'.
609 (defvar notmuch-show-w3m-cid-store nil)
610 (make-variable-buffer-local 'notmuch-show-w3m-cid-store)
611
612 (defun notmuch-show-w3m-cid-store-internal (content-id
613                                             message-id
614                                             part-number
615                                             content-type
616                                             content)
617   (push (list content-id
618               message-id
619               part-number
620               content-type
621               content)
622         notmuch-show-w3m-cid-store))
623
624 (defun notmuch-show-w3m-cid-store (msg part)
625   (let ((content-id (plist-get part :content-id)))
626     (when content-id
627       (notmuch-show-w3m-cid-store-internal (concat "cid:" content-id)
628                                            (plist-get msg :id)
629                                            (plist-get part :id)
630                                            (plist-get part :content-type)
631                                            nil))))
632
633 (defun notmuch-show-w3m-cid-retrieve (url &rest args)
634   (let ((matching-part (with-current-buffer w3m-current-buffer
635                          (assoc url notmuch-show-w3m-cid-store))))
636     (if matching-part
637         (let ((message-id (nth 1 matching-part))
638               (part-number (nth 2 matching-part))
639               (content-type (nth 3 matching-part))
640               (content (nth 4 matching-part)))
641           ;; If we don't already have the content, get it and cache
642           ;; it, as some messages reference the same cid: part many
643           ;; times (hundreds!), which results in many calls to
644           ;; `notmuch part'.
645           (unless content
646             (setq content (notmuch-get-bodypart-internal (notmuch-id-to-query message-id)
647                                                               part-number notmuch-show-process-crypto))
648             (with-current-buffer w3m-current-buffer
649               (notmuch-show-w3m-cid-store-internal url
650                                                    message-id
651                                                    part-number
652                                                    content-type
653                                                    content)))
654           (insert content)
655           content-type)
656       nil)))
657
658 (defun notmuch-show-insert-part-multipart/related (msg part content-type nth depth declared-type)
659   (notmuch-show-insert-part-header nth declared-type content-type nil)
660   (let ((inner-parts (plist-get part :content))
661         (start (point)))
662
663     ;; We assume that the first part is text/html and the remainder
664     ;; things that it references.
665
666     ;; Stash the non-primary parts.
667     (mapc (lambda (part)
668             (notmuch-show-w3m-cid-store msg part))
669           (cdr inner-parts))
670
671     ;; Render the primary part.
672     (notmuch-show-insert-bodypart msg (car inner-parts) depth)
673
674     (when notmuch-show-indent-multipart
675       (indent-rigidly start (point) 1)))
676   t)
677
678 (defun notmuch-show-insert-part-multipart/signed (msg part content-type nth depth declared-type)
679   (let ((button (notmuch-show-insert-part-header nth declared-type content-type nil)))
680     (button-put button 'face 'notmuch-crypto-part-header)
681     ;; add signature status button if sigstatus provided
682     (if (plist-member part :sigstatus)
683         (let* ((from (notmuch-show-get-header :From msg))
684                (sigstatus (car (plist-get part :sigstatus))))
685           (notmuch-crypto-insert-sigstatus-button sigstatus from))
686       ;; if we're not adding sigstatus, tell the user how they can get it
687       (button-put button 'help-echo "Set notmuch-crypto-process-mime to process cryptographic MIME parts.")))
688
689   (let ((inner-parts (plist-get part :content))
690         (start (point)))
691     ;; Show all of the parts.
692     (mapc (lambda (inner-part)
693             (notmuch-show-insert-bodypart msg inner-part depth))
694           inner-parts)
695
696     (when notmuch-show-indent-multipart
697       (indent-rigidly start (point) 1)))
698   t)
699
700 (defun notmuch-show-insert-part-multipart/encrypted (msg part content-type nth depth declared-type)
701   (let ((button (notmuch-show-insert-part-header nth declared-type content-type nil)))
702     (button-put button 'face 'notmuch-crypto-part-header)
703     ;; add encryption status button if encstatus specified
704     (if (plist-member part :encstatus)
705         (let ((encstatus (car (plist-get part :encstatus))))
706           (notmuch-crypto-insert-encstatus-button encstatus)
707           ;; add signature status button if sigstatus specified
708           (if (plist-member part :sigstatus)
709               (let* ((from (notmuch-show-get-header :From msg))
710                      (sigstatus (car (plist-get part :sigstatus))))
711                 (notmuch-crypto-insert-sigstatus-button sigstatus from))))
712       ;; if we're not adding encstatus, tell the user how they can get it
713       (button-put button 'help-echo "Set notmuch-crypto-process-mime to process cryptographic MIME parts.")))
714
715   (let ((inner-parts (plist-get part :content))
716         (start (point)))
717     ;; Show all of the parts.
718     (mapc (lambda (inner-part)
719             (notmuch-show-insert-bodypart msg inner-part depth))
720           inner-parts)
721
722     (when notmuch-show-indent-multipart
723       (indent-rigidly start (point) 1)))
724   t)
725
726 (defun notmuch-show-insert-part-multipart/* (msg part content-type nth depth declared-type)
727   (notmuch-show-insert-part-header nth declared-type content-type nil)
728   (let ((inner-parts (plist-get part :content))
729         (start (point)))
730     ;; Show all of the parts.
731     (mapc (lambda (inner-part)
732             (notmuch-show-insert-bodypart msg inner-part depth))
733           inner-parts)
734
735     (when notmuch-show-indent-multipart
736       (indent-rigidly start (point) 1)))
737   t)
738
739 (defun notmuch-show-insert-part-message/rfc822 (msg part content-type nth depth declared-type)
740   (notmuch-show-insert-part-header nth declared-type content-type nil)
741   (let* ((message (car (plist-get part :content)))
742          (body (car (plist-get message :body)))
743          (start (point)))
744
745     ;; Override `notmuch-message-headers' to force `From' to be
746     ;; displayed.
747     (let ((notmuch-message-headers '("From" "Subject" "To" "Cc" "Date")))
748       (notmuch-show-insert-headers (plist-get message :headers)))
749
750     ;; Blank line after headers to be compatible with the normal
751     ;; message display.
752     (insert "\n")
753
754     ;; Show the body
755     (notmuch-show-insert-bodypart msg body depth)
756
757     (when notmuch-show-indent-multipart
758       (indent-rigidly start (point) 1)))
759   t)
760
761 (defun notmuch-show-insert-part-text/plain (msg part content-type nth depth declared-type)
762   (let ((start (point)))
763     ;; If this text/plain part is not the first part in the message,
764     ;; insert a header to make this clear.
765     (if (> nth 1)
766         (notmuch-show-insert-part-header nth declared-type content-type (plist-get part :filename)))
767     (insert (notmuch-get-bodypart-content msg part nth notmuch-show-process-crypto))
768     (save-excursion
769       (save-restriction
770         (narrow-to-region start (point-max))
771         (run-hook-with-args 'notmuch-show-insert-text/plain-hook msg depth))))
772   t)
773
774 (defun notmuch-show-insert-part-text/calendar (msg part content-type nth depth declared-type)
775   (notmuch-show-insert-part-header nth declared-type content-type (plist-get part :filename))
776   (insert (with-temp-buffer
777             (insert (notmuch-get-bodypart-content msg part nth notmuch-show-process-crypto))
778             ;; notmuch-get-bodypart-content provides "raw", non-converted
779             ;; data. Replace CRLF with LF before icalendar can use it.
780             (goto-char (point-min))
781             (while (re-search-forward "\r\n" nil t)
782               (replace-match "\n" nil nil))
783             (let ((file (make-temp-file "notmuch-ical"))
784                   result)
785               (unwind-protect
786                   (progn
787                     (unless (icalendar-import-buffer file t)
788                       (error "Icalendar import error. See *icalendar-errors* for more information"))
789                     (set-buffer (get-file-buffer file))
790                     (setq result (buffer-substring (point-min) (point-max)))
791                     (set-buffer-modified-p nil)
792                     (kill-buffer (current-buffer)))
793                 (delete-file file))
794               result)))
795   t)
796
797 ;; For backwards compatibility.
798 (defun notmuch-show-insert-part-text/x-vcalendar (msg part content-type nth depth declared-type)
799   (notmuch-show-insert-part-text/calendar msg part content-type nth depth declared-type))
800
801 (defun notmuch-show-insert-part-application/octet-stream (msg part content-type nth depth declared-type)
802   ;; If we can deduce a MIME type from the filename of the attachment,
803   ;; do so and pass it on to the handler for that type.
804   (if (plist-get part :filename)
805       (let ((extension (file-name-extension (plist-get part :filename)))
806             mime-type)
807         (if extension
808             (progn
809               (mailcap-parse-mimetypes)
810               (setq mime-type (mailcap-extension-to-mime extension))
811               (if (and mime-type
812                        (not (string-equal mime-type "application/octet-stream")))
813                   (notmuch-show-insert-bodypart-internal msg part mime-type nth depth content-type)
814                 nil))
815           nil))))
816
817 ;; Handler for wash generated inline patch fake parts.
818 (defun notmuch-show-insert-part-inline-patch-fake-part (msg part content-type nth depth declared-type)
819   (notmuch-show-insert-part-*/* msg part "text/x-diff" nth depth "inline patch"))
820
821 (defun notmuch-show-insert-part-text/html (msg part content-type nth depth declared-type)
822   ;; text/html handler to work around bugs in renderers and our
823   ;; invisibile parts code. In particular w3m sets up a keymap which
824   ;; "leaks" outside the invisible region and causes strange effects
825   ;; in notmuch. We set mm-inline-text-html-with-w3m-keymap to nil to
826   ;; tell w3m not to set a keymap (so the normal notmuch-show-mode-map
827   ;; remains).
828   (let ((mm-inline-text-html-with-w3m-keymap nil))
829     (notmuch-show-insert-part-*/* msg part content-type nth depth declared-type)))
830
831 (defun notmuch-show-insert-part-*/* (msg part content-type nth depth declared-type)
832   ;; This handler _must_ succeed - it is the handler of last resort.
833   (notmuch-show-insert-part-header nth content-type declared-type (plist-get part :filename))
834   (notmuch-mm-display-part-inline msg part nth content-type notmuch-show-process-crypto)
835   t)
836
837 ;; Functions for determining how to handle MIME parts.
838
839 (defun notmuch-show-handlers-for (content-type)
840   "Return a list of content handlers for a part of type CONTENT-TYPE."
841   (let (result)
842     (mapc (lambda (func)
843             (if (functionp func)
844                 (push func result)))
845           ;; Reverse order of prefrence.
846           (list (intern (concat "notmuch-show-insert-part-*/*"))
847                 (intern (concat
848                          "notmuch-show-insert-part-"
849                          (car (notmuch-split-content-type content-type))
850                          "/*"))
851                 (intern (concat "notmuch-show-insert-part-" content-type))))
852     result))
853
854 ;; \f
855
856 (defun notmuch-show-insert-bodypart-internal (msg part content-type nth depth declared-type)
857   (let ((handlers (notmuch-show-handlers-for content-type)))
858     ;; Run the content handlers until one of them returns a non-nil
859     ;; value.
860     (while (and handlers
861                 (not (condition-case err
862                          (funcall (car handlers) msg part content-type nth depth declared-type)
863                        (error (progn
864                                 (insert "!!! Bodypart insert error: ")
865                                 (insert (error-message-string err))
866                                 (insert " !!!\n") nil)))))
867       (setq handlers (cdr handlers))))
868   t)
869
870 (defun notmuch-show-create-part-overlays (msg beg end hide)
871   "Add an overlay to the part between BEG and END"
872   (let* ((button (button-at beg))
873          (part-beg (and button (1+ (button-end button)))))
874
875     ;; If the part contains no text we do not make it toggleable. We
876     ;; also need to check that the button is a genuine part button not
877     ;; a notmuch-wash button.
878     (when (and button (/= part-beg end) (button-get button :base-label))
879       (button-put button 'overlay (make-overlay part-beg end))
880       ;; We toggle the button for hidden parts as that gets the
881       ;; button label right.
882       (save-excursion
883         (when hide
884           (notmuch-show-toggle-part-invisibility button))))))
885
886 (defun notmuch-show-insert-bodypart (msg part depth &optional hide)
887   "Insert the body part PART at depth DEPTH in the current thread.
888
889 If HIDE is non-nil then initially hide this part."
890   (let ((content-type (downcase (plist-get part :content-type)))
891         (nth (plist-get part :id))
892         (beg (point)))
893
894     (notmuch-show-insert-bodypart-internal msg part content-type nth depth content-type)
895     ;; Some of the body part handlers leave point somewhere up in the
896     ;; part, so we make sure that we're down at the end.
897     (goto-char (point-max))
898     ;; Ensure that the part ends with a carriage return.
899     (unless (bolp)
900       (insert "\n"))
901     (notmuch-show-create-part-overlays msg beg (point) hide)))
902
903 (defun notmuch-show-insert-body (msg body depth)
904   "Insert the body BODY at depth DEPTH in the current thread."
905   (mapc (lambda (part) (notmuch-show-insert-bodypart msg part depth)) body))
906
907 (defun notmuch-show-make-symbol (type)
908   (make-symbol (concat "notmuch-show-" type)))
909
910 (defun notmuch-show-strip-re (string)
911   (replace-regexp-in-string "^\\([Rr]e: *\\)+" "" string))
912
913 (defvar notmuch-show-previous-subject "")
914 (make-variable-buffer-local 'notmuch-show-previous-subject)
915
916 (defun notmuch-show-insert-msg (msg depth)
917   "Insert the message MSG at depth DEPTH in the current thread."
918   (let* ((headers (plist-get msg :headers))
919          ;; Indentation causes the buffer offset of the start/end
920          ;; points to move, so we must use markers.
921          message-start message-end
922          content-start content-end
923          headers-start headers-end
924          (bare-subject (notmuch-show-strip-re (plist-get headers :Subject))))
925
926     (setq message-start (point-marker))
927
928     (notmuch-show-insert-headerline headers
929                                     (or (if notmuch-show-relative-dates
930                                             (plist-get msg :date_relative)
931                                           nil)
932                                         (plist-get headers :Date))
933                                     (plist-get msg :tags) depth)
934
935     (setq content-start (point-marker))
936
937     ;; Set `headers-start' to point after the 'Subject:' header to be
938     ;; compatible with the existing implementation. This just sets it
939     ;; to after the first header.
940     (notmuch-show-insert-headers headers)
941     (save-excursion
942       (goto-char content-start)
943       ;; If the subject of this message is the same as that of the
944       ;; previous message, don't display it when this message is
945       ;; collapsed.
946       (when (not (string= notmuch-show-previous-subject
947                           bare-subject))
948         (forward-line 1))
949       (setq headers-start (point-marker)))
950     (setq headers-end (point-marker))
951
952     (setq notmuch-show-previous-subject bare-subject)
953
954     ;; A blank line between the headers and the body.
955     (insert "\n")
956     (notmuch-show-insert-body msg (plist-get msg :body)
957                               (if notmuch-show-indent-content depth 0))
958     ;; Ensure that the body ends with a newline.
959     (unless (bolp)
960       (insert "\n"))
961     (setq content-end (point-marker))
962
963     ;; Indent according to the depth in the thread.
964     (if notmuch-show-indent-content
965         (indent-rigidly content-start content-end (* notmuch-show-indent-messages-width depth)))
966
967     (setq message-end (point-max-marker))
968
969     ;; Save the extents of this message over the whole text of the
970     ;; message.
971     (put-text-property message-start message-end :notmuch-message-extent (cons message-start message-end))
972
973     ;; Create overlays used to control visibility
974     (plist-put msg :headers-overlay (make-overlay headers-start headers-end))
975     (plist-put msg :message-overlay (make-overlay headers-start content-end))
976
977     (plist-put msg :depth depth)
978
979     ;; Save the properties for this message. Currently this saves the
980     ;; entire message (augmented it with other stuff), which seems
981     ;; like overkill. We might save a reduced subset (for example, not
982     ;; the content).
983     (notmuch-show-set-message-properties msg)
984
985     ;; Set header visibility.
986     (notmuch-show-headers-visible msg notmuch-message-headers-visible)
987
988     ;; Message visibility depends on whether it matched the search
989     ;; criteria.
990     (notmuch-show-message-visible msg (and (plist-get msg :match)
991                                            (not (plist-get msg :excluded))))))
992
993 (defun notmuch-show-toggle-process-crypto ()
994   "Toggle the processing of cryptographic MIME parts."
995   (interactive)
996   (setq notmuch-show-process-crypto (not notmuch-show-process-crypto))
997   (message (if notmuch-show-process-crypto
998                "Processing cryptographic MIME parts."
999              "Not processing cryptographic MIME parts."))
1000   (notmuch-show-refresh-view))
1001
1002 (defun notmuch-show-toggle-elide-non-matching ()
1003   "Toggle the display of non-matching messages."
1004   (interactive)
1005   (setq notmuch-show-elide-non-matching-messages (not notmuch-show-elide-non-matching-messages))
1006   (message (if notmuch-show-elide-non-matching-messages
1007                "Showing matching messages only."
1008              "Showing all messages."))
1009   (notmuch-show-refresh-view))
1010
1011 (defun notmuch-show-toggle-thread-indentation ()
1012   "Toggle the indentation of threads."
1013   (interactive)
1014   (setq notmuch-show-indent-content (not notmuch-show-indent-content))
1015   (message (if notmuch-show-indent-content
1016                "Content is indented."
1017              "Content is not indented."))
1018   (notmuch-show-refresh-view))
1019
1020 (defun notmuch-show-insert-tree (tree depth)
1021   "Insert the message tree TREE at depth DEPTH in the current thread."
1022   (let ((msg (car tree))
1023         (replies (cadr tree)))
1024     ;; We test whether there is a message or just some replies.
1025     (when msg
1026       (notmuch-show-insert-msg msg depth))
1027     (notmuch-show-insert-thread replies (1+ depth))))
1028
1029 (defun notmuch-show-insert-thread (thread depth)
1030   "Insert the thread THREAD at depth DEPTH in the current forest."
1031   (mapc (lambda (tree) (notmuch-show-insert-tree tree depth)) thread))
1032
1033 (defun notmuch-show-insert-forest (forest)
1034   "Insert the forest of threads FOREST."
1035   (mapc (lambda (thread) (notmuch-show-insert-thread thread 0)) forest))
1036
1037 (defvar notmuch-id-regexp
1038   (concat
1039    ;; Match the id: prefix only if it begins a word (to disallow, for
1040    ;; example, matching cid:).
1041    "\\<id:\\("
1042    ;; If the term starts with a ", then parse Xapian's quoted boolean
1043    ;; term syntax, which allows for anything as long as embedded
1044    ;; double quotes escaped by doubling them.  We also disallow
1045    ;; newlines (which Xapian allows) to prevent runaway terms.
1046    "\"\\([^\"\n]\\|\"\"\\)*\""
1047    ;; Otherwise, parse Xapian's unquoted syntax, which goes up to the
1048    ;; next space or ).  We disallow [.,;] as the last character
1049    ;; because these are probably part of the surrounding text, and not
1050    ;; part of the id.  This doesn't match single character ids; meh.
1051    "\\|[^\"[:space:])][^[:space:])]*[^])[:space:].,:;?!]"
1052    "\\)")
1053   "The regexp used to match id: links in messages.")
1054
1055 (defvar notmuch-mid-regexp
1056   ;; goto-address-url-regexp matched cid: links, which have the same
1057   ;; grammar as the message ID part of a mid: link.  Construct the
1058   ;; regexp using the same technique as goto-address-url-regexp.
1059   (concat "\\<mid:\\(" thing-at-point-url-path-regexp "\\)")
1060   "The regexp used to match mid: links in messages.
1061
1062 See RFC 2392.")
1063
1064 (defun notmuch-show-buttonise-links (start end)
1065   "Buttonise URLs and mail addresses between START and END.
1066
1067 This also turns id:\"<message id>\"-parts and mid: links into
1068 buttons for a corresponding notmuch search."
1069   (goto-address-fontify-region start end)
1070   (save-excursion
1071     (let (links)
1072       (goto-char start)
1073       (while (re-search-forward notmuch-id-regexp end t)
1074         (push (list (match-beginning 0) (match-end 0)
1075                     (match-string-no-properties 0)) links))
1076       (goto-char start)
1077       (while (re-search-forward notmuch-mid-regexp end t)
1078         (let* ((mid-cid (match-string-no-properties 1))
1079                (mid (save-match-data
1080                       (string-match "^[^/]*" mid-cid)
1081                       (url-unhex-string (match-string 0 mid-cid)))))
1082           (push (list (match-beginning 0) (match-end 0)
1083                       (notmuch-id-to-query mid)) links)))
1084       (dolist (link links)
1085         ;; Remove the overlay created by goto-address-mode
1086         (remove-overlays (first link) (second link) 'goto-address t)
1087         (make-text-button (first link) (second link)
1088                           'action `(lambda (arg)
1089                                      (notmuch-show ,(third link)))
1090                           'follow-link t
1091                           'help-echo "Mouse-1, RET: search for this message"
1092                           'face goto-address-mail-face)))))
1093
1094 ;;;###autoload
1095 (defun notmuch-show (thread-id &optional parent-buffer query-context buffer-name)
1096   "Run \"notmuch show\" with the given thread ID and display results.
1097
1098 The optional PARENT-BUFFER is the notmuch-search buffer from
1099 which this notmuch-show command was executed, (so that the
1100 next thread from that buffer can be show when done with this
1101 one).
1102
1103 The optional QUERY-CONTEXT is a notmuch search term. Only
1104 messages from the thread matching this search term are shown if
1105 non-nil.
1106
1107 The optional BUFFER-NAME provides the name of the buffer in
1108 which the message thread is shown. If it is nil (which occurs
1109 when the command is called interactively) the argument to the
1110 function is used."
1111   (interactive "sNotmuch show: ")
1112   (let ((buffer-name (generate-new-buffer-name
1113                       (or buffer-name
1114                           (concat "*notmuch-" thread-id "*")))))
1115     (switch-to-buffer (get-buffer-create buffer-name))
1116     ;; Set the default value for `notmuch-show-process-crypto' in this
1117     ;; buffer.
1118     (setq notmuch-show-process-crypto notmuch-crypto-process-mime)
1119     ;; Set the default value for
1120     ;; `notmuch-show-elide-non-matching-messages' in this buffer. If
1121     ;; there is a prefix argument, invert the default.
1122     (setq notmuch-show-elide-non-matching-messages notmuch-show-only-matching-messages)
1123     (if current-prefix-arg
1124         (setq notmuch-show-elide-non-matching-messages (not notmuch-show-elide-non-matching-messages)))
1125
1126     (setq notmuch-show-thread-id thread-id
1127           notmuch-show-parent-buffer parent-buffer
1128           notmuch-show-query-context query-context)
1129     (notmuch-show-build-buffer)
1130     (notmuch-show-goto-first-wanted-message)
1131     (current-buffer)))
1132
1133 (defun notmuch-show-build-buffer ()
1134   (let ((inhibit-read-only t))
1135
1136     (notmuch-show-mode)
1137     ;; Don't track undo information for this buffer
1138     (set 'buffer-undo-list t)
1139
1140     (erase-buffer)
1141     (goto-char (point-min))
1142     (save-excursion
1143       (let* ((basic-args (list notmuch-show-thread-id))
1144              (args (if notmuch-show-query-context
1145                        (append (list "\'") basic-args
1146                                (list "and (" notmuch-show-query-context ")\'"))
1147                      (append (list "\'") basic-args (list "\'"))))
1148              (cli-args (cons "--exclude=false"
1149                              (when notmuch-show-elide-non-matching-messages
1150                                (list "--entire-thread=false")))))
1151
1152         (notmuch-show-insert-forest (notmuch-query-get-threads (append cli-args args)))
1153         ;; If the query context reduced the results to nothing, run
1154         ;; the basic query.
1155         (when (and (eq (buffer-size) 0)
1156                    notmuch-show-query-context)
1157           (notmuch-show-insert-forest
1158            (notmuch-query-get-threads (append cli-args basic-args)))))
1159
1160       (jit-lock-register #'notmuch-show-buttonise-links)
1161
1162       ;; Set the header line to the subject of the first message.
1163       (setq header-line-format (notmuch-show-strip-re (notmuch-show-get-subject)))
1164
1165       (run-hooks 'notmuch-show-hook))))
1166
1167 (defun notmuch-show-capture-state ()
1168   "Capture the state of the current buffer.
1169
1170 This includes:
1171  - the list of open messages,
1172  - the current message."
1173   (list (notmuch-show-get-message-id) (notmuch-show-get-message-ids-for-open-messages)))
1174
1175 (defun notmuch-show-apply-state (state)
1176   "Apply STATE to the current buffer.
1177
1178 This includes:
1179  - opening the messages previously opened,
1180  - closing all other messages,
1181  - moving to the correct current message."
1182   (let ((current (car state))
1183         (open (cadr state)))
1184
1185     ;; Open those that were open.
1186     (goto-char (point-min))
1187     (loop do (notmuch-show-message-visible (notmuch-show-get-message-properties)
1188                                            (member (notmuch-show-get-message-id) open))
1189           until (not (notmuch-show-goto-message-next)))
1190
1191     ;; Go to the previously open message.
1192     (goto-char (point-min))
1193     (unless (loop if (string= current (notmuch-show-get-message-id))
1194                   return t
1195                   until (not (notmuch-show-goto-message-next)))
1196       (goto-char (point-min))
1197       (message "Previously current message not found."))
1198     (notmuch-show-message-adjust)))
1199
1200 (defun notmuch-show-refresh-view (&optional reset-state)
1201   "Refresh the current view.
1202
1203 Refreshes the current view, observing changes in display
1204 preferences. If invoked with a prefix argument (or RESET-STATE is
1205 non-nil) then the state of the buffer (open/closed messages) is
1206 reset based on the original query."
1207   (interactive "P")
1208   (let ((inhibit-read-only t)
1209         (state (unless reset-state
1210                  (notmuch-show-capture-state))))
1211     ;; erase-buffer does not seem to remove overlays, which can lead
1212     ;; to weird effects such as remaining images, so remove them
1213     ;; manually.
1214     (remove-overlays)
1215     (erase-buffer)
1216     (notmuch-show-build-buffer)
1217     (if state
1218         (notmuch-show-apply-state state)
1219       ;; We're resetting state, so navigate to the first open message
1220       ;; and mark it read, just like opening a new show buffer.
1221       (notmuch-show-goto-first-wanted-message))))
1222
1223 (defvar notmuch-show-stash-map
1224   (let ((map (make-sparse-keymap)))
1225     (define-key map "c" 'notmuch-show-stash-cc)
1226     (define-key map "d" 'notmuch-show-stash-date)
1227     (define-key map "F" 'notmuch-show-stash-filename)
1228     (define-key map "f" 'notmuch-show-stash-from)
1229     (define-key map "i" 'notmuch-show-stash-message-id)
1230     (define-key map "I" 'notmuch-show-stash-message-id-stripped)
1231     (define-key map "s" 'notmuch-show-stash-subject)
1232     (define-key map "T" 'notmuch-show-stash-tags)
1233     (define-key map "t" 'notmuch-show-stash-to)
1234     (define-key map "l" 'notmuch-show-stash-mlarchive-link)
1235     (define-key map "L" 'notmuch-show-stash-mlarchive-link-and-go)
1236     map)
1237   "Submap for stash commands")
1238 (fset 'notmuch-show-stash-map notmuch-show-stash-map)
1239
1240 (defvar notmuch-show-mode-map
1241       (let ((map (make-sparse-keymap)))
1242         (define-key map "?" 'notmuch-help)
1243         (define-key map "q" 'notmuch-kill-this-buffer)
1244         (define-key map (kbd "<C-tab>") 'widget-backward)
1245         (define-key map (kbd "M-TAB") 'notmuch-show-previous-button)
1246         (define-key map (kbd "<backtab>") 'notmuch-show-previous-button)
1247         (define-key map (kbd "TAB") 'notmuch-show-next-button)
1248         (define-key map "s" 'notmuch-search)
1249         (define-key map "m" 'notmuch-mua-new-mail)
1250         (define-key map "f" 'notmuch-show-forward-message)
1251         (define-key map "r" 'notmuch-show-reply-sender)
1252         (define-key map "R" 'notmuch-show-reply)
1253         (define-key map "|" 'notmuch-show-pipe-message)
1254         (define-key map "w" 'notmuch-show-save-attachments)
1255         (define-key map "V" 'notmuch-show-view-raw-message)
1256         (define-key map "v" 'notmuch-show-view-all-mime-parts)
1257         (define-key map "c" 'notmuch-show-stash-map)
1258         (define-key map "=" 'notmuch-show-refresh-view)
1259         (define-key map "h" 'notmuch-show-toggle-visibility-headers)
1260         (define-key map "*" 'notmuch-show-tag-all)
1261         (define-key map "-" 'notmuch-show-remove-tag)
1262         (define-key map "+" 'notmuch-show-add-tag)
1263         (define-key map "X" 'notmuch-show-archive-thread-then-exit)
1264         (define-key map "x" 'notmuch-show-archive-message-then-next-or-exit)
1265         (define-key map "A" 'notmuch-show-archive-thread-then-next)
1266         (define-key map "a" 'notmuch-show-archive-message-then-next-or-next-thread)
1267         (define-key map "N" 'notmuch-show-next-message)
1268         (define-key map "P" 'notmuch-show-previous-message)
1269         (define-key map "n" 'notmuch-show-next-open-message)
1270         (define-key map "p" 'notmuch-show-previous-open-message)
1271         (define-key map (kbd "DEL") 'notmuch-show-rewind)
1272         (define-key map " " 'notmuch-show-advance-and-archive)
1273         (define-key map (kbd "M-RET") 'notmuch-show-open-or-close-all)
1274         (define-key map (kbd "RET") 'notmuch-show-toggle-message)
1275         (define-key map "#" 'notmuch-show-print-message)
1276         (define-key map "!" 'notmuch-show-toggle-elide-non-matching)
1277         (define-key map "$" 'notmuch-show-toggle-process-crypto)
1278         (define-key map "<" 'notmuch-show-toggle-thread-indentation)
1279         (define-key map "t" 'toggle-truncate-lines)
1280         map)
1281       "Keymap for \"notmuch show\" buffers.")
1282 (fset 'notmuch-show-mode-map notmuch-show-mode-map)
1283
1284 (defun notmuch-show-mode ()
1285   "Major mode for viewing a thread with notmuch.
1286
1287 This buffer contains the results of the \"notmuch show\" command
1288 for displaying a single thread of email from your email archives.
1289
1290 By default, various components of email messages, (citations,
1291 signatures, already-read messages), are hidden. You can make
1292 these parts visible by clicking with the mouse button or by
1293 pressing RET after positioning the cursor on a hidden part, (for
1294 which \\[notmuch-show-next-button] and \\[notmuch-show-previous-button] are helpful).
1295
1296 Reading the thread sequentially is well-supported by pressing
1297 \\[notmuch-show-advance-and-archive]. This will scroll the current message (if necessary), advance
1298 to the next message, or advance to the next thread (if already on
1299 the last message of a thread).
1300
1301 Other commands are available to read or manipulate the thread
1302 more selectively, (such as '\\[notmuch-show-next-message]' and '\\[notmuch-show-previous-message]' to advance to messages
1303 without removing any tags, and '\\[notmuch-show-archive-thread]' to archive an entire thread
1304 without scrolling through with \\[notmuch-show-advance-and-archive]).
1305
1306 You can add or remove arbitrary tags from the current message with
1307 '\\[notmuch-show-add-tag]' or '\\[notmuch-show-remove-tag]'.
1308
1309 All currently available key bindings:
1310
1311 \\{notmuch-show-mode-map}"
1312   (interactive)
1313   (kill-all-local-variables)
1314   (use-local-map notmuch-show-mode-map)
1315   (setq major-mode 'notmuch-show-mode
1316         mode-name "notmuch-show")
1317   (setq buffer-read-only t
1318         truncate-lines t))
1319
1320 (defun notmuch-show-move-to-message-top ()
1321   (goto-char (notmuch-show-message-top)))
1322
1323 (defun notmuch-show-move-to-message-bottom ()
1324   (goto-char (notmuch-show-message-bottom)))
1325
1326 (defun notmuch-show-message-adjust ()
1327   (recenter 0))
1328
1329 ;; Movement related functions.
1330
1331 ;; There's some strangeness here where a text property applied to a
1332 ;; region a->b is not found when point is at b. We walk backwards
1333 ;; until finding the property.
1334 (defun notmuch-show-message-extent ()
1335   (let (r)
1336     (save-excursion
1337       (while (not (setq r (get-text-property (point) :notmuch-message-extent)))
1338         (backward-char)))
1339     r))
1340
1341 (defun notmuch-show-message-top ()
1342   (car (notmuch-show-message-extent)))
1343
1344 (defun notmuch-show-message-bottom ()
1345   (cdr (notmuch-show-message-extent)))
1346
1347 (defun notmuch-show-goto-message-next ()
1348   (let ((start (point)))
1349     (notmuch-show-move-to-message-bottom)
1350     (if (not (eobp))
1351         t
1352       (goto-char start)
1353       nil)))
1354
1355 (defun notmuch-show-goto-message-previous ()
1356   (notmuch-show-move-to-message-top)
1357   (if (bobp)
1358       nil
1359     (backward-char)
1360     (notmuch-show-move-to-message-top)
1361     t))
1362
1363 (defun notmuch-show-mapc (function)
1364   "Iterate through all messages in the current thread with
1365 `notmuch-show-goto-message-next' and call FUNCTION for side
1366 effects."
1367   (save-excursion
1368     (goto-char (point-min))
1369     (loop do (funcall function)
1370           while (notmuch-show-goto-message-next))))
1371
1372 ;; Functions relating to the visibility of messages and their
1373 ;; components.
1374
1375 (defun notmuch-show-message-visible (props visible-p)
1376   (overlay-put (plist-get props :message-overlay) 'invisible (not visible-p))
1377   (notmuch-show-set-prop :message-visible visible-p props))
1378
1379 (defun notmuch-show-headers-visible (props visible-p)
1380   (overlay-put (plist-get props :headers-overlay) 'invisible (not visible-p))
1381   (notmuch-show-set-prop :headers-visible visible-p props))
1382
1383 ;; Functions for setting and getting attributes of the current
1384 ;; message.
1385
1386 (defun notmuch-show-set-message-properties (props)
1387   (save-excursion
1388     (notmuch-show-move-to-message-top)
1389     (put-text-property (point) (+ (point) 1) :notmuch-message-properties props)))
1390
1391 (defun notmuch-show-get-message-properties ()
1392   "Return the properties of the current message as a plist.
1393
1394 Some useful entries are:
1395 :headers - Property list containing the headers :Date, :Subject, :From, etc.
1396 :body - Body of the message
1397 :tags - Tags for this message"
1398   (save-excursion
1399     (notmuch-show-move-to-message-top)
1400     (get-text-property (point) :notmuch-message-properties)))
1401
1402 (defun notmuch-show-set-prop (prop val &optional props)
1403   (let ((inhibit-read-only t)
1404         (props (or props
1405                    (notmuch-show-get-message-properties))))
1406     (plist-put props prop val)
1407     (notmuch-show-set-message-properties props)))
1408
1409 (defun notmuch-show-get-prop (prop &optional props)
1410   (let ((props (or props
1411                    (notmuch-show-get-message-properties))))
1412     (plist-get props prop)))
1413
1414 (defun notmuch-show-get-message-id (&optional bare)
1415   "Return an id: query for the Message-Id of the current message.
1416
1417 If optional argument BARE is non-nil, return
1418 the Message-Id without id: prefix and escaping."
1419   (if bare
1420       (notmuch-show-get-prop :id)
1421     (notmuch-id-to-query (notmuch-show-get-prop :id))))
1422
1423 (defun notmuch-show-get-messages-ids ()
1424   "Return all id: queries of messages in the current thread."
1425   (let ((message-ids))
1426     (notmuch-show-mapc
1427      (lambda () (push (notmuch-show-get-message-id) message-ids)))
1428     message-ids))
1429
1430 (defun notmuch-show-get-messages-ids-search ()
1431   "Return a search string for all message ids of messages in the
1432 current thread."
1433   (mapconcat 'identity (notmuch-show-get-messages-ids) " or "))
1434
1435 ;; dme: Would it make sense to use a macro for many of these?
1436
1437 (defun notmuch-show-get-filename ()
1438   "Return the filename of the current message."
1439   (notmuch-show-get-prop :filename))
1440
1441 (defun notmuch-show-get-header (header &optional props)
1442   "Return the named header of the current message, if any."
1443   (plist-get (notmuch-show-get-prop :headers props) header))
1444
1445 (defun notmuch-show-get-cc ()
1446   (notmuch-show-get-header :Cc))
1447
1448 (defun notmuch-show-get-date ()
1449   (notmuch-show-get-header :Date))
1450
1451 (defun notmuch-show-get-from ()
1452   (notmuch-show-get-header :From))
1453
1454 (defun notmuch-show-get-subject ()
1455   (notmuch-show-get-header :Subject))
1456
1457 (defun notmuch-show-get-to ()
1458   (notmuch-show-get-header :To))
1459
1460 (defun notmuch-show-get-depth ()
1461   (notmuch-show-get-prop :depth))
1462
1463 (defun notmuch-show-set-tags (tags)
1464   "Set the tags of the current message."
1465   (notmuch-show-set-prop :tags tags)
1466   (notmuch-show-update-tags tags))
1467
1468 (defun notmuch-show-get-tags ()
1469   "Return the tags of the current message."
1470   (notmuch-show-get-prop :tags))
1471
1472 (defun notmuch-show-message-visible-p ()
1473   "Is the current message visible?"
1474   (notmuch-show-get-prop :message-visible))
1475
1476 (defun notmuch-show-headers-visible-p ()
1477   "Are the headers of the current message visible?"
1478   (notmuch-show-get-prop :headers-visible))
1479
1480 (defun notmuch-show-mark-read (&optional unread)
1481   "Mark the current message as read.
1482
1483 Mark the current message as read by applying the tag changes in
1484 `notmuch-show-mark-read-tags' to it (remove the \"unread\" tag by
1485 default). If a prefix argument is given, the message will be
1486 marked as unread, i.e. the tag changes in
1487 `notmuch-show-mark-read-tags' will be reversed."
1488   (interactive "P")
1489   (when notmuch-show-mark-read-tags
1490     (apply 'notmuch-show-tag-message
1491            (notmuch-tag-change-list notmuch-show-mark-read-tags unread))))
1492
1493 ;; Functions for getting attributes of several messages in the current
1494 ;; thread.
1495
1496 (defun notmuch-show-get-message-ids-for-open-messages ()
1497   "Return a list of all id: queries for open messages in the current thread."
1498   (save-excursion
1499     (let (message-ids done)
1500       (goto-char (point-min))
1501       (while (not done)
1502         (if (notmuch-show-message-visible-p)
1503             (setq message-ids (append message-ids (list (notmuch-show-get-message-id)))))
1504         (setq done (not (notmuch-show-goto-message-next)))
1505         )
1506       message-ids
1507       )))
1508
1509 ;; Commands typically bound to keys.
1510
1511 (defun notmuch-show-advance ()
1512   "Advance through thread.
1513
1514 If the current message in the thread is not yet fully visible,
1515 scroll by a near screenful to read more of the message.
1516
1517 Otherwise, (the end of the current message is already within the
1518 current window), advance to the next open message."
1519   (interactive)
1520   (let* ((end-of-this-message (notmuch-show-message-bottom))
1521          (visible-end-of-this-message (1- end-of-this-message))
1522          (ret nil))
1523     (while (invisible-p visible-end-of-this-message)
1524       (setq visible-end-of-this-message
1525             (max (point-min)
1526                  (1- (previous-single-char-property-change
1527                       visible-end-of-this-message 'invisible)))))
1528     (cond
1529      ;; Ideally we would test `end-of-this-message' against the result
1530      ;; of `window-end', but that doesn't account for the fact that
1531      ;; the end of the message might be hidden.
1532      ((and visible-end-of-this-message
1533            (> visible-end-of-this-message (window-end)))
1534       ;; The bottom of this message is not visible - scroll.
1535       (scroll-up nil))
1536
1537      ((not (= end-of-this-message (point-max)))
1538       ;; This is not the last message - move to the next visible one.
1539       (notmuch-show-next-open-message))
1540
1541      ((not (= (point) (point-max)))
1542       ;; This is the last message, but the cursor is not at the end of
1543       ;; the buffer. Move it there.
1544       (goto-char (point-max)))
1545
1546      (t
1547       ;; This is the last message - change the return value
1548       (setq ret t)))
1549     ret))
1550
1551 (defun notmuch-show-advance-and-archive ()
1552   "Advance through thread and archive.
1553
1554 This command is intended to be one of the simplest ways to
1555 process a thread of email. It works exactly like
1556 notmuch-show-advance, in that it scrolls through messages in a
1557 show buffer, except that when it gets to the end of the buffer it
1558 archives the entire current thread, (remove the \"inbox\" tag
1559 from each message), kills the buffer, and displays the next
1560 thread from the search from which this thread was originally
1561 shown."
1562   (interactive)
1563   (if (notmuch-show-advance)
1564       (notmuch-show-archive-thread-then-next)))
1565
1566 (defun notmuch-show-rewind ()
1567   "Backup through the thread, (reverse scrolling compared to \\[notmuch-show-advance-and-archive]).
1568
1569 Specifically, if the beginning of the previous email is fewer
1570 than `window-height' lines from the current point, move to it
1571 just like `notmuch-show-previous-message'.
1572
1573 Otherwise, just scroll down a screenful of the current message.
1574
1575 This command does not modify any message tags, (it does not undo
1576 any effects from previous calls to
1577 `notmuch-show-advance-and-archive'."
1578   (interactive)
1579   (let ((start-of-message (notmuch-show-message-top))
1580         (start-of-window (window-start)))
1581     (cond
1582       ;; Either this message is properly aligned with the start of the
1583       ;; window or the start of this message is not visible on the
1584       ;; screen - scroll.
1585      ((or (= start-of-message start-of-window)
1586           (< start-of-message start-of-window))
1587       (scroll-down)
1588       ;; If a small number of lines from the previous message are
1589       ;; visible, realign so that the top of the current message is at
1590       ;; the top of the screen.
1591       (when (<= (count-screen-lines (window-start) start-of-message)
1592                 next-screen-context-lines)
1593         (goto-char (notmuch-show-message-top))
1594         (notmuch-show-message-adjust))
1595       ;; Move to the top left of the window.
1596       (goto-char (window-start)))
1597      (t
1598       ;; Move to the previous message.
1599       (notmuch-show-previous-message)))))
1600
1601 (defun notmuch-show-reply (&optional prompt-for-sender)
1602   "Reply to the sender and all recipients of the current message."
1603   (interactive "P")
1604   (notmuch-mua-new-reply (notmuch-show-get-message-id) prompt-for-sender t))
1605
1606 (defun notmuch-show-reply-sender (&optional prompt-for-sender)
1607   "Reply to the sender of the current message."
1608   (interactive "P")
1609   (notmuch-mua-new-reply (notmuch-show-get-message-id) prompt-for-sender nil))
1610
1611 (defun notmuch-show-forward-message (&optional prompt-for-sender)
1612   "Forward the current message."
1613   (interactive "P")
1614   (with-current-notmuch-show-message
1615    (notmuch-mua-new-forward-message prompt-for-sender)))
1616
1617 (defun notmuch-show-next-message (&optional pop-at-end)
1618   "Show the next message.
1619
1620 If a prefix argument is given and this is the last message in the
1621 thread, navigate to the next thread in the parent search buffer."
1622   (interactive "P")
1623   (if (notmuch-show-goto-message-next)
1624       (progn
1625         (notmuch-show-mark-read)
1626         (notmuch-show-message-adjust))
1627     (if pop-at-end
1628         (notmuch-show-next-thread)
1629       (goto-char (point-max)))))
1630
1631 (defun notmuch-show-previous-message ()
1632   "Show the previous message or the start of the current message."
1633   (interactive)
1634   (if (= (point) (notmuch-show-message-top))
1635       (notmuch-show-goto-message-previous)
1636     (notmuch-show-move-to-message-top))
1637   (notmuch-show-mark-read)
1638   (notmuch-show-message-adjust))
1639
1640 (defun notmuch-show-next-open-message (&optional pop-at-end)
1641   "Show the next open message.
1642
1643 If a prefix argument is given and this is the last open message
1644 in the thread, navigate to the next thread in the parent search
1645 buffer. Return t if there was a next open message in the thread
1646 to show, nil otherwise."
1647   (interactive "P")
1648   (let (r)
1649     (while (and (setq r (notmuch-show-goto-message-next))
1650                 (not (notmuch-show-message-visible-p))))
1651     (if r
1652         (progn
1653           (notmuch-show-mark-read)
1654           (notmuch-show-message-adjust))
1655       (if pop-at-end
1656           (notmuch-show-next-thread)
1657         (goto-char (point-max))))
1658     r))
1659
1660 (defun notmuch-show-next-matching-message ()
1661   "Show the next matching message."
1662   (interactive)
1663   (let (r)
1664     (while (and (setq r (notmuch-show-goto-message-next))
1665                 (not (notmuch-show-get-prop :match))))
1666     (if r
1667         (progn
1668           (notmuch-show-mark-read)
1669           (notmuch-show-message-adjust))
1670       (goto-char (point-max)))))
1671
1672 (defun notmuch-show-open-if-matched ()
1673   "Open a message if it is matched (whether or not excluded)."
1674   (let ((props (notmuch-show-get-message-properties)))
1675     (notmuch-show-message-visible props (plist-get props :match))))
1676
1677 (defun notmuch-show-goto-first-wanted-message ()
1678   "Move to the first open message and mark it read"
1679   (goto-char (point-min))
1680   (if (notmuch-show-message-visible-p)
1681       (notmuch-show-mark-read)
1682     (notmuch-show-next-open-message))
1683   (when (eobp)
1684     ;; There are no matched non-excluded messages so open all matched
1685     ;; (necessarily excluded) messages and go to the first.
1686     (notmuch-show-mapc 'notmuch-show-open-if-matched)
1687     (force-window-update)
1688     (goto-char (point-min))
1689     (if (notmuch-show-message-visible-p)
1690         (notmuch-show-mark-read)
1691       (notmuch-show-next-open-message))))
1692
1693 (defun notmuch-show-previous-open-message ()
1694   "Show the previous open message."
1695   (interactive)
1696   (while (and (if (= (point) (notmuch-show-message-top))
1697                   (notmuch-show-goto-message-previous)
1698                 (notmuch-show-move-to-message-top))
1699               (not (notmuch-show-message-visible-p))))
1700   (notmuch-show-mark-read)
1701   (notmuch-show-message-adjust))
1702
1703 (defun notmuch-show-view-raw-message ()
1704   "View the file holding the current message."
1705   (interactive)
1706   (let* ((id (notmuch-show-get-message-id))
1707          (buf (get-buffer-create (concat "*notmuch-raw-" id "*"))))
1708     (call-process notmuch-command nil buf nil "show" "--format=raw" id)
1709     (switch-to-buffer buf)
1710     (goto-char (point-min))
1711     (set-buffer-modified-p nil)
1712     (view-buffer buf 'kill-buffer-if-not-modified)))
1713
1714 (defun notmuch-show-pipe-message (entire-thread command)
1715   "Pipe the contents of the current message (or thread) to the given command.
1716
1717 The given command will be executed with the raw contents of the
1718 current email message as stdin. Anything printed by the command
1719 to stdout or stderr will appear in the *notmuch-pipe* buffer.
1720
1721 When invoked with a prefix argument, the command will receive all
1722 open messages in the current thread (formatted as an mbox) rather
1723 than only the current message."
1724   (interactive "P\nsPipe message to command: ")
1725   (let (shell-command)
1726     (if entire-thread
1727         (setq shell-command
1728               (concat notmuch-command " show --format=mbox --exclude=false "
1729                       (shell-quote-argument
1730                        (mapconcat 'identity (notmuch-show-get-message-ids-for-open-messages) " OR "))
1731                       " | " command))
1732       (setq shell-command
1733             (concat notmuch-command " show --format=raw "
1734                     (shell-quote-argument (notmuch-show-get-message-id)) " | " command)))
1735     (let ((buf (get-buffer-create (concat "*notmuch-pipe*"))))
1736       (with-current-buffer buf
1737         (setq buffer-read-only nil)
1738         (erase-buffer)
1739         (let ((exit-code (call-process-shell-command shell-command nil buf)))
1740           (goto-char (point-max))
1741           (set-buffer-modified-p nil)
1742           (setq buffer-read-only t)
1743           (unless (zerop exit-code)
1744             (switch-to-buffer-other-window buf)
1745             (message (format "Command '%s' exited abnormally with code %d"
1746                              shell-command exit-code))))))))
1747
1748 (defun notmuch-show-tag-message (&rest tag-changes)
1749   "Change tags for the current message.
1750
1751 TAG-CHANGES is a list of tag operations for `notmuch-tag'."
1752   (let* ((current-tags (notmuch-show-get-tags))
1753          (new-tags (notmuch-update-tags current-tags tag-changes)))
1754     (unless (equal current-tags new-tags)
1755       (funcall 'notmuch-tag (notmuch-show-get-message-id) tag-changes)
1756       (notmuch-show-set-tags new-tags))))
1757
1758 (defun notmuch-show-tag (&optional tag-changes)
1759   "Change tags for the current message.
1760
1761 See `notmuch-tag' for information on the format of TAG-CHANGES."
1762   (interactive)
1763   (setq tag-changes (funcall 'notmuch-tag (notmuch-show-get-message-id) tag-changes))
1764   (let* ((current-tags (notmuch-show-get-tags))
1765          (new-tags (notmuch-update-tags current-tags tag-changes)))
1766     (unless (equal current-tags new-tags)
1767       (notmuch-show-set-tags new-tags))))
1768
1769 (defun notmuch-show-tag-all (&optional tag-changes)
1770   "Change tags for all messages in the current show buffer.
1771
1772 See `notmuch-tag' for information on the format of TAG-CHANGES."
1773   (interactive)
1774   (setq tag-changes (funcall 'notmuch-tag (notmuch-show-get-messages-ids-search) tag-changes))
1775   (notmuch-show-mapc
1776    (lambda ()
1777      (let* ((current-tags (notmuch-show-get-tags))
1778             (new-tags (notmuch-update-tags current-tags tag-changes)))
1779        (unless (equal current-tags new-tags)
1780          (notmuch-show-set-tags new-tags))))))
1781
1782 (defun notmuch-show-add-tag ()
1783   "Same as `notmuch-show-tag' but sets initial input to '+'."
1784   (interactive)
1785   (notmuch-show-tag "+"))
1786
1787 (defun notmuch-show-remove-tag ()
1788   "Same as `notmuch-show-tag' but sets initial input to '-'."
1789   (interactive)
1790   (notmuch-show-tag "-"))
1791
1792 (defun notmuch-show-toggle-visibility-headers ()
1793   "Toggle the visibility of the current message headers."
1794   (interactive)
1795   (let ((props (notmuch-show-get-message-properties)))
1796     (notmuch-show-headers-visible
1797      props
1798      (not (plist-get props :headers-visible))))
1799   (force-window-update))
1800
1801 (defun notmuch-show-toggle-message ()
1802   "Toggle the visibility of the current message."
1803   (interactive)
1804   (let ((props (notmuch-show-get-message-properties)))
1805     (notmuch-show-message-visible
1806      props
1807      (not (plist-get props :message-visible))))
1808   (force-window-update))
1809
1810 (defun notmuch-show-open-or-close-all ()
1811   "Set the visibility all of the messages in the current thread.
1812 By default make all of the messages visible. With a prefix
1813 argument, hide all of the messages."
1814   (interactive)
1815   (save-excursion
1816     (goto-char (point-min))
1817     (loop do (notmuch-show-message-visible (notmuch-show-get-message-properties)
1818                                            (not current-prefix-arg))
1819           until (not (notmuch-show-goto-message-next))))
1820   (force-window-update))
1821
1822 (defun notmuch-show-next-button ()
1823   "Advance point to the next button in the buffer."
1824   (interactive)
1825   (forward-button 1))
1826
1827 (defun notmuch-show-previous-button ()
1828   "Move point back to the previous button in the buffer."
1829   (interactive)
1830   (backward-button 1))
1831
1832 (defun notmuch-show-next-thread (&optional show-next)
1833   "Move to the next item in the search results, if any."
1834   (interactive "P")
1835   (let ((parent-buffer notmuch-show-parent-buffer))
1836     (notmuch-kill-this-buffer)
1837     (when (buffer-live-p parent-buffer)
1838       (switch-to-buffer parent-buffer)
1839       (notmuch-search-next-thread)
1840       (if show-next
1841           (notmuch-search-show-thread)))))
1842
1843 (defun notmuch-show-archive-thread (&optional unarchive)
1844   "Archive each message in thread.
1845
1846 Archive each message currently shown by applying the tag changes
1847 in `notmuch-archive-tags' to each (remove the \"inbox\" tag by
1848 default). If a prefix argument is given, the messages will be
1849 \"unarchived\", i.e. the tag changes in `notmuch-archive-tags'
1850 will be reversed.
1851
1852 Note: This command is safe from any race condition of new messages
1853 being delivered to the same thread. It does not archive the
1854 entire thread, but only the messages shown in the current
1855 buffer."
1856   (interactive "P")
1857   (when notmuch-archive-tags
1858     (notmuch-show-tag-all
1859      (notmuch-tag-change-list notmuch-archive-tags unarchive))))
1860
1861 (defun notmuch-show-archive-thread-then-next ()
1862   "Archive all messages in the current buffer, then show next thread from search."
1863   (interactive)
1864   (notmuch-show-archive-thread)
1865   (notmuch-show-next-thread t))
1866
1867 (defun notmuch-show-archive-thread-then-exit ()
1868   "Archive all messages in the current buffer, then exit back to search results."
1869   (interactive)
1870   (notmuch-show-archive-thread)
1871   (notmuch-show-next-thread))
1872
1873 (defun notmuch-show-archive-message (&optional unarchive)
1874   "Archive the current message.
1875
1876 Archive the current message by applying the tag changes in
1877 `notmuch-archive-tags' to it (remove the \"inbox\" tag by
1878 default). If a prefix argument is given, the message will be
1879 \"unarchived\", i.e. the tag changes in `notmuch-archive-tags'
1880 will be reversed."
1881   (interactive "P")
1882   (when notmuch-archive-tags
1883     (apply 'notmuch-show-tag-message
1884            (notmuch-tag-change-list notmuch-archive-tags unarchive))))
1885
1886 (defun notmuch-show-archive-message-then-next-or-exit ()
1887   "Archive the current message, then show the next open message in the current thread.
1888
1889 If at the last open message in the current thread, then exit back
1890 to search results."
1891   (interactive)
1892   (notmuch-show-archive-message)
1893   (notmuch-show-next-open-message t))
1894
1895 (defun notmuch-show-archive-message-then-next-or-next-thread ()
1896   "Archive the current message, then show the next open message in the current thread.
1897
1898 If at the last open message in the current thread, then show next
1899 thread from search."
1900   (interactive)
1901   (notmuch-show-archive-message)
1902   (unless (notmuch-show-next-open-message)
1903     (notmuch-show-next-thread t)))
1904
1905 (defun notmuch-show-stash-cc ()
1906   "Copy CC field of current message to kill-ring."
1907   (interactive)
1908   (notmuch-common-do-stash (notmuch-show-get-cc)))
1909
1910 (defun notmuch-show-stash-date ()
1911   "Copy date of current message to kill-ring."
1912   (interactive)
1913   (notmuch-common-do-stash (notmuch-show-get-date)))
1914
1915 (defun notmuch-show-stash-filename ()
1916   "Copy filename of current message to kill-ring."
1917   (interactive)
1918   (notmuch-common-do-stash (notmuch-show-get-filename)))
1919
1920 (defun notmuch-show-stash-from ()
1921   "Copy From address of current message to kill-ring."
1922   (interactive)
1923   (notmuch-common-do-stash (notmuch-show-get-from)))
1924
1925 (defun notmuch-show-stash-message-id (&optional stash-thread-id)
1926   "Copy id: query matching the current message to kill-ring.
1927
1928 If invoked with a prefix argument (or STASH-THREAD-ID is
1929 non-nil), copy thread: query matching the current thread to
1930 kill-ring."
1931   (interactive "P")
1932   (if stash-thread-id
1933       (notmuch-common-do-stash notmuch-show-thread-id)
1934     (notmuch-common-do-stash (notmuch-show-get-message-id))))
1935
1936 (defun notmuch-show-stash-message-id-stripped ()
1937   "Copy message ID of current message (sans `id:' prefix) to kill-ring."
1938   (interactive)
1939   (notmuch-common-do-stash (notmuch-show-get-message-id t)))
1940
1941 (defun notmuch-show-stash-subject ()
1942   "Copy Subject field of current message to kill-ring."
1943   (interactive)
1944   (notmuch-common-do-stash (notmuch-show-get-subject)))
1945
1946 (defun notmuch-show-stash-tags ()
1947   "Copy tags of current message to kill-ring as a comma separated list."
1948   (interactive)
1949   (notmuch-common-do-stash (mapconcat 'identity (notmuch-show-get-tags) ",")))
1950
1951 (defun notmuch-show-stash-to ()
1952   "Copy To address of current message to kill-ring."
1953   (interactive)
1954   (notmuch-common-do-stash (notmuch-show-get-to)))
1955
1956 (defun notmuch-show-stash-mlarchive-link (&optional mla)
1957   "Copy an ML Archive URI for the current message to the kill-ring.
1958
1959 This presumes that the message is available at the selected Mailing List Archive.
1960
1961 If optional argument MLA is non-nil, use the provided key instead of prompting
1962 the user (see `notmuch-show-stash-mlarchive-link-alist')."
1963   (interactive)
1964   (notmuch-common-do-stash
1965    (concat (cdr (assoc
1966                  (or mla
1967                      (let ((completion-ignore-case t))
1968                        (completing-read
1969                         "Mailing List Archive: "
1970                         notmuch-show-stash-mlarchive-link-alist
1971                         nil t nil nil notmuch-show-stash-mlarchive-link-default)))
1972                  notmuch-show-stash-mlarchive-link-alist))
1973            (notmuch-show-get-message-id t))))
1974
1975 (defun notmuch-show-stash-mlarchive-link-and-go (&optional mla)
1976   "Copy an ML Archive URI for the current message to the kill-ring and visit it.
1977
1978 This presumes that the message is available at the selected Mailing List Archive.
1979
1980 If optional argument MLA is non-nil, use the provided key instead of prompting
1981 the user (see `notmuch-show-stash-mlarchive-link-alist')."
1982   (interactive)
1983   (notmuch-show-stash-mlarchive-link mla)
1984   (browse-url (current-kill 0 t)))
1985
1986 ;; Commands typically bound to buttons.
1987
1988 (defun notmuch-show-part-button-default (&optional button)
1989   (interactive)
1990   (let ((button (or button (button-at (point)))))
1991     (if (button-get button 'overlay)
1992         (notmuch-show-toggle-part-invisibility button)
1993       (notmuch-show-part-button-internal button notmuch-show-part-button-default-action))))
1994
1995 (defun notmuch-show-part-button-save (&optional button)
1996   (interactive)
1997   (notmuch-show-part-button-internal button #'notmuch-show-save-part))
1998
1999 (defun notmuch-show-part-button-view (&optional button)
2000   (interactive)
2001   (notmuch-show-part-button-internal button #'notmuch-show-view-part))
2002
2003 (defun notmuch-show-part-button-interactively-view (&optional button)
2004   (interactive)
2005   (notmuch-show-part-button-internal button #'notmuch-show-interactively-view-part))
2006
2007 (defun notmuch-show-part-button-pipe (&optional button)
2008   (interactive)
2009   (notmuch-show-part-button-internal button #'notmuch-show-pipe-part))
2010
2011 (defun notmuch-show-part-button-internal (button handler)
2012   (let ((button (or button (button-at (point)))))
2013     (if button
2014         (let ((nth (button-get button :notmuch-part)))
2015           (if nth
2016               (funcall handler (notmuch-show-get-message-id) nth
2017                        (button-get button :notmuch-filename)
2018                        (button-get button :notmuch-content-type)))))))
2019
2020 ;;
2021
2022 (provide 'notmuch-show)