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