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