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