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