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