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