]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-show.el
acaef8ef2afd3871b071e468025fec44ab9f124c
[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   :supertype 'notmuch-button-type)
474
475 (defvar notmuch-show-part-button-map
476   (let ((map (make-sparse-keymap)))
477     (set-keymap-parent map button-map)
478     (define-key map "s" 'notmuch-show-part-button-save)
479     (define-key map "v" 'notmuch-show-part-button-view)
480     (define-key map "o" 'notmuch-show-part-button-interactively-view)
481     (define-key map "|" 'notmuch-show-part-button-pipe)
482     map)
483   "Submap for button commands")
484 (fset 'notmuch-show-part-button-map notmuch-show-part-button-map)
485
486 (defun notmuch-show-insert-part-header (nth content-type declared-type &optional name comment)
487   (let ((button)
488         (base-label (concat (when name (concat name ": "))
489                             declared-type
490                             (unless (string-equal declared-type content-type)
491                               (concat " (as " content-type ")"))
492                             comment)))
493
494     (setq button
495           (insert-button
496            (concat "[ " base-label " ]")
497            :base-label base-label
498            :type 'notmuch-show-part-button-type
499            :notmuch-part nth
500            :notmuch-filename name
501            :notmuch-content-type content-type))
502     (insert "\n")
503     ;; return button
504     button))
505
506 ;; Functions handling particular MIME parts.
507
508 (defmacro notmuch-with-temp-part-buffer (message-id nth &rest body)
509   (declare (indent 2))
510   (let ((process-crypto (make-symbol "process-crypto")))
511     `(let ((,process-crypto notmuch-show-process-crypto))
512        (with-temp-buffer
513          (setq notmuch-show-process-crypto ,process-crypto)
514          ;; Always acquires the part via `notmuch part', even if it is
515          ;; available in the JSON output.
516          (insert (notmuch-get-bodypart-internal ,message-id ,nth notmuch-show-process-crypto))
517          ,@body))))
518
519 (defun notmuch-show-save-part (message-id nth &optional filename content-type)
520   (notmuch-with-temp-part-buffer message-id nth
521     (let ((file (read-file-name
522                  "Filename to save as: "
523                  (or mailcap-download-directory "~/")
524                  nil nil
525                  filename)))
526       ;; Don't re-compress .gz & al.  Arguably we should make
527       ;; `file-name-handler-alist' nil, but that would chop
528       ;; ange-ftp, which is reasonable to use here.
529       (mm-write-region (point-min) (point-max) file nil nil nil 'no-conversion t))))
530
531 (defun notmuch-show-view-part (message-id nth &optional filename content-type )
532   (notmuch-with-temp-part-buffer message-id nth
533     ;; set mm-inlined-types to nil to force an external viewer
534     (let ((handle (mm-make-handle (current-buffer) (list content-type)))
535           (mm-inlined-types nil))
536       ;; We override mm-save-part as notmuch-show-save-part is better
537       ;; since it offers the filename. We need to lexically bind
538       ;; everything we need for notmuch-show-save-part to prevent
539       ;; potential dynamic shadowing.
540       (lexical-let ((message-id message-id)
541                     (nth nth)
542                     (filename filename)
543                     (content-type content-type))
544         (flet ((mm-save-part (&rest args) (notmuch-show-save-part
545                                            message-id nth filename content-type)))
546           (mm-display-part handle))))))
547
548 (defun notmuch-show-interactively-view-part (message-id nth &optional filename content-type)
549   (notmuch-with-temp-part-buffer message-id nth
550     (let ((handle (mm-make-handle (current-buffer) (list content-type))))
551       (mm-interactively-view-part handle))))
552
553 (defun notmuch-show-pipe-part (message-id nth &optional filename content-type)
554   (notmuch-with-temp-part-buffer message-id nth
555     (let ((handle (mm-make-handle (current-buffer) (list content-type))))
556       (mm-pipe-part handle))))
557
558 ;; This is taken from notmuch-wash: maybe it should be unified?
559 (defun notmuch-show-toggle-part-invisibility (&optional button)
560   (interactive)
561   (let* ((button (or button (button-at (point))))
562          (overlay (button-get button 'overlay)))
563     (when overlay
564       (let* ((show (overlay-get overlay 'invisible))
565              (new-start (button-start button))
566              (button-label (button-get button :base-label))
567              (old-point (point))
568              (inhibit-read-only t))
569         (overlay-put overlay 'invisible (not show))
570         (goto-char new-start)
571         (insert "[ " button-label (if show " ]" " (hidden) ]"))
572         (let ((old-end (button-end button)))
573           (move-overlay button new-start (point))
574           (delete-region (point) old-end))
575         (goto-char (min old-point (1- (button-end button))))))))
576
577 (defun notmuch-show-multipart/*-to-list (part)
578   (mapcar (lambda (inner-part) (plist-get inner-part :content-type))
579           (plist-get part :content)))
580
581 (defun notmuch-show-insert-part-multipart/alternative (msg part content-type nth depth declared-type)
582   (notmuch-show-insert-part-header nth declared-type content-type nil)
583   (let ((chosen-type (car (notmuch-multipart/alternative-choose (notmuch-show-multipart/*-to-list part))))
584         (inner-parts (plist-get part :content))
585         (start (point)))
586     ;; This inserts all parts of the chosen type rather than just one,
587     ;; but it's not clear that this is the wrong thing to do - which
588     ;; should be chosen if there are more than one that match?
589     (mapc (lambda (inner-part)
590             (let* ((inner-type (plist-get inner-part :content-type))
591                   (hide (not (or notmuch-show-all-multipart/alternative-parts
592                            (string= chosen-type inner-type)))))
593               (notmuch-show-insert-bodypart msg inner-part depth hide)))
594           inner-parts)
595
596     (when notmuch-show-indent-multipart
597       (indent-rigidly start (point) 1)))
598   t)
599
600 (defun notmuch-show-setup-w3m ()
601   "Instruct w3m how to retrieve content from a \"related\" part of a message."
602   (interactive)
603   (if (boundp 'w3m-cid-retrieve-function-alist)
604     (unless (assq 'notmuch-show-mode w3m-cid-retrieve-function-alist)
605       (push (cons 'notmuch-show-mode 'notmuch-show-w3m-cid-retrieve)
606             w3m-cid-retrieve-function-alist)))
607   (setq mm-inline-text-html-with-images t))
608
609 (defvar w3m-current-buffer) ;; From `w3m.el'.
610 (defvar notmuch-show-w3m-cid-store nil)
611 (make-variable-buffer-local 'notmuch-show-w3m-cid-store)
612
613 (defun notmuch-show-w3m-cid-store-internal (content-id
614                                             message-id
615                                             part-number
616                                             content-type
617                                             content)
618   (push (list content-id
619               message-id
620               part-number
621               content-type
622               content)
623         notmuch-show-w3m-cid-store))
624
625 (defun notmuch-show-w3m-cid-store (msg part)
626   (let ((content-id (plist-get part :content-id)))
627     (when content-id
628       (notmuch-show-w3m-cid-store-internal (concat "cid:" content-id)
629                                            (plist-get msg :id)
630                                            (plist-get part :id)
631                                            (plist-get part :content-type)
632                                            nil))))
633
634 (defun notmuch-show-w3m-cid-retrieve (url &rest args)
635   (let ((matching-part (with-current-buffer w3m-current-buffer
636                          (assoc url notmuch-show-w3m-cid-store))))
637     (if matching-part
638         (let ((message-id (nth 1 matching-part))
639               (part-number (nth 2 matching-part))
640               (content-type (nth 3 matching-part))
641               (content (nth 4 matching-part)))
642           ;; If we don't already have the content, get it and cache
643           ;; it, as some messages reference the same cid: part many
644           ;; times (hundreds!), which results in many calls to
645           ;; `notmuch part'.
646           (unless content
647             (setq content (notmuch-get-bodypart-internal (notmuch-id-to-query message-id)
648                                                               part-number notmuch-show-process-crypto))
649             (with-current-buffer w3m-current-buffer
650               (notmuch-show-w3m-cid-store-internal url
651                                                    message-id
652                                                    part-number
653                                                    content-type
654                                                    content)))
655           (insert content)
656           content-type)
657       nil)))
658
659 (defun notmuch-show-insert-part-multipart/related (msg part content-type nth depth declared-type)
660   (notmuch-show-insert-part-header nth declared-type content-type nil)
661   (let ((inner-parts (plist-get part :content))
662         (start (point)))
663
664     ;; We assume that the first part is text/html and the remainder
665     ;; things that it references.
666
667     ;; Stash the non-primary parts.
668     (mapc (lambda (part)
669             (notmuch-show-w3m-cid-store msg part))
670           (cdr inner-parts))
671
672     ;; Render the primary part.
673     (notmuch-show-insert-bodypart msg (car inner-parts) depth)
674
675     (when notmuch-show-indent-multipart
676       (indent-rigidly start (point) 1)))
677   t)
678
679 (defun notmuch-show-insert-part-multipart/signed (msg part content-type nth depth declared-type)
680   (let ((button (notmuch-show-insert-part-header nth declared-type content-type nil)))
681     (button-put button 'face 'notmuch-crypto-part-header)
682     ;; add signature status button if sigstatus provided
683     (if (plist-member part :sigstatus)
684         (let* ((from (notmuch-show-get-header :From msg))
685                (sigstatus (car (plist-get part :sigstatus))))
686           (notmuch-crypto-insert-sigstatus-button sigstatus from))
687       ;; if we're not adding sigstatus, tell the user how they can get it
688       (button-put button 'help-echo "Set notmuch-crypto-process-mime to process cryptographic MIME parts.")))
689
690   (let ((inner-parts (plist-get part :content))
691         (start (point)))
692     ;; Show all of the parts.
693     (mapc (lambda (inner-part)
694             (notmuch-show-insert-bodypart msg inner-part depth))
695           inner-parts)
696
697     (when notmuch-show-indent-multipart
698       (indent-rigidly start (point) 1)))
699   t)
700
701 (defun notmuch-show-insert-part-multipart/encrypted (msg part content-type nth depth declared-type)
702   (let ((button (notmuch-show-insert-part-header nth declared-type content-type nil)))
703     (button-put button 'face 'notmuch-crypto-part-header)
704     ;; add encryption status button if encstatus specified
705     (if (plist-member part :encstatus)
706         (let ((encstatus (car (plist-get part :encstatus))))
707           (notmuch-crypto-insert-encstatus-button encstatus)
708           ;; add signature status button if sigstatus specified
709           (if (plist-member part :sigstatus)
710               (let* ((from (notmuch-show-get-header :From msg))
711                      (sigstatus (car (plist-get part :sigstatus))))
712                 (notmuch-crypto-insert-sigstatus-button sigstatus from))))
713       ;; if we're not adding encstatus, tell the user how they can get it
714       (button-put button 'help-echo "Set notmuch-crypto-process-mime to process cryptographic MIME parts.")))
715
716   (let ((inner-parts (plist-get part :content))
717         (start (point)))
718     ;; Show all of the parts.
719     (mapc (lambda (inner-part)
720             (notmuch-show-insert-bodypart msg inner-part depth))
721           inner-parts)
722
723     (when notmuch-show-indent-multipart
724       (indent-rigidly start (point) 1)))
725   t)
726
727 (defun notmuch-show-insert-part-multipart/* (msg part content-type nth depth declared-type)
728   (notmuch-show-insert-part-header nth declared-type content-type nil)
729   (let ((inner-parts (plist-get part :content))
730         (start (point)))
731     ;; Show all of the parts.
732     (mapc (lambda (inner-part)
733             (notmuch-show-insert-bodypart msg inner-part depth))
734           inner-parts)
735
736     (when notmuch-show-indent-multipart
737       (indent-rigidly start (point) 1)))
738   t)
739
740 (defun notmuch-show-insert-part-message/rfc822 (msg part content-type nth depth declared-type)
741   (notmuch-show-insert-part-header nth declared-type content-type nil)
742   (let* ((message (car (plist-get part :content)))
743          (body (car (plist-get message :body)))
744          (start (point)))
745
746     ;; Override `notmuch-message-headers' to force `From' to be
747     ;; displayed.
748     (let ((notmuch-message-headers '("From" "Subject" "To" "Cc" "Date")))
749       (notmuch-show-insert-headers (plist-get message :headers)))
750
751     ;; Blank line after headers to be compatible with the normal
752     ;; message display.
753     (insert "\n")
754
755     ;; Show the body
756     (notmuch-show-insert-bodypart msg body depth)
757
758     (when notmuch-show-indent-multipart
759       (indent-rigidly start (point) 1)))
760   t)
761
762 (defun notmuch-show-insert-part-text/plain (msg part content-type nth depth declared-type)
763   (let ((start (point)))
764     ;; If this text/plain part is not the first part in the message,
765     ;; insert a header to make this clear.
766     (if (> nth 1)
767         (notmuch-show-insert-part-header nth declared-type content-type (plist-get part :filename)))
768     (insert (notmuch-get-bodypart-content msg part nth notmuch-show-process-crypto))
769     (save-excursion
770       (save-restriction
771         (narrow-to-region start (point-max))
772         (run-hook-with-args 'notmuch-show-insert-text/plain-hook msg depth))))
773   t)
774
775 (defun notmuch-show-insert-part-text/calendar (msg part content-type nth depth declared-type)
776   (notmuch-show-insert-part-header nth declared-type content-type (plist-get part :filename))
777   (insert (with-temp-buffer
778             (insert (notmuch-get-bodypart-content msg part nth notmuch-show-process-crypto))
779             ;; notmuch-get-bodypart-content provides "raw", non-converted
780             ;; data. Replace CRLF with LF before icalendar can use it.
781             (goto-char (point-min))
782             (while (re-search-forward "\r\n" nil t)
783               (replace-match "\n" nil nil))
784             (let ((file (make-temp-file "notmuch-ical"))
785                   result)
786               (unwind-protect
787                   (progn
788                     (unless (icalendar-import-buffer file t)
789                       (error "Icalendar import error. See *icalendar-errors* for more information"))
790                     (set-buffer (get-file-buffer file))
791                     (setq result (buffer-substring (point-min) (point-max)))
792                     (set-buffer-modified-p nil)
793                     (kill-buffer (current-buffer)))
794                 (delete-file file))
795               result)))
796   t)
797
798 ;; For backwards compatibility.
799 (defun notmuch-show-insert-part-text/x-vcalendar (msg part content-type nth depth declared-type)
800   (notmuch-show-insert-part-text/calendar msg part content-type nth depth declared-type))
801
802 (defun notmuch-show-insert-part-application/octet-stream (msg part content-type nth depth declared-type)
803   ;; If we can deduce a MIME type from the filename of the attachment,
804   ;; do so and pass it on to the handler for that type.
805   (if (plist-get part :filename)
806       (let ((extension (file-name-extension (plist-get part :filename)))
807             mime-type)
808         (if extension
809             (progn
810               (mailcap-parse-mimetypes)
811               (setq mime-type (mailcap-extension-to-mime extension))
812               (if (and mime-type
813                        (not (string-equal mime-type "application/octet-stream")))
814                   (notmuch-show-insert-bodypart-internal msg part mime-type nth depth content-type)
815                 nil))
816           nil))))
817
818 ;; Handler for wash generated inline patch fake parts.
819 (defun notmuch-show-insert-part-inline-patch-fake-part (msg part content-type nth depth declared-type)
820   (notmuch-show-insert-part-*/* msg part "text/x-diff" nth depth "inline patch"))
821
822 (defun notmuch-show-insert-part-text/html (msg part content-type nth depth declared-type)
823   ;; text/html handler to work around bugs in renderers and our
824   ;; invisibile parts code. In particular w3m sets up a keymap which
825   ;; "leaks" outside the invisible region and causes strange effects
826   ;; in notmuch. We set mm-inline-text-html-with-w3m-keymap to nil to
827   ;; tell w3m not to set a keymap (so the normal notmuch-show-mode-map
828   ;; remains).
829   (let ((mm-inline-text-html-with-w3m-keymap nil))
830     (notmuch-show-insert-part-*/* msg part content-type nth depth declared-type)))
831
832 (defun notmuch-show-insert-part-*/* (msg part content-type nth depth declared-type)
833   ;; This handler _must_ succeed - it is the handler of last resort.
834   (notmuch-show-insert-part-header nth content-type declared-type (plist-get part :filename))
835   (notmuch-mm-display-part-inline msg part nth content-type notmuch-show-process-crypto)
836   t)
837
838 ;; Functions for determining how to handle MIME parts.
839
840 (defun notmuch-show-handlers-for (content-type)
841   "Return a list of content handlers for a part of type CONTENT-TYPE."
842   (let (result)
843     (mapc (lambda (func)
844             (if (functionp func)
845                 (push func result)))
846           ;; Reverse order of prefrence.
847           (list (intern (concat "notmuch-show-insert-part-*/*"))
848                 (intern (concat
849                          "notmuch-show-insert-part-"
850                          (car (notmuch-split-content-type content-type))
851                          "/*"))
852                 (intern (concat "notmuch-show-insert-part-" content-type))))
853     result))
854
855 ;; \f
856
857 (defun notmuch-show-insert-bodypart-internal (msg part content-type nth depth declared-type)
858   (let ((handlers (notmuch-show-handlers-for content-type)))
859     ;; Run the content handlers until one of them returns a non-nil
860     ;; value.
861     (while (and handlers
862                 (not (condition-case err
863                          (funcall (car handlers) msg part content-type nth depth declared-type)
864                        (error (progn
865                                 (insert "!!! Bodypart insert error: ")
866                                 (insert (error-message-string err))
867                                 (insert " !!!\n") nil)))))
868       (setq handlers (cdr handlers))))
869   t)
870
871 (defun notmuch-show-create-part-overlays (msg beg end hide)
872   "Add an overlay to the part between BEG and END"
873   (let* ((button (button-at beg))
874          (part-beg (and button (1+ (button-end button)))))
875
876     ;; If the part contains no text we do not make it toggleable. We
877     ;; also need to check that the button is a genuine part button not
878     ;; a notmuch-wash button.
879     (when (and button (/= part-beg end) (button-get button :base-label))
880       (button-put button 'overlay (make-overlay part-beg end))
881       ;; We toggle the button for hidden parts as that gets the
882       ;; button label right.
883       (save-excursion
884         (when hide
885           (notmuch-show-toggle-part-invisibility button))))))
886
887 (defun notmuch-show-insert-bodypart (msg part depth &optional hide)
888   "Insert the body part PART at depth DEPTH in the current thread.
889
890 If HIDE is non-nil then initially hide this part."
891   (let ((content-type (downcase (plist-get part :content-type)))
892         (nth (plist-get part :id))
893         (beg (point)))
894
895     (notmuch-show-insert-bodypart-internal msg part content-type nth depth content-type)
896     ;; Some of the body part handlers leave point somewhere up in the
897     ;; part, so we make sure that we're down at the end.
898     (goto-char (point-max))
899     ;; Ensure that the part ends with a carriage return.
900     (unless (bolp)
901       (insert "\n"))
902     (notmuch-show-create-part-overlays msg beg (point) hide)))
903
904 (defun notmuch-show-insert-body (msg body depth)
905   "Insert the body BODY at depth DEPTH in the current thread."
906   (mapc (lambda (part) (notmuch-show-insert-bodypart msg part depth)) body))
907
908 (defun notmuch-show-make-symbol (type)
909   (make-symbol (concat "notmuch-show-" type)))
910
911 (defun notmuch-show-strip-re (string)
912   (replace-regexp-in-string "^\\([Rr]e: *\\)+" "" string))
913
914 (defvar notmuch-show-previous-subject "")
915 (make-variable-buffer-local 'notmuch-show-previous-subject)
916
917 (defun notmuch-show-insert-msg (msg depth)
918   "Insert the message MSG at depth DEPTH in the current thread."
919   (let* ((headers (plist-get msg :headers))
920          ;; Indentation causes the buffer offset of the start/end
921          ;; points to move, so we must use markers.
922          message-start message-end
923          content-start content-end
924          headers-start headers-end
925          (bare-subject (notmuch-show-strip-re (plist-get headers :Subject))))
926
927     (setq message-start (point-marker))
928
929     (notmuch-show-insert-headerline headers
930                                     (or (if notmuch-show-relative-dates
931                                             (plist-get msg :date_relative)
932                                           nil)
933                                         (plist-get headers :Date))
934                                     (plist-get msg :tags) depth)
935
936     (setq content-start (point-marker))
937
938     ;; Set `headers-start' to point after the 'Subject:' header to be
939     ;; compatible with the existing implementation. This just sets it
940     ;; to after the first header.
941     (notmuch-show-insert-headers headers)
942     (save-excursion
943       (goto-char content-start)
944       ;; If the subject of this message is the same as that of the
945       ;; previous message, don't display it when this message is
946       ;; collapsed.
947       (when (not (string= notmuch-show-previous-subject
948                           bare-subject))
949         (forward-line 1))
950       (setq headers-start (point-marker)))
951     (setq headers-end (point-marker))
952
953     (setq notmuch-show-previous-subject bare-subject)
954
955     ;; A blank line between the headers and the body.
956     (insert "\n")
957     (notmuch-show-insert-body msg (plist-get msg :body)
958                               (if notmuch-show-indent-content depth 0))
959     ;; Ensure that the body ends with a newline.
960     (unless (bolp)
961       (insert "\n"))
962     (setq content-end (point-marker))
963
964     ;; Indent according to the depth in the thread.
965     (if notmuch-show-indent-content
966         (indent-rigidly content-start content-end (* notmuch-show-indent-messages-width depth)))
967
968     (setq message-end (point-max-marker))
969
970     ;; Save the extents of this message over the whole text of the
971     ;; message.
972     (put-text-property message-start message-end :notmuch-message-extent (cons message-start message-end))
973
974     ;; Create overlays used to control visibility
975     (plist-put msg :headers-overlay (make-overlay headers-start headers-end))
976     (plist-put msg :message-overlay (make-overlay headers-start content-end))
977
978     (plist-put msg :depth depth)
979
980     ;; Save the properties for this message. Currently this saves the
981     ;; entire message (augmented it with other stuff), which seems
982     ;; like overkill. We might save a reduced subset (for example, not
983     ;; the content).
984     (notmuch-show-set-message-properties msg)
985
986     ;; Set header visibility.
987     (notmuch-show-headers-visible msg notmuch-message-headers-visible)
988
989     ;; Message visibility depends on whether it matched the search
990     ;; criteria.
991     (notmuch-show-message-visible msg (and (plist-get msg :match)
992                                            (not (plist-get msg :excluded))))))
993
994 (defun notmuch-show-toggle-process-crypto ()
995   "Toggle the processing of cryptographic MIME parts."
996   (interactive)
997   (setq notmuch-show-process-crypto (not notmuch-show-process-crypto))
998   (message (if notmuch-show-process-crypto
999                "Processing cryptographic MIME parts."
1000              "Not processing cryptographic MIME parts."))
1001   (notmuch-show-refresh-view))
1002
1003 (defun notmuch-show-toggle-elide-non-matching ()
1004   "Toggle the display of non-matching messages."
1005   (interactive)
1006   (setq notmuch-show-elide-non-matching-messages (not notmuch-show-elide-non-matching-messages))
1007   (message (if notmuch-show-elide-non-matching-messages
1008                "Showing matching messages only."
1009              "Showing all messages."))
1010   (notmuch-show-refresh-view))
1011
1012 (defun notmuch-show-toggle-thread-indentation ()
1013   "Toggle the indentation of threads."
1014   (interactive)
1015   (setq notmuch-show-indent-content (not notmuch-show-indent-content))
1016   (message (if notmuch-show-indent-content
1017                "Content is indented."
1018              "Content is not indented."))
1019   (notmuch-show-refresh-view))
1020
1021 (defun notmuch-show-insert-tree (tree depth)
1022   "Insert the message tree TREE at depth DEPTH in the current thread."
1023   (let ((msg (car tree))
1024         (replies (cadr tree)))
1025     ;; We test whether there is a message or just some replies.
1026     (when msg
1027       (notmuch-show-insert-msg msg depth))
1028     (notmuch-show-insert-thread replies (1+ depth))))
1029
1030 (defun notmuch-show-insert-thread (thread depth)
1031   "Insert the thread THREAD at depth DEPTH in the current forest."
1032   (mapc (lambda (tree) (notmuch-show-insert-tree tree depth)) thread))
1033
1034 (defun notmuch-show-insert-forest (forest)
1035   "Insert the forest of threads FOREST."
1036   (mapc (lambda (thread) (notmuch-show-insert-thread thread 0)) forest))
1037
1038 (defvar notmuch-id-regexp
1039   (concat
1040    ;; Match the id: prefix only if it begins a word (to disallow, for
1041    ;; example, matching cid:).
1042    "\\<id:\\("
1043    ;; If the term starts with a ", then parse Xapian's quoted boolean
1044    ;; term syntax, which allows for anything as long as embedded
1045    ;; double quotes escaped by doubling them.  We also disallow
1046    ;; newlines (which Xapian allows) to prevent runaway terms.
1047    "\"\\([^\"\n]\\|\"\"\\)*\""
1048    ;; Otherwise, parse Xapian's unquoted syntax, which goes up to the
1049    ;; next space or ).  We disallow [.,;] as the last character
1050    ;; because these are probably part of the surrounding text, and not
1051    ;; part of the id.  This doesn't match single character ids; meh.
1052    "\\|[^\"[:space:])][^[:space:])]*[^])[:space:].,:;?!]"
1053    "\\)")
1054   "The regexp used to match id: links in messages.")
1055
1056 (defvar notmuch-mid-regexp
1057   ;; goto-address-url-regexp matched cid: links, which have the same
1058   ;; grammar as the message ID part of a mid: link.  Construct the
1059   ;; regexp using the same technique as goto-address-url-regexp.
1060   (concat "\\<mid:\\(" thing-at-point-url-path-regexp "\\)")
1061   "The regexp used to match mid: links in messages.
1062
1063 See RFC 2392.")
1064
1065 (defun notmuch-show-buttonise-links (start end)
1066   "Buttonise URLs and mail addresses between START and END.
1067
1068 This also turns id:\"<message id>\"-parts and mid: links into
1069 buttons for a corresponding notmuch search."
1070   (goto-address-fontify-region start end)
1071   (save-excursion
1072     (let (links)
1073       (goto-char start)
1074       (while (re-search-forward notmuch-id-regexp end t)
1075         (push (list (match-beginning 0) (match-end 0)
1076                     (match-string-no-properties 0)) links))
1077       (goto-char start)
1078       (while (re-search-forward notmuch-mid-regexp end t)
1079         (let* ((mid-cid (match-string-no-properties 1))
1080                (mid (save-match-data
1081                       (string-match "^[^/]*" mid-cid)
1082                       (url-unhex-string (match-string 0 mid-cid)))))
1083           (push (list (match-beginning 0) (match-end 0)
1084                       (notmuch-id-to-query mid)) links)))
1085       (dolist (link links)
1086         ;; Remove the overlay created by goto-address-mode
1087         (remove-overlays (first link) (second link) 'goto-address t)
1088         (make-text-button (first link) (second link)
1089                           :type 'notmuch-button-type
1090                           'action `(lambda (arg)
1091                                      (notmuch-show ,(third link)))
1092                           'follow-link t
1093                           'help-echo "Mouse-1, RET: search for this message"
1094                           'face goto-address-mail-face)))))
1095
1096 ;;;###autoload
1097 (defun notmuch-show (thread-id &optional parent-buffer query-context buffer-name)
1098   "Run \"notmuch show\" with the given thread ID and display results.
1099
1100 The optional PARENT-BUFFER is the notmuch-search buffer from
1101 which this notmuch-show command was executed, (so that the
1102 next thread from that buffer can be show when done with this
1103 one).
1104
1105 The optional QUERY-CONTEXT is a notmuch search term. Only
1106 messages from the thread matching this search term are shown if
1107 non-nil.
1108
1109 The optional BUFFER-NAME provides the name of the buffer in
1110 which the message thread is shown. If it is nil (which occurs
1111 when the command is called interactively) the argument to the
1112 function is used."
1113   (interactive "sNotmuch show: ")
1114   (let ((buffer-name (generate-new-buffer-name
1115                       (or buffer-name
1116                           (concat "*notmuch-" thread-id "*")))))
1117     (switch-to-buffer (get-buffer-create buffer-name))
1118     ;; Set the default value for `notmuch-show-process-crypto' in this
1119     ;; buffer.
1120     (setq notmuch-show-process-crypto notmuch-crypto-process-mime)
1121     ;; Set the default value for
1122     ;; `notmuch-show-elide-non-matching-messages' in this buffer. If
1123     ;; there is a prefix argument, invert the default.
1124     (setq notmuch-show-elide-non-matching-messages notmuch-show-only-matching-messages)
1125     (if current-prefix-arg
1126         (setq notmuch-show-elide-non-matching-messages (not notmuch-show-elide-non-matching-messages)))
1127
1128     (setq notmuch-show-thread-id thread-id
1129           notmuch-show-parent-buffer parent-buffer
1130           notmuch-show-query-context query-context)
1131     (notmuch-show-build-buffer)
1132     (notmuch-show-goto-first-wanted-message)
1133     (current-buffer)))
1134
1135 (defun notmuch-show-build-buffer ()
1136   (let ((inhibit-read-only t))
1137
1138     (notmuch-show-mode)
1139     ;; Don't track undo information for this buffer
1140     (set 'buffer-undo-list t)
1141
1142     (erase-buffer)
1143     (goto-char (point-min))
1144     (save-excursion
1145       (let* ((basic-args (list notmuch-show-thread-id))
1146              (args (if notmuch-show-query-context
1147                        (append (list "\'") basic-args
1148                                (list "and (" notmuch-show-query-context ")\'"))
1149                      (append (list "\'") basic-args (list "\'"))))
1150              (cli-args (cons "--exclude=false"
1151                              (when notmuch-show-elide-non-matching-messages
1152                                (list "--entire-thread=false")))))
1153
1154         (notmuch-show-insert-forest (notmuch-query-get-threads (append cli-args args)))
1155         ;; If the query context reduced the results to nothing, run
1156         ;; the basic query.
1157         (when (and (eq (buffer-size) 0)
1158                    notmuch-show-query-context)
1159           (notmuch-show-insert-forest
1160            (notmuch-query-get-threads (append cli-args basic-args)))))
1161
1162       (jit-lock-register #'notmuch-show-buttonise-links)
1163
1164       ;; Set the header line to the subject of the first message.
1165       (setq header-line-format (notmuch-show-strip-re (notmuch-show-get-subject)))
1166
1167       (run-hooks 'notmuch-show-hook))))
1168
1169 (defun notmuch-show-capture-state ()
1170   "Capture the state of the current buffer.
1171
1172 This includes:
1173  - the list of open messages,
1174  - the current message."
1175   (list (notmuch-show-get-message-id) (notmuch-show-get-message-ids-for-open-messages)))
1176
1177 (defun notmuch-show-apply-state (state)
1178   "Apply STATE to the current buffer.
1179
1180 This includes:
1181  - opening the messages previously opened,
1182  - closing all other messages,
1183  - moving to the correct current message."
1184   (let ((current (car state))
1185         (open (cadr state)))
1186
1187     ;; Open those that were open.
1188     (goto-char (point-min))
1189     (loop do (notmuch-show-message-visible (notmuch-show-get-message-properties)
1190                                            (member (notmuch-show-get-message-id) open))
1191           until (not (notmuch-show-goto-message-next)))
1192
1193     ;; Go to the previously open message.
1194     (goto-char (point-min))
1195     (unless (loop if (string= current (notmuch-show-get-message-id))
1196                   return t
1197                   until (not (notmuch-show-goto-message-next)))
1198       (goto-char (point-min))
1199       (message "Previously current message not found."))
1200     (notmuch-show-message-adjust)))
1201
1202 (defun notmuch-show-refresh-view (&optional reset-state)
1203   "Refresh the current view.
1204
1205 Refreshes the current view, observing changes in display
1206 preferences. If invoked with a prefix argument (or RESET-STATE is
1207 non-nil) then the state of the buffer (open/closed messages) is
1208 reset based on the original query."
1209   (interactive "P")
1210   (let ((inhibit-read-only t)
1211         (state (unless reset-state
1212                  (notmuch-show-capture-state))))
1213     ;; erase-buffer does not seem to remove overlays, which can lead
1214     ;; to weird effects such as remaining images, so remove them
1215     ;; manually.
1216     (remove-overlays)
1217     (erase-buffer)
1218     (notmuch-show-build-buffer)
1219     (if state
1220         (notmuch-show-apply-state state)
1221       ;; We're resetting state, so navigate to the first open message
1222       ;; and mark it read, just like opening a new show buffer.
1223       (notmuch-show-goto-first-wanted-message))))
1224
1225 (defvar notmuch-show-stash-map
1226   (let ((map (make-sparse-keymap)))
1227     (define-key map "c" 'notmuch-show-stash-cc)
1228     (define-key map "d" 'notmuch-show-stash-date)
1229     (define-key map "F" 'notmuch-show-stash-filename)
1230     (define-key map "f" 'notmuch-show-stash-from)
1231     (define-key map "i" 'notmuch-show-stash-message-id)
1232     (define-key map "I" 'notmuch-show-stash-message-id-stripped)
1233     (define-key map "s" 'notmuch-show-stash-subject)
1234     (define-key map "T" 'notmuch-show-stash-tags)
1235     (define-key map "t" 'notmuch-show-stash-to)
1236     (define-key map "l" 'notmuch-show-stash-mlarchive-link)
1237     (define-key map "L" 'notmuch-show-stash-mlarchive-link-and-go)
1238     map)
1239   "Submap for stash commands")
1240 (fset 'notmuch-show-stash-map notmuch-show-stash-map)
1241
1242 (defvar notmuch-show-mode-map
1243       (let ((map (make-sparse-keymap)))
1244         (define-key map "?" 'notmuch-help)
1245         (define-key map "q" 'notmuch-kill-this-buffer)
1246         (define-key map (kbd "<C-tab>") 'widget-backward)
1247         (define-key map (kbd "M-TAB") 'notmuch-show-previous-button)
1248         (define-key map (kbd "<backtab>") 'notmuch-show-previous-button)
1249         (define-key map (kbd "TAB") 'notmuch-show-next-button)
1250         (define-key map "s" 'notmuch-search)
1251         (define-key map "m" 'notmuch-mua-new-mail)
1252         (define-key map "f" 'notmuch-show-forward-message)
1253         (define-key map "r" 'notmuch-show-reply-sender)
1254         (define-key map "R" 'notmuch-show-reply)
1255         (define-key map "|" 'notmuch-show-pipe-message)
1256         (define-key map "w" 'notmuch-show-save-attachments)
1257         (define-key map "V" 'notmuch-show-view-raw-message)
1258         (define-key map "v" 'notmuch-show-view-all-mime-parts)
1259         (define-key map "c" 'notmuch-show-stash-map)
1260         (define-key map "=" 'notmuch-show-refresh-view)
1261         (define-key map "h" 'notmuch-show-toggle-visibility-headers)
1262         (define-key map "*" 'notmuch-show-tag-all)
1263         (define-key map "-" 'notmuch-show-remove-tag)
1264         (define-key map "+" 'notmuch-show-add-tag)
1265         (define-key map "X" 'notmuch-show-archive-thread-then-exit)
1266         (define-key map "x" 'notmuch-show-archive-message-then-next-or-exit)
1267         (define-key map "A" 'notmuch-show-archive-thread-then-next)
1268         (define-key map "a" 'notmuch-show-archive-message-then-next-or-next-thread)
1269         (define-key map "N" 'notmuch-show-next-message)
1270         (define-key map "P" 'notmuch-show-previous-message)
1271         (define-key map "n" 'notmuch-show-next-open-message)
1272         (define-key map "p" 'notmuch-show-previous-open-message)
1273         (define-key map (kbd "DEL") 'notmuch-show-rewind)
1274         (define-key map " " 'notmuch-show-advance-and-archive)
1275         (define-key map (kbd "M-RET") 'notmuch-show-open-or-close-all)
1276         (define-key map (kbd "RET") 'notmuch-show-toggle-message)
1277         (define-key map "#" 'notmuch-show-print-message)
1278         (define-key map "!" 'notmuch-show-toggle-elide-non-matching)
1279         (define-key map "$" 'notmuch-show-toggle-process-crypto)
1280         (define-key map "<" 'notmuch-show-toggle-thread-indentation)
1281         (define-key map "t" 'toggle-truncate-lines)
1282         map)
1283       "Keymap for \"notmuch show\" buffers.")
1284 (fset 'notmuch-show-mode-map notmuch-show-mode-map)
1285
1286 (defun notmuch-show-mode ()
1287   "Major mode for viewing a thread with notmuch.
1288
1289 This buffer contains the results of the \"notmuch show\" command
1290 for displaying a single thread of email from your email archives.
1291
1292 By default, various components of email messages, (citations,
1293 signatures, already-read messages), are hidden. You can make
1294 these parts visible by clicking with the mouse button or by
1295 pressing RET after positioning the cursor on a hidden part, (for
1296 which \\[notmuch-show-next-button] and \\[notmuch-show-previous-button] are helpful).
1297
1298 Reading the thread sequentially is well-supported by pressing
1299 \\[notmuch-show-advance-and-archive]. This will scroll the current message (if necessary), advance
1300 to the next message, or advance to the next thread (if already on
1301 the last message of a thread).
1302
1303 Other commands are available to read or manipulate the thread
1304 more selectively, (such as '\\[notmuch-show-next-message]' and '\\[notmuch-show-previous-message]' to advance to messages
1305 without removing any tags, and '\\[notmuch-show-archive-thread]' to archive an entire thread
1306 without scrolling through with \\[notmuch-show-advance-and-archive]).
1307
1308 You can add or remove arbitrary tags from the current message with
1309 '\\[notmuch-show-add-tag]' or '\\[notmuch-show-remove-tag]'.
1310
1311 All currently available key bindings:
1312
1313 \\{notmuch-show-mode-map}"
1314   (interactive)
1315   (kill-all-local-variables)
1316   (use-local-map notmuch-show-mode-map)
1317   (setq major-mode 'notmuch-show-mode
1318         mode-name "notmuch-show")
1319   (setq buffer-read-only t
1320         truncate-lines t))
1321
1322 (defun notmuch-show-move-to-message-top ()
1323   (goto-char (notmuch-show-message-top)))
1324
1325 (defun notmuch-show-move-to-message-bottom ()
1326   (goto-char (notmuch-show-message-bottom)))
1327
1328 (defun notmuch-show-message-adjust ()
1329   (recenter 0))
1330
1331 ;; Movement related functions.
1332
1333 ;; There's some strangeness here where a text property applied to a
1334 ;; region a->b is not found when point is at b. We walk backwards
1335 ;; until finding the property.
1336 (defun notmuch-show-message-extent ()
1337   (let (r)
1338     (save-excursion
1339       (while (not (setq r (get-text-property (point) :notmuch-message-extent)))
1340         (backward-char)))
1341     r))
1342
1343 (defun notmuch-show-message-top ()
1344   (car (notmuch-show-message-extent)))
1345
1346 (defun notmuch-show-message-bottom ()
1347   (cdr (notmuch-show-message-extent)))
1348
1349 (defun notmuch-show-goto-message-next ()
1350   (let ((start (point)))
1351     (notmuch-show-move-to-message-bottom)
1352     (if (not (eobp))
1353         t
1354       (goto-char start)
1355       nil)))
1356
1357 (defun notmuch-show-goto-message-previous ()
1358   (notmuch-show-move-to-message-top)
1359   (if (bobp)
1360       nil
1361     (backward-char)
1362     (notmuch-show-move-to-message-top)
1363     t))
1364
1365 (defun notmuch-show-mapc (function)
1366   "Iterate through all messages in the current thread with
1367 `notmuch-show-goto-message-next' and call FUNCTION for side
1368 effects."
1369   (save-excursion
1370     (goto-char (point-min))
1371     (loop do (funcall function)
1372           while (notmuch-show-goto-message-next))))
1373
1374 ;; Functions relating to the visibility of messages and their
1375 ;; components.
1376
1377 (defun notmuch-show-message-visible (props visible-p)
1378   (overlay-put (plist-get props :message-overlay) 'invisible (not visible-p))
1379   (notmuch-show-set-prop :message-visible visible-p props))
1380
1381 (defun notmuch-show-headers-visible (props visible-p)
1382   (overlay-put (plist-get props :headers-overlay) 'invisible (not visible-p))
1383   (notmuch-show-set-prop :headers-visible visible-p props))
1384
1385 ;; Functions for setting and getting attributes of the current
1386 ;; message.
1387
1388 (defun notmuch-show-set-message-properties (props)
1389   (save-excursion
1390     (notmuch-show-move-to-message-top)
1391     (put-text-property (point) (+ (point) 1) :notmuch-message-properties props)))
1392
1393 (defun notmuch-show-get-message-properties ()
1394   "Return the properties of the current message as a plist.
1395
1396 Some useful entries are:
1397 :headers - Property list containing the headers :Date, :Subject, :From, etc.
1398 :body - Body of the message
1399 :tags - Tags for this message"
1400   (save-excursion
1401     (notmuch-show-move-to-message-top)
1402     (get-text-property (point) :notmuch-message-properties)))
1403
1404 (defun notmuch-show-set-prop (prop val &optional props)
1405   (let ((inhibit-read-only t)
1406         (props (or props
1407                    (notmuch-show-get-message-properties))))
1408     (plist-put props prop val)
1409     (notmuch-show-set-message-properties props)))
1410
1411 (defun notmuch-show-get-prop (prop &optional props)
1412   (let ((props (or props
1413                    (notmuch-show-get-message-properties))))
1414     (plist-get props prop)))
1415
1416 (defun notmuch-show-get-message-id (&optional bare)
1417   "Return an id: query for the Message-Id of the current message.
1418
1419 If optional argument BARE is non-nil, return
1420 the Message-Id without id: prefix and escaping."
1421   (if bare
1422       (notmuch-show-get-prop :id)
1423     (notmuch-id-to-query (notmuch-show-get-prop :id))))
1424
1425 (defun notmuch-show-get-messages-ids ()
1426   "Return all id: queries of messages in the current thread."
1427   (let ((message-ids))
1428     (notmuch-show-mapc
1429      (lambda () (push (notmuch-show-get-message-id) message-ids)))
1430     message-ids))
1431
1432 (defun notmuch-show-get-messages-ids-search ()
1433   "Return a search string for all message ids of messages in the
1434 current thread."
1435   (mapconcat 'identity (notmuch-show-get-messages-ids) " or "))
1436
1437 ;; dme: Would it make sense to use a macro for many of these?
1438
1439 (defun notmuch-show-get-filename ()
1440   "Return the filename of the current message."
1441   (notmuch-show-get-prop :filename))
1442
1443 (defun notmuch-show-get-header (header &optional props)
1444   "Return the named header of the current message, if any."
1445   (plist-get (notmuch-show-get-prop :headers props) header))
1446
1447 (defun notmuch-show-get-cc ()
1448   (notmuch-show-get-header :Cc))
1449
1450 (defun notmuch-show-get-date ()
1451   (notmuch-show-get-header :Date))
1452
1453 (defun notmuch-show-get-from ()
1454   (notmuch-show-get-header :From))
1455
1456 (defun notmuch-show-get-subject ()
1457   (notmuch-show-get-header :Subject))
1458
1459 (defun notmuch-show-get-to ()
1460   (notmuch-show-get-header :To))
1461
1462 (defun notmuch-show-get-depth ()
1463   (notmuch-show-get-prop :depth))
1464
1465 (defun notmuch-show-set-tags (tags)
1466   "Set the tags of the current message."
1467   (notmuch-show-set-prop :tags tags)
1468   (notmuch-show-update-tags tags))
1469
1470 (defun notmuch-show-get-tags ()
1471   "Return the tags of the current message."
1472   (notmuch-show-get-prop :tags))
1473
1474 (defun notmuch-show-message-visible-p ()
1475   "Is the current message visible?"
1476   (notmuch-show-get-prop :message-visible))
1477
1478 (defun notmuch-show-headers-visible-p ()
1479   "Are the headers of the current message visible?"
1480   (notmuch-show-get-prop :headers-visible))
1481
1482 (defun notmuch-show-mark-read (&optional unread)
1483   "Mark the current message as read.
1484
1485 Mark the current message as read by applying the tag changes in
1486 `notmuch-show-mark-read-tags' to it (remove the \"unread\" tag by
1487 default). If a prefix argument is given, the message will be
1488 marked as unread, i.e. the tag changes in
1489 `notmuch-show-mark-read-tags' will be reversed."
1490   (interactive "P")
1491   (when notmuch-show-mark-read-tags
1492     (apply 'notmuch-show-tag-message
1493            (notmuch-tag-change-list notmuch-show-mark-read-tags unread))))
1494
1495 ;; Functions for getting attributes of several messages in the current
1496 ;; thread.
1497
1498 (defun notmuch-show-get-message-ids-for-open-messages ()
1499   "Return a list of all id: queries for open messages in the current thread."
1500   (save-excursion
1501     (let (message-ids done)
1502       (goto-char (point-min))
1503       (while (not done)
1504         (if (notmuch-show-message-visible-p)
1505             (setq message-ids (append message-ids (list (notmuch-show-get-message-id)))))
1506         (setq done (not (notmuch-show-goto-message-next)))
1507         )
1508       message-ids
1509       )))
1510
1511 ;; Commands typically bound to keys.
1512
1513 (defun notmuch-show-advance ()
1514   "Advance through thread.
1515
1516 If the current message in the thread is not yet fully visible,
1517 scroll by a near screenful to read more of the message.
1518
1519 Otherwise, (the end of the current message is already within the
1520 current window), advance to the next open message."
1521   (interactive)
1522   (let* ((end-of-this-message (notmuch-show-message-bottom))
1523          (visible-end-of-this-message (1- end-of-this-message))
1524          (ret nil))
1525     (while (invisible-p visible-end-of-this-message)
1526       (setq visible-end-of-this-message
1527             (max (point-min)
1528                  (1- (previous-single-char-property-change
1529                       visible-end-of-this-message 'invisible)))))
1530     (cond
1531      ;; Ideally we would test `end-of-this-message' against the result
1532      ;; of `window-end', but that doesn't account for the fact that
1533      ;; the end of the message might be hidden.
1534      ((and visible-end-of-this-message
1535            (> visible-end-of-this-message (window-end)))
1536       ;; The bottom of this message is not visible - scroll.
1537       (scroll-up nil))
1538
1539      ((not (= end-of-this-message (point-max)))
1540       ;; This is not the last message - move to the next visible one.
1541       (notmuch-show-next-open-message))
1542
1543      ((not (= (point) (point-max)))
1544       ;; This is the last message, but the cursor is not at the end of
1545       ;; the buffer. Move it there.
1546       (goto-char (point-max)))
1547
1548      (t
1549       ;; This is the last message - change the return value
1550       (setq ret t)))
1551     ret))
1552
1553 (defun notmuch-show-advance-and-archive ()
1554   "Advance through thread and archive.
1555
1556 This command is intended to be one of the simplest ways to
1557 process a thread of email. It works exactly like
1558 notmuch-show-advance, in that it scrolls through messages in a
1559 show buffer, except that when it gets to the end of the buffer it
1560 archives the entire current thread, (remove the \"inbox\" tag
1561 from each message), kills the buffer, and displays the next
1562 thread from the search from which this thread was originally
1563 shown."
1564   (interactive)
1565   (if (notmuch-show-advance)
1566       (notmuch-show-archive-thread-then-next)))
1567
1568 (defun notmuch-show-rewind ()
1569   "Backup through the thread, (reverse scrolling compared to \\[notmuch-show-advance-and-archive]).
1570
1571 Specifically, if the beginning of the previous email is fewer
1572 than `window-height' lines from the current point, move to it
1573 just like `notmuch-show-previous-message'.
1574
1575 Otherwise, just scroll down a screenful of the current message.
1576
1577 This command does not modify any message tags, (it does not undo
1578 any effects from previous calls to
1579 `notmuch-show-advance-and-archive'."
1580   (interactive)
1581   (let ((start-of-message (notmuch-show-message-top))
1582         (start-of-window (window-start)))
1583     (cond
1584       ;; Either this message is properly aligned with the start of the
1585       ;; window or the start of this message is not visible on the
1586       ;; screen - scroll.
1587      ((or (= start-of-message start-of-window)
1588           (< start-of-message start-of-window))
1589       (scroll-down)
1590       ;; If a small number of lines from the previous message are
1591       ;; visible, realign so that the top of the current message is at
1592       ;; the top of the screen.
1593       (when (<= (count-screen-lines (window-start) start-of-message)
1594                 next-screen-context-lines)
1595         (goto-char (notmuch-show-message-top))
1596         (notmuch-show-message-adjust))
1597       ;; Move to the top left of the window.
1598       (goto-char (window-start)))
1599      (t
1600       ;; Move to the previous message.
1601       (notmuch-show-previous-message)))))
1602
1603 (defun notmuch-show-reply (&optional prompt-for-sender)
1604   "Reply to the sender and all recipients of the current message."
1605   (interactive "P")
1606   (notmuch-mua-new-reply (notmuch-show-get-message-id) prompt-for-sender t))
1607
1608 (defun notmuch-show-reply-sender (&optional prompt-for-sender)
1609   "Reply to the sender of the current message."
1610   (interactive "P")
1611   (notmuch-mua-new-reply (notmuch-show-get-message-id) prompt-for-sender nil))
1612
1613 (defun notmuch-show-forward-message (&optional prompt-for-sender)
1614   "Forward the current message."
1615   (interactive "P")
1616   (with-current-notmuch-show-message
1617    (notmuch-mua-new-forward-message prompt-for-sender)))
1618
1619 (defun notmuch-show-next-message (&optional pop-at-end)
1620   "Show the next message.
1621
1622 If a prefix argument is given and this is the last message in the
1623 thread, navigate to the next thread in the parent search buffer."
1624   (interactive "P")
1625   (if (notmuch-show-goto-message-next)
1626       (progn
1627         (notmuch-show-mark-read)
1628         (notmuch-show-message-adjust))
1629     (if pop-at-end
1630         (notmuch-show-next-thread)
1631       (goto-char (point-max)))))
1632
1633 (defun notmuch-show-previous-message ()
1634   "Show the previous message or the start of the current message."
1635   (interactive)
1636   (if (= (point) (notmuch-show-message-top))
1637       (notmuch-show-goto-message-previous)
1638     (notmuch-show-move-to-message-top))
1639   (notmuch-show-mark-read)
1640   (notmuch-show-message-adjust))
1641
1642 (defun notmuch-show-next-open-message (&optional pop-at-end)
1643   "Show the next open message.
1644
1645 If a prefix argument is given and this is the last open message
1646 in the thread, navigate to the next thread in the parent search
1647 buffer. Return t if there was a next open message in the thread
1648 to show, nil otherwise."
1649   (interactive "P")
1650   (let (r)
1651     (while (and (setq r (notmuch-show-goto-message-next))
1652                 (not (notmuch-show-message-visible-p))))
1653     (if r
1654         (progn
1655           (notmuch-show-mark-read)
1656           (notmuch-show-message-adjust))
1657       (if pop-at-end
1658           (notmuch-show-next-thread)
1659         (goto-char (point-max))))
1660     r))
1661
1662 (defun notmuch-show-next-matching-message ()
1663   "Show the next matching message."
1664   (interactive)
1665   (let (r)
1666     (while (and (setq r (notmuch-show-goto-message-next))
1667                 (not (notmuch-show-get-prop :match))))
1668     (if r
1669         (progn
1670           (notmuch-show-mark-read)
1671           (notmuch-show-message-adjust))
1672       (goto-char (point-max)))))
1673
1674 (defun notmuch-show-open-if-matched ()
1675   "Open a message if it is matched (whether or not excluded)."
1676   (let ((props (notmuch-show-get-message-properties)))
1677     (notmuch-show-message-visible props (plist-get props :match))))
1678
1679 (defun notmuch-show-goto-first-wanted-message ()
1680   "Move to the first open message and mark it read"
1681   (goto-char (point-min))
1682   (if (notmuch-show-message-visible-p)
1683       (notmuch-show-mark-read)
1684     (notmuch-show-next-open-message))
1685   (when (eobp)
1686     ;; There are no matched non-excluded messages so open all matched
1687     ;; (necessarily excluded) messages and go to the first.
1688     (notmuch-show-mapc 'notmuch-show-open-if-matched)
1689     (force-window-update)
1690     (goto-char (point-min))
1691     (if (notmuch-show-message-visible-p)
1692         (notmuch-show-mark-read)
1693       (notmuch-show-next-open-message))))
1694
1695 (defun notmuch-show-previous-open-message ()
1696   "Show the previous open message."
1697   (interactive)
1698   (while (and (if (= (point) (notmuch-show-message-top))
1699                   (notmuch-show-goto-message-previous)
1700                 (notmuch-show-move-to-message-top))
1701               (not (notmuch-show-message-visible-p))))
1702   (notmuch-show-mark-read)
1703   (notmuch-show-message-adjust))
1704
1705 (defun notmuch-show-view-raw-message ()
1706   "View the file holding the current message."
1707   (interactive)
1708   (let* ((id (notmuch-show-get-message-id))
1709          (buf (get-buffer-create (concat "*notmuch-raw-" id "*"))))
1710     (call-process notmuch-command nil buf nil "show" "--format=raw" id)
1711     (switch-to-buffer buf)
1712     (goto-char (point-min))
1713     (set-buffer-modified-p nil)
1714     (view-buffer buf 'kill-buffer-if-not-modified)))
1715
1716 (defun notmuch-show-pipe-message (entire-thread command)
1717   "Pipe the contents of the current message (or thread) to the given command.
1718
1719 The given command will be executed with the raw contents of the
1720 current email message as stdin. Anything printed by the command
1721 to stdout or stderr will appear in the *notmuch-pipe* buffer.
1722
1723 When invoked with a prefix argument, the command will receive all
1724 open messages in the current thread (formatted as an mbox) rather
1725 than only the current message."
1726   (interactive "P\nsPipe message to command: ")
1727   (let (shell-command)
1728     (if entire-thread
1729         (setq shell-command
1730               (concat notmuch-command " show --format=mbox --exclude=false "
1731                       (shell-quote-argument
1732                        (mapconcat 'identity (notmuch-show-get-message-ids-for-open-messages) " OR "))
1733                       " | " command))
1734       (setq shell-command
1735             (concat notmuch-command " show --format=raw "
1736                     (shell-quote-argument (notmuch-show-get-message-id)) " | " command)))
1737     (let ((buf (get-buffer-create (concat "*notmuch-pipe*"))))
1738       (with-current-buffer buf
1739         (setq buffer-read-only nil)
1740         (erase-buffer)
1741         (let ((exit-code (call-process-shell-command shell-command nil buf)))
1742           (goto-char (point-max))
1743           (set-buffer-modified-p nil)
1744           (setq buffer-read-only t)
1745           (unless (zerop exit-code)
1746             (switch-to-buffer-other-window buf)
1747             (message (format "Command '%s' exited abnormally with code %d"
1748                              shell-command exit-code))))))))
1749
1750 (defun notmuch-show-tag-message (&rest tag-changes)
1751   "Change tags for the current message.
1752
1753 TAG-CHANGES is a list of tag operations for `notmuch-tag'."
1754   (let* ((current-tags (notmuch-show-get-tags))
1755          (new-tags (notmuch-update-tags current-tags tag-changes)))
1756     (unless (equal current-tags new-tags)
1757       (funcall 'notmuch-tag (notmuch-show-get-message-id) tag-changes)
1758       (notmuch-show-set-tags new-tags))))
1759
1760 (defun notmuch-show-tag (&optional tag-changes)
1761   "Change tags for the current message.
1762
1763 See `notmuch-tag' for information on the format of TAG-CHANGES."
1764   (interactive)
1765   (setq tag-changes (funcall 'notmuch-tag (notmuch-show-get-message-id) tag-changes))
1766   (let* ((current-tags (notmuch-show-get-tags))
1767          (new-tags (notmuch-update-tags current-tags tag-changes)))
1768     (unless (equal current-tags new-tags)
1769       (notmuch-show-set-tags new-tags))))
1770
1771 (defun notmuch-show-tag-all (&optional tag-changes)
1772   "Change tags for all messages in the current show buffer.
1773
1774 See `notmuch-tag' for information on the format of TAG-CHANGES."
1775   (interactive)
1776   (setq tag-changes (funcall 'notmuch-tag (notmuch-show-get-messages-ids-search) tag-changes))
1777   (notmuch-show-mapc
1778    (lambda ()
1779      (let* ((current-tags (notmuch-show-get-tags))
1780             (new-tags (notmuch-update-tags current-tags tag-changes)))
1781        (unless (equal current-tags new-tags)
1782          (notmuch-show-set-tags new-tags))))))
1783
1784 (defun notmuch-show-add-tag ()
1785   "Same as `notmuch-show-tag' but sets initial input to '+'."
1786   (interactive)
1787   (notmuch-show-tag "+"))
1788
1789 (defun notmuch-show-remove-tag ()
1790   "Same as `notmuch-show-tag' but sets initial input to '-'."
1791   (interactive)
1792   (notmuch-show-tag "-"))
1793
1794 (defun notmuch-show-toggle-visibility-headers ()
1795   "Toggle the visibility of the current message headers."
1796   (interactive)
1797   (let ((props (notmuch-show-get-message-properties)))
1798     (notmuch-show-headers-visible
1799      props
1800      (not (plist-get props :headers-visible))))
1801   (force-window-update))
1802
1803 (defun notmuch-show-toggle-message ()
1804   "Toggle the visibility of the current message."
1805   (interactive)
1806   (let ((props (notmuch-show-get-message-properties)))
1807     (notmuch-show-message-visible
1808      props
1809      (not (plist-get props :message-visible))))
1810   (force-window-update))
1811
1812 (defun notmuch-show-open-or-close-all ()
1813   "Set the visibility all of the messages in the current thread.
1814 By default make all of the messages visible. With a prefix
1815 argument, hide all of the messages."
1816   (interactive)
1817   (save-excursion
1818     (goto-char (point-min))
1819     (loop do (notmuch-show-message-visible (notmuch-show-get-message-properties)
1820                                            (not current-prefix-arg))
1821           until (not (notmuch-show-goto-message-next))))
1822   (force-window-update))
1823
1824 (defun notmuch-show-next-button ()
1825   "Advance point to the next button in the buffer."
1826   (interactive)
1827   (forward-button 1))
1828
1829 (defun notmuch-show-previous-button ()
1830   "Move point back to the previous button in the buffer."
1831   (interactive)
1832   (backward-button 1))
1833
1834 (defun notmuch-show-next-thread (&optional show-next)
1835   "Move to the next item in the search results, if any."
1836   (interactive "P")
1837   (let ((parent-buffer notmuch-show-parent-buffer))
1838     (notmuch-kill-this-buffer)
1839     (when (buffer-live-p parent-buffer)
1840       (switch-to-buffer parent-buffer)
1841       (notmuch-search-next-thread)
1842       (if show-next
1843           (notmuch-search-show-thread)))))
1844
1845 (defun notmuch-show-archive-thread (&optional unarchive)
1846   "Archive each message in thread.
1847
1848 Archive each message currently shown by applying the tag changes
1849 in `notmuch-archive-tags' to each (remove the \"inbox\" tag by
1850 default). If a prefix argument is given, the messages will be
1851 \"unarchived\", i.e. the tag changes in `notmuch-archive-tags'
1852 will be reversed.
1853
1854 Note: This command is safe from any race condition of new messages
1855 being delivered to the same thread. It does not archive the
1856 entire thread, but only the messages shown in the current
1857 buffer."
1858   (interactive "P")
1859   (when notmuch-archive-tags
1860     (notmuch-show-tag-all
1861      (notmuch-tag-change-list notmuch-archive-tags unarchive))))
1862
1863 (defun notmuch-show-archive-thread-then-next ()
1864   "Archive all messages in the current buffer, then show next thread from search."
1865   (interactive)
1866   (notmuch-show-archive-thread)
1867   (notmuch-show-next-thread t))
1868
1869 (defun notmuch-show-archive-thread-then-exit ()
1870   "Archive all messages in the current buffer, then exit back to search results."
1871   (interactive)
1872   (notmuch-show-archive-thread)
1873   (notmuch-show-next-thread))
1874
1875 (defun notmuch-show-archive-message (&optional unarchive)
1876   "Archive the current message.
1877
1878 Archive the current message by applying the tag changes in
1879 `notmuch-archive-tags' to it (remove the \"inbox\" tag by
1880 default). If a prefix argument is given, the message will be
1881 \"unarchived\", i.e. the tag changes in `notmuch-archive-tags'
1882 will be reversed."
1883   (interactive "P")
1884   (when notmuch-archive-tags
1885     (apply 'notmuch-show-tag-message
1886            (notmuch-tag-change-list notmuch-archive-tags unarchive))))
1887
1888 (defun notmuch-show-archive-message-then-next-or-exit ()
1889   "Archive the current message, then show the next open message in the current thread.
1890
1891 If at the last open message in the current thread, then exit back
1892 to search results."
1893   (interactive)
1894   (notmuch-show-archive-message)
1895   (notmuch-show-next-open-message t))
1896
1897 (defun notmuch-show-archive-message-then-next-or-next-thread ()
1898   "Archive the current message, then show the next open message in the current thread.
1899
1900 If at the last open message in the current thread, then show next
1901 thread from search."
1902   (interactive)
1903   (notmuch-show-archive-message)
1904   (unless (notmuch-show-next-open-message)
1905     (notmuch-show-next-thread t)))
1906
1907 (defun notmuch-show-stash-cc ()
1908   "Copy CC field of current message to kill-ring."
1909   (interactive)
1910   (notmuch-common-do-stash (notmuch-show-get-cc)))
1911
1912 (defun notmuch-show-stash-date ()
1913   "Copy date of current message to kill-ring."
1914   (interactive)
1915   (notmuch-common-do-stash (notmuch-show-get-date)))
1916
1917 (defun notmuch-show-stash-filename ()
1918   "Copy filename of current message to kill-ring."
1919   (interactive)
1920   (notmuch-common-do-stash (notmuch-show-get-filename)))
1921
1922 (defun notmuch-show-stash-from ()
1923   "Copy From address of current message to kill-ring."
1924   (interactive)
1925   (notmuch-common-do-stash (notmuch-show-get-from)))
1926
1927 (defun notmuch-show-stash-message-id (&optional stash-thread-id)
1928   "Copy id: query matching the current message to kill-ring.
1929
1930 If invoked with a prefix argument (or STASH-THREAD-ID is
1931 non-nil), copy thread: query matching the current thread to
1932 kill-ring."
1933   (interactive "P")
1934   (if stash-thread-id
1935       (notmuch-common-do-stash notmuch-show-thread-id)
1936     (notmuch-common-do-stash (notmuch-show-get-message-id))))
1937
1938 (defun notmuch-show-stash-message-id-stripped ()
1939   "Copy message ID of current message (sans `id:' prefix) to kill-ring."
1940   (interactive)
1941   (notmuch-common-do-stash (notmuch-show-get-message-id t)))
1942
1943 (defun notmuch-show-stash-subject ()
1944   "Copy Subject field of current message to kill-ring."
1945   (interactive)
1946   (notmuch-common-do-stash (notmuch-show-get-subject)))
1947
1948 (defun notmuch-show-stash-tags ()
1949   "Copy tags of current message to kill-ring as a comma separated list."
1950   (interactive)
1951   (notmuch-common-do-stash (mapconcat 'identity (notmuch-show-get-tags) ",")))
1952
1953 (defun notmuch-show-stash-to ()
1954   "Copy To address of current message to kill-ring."
1955   (interactive)
1956   (notmuch-common-do-stash (notmuch-show-get-to)))
1957
1958 (defun notmuch-show-stash-mlarchive-link (&optional mla)
1959   "Copy an ML Archive URI for the current message to the kill-ring.
1960
1961 This presumes that the message is available at the selected Mailing List Archive.
1962
1963 If optional argument MLA is non-nil, use the provided key instead of prompting
1964 the user (see `notmuch-show-stash-mlarchive-link-alist')."
1965   (interactive)
1966   (notmuch-common-do-stash
1967    (concat (cdr (assoc
1968                  (or mla
1969                      (let ((completion-ignore-case t))
1970                        (completing-read
1971                         "Mailing List Archive: "
1972                         notmuch-show-stash-mlarchive-link-alist
1973                         nil t nil nil notmuch-show-stash-mlarchive-link-default)))
1974                  notmuch-show-stash-mlarchive-link-alist))
1975            (notmuch-show-get-message-id t))))
1976
1977 (defun notmuch-show-stash-mlarchive-link-and-go (&optional mla)
1978   "Copy an ML Archive URI for the current message to the kill-ring and visit it.
1979
1980 This presumes that the message is available at the selected Mailing List Archive.
1981
1982 If optional argument MLA is non-nil, use the provided key instead of prompting
1983 the user (see `notmuch-show-stash-mlarchive-link-alist')."
1984   (interactive)
1985   (notmuch-show-stash-mlarchive-link mla)
1986   (browse-url (current-kill 0 t)))
1987
1988 ;; Commands typically bound to buttons.
1989
1990 (defun notmuch-show-part-button-default (&optional button)
1991   (interactive)
1992   (let ((button (or button (button-at (point)))))
1993     (if (button-get button 'overlay)
1994         (notmuch-show-toggle-part-invisibility button)
1995       (notmuch-show-part-button-internal button notmuch-show-part-button-default-action))))
1996
1997 (defun notmuch-show-part-button-save (&optional button)
1998   (interactive)
1999   (notmuch-show-part-button-internal button #'notmuch-show-save-part))
2000
2001 (defun notmuch-show-part-button-view (&optional button)
2002   (interactive)
2003   (notmuch-show-part-button-internal button #'notmuch-show-view-part))
2004
2005 (defun notmuch-show-part-button-interactively-view (&optional button)
2006   (interactive)
2007   (notmuch-show-part-button-internal button #'notmuch-show-interactively-view-part))
2008
2009 (defun notmuch-show-part-button-pipe (&optional button)
2010   (interactive)
2011   (notmuch-show-part-button-internal button #'notmuch-show-pipe-part))
2012
2013 (defun notmuch-show-part-button-internal (button handler)
2014   (let ((button (or button (button-at (point)))))
2015     (if button
2016         (let ((nth (button-get button :notmuch-part)))
2017           (if nth
2018               (funcall handler (notmuch-show-get-message-id) nth
2019                        (button-get button :notmuch-filename)
2020                        (button-get button :notmuch-content-type)))))))
2021
2022 ;;
2023
2024 (provide 'notmuch-show)