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