]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-show.el
Make keys of notmuch-tag-formats regexps and use caching
[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     (notmuch-tag-clear-cache)
1149     (erase-buffer)
1150     (goto-char (point-min))
1151     (save-excursion
1152       (let* ((basic-args (list notmuch-show-thread-id))
1153              (args (if notmuch-show-query-context
1154                        (append (list "\'") basic-args
1155                                (list "and (" notmuch-show-query-context ")\'"))
1156                      (append (list "\'") basic-args (list "\'"))))
1157              (cli-args (cons "--exclude=false"
1158                              (when notmuch-show-elide-non-matching-messages
1159                                (list "--entire-thread=false")))))
1160
1161         (notmuch-show-insert-forest (notmuch-query-get-threads (append cli-args args)))
1162         ;; If the query context reduced the results to nothing, run
1163         ;; the basic query.
1164         (when (and (eq (buffer-size) 0)
1165                    notmuch-show-query-context)
1166           (notmuch-show-insert-forest
1167            (notmuch-query-get-threads (append cli-args basic-args)))))
1168
1169       (jit-lock-register #'notmuch-show-buttonise-links)
1170
1171       ;; Set the header line to the subject of the first message.
1172       (setq header-line-format (notmuch-sanitize (notmuch-show-strip-re (notmuch-show-get-subject))))
1173
1174       (run-hooks 'notmuch-show-hook))))
1175
1176 (defun notmuch-show-capture-state ()
1177   "Capture the state of the current buffer.
1178
1179 This includes:
1180  - the list of open messages,
1181  - the current message."
1182   (list (notmuch-show-get-message-id) (notmuch-show-get-message-ids-for-open-messages)))
1183
1184 (defun notmuch-show-apply-state (state)
1185   "Apply STATE to the current buffer.
1186
1187 This includes:
1188  - opening the messages previously opened,
1189  - closing all other messages,
1190  - moving to the correct current message."
1191   (let ((current (car state))
1192         (open (cadr state)))
1193
1194     ;; Open those that were open.
1195     (goto-char (point-min))
1196     (loop do (notmuch-show-message-visible (notmuch-show-get-message-properties)
1197                                            (member (notmuch-show-get-message-id) open))
1198           until (not (notmuch-show-goto-message-next)))
1199
1200     ;; Go to the previously open message.
1201     (goto-char (point-min))
1202     (unless (loop if (string= current (notmuch-show-get-message-id))
1203                   return t
1204                   until (not (notmuch-show-goto-message-next)))
1205       (goto-char (point-min))
1206       (message "Previously current message not found."))
1207     (notmuch-show-message-adjust)))
1208
1209 (defun notmuch-show-refresh-view (&optional reset-state)
1210   "Refresh the current view.
1211
1212 Refreshes the current view, observing changes in display
1213 preferences. If invoked with a prefix argument (or RESET-STATE is
1214 non-nil) then the state of the buffer (open/closed messages) is
1215 reset based on the original query."
1216   (interactive "P")
1217   (let ((inhibit-read-only t)
1218         (state (unless reset-state
1219                  (notmuch-show-capture-state))))
1220     ;; erase-buffer does not seem to remove overlays, which can lead
1221     ;; to weird effects such as remaining images, so remove them
1222     ;; manually.
1223     (remove-overlays)
1224     (erase-buffer)
1225     (notmuch-show-build-buffer)
1226     (if state
1227         (notmuch-show-apply-state state)
1228       ;; We're resetting state, so navigate to the first open message
1229       ;; and mark it read, just like opening a new show buffer.
1230       (notmuch-show-goto-first-wanted-message))))
1231
1232 (defvar notmuch-show-stash-map
1233   (let ((map (make-sparse-keymap)))
1234     (define-key map "c" 'notmuch-show-stash-cc)
1235     (define-key map "d" 'notmuch-show-stash-date)
1236     (define-key map "F" 'notmuch-show-stash-filename)
1237     (define-key map "f" 'notmuch-show-stash-from)
1238     (define-key map "i" 'notmuch-show-stash-message-id)
1239     (define-key map "I" 'notmuch-show-stash-message-id-stripped)
1240     (define-key map "s" 'notmuch-show-stash-subject)
1241     (define-key map "T" 'notmuch-show-stash-tags)
1242     (define-key map "t" 'notmuch-show-stash-to)
1243     (define-key map "l" 'notmuch-show-stash-mlarchive-link)
1244     (define-key map "L" 'notmuch-show-stash-mlarchive-link-and-go)
1245     (define-key map "?" 'notmuch-subkeymap-help)
1246     map)
1247   "Submap for stash commands")
1248 (fset 'notmuch-show-stash-map notmuch-show-stash-map)
1249
1250 (defvar notmuch-show-part-map
1251   (let ((map (make-sparse-keymap)))
1252     (define-key map "s" 'notmuch-show-save-part)
1253     (define-key map "v" 'notmuch-show-view-part)
1254     (define-key map "o" 'notmuch-show-interactively-view-part)
1255     (define-key map "|" 'notmuch-show-pipe-part)
1256     (define-key map "?" 'notmuch-subkeymap-help)
1257     map)
1258   "Submap for part commands")
1259 (fset 'notmuch-show-part-map notmuch-show-part-map)
1260
1261 (defvar notmuch-show-mode-map
1262       (let ((map (make-sparse-keymap)))
1263         (set-keymap-parent map notmuch-common-keymap)
1264         (define-key map "Z" 'notmuch-tree-from-show-current-query)
1265         (define-key map (kbd "<C-tab>") 'widget-backward)
1266         (define-key map (kbd "M-TAB") 'notmuch-show-previous-button)
1267         (define-key map (kbd "<backtab>") 'notmuch-show-previous-button)
1268         (define-key map (kbd "TAB") 'notmuch-show-next-button)
1269         (define-key map "f" 'notmuch-show-forward-message)
1270         (define-key map "r" 'notmuch-show-reply-sender)
1271         (define-key map "R" 'notmuch-show-reply)
1272         (define-key map "|" 'notmuch-show-pipe-message)
1273         (define-key map "w" 'notmuch-show-save-attachments)
1274         (define-key map "V" 'notmuch-show-view-raw-message)
1275         (define-key map "c" 'notmuch-show-stash-map)
1276         (define-key map "h" 'notmuch-show-toggle-visibility-headers)
1277         (define-key map "*" 'notmuch-show-tag-all)
1278         (define-key map "-" 'notmuch-show-remove-tag)
1279         (define-key map "+" 'notmuch-show-add-tag)
1280         (define-key map "X" 'notmuch-show-archive-thread-then-exit)
1281         (define-key map "x" 'notmuch-show-archive-message-then-next-or-exit)
1282         (define-key map "A" 'notmuch-show-archive-thread-then-next)
1283         (define-key map "a" 'notmuch-show-archive-message-then-next-or-next-thread)
1284         (define-key map "N" 'notmuch-show-next-message)
1285         (define-key map "P" 'notmuch-show-previous-message)
1286         (define-key map "n" 'notmuch-show-next-open-message)
1287         (define-key map "p" 'notmuch-show-previous-open-message)
1288         (define-key map (kbd "M-n") 'notmuch-show-next-thread-show)
1289         (define-key map (kbd "M-p") 'notmuch-show-previous-thread-show)
1290         (define-key map (kbd "DEL") 'notmuch-show-rewind)
1291         (define-key map " " 'notmuch-show-advance-and-archive)
1292         (define-key map (kbd "M-RET") 'notmuch-show-open-or-close-all)
1293         (define-key map (kbd "RET") 'notmuch-show-toggle-message)
1294         (define-key map "#" 'notmuch-show-print-message)
1295         (define-key map "!" 'notmuch-show-toggle-elide-non-matching)
1296         (define-key map "$" 'notmuch-show-toggle-process-crypto)
1297         (define-key map "<" 'notmuch-show-toggle-thread-indentation)
1298         (define-key map "t" 'toggle-truncate-lines)
1299         (define-key map "." 'notmuch-show-part-map)
1300         map)
1301       "Keymap for \"notmuch show\" buffers.")
1302 (fset 'notmuch-show-mode-map notmuch-show-mode-map)
1303
1304 (defun notmuch-show-mode ()
1305   "Major mode for viewing a thread with notmuch.
1306
1307 This buffer contains the results of the \"notmuch show\" command
1308 for displaying a single thread of email from your email archives.
1309
1310 By default, various components of email messages, (citations,
1311 signatures, already-read messages), are hidden. You can make
1312 these parts visible by clicking with the mouse button or by
1313 pressing RET after positioning the cursor on a hidden part, (for
1314 which \\[notmuch-show-next-button] and \\[notmuch-show-previous-button] are helpful).
1315
1316 Reading the thread sequentially is well-supported by pressing
1317 \\[notmuch-show-advance-and-archive]. This will scroll the current message (if necessary), advance
1318 to the next message, or advance to the next thread (if already on
1319 the last message of a thread).
1320
1321 Other commands are available to read or manipulate the thread
1322 more selectively, (such as '\\[notmuch-show-next-message]' and '\\[notmuch-show-previous-message]' to advance to messages
1323 without removing any tags, and '\\[notmuch-show-archive-thread]' to archive an entire thread
1324 without scrolling through with \\[notmuch-show-advance-and-archive]).
1325
1326 You can add or remove arbitrary tags from the current message with
1327 '\\[notmuch-show-add-tag]' or '\\[notmuch-show-remove-tag]'.
1328
1329 All currently available key bindings:
1330
1331 \\{notmuch-show-mode-map}"
1332   (interactive)
1333   (kill-all-local-variables)
1334   (setq notmuch-buffer-refresh-function #'notmuch-show-refresh-view)
1335   (use-local-map notmuch-show-mode-map)
1336   (setq major-mode 'notmuch-show-mode
1337         mode-name "notmuch-show")
1338   (setq buffer-read-only t
1339         truncate-lines t))
1340
1341 (defun notmuch-tree-from-show-current-query ()
1342   "Call notmuch tree with the current query"
1343   (interactive)
1344   (notmuch-tree notmuch-show-thread-id
1345                 notmuch-show-query-context
1346                 (notmuch-show-get-message-id)))
1347
1348 (defun notmuch-show-move-to-message-top ()
1349   (goto-char (notmuch-show-message-top)))
1350
1351 (defun notmuch-show-move-to-message-bottom ()
1352   (goto-char (notmuch-show-message-bottom)))
1353
1354 (defun notmuch-show-message-adjust ()
1355   (recenter 0))
1356
1357 ;; Movement related functions.
1358
1359 ;; There's some strangeness here where a text property applied to a
1360 ;; region a->b is not found when point is at b. We walk backwards
1361 ;; until finding the property.
1362 (defun notmuch-show-message-extent ()
1363   (let (r)
1364     (save-excursion
1365       (while (not (setq r (get-text-property (point) :notmuch-message-extent)))
1366         (backward-char)))
1367     r))
1368
1369 (defun notmuch-show-message-top ()
1370   (car (notmuch-show-message-extent)))
1371
1372 (defun notmuch-show-message-bottom ()
1373   (cdr (notmuch-show-message-extent)))
1374
1375 (defun notmuch-show-goto-message-next ()
1376   (let ((start (point)))
1377     (notmuch-show-move-to-message-bottom)
1378     (if (not (eobp))
1379         t
1380       (goto-char start)
1381       nil)))
1382
1383 (defun notmuch-show-goto-message-previous ()
1384   (notmuch-show-move-to-message-top)
1385   (if (bobp)
1386       nil
1387     (backward-char)
1388     (notmuch-show-move-to-message-top)
1389     t))
1390
1391 (defun notmuch-show-mapc (function)
1392   "Iterate through all messages in the current thread with
1393 `notmuch-show-goto-message-next' and call FUNCTION for side
1394 effects."
1395   (save-excursion
1396     (goto-char (point-min))
1397     (loop do (funcall function)
1398           while (notmuch-show-goto-message-next))))
1399
1400 ;; Functions relating to the visibility of messages and their
1401 ;; components.
1402
1403 (defun notmuch-show-message-visible (props visible-p)
1404   (overlay-put (plist-get props :message-overlay) 'invisible (not visible-p))
1405   (notmuch-show-set-prop :message-visible visible-p props))
1406
1407 (defun notmuch-show-headers-visible (props visible-p)
1408   (overlay-put (plist-get props :headers-overlay) 'invisible (not visible-p))
1409   (notmuch-show-set-prop :headers-visible visible-p props))
1410
1411 ;; Functions for setting and getting attributes of the current
1412 ;; message.
1413
1414 (defun notmuch-show-set-message-properties (props)
1415   (save-excursion
1416     (notmuch-show-move-to-message-top)
1417     (put-text-property (point) (+ (point) 1) :notmuch-message-properties props)))
1418
1419 (defun notmuch-show-get-message-properties ()
1420   "Return the properties of the current message as a plist.
1421
1422 Some useful entries are:
1423 :headers - Property list containing the headers :Date, :Subject, :From, etc.
1424 :body - Body of the message
1425 :tags - Tags for this message"
1426   (save-excursion
1427     (notmuch-show-move-to-message-top)
1428     (get-text-property (point) :notmuch-message-properties)))
1429
1430 (defun notmuch-show-get-part-properties ()
1431   "Return the properties of the innermost part containing point.
1432
1433 This is the part property list retrieved from the CLI.  Signals
1434 an error if there is no part containing point."
1435   (or (get-text-property (point) :notmuch-part)
1436       (error "No message part here")))
1437
1438 (defun notmuch-show-set-prop (prop val &optional props)
1439   (let ((inhibit-read-only t)
1440         (props (or props
1441                    (notmuch-show-get-message-properties))))
1442     (plist-put props prop val)
1443     (notmuch-show-set-message-properties props)))
1444
1445 (defun notmuch-show-get-prop (prop &optional props)
1446   (let ((props (or props
1447                    (notmuch-show-get-message-properties))))
1448     (plist-get props prop)))
1449
1450 (defun notmuch-show-get-message-id (&optional bare)
1451   "Return an id: query for the Message-Id of the current message.
1452
1453 If optional argument BARE is non-nil, return
1454 the Message-Id without id: prefix and escaping."
1455   (if bare
1456       (notmuch-show-get-prop :id)
1457     (notmuch-id-to-query (notmuch-show-get-prop :id))))
1458
1459 (defun notmuch-show-get-messages-ids ()
1460   "Return all id: queries of messages in the current thread."
1461   (let ((message-ids))
1462     (notmuch-show-mapc
1463      (lambda () (push (notmuch-show-get-message-id) message-ids)))
1464     message-ids))
1465
1466 (defun notmuch-show-get-messages-ids-search ()
1467   "Return a search string for all message ids of messages in the
1468 current thread."
1469   (mapconcat 'identity (notmuch-show-get-messages-ids) " or "))
1470
1471 ;; dme: Would it make sense to use a macro for many of these?
1472
1473 (defun notmuch-show-get-filename ()
1474   "Return the filename of the current message."
1475   (notmuch-show-get-prop :filename))
1476
1477 (defun notmuch-show-get-header (header &optional props)
1478   "Return the named header of the current message, if any."
1479   (plist-get (notmuch-show-get-prop :headers props) header))
1480
1481 (defun notmuch-show-get-cc ()
1482   (notmuch-show-get-header :Cc))
1483
1484 (defun notmuch-show-get-date ()
1485   (notmuch-show-get-header :Date))
1486
1487 (defun notmuch-show-get-from ()
1488   (notmuch-show-get-header :From))
1489
1490 (defun notmuch-show-get-subject ()
1491   (notmuch-show-get-header :Subject))
1492
1493 (defun notmuch-show-get-to ()
1494   (notmuch-show-get-header :To))
1495
1496 (defun notmuch-show-get-depth ()
1497   (notmuch-show-get-prop :depth))
1498
1499 (defun notmuch-show-set-tags (tags)
1500   "Set the tags of the current message."
1501   (notmuch-show-set-prop :tags tags)
1502   (notmuch-show-update-tags tags))
1503
1504 (defun notmuch-show-get-tags ()
1505   "Return the tags of the current message."
1506   (notmuch-show-get-prop :tags))
1507
1508 (defun notmuch-show-message-visible-p ()
1509   "Is the current message visible?"
1510   (notmuch-show-get-prop :message-visible))
1511
1512 (defun notmuch-show-headers-visible-p ()
1513   "Are the headers of the current message visible?"
1514   (notmuch-show-get-prop :headers-visible))
1515
1516 (put 'notmuch-show-mark-read 'notmuch-prefix-doc
1517      "Mark the current message as unread.")
1518 (defun notmuch-show-mark-read (&optional unread)
1519   "Mark the current message as read.
1520
1521 Mark the current message as read by applying the tag changes in
1522 `notmuch-show-mark-read-tags' to it (remove the \"unread\" tag by
1523 default). If a prefix argument is given, the message will be
1524 marked as unread, i.e. the tag changes in
1525 `notmuch-show-mark-read-tags' will be reversed."
1526   (interactive "P")
1527   (when notmuch-show-mark-read-tags
1528     (apply 'notmuch-show-tag-message
1529            (notmuch-tag-change-list notmuch-show-mark-read-tags unread))))
1530
1531 ;; Functions for getting attributes of several messages in the current
1532 ;; thread.
1533
1534 (defun notmuch-show-get-message-ids-for-open-messages ()
1535   "Return a list of all id: queries for open messages in the current thread."
1536   (save-excursion
1537     (let (message-ids done)
1538       (goto-char (point-min))
1539       (while (not done)
1540         (if (notmuch-show-message-visible-p)
1541             (setq message-ids (append message-ids (list (notmuch-show-get-message-id)))))
1542         (setq done (not (notmuch-show-goto-message-next)))
1543         )
1544       message-ids
1545       )))
1546
1547 ;; Commands typically bound to keys.
1548
1549 (defun notmuch-show-advance ()
1550   "Advance through thread.
1551
1552 If the current message in the thread is not yet fully visible,
1553 scroll by a near screenful to read more of the message.
1554
1555 Otherwise, (the end of the current message is already within the
1556 current window), advance to the next open message."
1557   (interactive)
1558   (let* ((end-of-this-message (notmuch-show-message-bottom))
1559          (visible-end-of-this-message (1- end-of-this-message))
1560          (ret nil))
1561     (while (invisible-p visible-end-of-this-message)
1562       (setq visible-end-of-this-message
1563             (max (point-min)
1564                  (1- (previous-single-char-property-change
1565                       visible-end-of-this-message 'invisible)))))
1566     (cond
1567      ;; Ideally we would test `end-of-this-message' against the result
1568      ;; of `window-end', but that doesn't account for the fact that
1569      ;; the end of the message might be hidden.
1570      ((and visible-end-of-this-message
1571            (> visible-end-of-this-message (window-end)))
1572       ;; The bottom of this message is not visible - scroll.
1573       (scroll-up nil))
1574
1575      ((not (= end-of-this-message (point-max)))
1576       ;; This is not the last message - move to the next visible one.
1577       (notmuch-show-next-open-message))
1578
1579      ((not (= (point) (point-max)))
1580       ;; This is the last message, but the cursor is not at the end of
1581       ;; the buffer. Move it there.
1582       (goto-char (point-max)))
1583
1584      (t
1585       ;; This is the last message - change the return value
1586       (setq ret t)))
1587     ret))
1588
1589 (defun notmuch-show-advance-and-archive ()
1590   "Advance through thread and archive.
1591
1592 This command is intended to be one of the simplest ways to
1593 process a thread of email. It works exactly like
1594 notmuch-show-advance, in that it scrolls through messages in a
1595 show buffer, except that when it gets to the end of the buffer it
1596 archives the entire current thread, (apply changes in
1597 `notmuch-archive-tags'), kills the buffer, and displays the next
1598 thread from the search from which this thread was originally
1599 shown."
1600   (interactive)
1601   (if (notmuch-show-advance)
1602       (notmuch-show-archive-thread-then-next)))
1603
1604 (defun notmuch-show-rewind ()
1605   "Backup through the thread (reverse scrolling compared to \\[notmuch-show-advance-and-archive]).
1606
1607 Specifically, if the beginning of the previous email is fewer
1608 than `window-height' lines from the current point, move to it
1609 just like `notmuch-show-previous-message'.
1610
1611 Otherwise, just scroll down a screenful of the current message.
1612
1613 This command does not modify any message tags, (it does not undo
1614 any effects from previous calls to
1615 `notmuch-show-advance-and-archive'."
1616   (interactive)
1617   (let ((start-of-message (notmuch-show-message-top))
1618         (start-of-window (window-start)))
1619     (cond
1620       ;; Either this message is properly aligned with the start of the
1621       ;; window or the start of this message is not visible on the
1622       ;; screen - scroll.
1623      ((or (= start-of-message start-of-window)
1624           (< start-of-message start-of-window))
1625       (scroll-down)
1626       ;; If a small number of lines from the previous message are
1627       ;; visible, realign so that the top of the current message is at
1628       ;; the top of the screen.
1629       (when (<= (count-screen-lines (window-start) start-of-message)
1630                 next-screen-context-lines)
1631         (goto-char (notmuch-show-message-top))
1632         (notmuch-show-message-adjust))
1633       ;; Move to the top left of the window.
1634       (goto-char (window-start)))
1635      (t
1636       ;; Move to the previous message.
1637       (notmuch-show-previous-message)))))
1638
1639 (put 'notmuch-show-reply 'notmuch-prefix-doc "... and prompt for sender")
1640 (defun notmuch-show-reply (&optional prompt-for-sender)
1641   "Reply to the sender and all recipients of the current message."
1642   (interactive "P")
1643   (notmuch-mua-new-reply (notmuch-show-get-message-id) prompt-for-sender t))
1644
1645 (put 'notmuch-show-reply-sender 'notmuch-prefix-doc "... and prompt for sender")
1646 (defun notmuch-show-reply-sender (&optional prompt-for-sender)
1647   "Reply to the sender of the current message."
1648   (interactive "P")
1649   (notmuch-mua-new-reply (notmuch-show-get-message-id) prompt-for-sender nil))
1650
1651 (put 'notmuch-show-forward-message 'notmuch-prefix-doc
1652      "... and prompt for sender")
1653 (defun notmuch-show-forward-message (&optional prompt-for-sender)
1654   "Forward the current message."
1655   (interactive "P")
1656   (with-current-notmuch-show-message
1657    (notmuch-mua-new-forward-message prompt-for-sender)))
1658
1659 (defun notmuch-show-next-message (&optional pop-at-end)
1660   "Show the next message.
1661
1662 If a prefix argument is given and this is the last message in the
1663 thread, navigate to the next thread in the parent search buffer."
1664   (interactive "P")
1665   (if (notmuch-show-goto-message-next)
1666       (progn
1667         (notmuch-show-mark-read)
1668         (notmuch-show-message-adjust))
1669     (if pop-at-end
1670         (notmuch-show-next-thread)
1671       (goto-char (point-max)))))
1672
1673 (defun notmuch-show-previous-message ()
1674   "Show the previous message or the start of the current message."
1675   (interactive)
1676   (if (= (point) (notmuch-show-message-top))
1677       (notmuch-show-goto-message-previous)
1678     (notmuch-show-move-to-message-top))
1679   (notmuch-show-mark-read)
1680   (notmuch-show-message-adjust))
1681
1682 (defun notmuch-show-next-open-message (&optional pop-at-end)
1683   "Show the next open message.
1684
1685 If a prefix argument is given and this is the last open message
1686 in the thread, navigate to the next thread in the parent search
1687 buffer. Return t if there was a next open message in the thread
1688 to show, nil otherwise."
1689   (interactive "P")
1690   (let (r)
1691     (while (and (setq r (notmuch-show-goto-message-next))
1692                 (not (notmuch-show-message-visible-p))))
1693     (if r
1694         (progn
1695           (notmuch-show-mark-read)
1696           (notmuch-show-message-adjust))
1697       (if pop-at-end
1698           (notmuch-show-next-thread)
1699         (goto-char (point-max))))
1700     r))
1701
1702 (defun notmuch-show-next-matching-message ()
1703   "Show the next matching message."
1704   (interactive)
1705   (let (r)
1706     (while (and (setq r (notmuch-show-goto-message-next))
1707                 (not (notmuch-show-get-prop :match))))
1708     (if r
1709         (progn
1710           (notmuch-show-mark-read)
1711           (notmuch-show-message-adjust))
1712       (goto-char (point-max)))))
1713
1714 (defun notmuch-show-open-if-matched ()
1715   "Open a message if it is matched (whether or not excluded)."
1716   (let ((props (notmuch-show-get-message-properties)))
1717     (notmuch-show-message-visible props (plist-get props :match))))
1718
1719 (defun notmuch-show-goto-first-wanted-message ()
1720   "Move to the first open message and mark it read"
1721   (goto-char (point-min))
1722   (if (notmuch-show-message-visible-p)
1723       (notmuch-show-mark-read)
1724     (notmuch-show-next-open-message))
1725   (when (eobp)
1726     ;; There are no matched non-excluded messages so open all matched
1727     ;; (necessarily excluded) messages and go to the first.
1728     (notmuch-show-mapc 'notmuch-show-open-if-matched)
1729     (force-window-update)
1730     (goto-char (point-min))
1731     (if (notmuch-show-message-visible-p)
1732         (notmuch-show-mark-read)
1733       (notmuch-show-next-open-message))))
1734
1735 (defun notmuch-show-previous-open-message ()
1736   "Show the previous open message."
1737   (interactive)
1738   (while (and (if (= (point) (notmuch-show-message-top))
1739                   (notmuch-show-goto-message-previous)
1740                 (notmuch-show-move-to-message-top))
1741               (not (notmuch-show-message-visible-p))))
1742   (notmuch-show-mark-read)
1743   (notmuch-show-message-adjust))
1744
1745 (defun notmuch-show-view-raw-message ()
1746   "View the file holding the current message."
1747   (interactive)
1748   (let* ((id (notmuch-show-get-message-id))
1749          (buf (get-buffer-create (concat "*notmuch-raw-" id "*"))))
1750     (call-process notmuch-command nil buf nil "show" "--format=raw" id)
1751     (switch-to-buffer buf)
1752     (goto-char (point-min))
1753     (set-buffer-modified-p nil)
1754     (view-buffer buf 'kill-buffer-if-not-modified)))
1755
1756 (put 'notmuch-show-pipe-message 'notmuch-doc
1757      "Pipe the contents of the current message to a command.")
1758 (put 'notmuch-show-pipe-message 'notmuch-prefix-doc
1759      "Pipe the thread as an mbox to a command.")
1760 (defun notmuch-show-pipe-message (entire-thread command)
1761   "Pipe the contents of the current message (or thread) to COMMAND.
1762
1763 COMMAND will be executed with the raw contents of the current
1764 email message as stdin. Anything printed by the command to stdout
1765 or stderr will appear in the *notmuch-pipe* buffer.
1766
1767 If ENTIRE-THREAD is non-nil (or when invoked with a prefix
1768 argument), COMMAND will receive all open messages in the current
1769 thread (formatted as an mbox) rather than only the current
1770 message."
1771   (interactive (let ((query-string (if current-prefix-arg
1772                                        "Pipe all open messages to command: "
1773                                      "Pipe message to command: ")))
1774                  (list current-prefix-arg (read-string query-string))))
1775   (let (shell-command)
1776     (if entire-thread
1777         (setq shell-command
1778               (concat notmuch-command " show --format=mbox --exclude=false "
1779                       (shell-quote-argument
1780                        (mapconcat 'identity (notmuch-show-get-message-ids-for-open-messages) " OR "))
1781                       " | " command))
1782       (setq shell-command
1783             (concat notmuch-command " show --format=raw "
1784                     (shell-quote-argument (notmuch-show-get-message-id)) " | " command)))
1785     (let ((cwd default-directory)
1786           (buf (get-buffer-create (concat "*notmuch-pipe*"))))
1787       (with-current-buffer buf
1788         (setq buffer-read-only nil)
1789         (erase-buffer)
1790         ;; Use the originating buffer's working directory instead of
1791         ;; that of the pipe buffer.
1792         (cd cwd)
1793         (let ((exit-code (call-process-shell-command shell-command nil buf)))
1794           (goto-char (point-max))
1795           (set-buffer-modified-p nil)
1796           (setq buffer-read-only t)
1797           (unless (zerop exit-code)
1798             (switch-to-buffer-other-window buf)
1799             (message (format "Command '%s' exited abnormally with code %d"
1800                              shell-command exit-code))))))))
1801
1802 (defun notmuch-show-tag-message (&rest tag-changes)
1803   "Change tags for the current message.
1804
1805 TAG-CHANGES is a list of tag operations for `notmuch-tag'."
1806   (let* ((current-tags (notmuch-show-get-tags))
1807          (new-tags (notmuch-update-tags current-tags tag-changes)))
1808     (unless (equal current-tags new-tags)
1809       (notmuch-tag (notmuch-show-get-message-id) tag-changes)
1810       (notmuch-show-set-tags new-tags))))
1811
1812 (defun notmuch-show-tag (tag-changes)
1813   "Change tags for the current message.
1814
1815 See `notmuch-tag' for information on the format of TAG-CHANGES."
1816   (interactive (list (notmuch-read-tag-changes (notmuch-show-get-tags)
1817                                                "Tag message")))
1818   (notmuch-tag (notmuch-show-get-message-id) tag-changes)
1819   (let* ((current-tags (notmuch-show-get-tags))
1820          (new-tags (notmuch-update-tags current-tags tag-changes)))
1821     (unless (equal current-tags new-tags)
1822       (notmuch-show-set-tags new-tags))))
1823
1824 (defun notmuch-show-tag-all (tag-changes)
1825   "Change tags for all messages in the current show buffer.
1826
1827 See `notmuch-tag' for information on the format of TAG-CHANGES."
1828   (interactive
1829    (list (let (tags)
1830            (notmuch-show-mapc
1831             (lambda () (setq tags (append (notmuch-show-get-tags) tags))))
1832            (notmuch-read-tag-changes tags "Tag thread"))))
1833   (notmuch-tag (notmuch-show-get-messages-ids-search) tag-changes)
1834   (notmuch-show-mapc
1835    (lambda ()
1836      (let* ((current-tags (notmuch-show-get-tags))
1837             (new-tags (notmuch-update-tags current-tags tag-changes)))
1838        (unless (equal current-tags new-tags)
1839          (notmuch-show-set-tags new-tags))))))
1840
1841 (defun notmuch-show-add-tag (tag-changes)
1842   "Change tags for the current message (defaulting to add).
1843
1844 Same as `notmuch-show-tag' but sets initial input to '+'."
1845   (interactive
1846    (list (notmuch-read-tag-changes (notmuch-show-get-tags) "Tag message" "+")))
1847   (notmuch-show-tag tag-changes))
1848
1849 (defun notmuch-show-remove-tag (tag-changes)
1850   "Change tags for the current message (defaulting to remove).
1851
1852 Same as `notmuch-show-tag' but sets initial input to '-'."
1853   (interactive
1854    (list (notmuch-read-tag-changes (notmuch-show-get-tags) "Tag message" "-")))
1855   (notmuch-show-tag tag-changes))
1856
1857 (defun notmuch-show-toggle-visibility-headers ()
1858   "Toggle the visibility of the current message headers."
1859   (interactive)
1860   (let ((props (notmuch-show-get-message-properties)))
1861     (notmuch-show-headers-visible
1862      props
1863      (not (plist-get props :headers-visible))))
1864   (force-window-update))
1865
1866 (defun notmuch-show-toggle-message ()
1867   "Toggle the visibility of the current message."
1868   (interactive)
1869   (let ((props (notmuch-show-get-message-properties)))
1870     (notmuch-show-message-visible
1871      props
1872      (not (plist-get props :message-visible))))
1873   (force-window-update))
1874
1875 (put 'notmuch-show-open-or-close-all 'notmuch-doc "Show all messages.")
1876 (put 'notmuch-show-open-or-close-all 'notmuch-prefix-doc "Hide all messages.")
1877 (defun notmuch-show-open-or-close-all ()
1878   "Set the visibility all of the messages in the current thread.
1879
1880 By default make all of the messages visible. With a prefix
1881 argument, hide all of the messages."
1882   (interactive)
1883   (save-excursion
1884     (goto-char (point-min))
1885     (loop do (notmuch-show-message-visible (notmuch-show-get-message-properties)
1886                                            (not current-prefix-arg))
1887           until (not (notmuch-show-goto-message-next))))
1888   (force-window-update))
1889
1890 (defun notmuch-show-next-button ()
1891   "Advance point to the next button in the buffer."
1892   (interactive)
1893   (forward-button 1))
1894
1895 (defun notmuch-show-previous-button ()
1896   "Move point back to the previous button in the buffer."
1897   (interactive)
1898   (backward-button 1))
1899
1900 (defun notmuch-show-next-thread (&optional show previous)
1901   "Move to the next item in the search results, if any.
1902
1903 If SHOW is non-nil, open the next item in a show
1904 buffer. Otherwise just highlight the next item in the search
1905 buffer. If PREVIOUS is non-nil, move to the previous item in the
1906 search results instead."
1907   (interactive "P")
1908   (let ((parent-buffer notmuch-show-parent-buffer))
1909     (notmuch-kill-this-buffer)
1910     (when (buffer-live-p parent-buffer)
1911       (switch-to-buffer parent-buffer)
1912       (and (if previous
1913                (notmuch-search-previous-thread)
1914              (notmuch-search-next-thread))
1915            show
1916            (notmuch-search-show-thread)))))
1917
1918 (defun notmuch-show-next-thread-show ()
1919   "Show the next thread in the search results, if any."
1920   (interactive)
1921   (notmuch-show-next-thread t))
1922
1923 (defun notmuch-show-previous-thread-show ()
1924   "Show the previous thread in the search results, if any."
1925   (interactive)
1926   (notmuch-show-next-thread t t))
1927
1928 (put 'notmuch-show-archive-thread 'notmuch-prefix-doc
1929      "Un-archive each message in thread.")
1930 (defun notmuch-show-archive-thread (&optional unarchive)
1931   "Archive each message in thread.
1932
1933 Archive each message currently shown by applying the tag changes
1934 in `notmuch-archive-tags' to each. If a prefix argument is given,
1935 the messages will be \"unarchived\", i.e. the tag changes in
1936 `notmuch-archive-tags' will be reversed.
1937
1938 Note: This command is safe from any race condition of new messages
1939 being delivered to the same thread. It does not archive the
1940 entire thread, but only the messages shown in the current
1941 buffer."
1942   (interactive "P")
1943   (when notmuch-archive-tags
1944     (notmuch-show-tag-all
1945      (notmuch-tag-change-list notmuch-archive-tags unarchive))))
1946
1947 (defun notmuch-show-archive-thread-then-next ()
1948   "Archive all messages in the current buffer, then show next thread from search."
1949   (interactive)
1950   (notmuch-show-archive-thread)
1951   (notmuch-show-next-thread t))
1952
1953 (defun notmuch-show-archive-thread-then-exit ()
1954   "Archive all messages in the current buffer, then exit back to search results."
1955   (interactive)
1956   (notmuch-show-archive-thread)
1957   (notmuch-show-next-thread))
1958
1959 (put 'notmuch-show-archive-message 'notmuch-prefix-doc
1960      "Un-archive the current message.")
1961 (defun notmuch-show-archive-message (&optional unarchive)
1962   "Archive the current message.
1963
1964 Archive the current message by applying the tag changes in
1965 `notmuch-archive-tags' to it. If a prefix argument is given, the
1966 message will be \"unarchived\", i.e. the tag changes in
1967 `notmuch-archive-tags' will be reversed."
1968   (interactive "P")
1969   (when notmuch-archive-tags
1970     (apply 'notmuch-show-tag-message
1971            (notmuch-tag-change-list notmuch-archive-tags unarchive))))
1972
1973 (defun notmuch-show-archive-message-then-next-or-exit ()
1974   "Archive the current message, then show the next open message in the current thread.
1975
1976 If at the last open message in the current thread, then exit back
1977 to search results."
1978   (interactive)
1979   (notmuch-show-archive-message)
1980   (notmuch-show-next-open-message t))
1981
1982 (defun notmuch-show-archive-message-then-next-or-next-thread ()
1983   "Archive the current message, then show the next open message in the current thread.
1984
1985 If at the last open message in the current thread, then show next
1986 thread from search."
1987   (interactive)
1988   (notmuch-show-archive-message)
1989   (unless (notmuch-show-next-open-message)
1990     (notmuch-show-next-thread t)))
1991
1992 (defun notmuch-show-stash-cc ()
1993   "Copy CC field of current message to kill-ring."
1994   (interactive)
1995   (notmuch-common-do-stash (notmuch-show-get-cc)))
1996
1997 (defun notmuch-show-stash-date ()
1998   "Copy date of current message to kill-ring."
1999   (interactive)
2000   (notmuch-common-do-stash (notmuch-show-get-date)))
2001
2002 (defun notmuch-show-stash-filename ()
2003   "Copy filename of current message to kill-ring."
2004   (interactive)
2005   (notmuch-common-do-stash (notmuch-show-get-filename)))
2006
2007 (defun notmuch-show-stash-from ()
2008   "Copy From address of current message to kill-ring."
2009   (interactive)
2010   (notmuch-common-do-stash (notmuch-show-get-from)))
2011
2012 (put 'notmuch-show-stash-message-id 'notmuch-prefix-doc
2013      "Copy thread: query matching current thread to kill-ring.")
2014 (defun notmuch-show-stash-message-id (&optional stash-thread-id)
2015   "Copy id: query matching the current message to kill-ring.
2016
2017 If invoked with a prefix argument (or STASH-THREAD-ID is
2018 non-nil), copy thread: query matching the current thread to
2019 kill-ring."
2020   (interactive "P")
2021   (if stash-thread-id
2022       (notmuch-common-do-stash notmuch-show-thread-id)
2023     (notmuch-common-do-stash (notmuch-show-get-message-id))))
2024
2025 (defun notmuch-show-stash-message-id-stripped ()
2026   "Copy message ID of current message (sans `id:' prefix) to kill-ring."
2027   (interactive)
2028   (notmuch-common-do-stash (notmuch-show-get-message-id t)))
2029
2030 (defun notmuch-show-stash-subject ()
2031   "Copy Subject field of current message to kill-ring."
2032   (interactive)
2033   (notmuch-common-do-stash (notmuch-show-get-subject)))
2034
2035 (defun notmuch-show-stash-tags ()
2036   "Copy tags of current message to kill-ring as a comma separated list."
2037   (interactive)
2038   (notmuch-common-do-stash (mapconcat 'identity (notmuch-show-get-tags) ",")))
2039
2040 (defun notmuch-show-stash-to ()
2041   "Copy To address of current message to kill-ring."
2042   (interactive)
2043   (notmuch-common-do-stash (notmuch-show-get-to)))
2044
2045 (defun notmuch-show-stash-mlarchive-link (&optional mla)
2046   "Copy an ML Archive URI for the current message to the kill-ring.
2047
2048 This presumes that the message is available at the selected Mailing List Archive.
2049
2050 If optional argument MLA is non-nil, use the provided key instead of prompting
2051 the user (see `notmuch-show-stash-mlarchive-link-alist')."
2052   (interactive)
2053   (notmuch-common-do-stash
2054    (concat (cdr (assoc
2055                  (or mla
2056                      (let ((completion-ignore-case t))
2057                        (completing-read
2058                         "Mailing List Archive: "
2059                         notmuch-show-stash-mlarchive-link-alist
2060                         nil t nil nil notmuch-show-stash-mlarchive-link-default)))
2061                  notmuch-show-stash-mlarchive-link-alist))
2062            (notmuch-show-get-message-id t))))
2063
2064 (defun notmuch-show-stash-mlarchive-link-and-go (&optional mla)
2065   "Copy an ML Archive URI for the current message to the kill-ring and visit it.
2066
2067 This presumes that the message is available at the selected Mailing List Archive.
2068
2069 If optional argument MLA is non-nil, use the provided key instead of prompting
2070 the user (see `notmuch-show-stash-mlarchive-link-alist')."
2071   (interactive)
2072   (notmuch-show-stash-mlarchive-link mla)
2073   (browse-url (current-kill 0 t)))
2074
2075 ;; Interactive part functions and their helpers
2076
2077 (defun notmuch-show-generate-part-buffer (message-id nth)
2078   "Return a temporary buffer containing the specified part's content."
2079   (let ((buf (generate-new-buffer " *notmuch-part*"))
2080         (process-crypto notmuch-show-process-crypto))
2081     (with-current-buffer buf
2082       (setq notmuch-show-process-crypto process-crypto)
2083       ;; Always acquires the part via `notmuch part', even if it is
2084       ;; available in the SEXP output.
2085       (insert (notmuch-get-bodypart-internal message-id nth notmuch-show-process-crypto)))
2086     buf))
2087
2088 (defun notmuch-show-current-part-handle ()
2089   "Return an mm-handle for the part containing point.
2090
2091 This creates a temporary buffer for the part's content; the
2092 caller is responsible for killing this buffer as appropriate."
2093   (let* ((part (notmuch-show-get-part-properties))
2094          (message-id (notmuch-show-get-message-id))
2095          (nth (plist-get part :id))
2096          (buf (notmuch-show-generate-part-buffer message-id nth))
2097          (computed-type (plist-get part :computed-type))
2098          (filename (plist-get part :filename))
2099          (disposition (if filename `(attachment (filename . ,filename)))))
2100     (mm-make-handle buf (list computed-type) nil nil disposition)))
2101
2102 (defun notmuch-show-apply-to-current-part-handle (fn)
2103   "Apply FN to an mm-handle for the part containing point.
2104
2105 This ensures that the temporary buffer created for the mm-handle
2106 is destroyed when FN returns."
2107   (let ((handle (notmuch-show-current-part-handle)))
2108     ;; emacs 24.3+ puts stdout/stderr into the calling buffer so we
2109     ;; call it from a temp-buffer, unless
2110     ;; notmuch-show-attachment-debug is non-nil in which case we put
2111     ;; it in " *notmuch-part*".
2112     (unwind-protect
2113         (if notmuch-show-attachment-debug
2114             (with-current-buffer (generate-new-buffer " *notmuch-part*")
2115               (funcall fn handle))
2116           (with-temp-buffer
2117             (funcall fn handle)))
2118       (kill-buffer (mm-handle-buffer handle)))))
2119
2120 (defun notmuch-show-part-button-default (&optional button)
2121   (interactive)
2122   (let ((button (or button (button-at (point)))))
2123     ;; Try to toggle the part, if that fails then call the default
2124     ;; action. The toggle fails if the part has no emacs renderable
2125     ;; content.
2126     (unless (notmuch-show-toggle-part-invisibility button)
2127       (call-interactively notmuch-show-part-button-default-action))))
2128
2129 (defun notmuch-show-save-part ()
2130   "Save the MIME part containing point to a file."
2131   (interactive)
2132   (notmuch-show-apply-to-current-part-handle #'mm-save-part))
2133
2134 (defun notmuch-show-view-part ()
2135   "View the MIME part containing point in an external viewer."
2136   (interactive)
2137   ;; Set mm-inlined-types to nil to force an external viewer
2138   (let ((mm-inlined-types nil))
2139     (notmuch-show-apply-to-current-part-handle #'mm-display-part)))
2140
2141 (defun notmuch-show-interactively-view-part ()
2142   "View the MIME part containing point, prompting for a viewer."
2143   (interactive)
2144   (notmuch-show-apply-to-current-part-handle #'mm-interactively-view-part))
2145
2146 (defun notmuch-show-pipe-part ()
2147   "Pipe the MIME part containing point to an external command."
2148   (interactive)
2149   (notmuch-show-apply-to-current-part-handle #'mm-pipe-part))
2150
2151
2152 (provide 'notmuch-show)