]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-tree.el
emacs/tree: introduce notmuch-tree-parent-buffer variable
[notmuch] / emacs / notmuch-tree.el
1 ;;; notmuch-tree.el --- displaying notmuch forests
2 ;;
3 ;; Copyright © Carl Worth
4 ;; Copyright © David Edmondson
5 ;; Copyright © Mark Walters
6 ;;
7 ;; This file is part of Notmuch.
8 ;;
9 ;; Notmuch is free software: you can redistribute it and/or modify it
10 ;; under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation, either version 3 of the License, or
12 ;; (at your option) any later version.
13 ;;
14 ;; Notmuch is distributed in the hope that it will be useful, but
15 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17 ;; General Public License for more details.
18 ;;
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with Notmuch.  If not, see <https://www.gnu.org/licenses/>.
21 ;;
22 ;; Authors: David Edmondson <dme@dme.org>
23 ;;          Mark Walters <markwalters1009@gmail.com>
24
25 ;;; Code:
26
27 (eval-when-compile (require 'cl-lib))
28
29 (require 'mail-parse)
30
31 (require 'notmuch-lib)
32 (require 'notmuch-query)
33 (require 'notmuch-show)
34 (require 'notmuch-tag)
35 (require 'notmuch-parser)
36 (require 'notmuch-jump)
37
38 (declare-function notmuch-search "notmuch"
39                   (&optional query oldest-first target-thread target-line))
40 (declare-function notmuch-call-notmuch-process "notmuch" (&rest args))
41 (declare-function notmuch-read-query "notmuch" (prompt))
42 (declare-function notmuch-search-find-thread-id "notmuch" (&optional bare))
43 (declare-function notmuch-search-find-subject "notmuch" ())
44
45 ;; the following variable is defined in notmuch.el
46 (defvar notmuch-search-query-string)
47
48 ;; this variable distinguishes the unthreaded display from the normal tree display
49 (defvar notmuch-tree-unthreaded nil
50   "A buffer local copy of argument unthreaded to the function notmuch-tree.")
51 (make-variable-buffer-local 'notmuch-tree-unthreaded)
52
53 (defgroup notmuch-tree nil
54   "Showing message and thread structure."
55   :group 'notmuch)
56
57 (defcustom notmuch-tree-show-out nil
58   "View selected messages in new window rather than split-pane."
59   :type 'boolean
60   :group 'notmuch-tree)
61
62 (defcustom notmuch-unthreaded-show-out t
63   "View selected messages in new window rather than split-pane."
64   :type 'boolean
65   :group 'notmuch-tree)
66
67 (defun notmuch-tree-show-out ()
68   (if notmuch-tree-unthreaded
69       notmuch-unthreaded-show-out
70     notmuch-tree-show-out))
71
72 (defcustom notmuch-tree-result-format
73   `(("date" . "%12s  ")
74     ("authors" . "%-20s")
75     ((("tree" . "%s")("subject" . "%s")) ." %-54s ")
76     ("tags" . "(%s)"))
77   "Result formatting for tree view. Supported fields are: date,
78 authors, subject, tree, tags.  Tree means the thread tree
79 box graphics. The field may also be a list in which case
80 the formatting rules are applied recursively and then the
81 output of all the fields in the list is inserted
82 according to format-string.
83
84 Note the author string should not contain
85 whitespace (put it in the neighbouring fields instead).
86 For example:
87         (setq notmuch-tree-result-format \(\(\"authors\" . \"%-40s\"\)
88                                           \(\"subject\" . \"%s\"\)\)\)"
89   :type '(alist :key-type (string) :value-type (string))
90   :group 'notmuch-tree)
91
92 (defcustom notmuch-unthreaded-result-format
93   `(("date" . "%12s  ")
94     ("authors" . "%-20s")
95     ((("subject" . "%s")) ." %-54s ")
96     ("tags" . "(%s)"))
97   "Result formatting for unthreaded tree view. Supported fields are: date,
98 authors, subject, tree, tags.  Tree means the thread tree
99 box graphics. The field may also be a list in which case
100 the formatting rules are applied recursively and then the
101 output of all the fields in the list is inserted
102 according to format-string.
103
104 Note the author string should not contain
105 whitespace (put it in the neighbouring fields instead).
106 For example:
107         (setq notmuch-tree-result-format \(\(\"authors\" . \"%-40s\"\)
108                                           \(\"subject\" . \"%s\"\)\)\)"
109   :type '(alist :key-type (string) :value-type (string))
110   :group 'notmuch-tree)
111
112 (defun notmuch-tree-result-format ()
113   (if notmuch-tree-unthreaded
114       notmuch-unthreaded-result-format
115     notmuch-tree-result-format))
116
117 ;; Faces for messages that match the query.
118 (defface notmuch-tree-match-face
119   '((t :inherit default))
120   "Default face used in tree mode face for matching messages"
121   :group 'notmuch-tree
122   :group 'notmuch-faces)
123
124 (defface notmuch-tree-match-date-face
125   nil
126   "Face used in tree mode for the date in messages matching the query."
127   :group 'notmuch-tree
128   :group 'notmuch-faces)
129
130 (defface notmuch-tree-match-author-face
131   '((((class color)
132       (background dark))
133      (:foreground "OliveDrab1"))
134     (((class color)
135       (background light))
136      (:foreground "dark blue"))
137     (t
138      (:bold t)))
139   "Face used in tree mode for the date in messages matching the query."
140   :group 'notmuch-tree
141   :group 'notmuch-faces)
142
143 (defface notmuch-tree-match-subject-face
144   nil
145   "Face used in tree mode for the subject in messages matching the query."
146   :group 'notmuch-tree
147   :group 'notmuch-faces)
148
149 (defface notmuch-tree-match-tree-face
150   nil
151   "Face used in tree mode for the thread tree block graphics in messages matching the query."
152   :group 'notmuch-tree
153   :group 'notmuch-faces)
154
155 (defface notmuch-tree-match-tag-face
156   '((((class color)
157       (background dark))
158      (:foreground "OliveDrab1"))
159     (((class color)
160       (background light))
161      (:foreground "navy blue" :bold t))
162     (t
163      (:bold t)))
164   "Face used in tree mode for tags in messages matching the query."
165   :group 'notmuch-tree
166   :group 'notmuch-faces)
167
168 ;; Faces for messages that do not match the query.
169 (defface notmuch-tree-no-match-face
170   '((t (:foreground "gray")))
171   "Default face used in tree mode face for non-matching messages."
172   :group 'notmuch-tree
173   :group 'notmuch-faces)
174
175 (defface notmuch-tree-no-match-date-face
176   nil
177   "Face used in tree mode for non-matching dates."
178   :group 'notmuch-tree
179   :group 'notmuch-faces)
180
181 (defface notmuch-tree-no-match-subject-face
182   nil
183   "Face used in tree mode for non-matching subjects."
184   :group 'notmuch-tree
185   :group 'notmuch-faces)
186
187 (defface notmuch-tree-no-match-tree-face
188   nil
189   "Face used in tree mode for the thread tree block graphics in messages matching the query."
190   :group 'notmuch-tree
191   :group 'notmuch-faces)
192
193 (defface notmuch-tree-no-match-author-face
194   nil
195   "Face used in tree mode for the date in messages matching the query."
196   :group 'notmuch-tree
197   :group 'notmuch-faces)
198
199 (defface notmuch-tree-no-match-tag-face
200   nil
201   "Face used in tree mode face for non-matching tags."
202   :group 'notmuch-tree
203   :group 'notmuch-faces)
204
205 (defvar notmuch-tree-previous-subject
206   "The subject of the most recent result shown during the async display.")
207 (make-variable-buffer-local 'notmuch-tree-previous-subject)
208
209 (defvar notmuch-tree-basic-query nil
210   "A buffer local copy of argument query to the function notmuch-tree.")
211 (make-variable-buffer-local 'notmuch-tree-basic-query)
212
213 (defvar notmuch-tree-query-context nil
214   "A buffer local copy of argument query-context to the function notmuch-tree.")
215 (make-variable-buffer-local 'notmuch-tree-query-context)
216
217 (defvar notmuch-tree-target-msg nil
218   "A buffer local copy of argument target to the function notmuch-tree.")
219 (make-variable-buffer-local 'notmuch-tree-target-msg)
220
221 (defvar notmuch-tree-open-target nil
222   "A buffer local copy of argument open-target to the function notmuch-tree.")
223 (make-variable-buffer-local 'notmuch-tree-open-target)
224
225 (defvar notmuch-tree-parent-buffer nil)
226 (make-variable-buffer-local 'notmuch-tree-parent-buffer)
227
228 (defvar notmuch-tree-message-window nil
229   "The window of the message pane.
230
231 It is set in both the tree buffer and the child show buffer. It
232 is used to try and close the message pane when quitting tree view
233 or the child show buffer.")
234 (make-variable-buffer-local 'notmuch-tree-message-window)
235 (put 'notmuch-tree-message-window 'permanent-local t)
236
237 (defvar notmuch-tree-message-buffer nil
238   "The buffer name of the show buffer in the message pane.
239
240 This is used to try and make sure we don't close the message pane
241 if the user has loaded a different buffer in that window.")
242 (make-variable-buffer-local 'notmuch-tree-message-buffer)
243 (put 'notmuch-tree-message-buffer 'permanent-local t)
244
245 (defun notmuch-tree-to-message-pane (func)
246   "Execute FUNC in message pane.
247
248 This function returns a function (so can be used as a keybinding)
249 which executes function FUNC in the message pane if it is
250 open (if the message pane is closed it does nothing)."
251   `(lambda ()
252      ,(concat "(In message pane) " (documentation func t))
253      (interactive)
254      (when (window-live-p notmuch-tree-message-window)
255        (with-selected-window notmuch-tree-message-window
256          (call-interactively #',func)))))
257
258 (defun notmuch-tree-inherit-from-message-pane (sym)
259   "Return value of SYM in message-pane if open, or tree-pane if not."
260   (if (window-live-p notmuch-tree-message-window)
261       (with-selected-window notmuch-tree-message-window
262         (symbol-value sym))
263     (symbol-value sym)))
264
265 (defun notmuch-tree-button-activate (&optional button)
266   "Activate BUTTON or button at point.
267
268 This function does not give an error if there is no button."
269   (interactive)
270   (let ((button (or button (button-at (point)))))
271     (when button (button-activate button))))
272
273 (defun notmuch-tree-close-message-pane-and (func)
274   "Close message pane and execute FUNC.
275
276 This function returns a function (so can be used as a keybinding)
277 which closes the message pane if open and then executes function
278 FUNC."
279   `(lambda ()
280      ,(concat "(Close message pane and) " (documentation func t))
281      (interactive)
282      (let ((notmuch-show-process-crypto
283             (notmuch-tree-inherit-from-message-pane 'notmuch-show-process-crypto)))
284        (notmuch-tree-close-message-window)
285        (call-interactively #',func))))
286
287 (defvar notmuch-tree-mode-map
288   (let ((map (make-sparse-keymap)))
289     (set-keymap-parent map notmuch-common-keymap)
290     ;; The following override the global keymap.
291     ;; Override because we want to close message pane first.
292     (define-key map [remap notmuch-help]
293       (notmuch-tree-close-message-pane-and #'notmuch-help))
294     ;; Override because we first close message pane and then close tree buffer.
295     (define-key map [remap notmuch-bury-or-kill-this-buffer] 'notmuch-tree-quit)
296     ;; Override because we close message pane after the search query is entered.
297     (define-key map [remap notmuch-search] 'notmuch-tree-to-search)
298     ;; Override because we want to close message pane first.
299     (define-key map [remap notmuch-mua-new-mail]
300       (notmuch-tree-close-message-pane-and #'notmuch-mua-new-mail))
301     ;; Override because we want to close message pane first.
302     (define-key map [remap notmuch-jump-search]
303       (notmuch-tree-close-message-pane-and #'notmuch-jump-search))
304
305     (define-key map "S" 'notmuch-search-from-tree-current-query)
306     (define-key map "U" 'notmuch-unthreaded-from-tree-current-query)
307     (define-key map "Z" 'notmuch-tree-from-unthreaded-current-query)
308
309     ;; these use notmuch-show functions directly
310     (define-key map "|" 'notmuch-show-pipe-message)
311     (define-key map "w" 'notmuch-show-save-attachments)
312     (define-key map "v" 'notmuch-show-view-all-mime-parts)
313     (define-key map "c" 'notmuch-show-stash-map)
314     (define-key map "b" 'notmuch-show-resend-message)
315
316     ;; these apply to the message pane
317     (define-key map (kbd "M-TAB")
318       (notmuch-tree-to-message-pane #'notmuch-show-previous-button))
319     (define-key map (kbd "<backtab>")
320       (notmuch-tree-to-message-pane #'notmuch-show-previous-button))
321     (define-key map (kbd "TAB")
322       (notmuch-tree-to-message-pane #'notmuch-show-next-button))
323     (define-key map "$"
324       (notmuch-tree-to-message-pane #'notmuch-show-toggle-process-crypto))
325
326     ;; bindings from show (or elsewhere) but we close the message pane first.
327     (define-key map "f"
328       (notmuch-tree-close-message-pane-and #'notmuch-show-forward-message))
329     (define-key map "r"
330       (notmuch-tree-close-message-pane-and #'notmuch-show-reply-sender))
331     (define-key map "R"
332       (notmuch-tree-close-message-pane-and #'notmuch-show-reply))
333     (define-key map "V"
334       (notmuch-tree-close-message-pane-and #'notmuch-show-view-raw-message))
335
336     ;; The main tree view bindings
337     (define-key map (kbd "RET") 'notmuch-tree-show-message)
338     (define-key map [mouse-1] 'notmuch-tree-show-message)
339     (define-key map "x" 'notmuch-tree-archive-message-then-next-or-exit)
340     (define-key map "X" 'notmuch-tree-archive-thread-then-exit)
341     (define-key map "A" 'notmuch-tree-archive-thread)
342     (define-key map "a" 'notmuch-tree-archive-message-then-next)
343     (define-key map "z" 'notmuch-tree-to-tree)
344     (define-key map "n" 'notmuch-tree-next-matching-message)
345     (define-key map "p" 'notmuch-tree-prev-matching-message)
346     (define-key map "N" 'notmuch-tree-next-message)
347     (define-key map "P" 'notmuch-tree-prev-message)
348     (define-key map (kbd "M-p") 'notmuch-tree-prev-thread)
349     (define-key map (kbd "M-n") 'notmuch-tree-next-thread)
350     (define-key map "k" 'notmuch-tag-jump)
351     (define-key map "-" 'notmuch-tree-remove-tag)
352     (define-key map "+" 'notmuch-tree-add-tag)
353     (define-key map "*" 'notmuch-tree-tag-thread)
354     (define-key map " " 'notmuch-tree-scroll-or-next)
355     (define-key map (kbd "DEL") 'notmuch-tree-scroll-message-window-back)
356     (define-key map "e" 'notmuch-tree-resume-message)
357     map))
358 (fset 'notmuch-tree-mode-map notmuch-tree-mode-map)
359
360 (defun notmuch-tree-get-message-properties ()
361   "Return the properties of the current message as a plist.
362
363 Some useful entries are:
364 :headers - Property list containing the headers :Date, :Subject, :From, etc.
365 :tags - Tags for this message."
366   (save-excursion
367     (beginning-of-line)
368     (get-text-property (point) :notmuch-message-properties)))
369
370 (defun notmuch-tree-set-message-properties (props)
371   (save-excursion
372     (beginning-of-line)
373     (put-text-property (point)
374                        (+ (point) 1)
375                        :notmuch-message-properties props)))
376
377 (defun notmuch-tree-set-prop (prop val &optional props)
378   (let ((inhibit-read-only t)
379         (props (or props
380                    (notmuch-tree-get-message-properties))))
381     (plist-put props prop val)
382     (notmuch-tree-set-message-properties props)))
383
384 (defun notmuch-tree-get-prop (prop &optional props)
385   (let ((props (or props
386                    (notmuch-tree-get-message-properties))))
387     (plist-get props prop)))
388
389 (defun notmuch-tree-set-tags (tags)
390   "Set the tags of the current message."
391   (notmuch-tree-set-prop :tags tags))
392
393 (defun notmuch-tree-get-tags ()
394   "Return the tags of the current message."
395   (notmuch-tree-get-prop :tags))
396
397 (defun notmuch-tree-get-message-id (&optional bare)
398   "Return the message id of the current message."
399   (let ((id (notmuch-tree-get-prop :id)))
400     (if id
401         (if bare
402             id
403           (notmuch-id-to-query id))
404       nil)))
405
406 (defun notmuch-tree-get-match ()
407   "Return whether the current message is a match."
408   (interactive)
409   (notmuch-tree-get-prop :match))
410
411 (defun notmuch-tree-refresh-result ()
412   "Redisplay the current message line.
413
414 This redisplays the current line based on the messages
415 properties (as they are now). This is used when tags are
416 updated."
417   (let ((init-point (point))
418         (end (line-end-position))
419         (msg (notmuch-tree-get-message-properties))
420         (inhibit-read-only t))
421     (beginning-of-line)
422     ;; This is a little tricky: we override
423     ;; notmuch-tree-previous-subject to get the decision between
424     ;; ... and a subject right and it stops notmuch-tree-insert-msg
425     ;; from overwriting the buffer local copy of
426     ;; notmuch-tree-previous-subject if this is called while the
427     ;; buffer is displaying.
428     (let ((notmuch-tree-previous-subject
429            (notmuch-tree-get-prop :previous-subject)))
430       (delete-region (point) (1+ (line-end-position)))
431       (notmuch-tree-insert-msg msg))
432     (let ((new-end (line-end-position)))
433       (goto-char (if (= init-point end)
434                      new-end
435                    (min init-point (- new-end 1)))))))
436
437 (defun notmuch-tree-tag-update-display (&optional tag-changes)
438   "Update display for TAG-CHANGES to current message.
439
440 Updates the message in the message pane if appropriate, but does
441 NOT change the database."
442   (let* ((current-tags (notmuch-tree-get-tags))
443          (new-tags (notmuch-update-tags current-tags tag-changes))
444          (tree-msg-id (notmuch-tree-get-message-id)))
445     (unless (equal current-tags new-tags)
446       (notmuch-tree-set-tags new-tags)
447       (notmuch-tree-refresh-result)
448       (when (window-live-p notmuch-tree-message-window)
449         (with-selected-window notmuch-tree-message-window
450           (when (string= tree-msg-id (notmuch-show-get-message-id))
451             (notmuch-show-update-tags new-tags)))))))
452
453 (defun notmuch-tree-tag (tag-changes)
454   "Change tags for the current message."
455   (interactive
456    (list (notmuch-read-tag-changes (notmuch-tree-get-tags) "Tag message")))
457   (notmuch-tag (notmuch-tree-get-message-id) tag-changes)
458   (notmuch-tree-tag-update-display tag-changes))
459
460 (defun notmuch-tree-add-tag (tag-changes)
461   "Same as `notmuch-tree-tag' but sets initial input to '+'."
462   (interactive
463    (list (notmuch-read-tag-changes (notmuch-tree-get-tags) "Tag message" "+")))
464   (notmuch-tree-tag tag-changes))
465
466 (defun notmuch-tree-remove-tag (tag-changes)
467   "Same as `notmuch-tree-tag' but sets initial input to '-'."
468   (interactive
469    (list (notmuch-read-tag-changes (notmuch-tree-get-tags) "Tag message" "-")))
470   (notmuch-tree-tag tag-changes))
471
472 (defun notmuch-tree-resume-message ()
473   "Resume EDITING the current draft message."
474   (interactive)
475   (notmuch-tree-close-message-window)
476   (let ((id (notmuch-tree-get-message-id)))
477     (if id
478         (notmuch-draft-resume id)
479       (message "No message to resume!"))))
480
481 ;; The next two functions close the message window before calling
482 ;; notmuch-search or notmuch-tree but they do so after the user has
483 ;; entered the query (in case the user was basing the query on
484 ;; something in the message window).
485
486 (defun notmuch-tree-to-search ()
487   "Run \"notmuch search\" with the given `query' and display results."
488   (interactive)
489   (let ((query (notmuch-read-query "Notmuch search: ")))
490     (notmuch-tree-close-message-window)
491     (notmuch-search query)))
492
493 (defun notmuch-tree-to-tree ()
494   "Run a query and display results in tree view."
495   (interactive)
496   (let ((query (notmuch-read-query "Notmuch tree view search: ")))
497     (notmuch-tree-close-message-window)
498     (notmuch-tree query)))
499
500 (defun notmuch-unthreaded-from-tree-current-query ()
501   "Switch from tree view to unthreaded view."
502   (interactive)
503   (unless notmuch-tree-unthreaded
504     (notmuch-tree-refresh-view 'unthreaded)))
505
506 (defun notmuch-tree-from-unthreaded-current-query ()
507   "Switch from unthreaded view to tree view."
508   (interactive)
509   (when notmuch-tree-unthreaded
510     (notmuch-tree-refresh-view 'tree)))
511
512 (defun notmuch-search-from-tree-current-query ()
513   "Call notmuch search with the current query."
514   (interactive)
515   (notmuch-tree-close-message-window)
516   (notmuch-search (notmuch-tree-get-query)))
517
518 (defun notmuch-tree-message-window-kill-hook ()
519   "Close the message pane when exiting the show buffer."
520   (let ((buffer (current-buffer)))
521     (when (and (window-live-p notmuch-tree-message-window)
522                (eq (window-buffer notmuch-tree-message-window) buffer))
523       ;; We do not want an error if this is the sole window in the
524       ;; frame and I do not know how to test for that in emacs pre
525       ;; 24. Hence we just ignore-errors.
526       (ignore-errors
527         (delete-window notmuch-tree-message-window)))))
528
529 (defun notmuch-tree-command-hook ()
530   (when (eq major-mode 'notmuch-tree-mode)
531     ;; We just run the notmuch-show-command-hook on the message pane.
532     (when (buffer-live-p notmuch-tree-message-buffer)
533       (with-current-buffer notmuch-tree-message-buffer
534         (notmuch-show-command-hook)))))
535
536 (defun notmuch-tree-show-message-in ()
537   "Show the current message (in split-pane)."
538   (interactive)
539   (let ((id (notmuch-tree-get-message-id))
540         (inhibit-read-only t)
541         buffer)
542     (when id
543       ;; We close and reopen the window to kill off un-needed buffers
544       ;; this might cause flickering but seems ok.
545       (notmuch-tree-close-message-window)
546       (setq notmuch-tree-message-window
547             (split-window-vertically (/ (window-height) 4)))
548       (with-selected-window notmuch-tree-message-window
549         ;; Since we are only displaying one message do not indent.
550         (let ((notmuch-show-indent-messages-width 0)
551               (notmuch-show-only-matching-messages t))
552           (setq buffer (notmuch-show id))))
553       ;; We need the `let' as notmuch-tree-message-window is buffer local.
554       (let ((window notmuch-tree-message-window))
555         (with-current-buffer buffer
556           (setq notmuch-tree-message-window window)
557           (add-hook 'kill-buffer-hook 'notmuch-tree-message-window-kill-hook)))
558       (when notmuch-show-mark-read-tags
559         (notmuch-tree-tag-update-display notmuch-show-mark-read-tags))
560       (setq notmuch-tree-message-buffer buffer))))
561
562 (defun notmuch-tree-show-message-out ()
563   "Show the current message (in whole window)."
564   (interactive)
565   (let ((id (notmuch-tree-get-message-id))
566         (inhibit-read-only t)
567         buffer)
568     (when id
569       ;; We close the window to kill off un-needed buffers.
570       (notmuch-tree-close-message-window)
571       (notmuch-show id))))
572
573 (defun notmuch-tree-show-message (arg)
574   "Show the current message.
575
576 Shows in split pane or whole window according to value of
577 `notmuch-tree-show-out'. A prefix argument reverses the choice."
578   (interactive "P")
579   (if (or (and (notmuch-tree-show-out) (not arg))
580           (and (not (notmuch-tree-show-out)) arg))
581       (notmuch-tree-show-message-out)
582     (notmuch-tree-show-message-in)))
583
584 (defun notmuch-tree-scroll-message-window ()
585   "Scroll the message window (if it exists)."
586   (interactive)
587   (when (window-live-p notmuch-tree-message-window)
588     (with-selected-window notmuch-tree-message-window
589       (if (pos-visible-in-window-p (point-max))
590           t
591         (scroll-up)))))
592
593 (defun notmuch-tree-scroll-message-window-back ()
594   "Scroll the message window back (if it exists)."
595   (interactive)
596   (when (window-live-p notmuch-tree-message-window)
597     (with-selected-window notmuch-tree-message-window
598       (if (pos-visible-in-window-p (point-min))
599           t
600         (scroll-down)))))
601
602 (defun notmuch-tree-scroll-or-next ()
603   "Scroll the message window.
604 If it at end go to next message."
605   (interactive)
606   (when (notmuch-tree-scroll-message-window)
607     (notmuch-tree-next-matching-message)))
608
609 (defun notmuch-tree-quit (&optional kill-both)
610   "Close the split view or exit tree."
611   (interactive "P")
612   (when (or (not (notmuch-tree-close-message-window)) kill-both)
613     (kill-buffer (current-buffer))))
614
615 (defun notmuch-tree-close-message-window ()
616   "Close the message-window. Return t if close succeeds."
617   (interactive)
618   (when (and (window-live-p notmuch-tree-message-window)
619              (eq (window-buffer notmuch-tree-message-window)
620                  notmuch-tree-message-buffer))
621     (delete-window notmuch-tree-message-window)
622     (unless (get-buffer-window-list notmuch-tree-message-buffer)
623       (kill-buffer notmuch-tree-message-buffer))
624     t))
625
626 (defun notmuch-tree-archive-message (&optional unarchive)
627   "Archive the current message.
628
629 Archive the current message by applying the tag changes in
630 `notmuch-archive-tags' to it. If a prefix argument is given, the
631 message will be \"unarchived\", i.e. the tag changes in
632 `notmuch-archive-tags' will be reversed."
633   (interactive "P")
634   (when notmuch-archive-tags
635     (notmuch-tree-tag
636      (notmuch-tag-change-list notmuch-archive-tags unarchive))))
637
638 (defun notmuch-tree-archive-message-then-next (&optional unarchive)
639   "Archive the current message and move to next matching message."
640   (interactive "P")
641   (notmuch-tree-archive-message unarchive)
642   (notmuch-tree-next-matching-message))
643
644 (defun notmuch-tree-archive-thread-then-exit ()
645   "Archive all messages in the current buffer, then exit notmuch-tree."
646   (interactive)
647   (notmuch-tree-archive-thread)
648   (notmuch-tree-quit t))
649
650 (defun notmuch-tree-archive-message-then-next-or-exit ()
651   "Archive current message, then show next open message in current thread.
652
653 If at the last open message in the current thread, then exit back
654 to search results."
655   (interactive)
656   (notmuch-tree-archive-message)
657   (notmuch-tree-next-matching-message t))
658
659 (defun notmuch-tree-next-message ()
660   "Move to next message."
661   (interactive)
662   (forward-line)
663   (when (window-live-p notmuch-tree-message-window)
664     (notmuch-tree-show-message-in)))
665
666 (defun notmuch-tree-prev-message ()
667   "Move to previous message."
668   (interactive)
669   (forward-line -1)
670   (when (window-live-p notmuch-tree-message-window)
671     (notmuch-tree-show-message-in)))
672
673 (defun notmuch-tree-goto-matching-message (&optional prev)
674   "Move to the next or previous matching message.
675
676 Returns t if there was a next matching message in the thread to show,
677 nil otherwise."
678   (let ((dir (if prev -1 nil))
679         (eobfn (if prev #'bobp #'eobp)))
680     (while (and (not (funcall eobfn))
681                 (not (notmuch-tree-get-match)))
682       (forward-line dir))
683     (not (funcall eobfn))))
684
685 (defun notmuch-tree-matching-message (&optional prev pop-at-end)
686   "Move to the next or previous matching message."
687   (interactive "P")
688   (forward-line (if prev -1 nil))
689   (if (and (not (notmuch-tree-goto-matching-message prev)) pop-at-end)
690       (notmuch-tree-quit pop-at-end)
691     (when (window-live-p notmuch-tree-message-window)
692       (notmuch-tree-show-message-in))))
693
694 (defun notmuch-tree-prev-matching-message (&optional pop-at-end)
695   "Move to previous matching message."
696   (interactive "P")
697   (notmuch-tree-matching-message t pop-at-end))
698
699 (defun notmuch-tree-next-matching-message (&optional pop-at-end)
700   "Move to next matching message."
701   (interactive "P")
702   (notmuch-tree-matching-message nil pop-at-end))
703
704 (defun notmuch-tree-refresh-view (&optional view)
705   "Refresh view."
706   (interactive)
707   (when (get-buffer-process (current-buffer))
708     (error "notmuch tree process already running for current buffer"))
709   (let ((inhibit-read-only t)
710         (basic-query notmuch-tree-basic-query)
711         (unthreaded (cond ((eq view 'unthreaded) t)
712                           ((eq view 'tree) nil)
713                           (t notmuch-tree-unthreaded)))
714         (query-context notmuch-tree-query-context)
715         (target (notmuch-tree-get-message-id)))
716     (erase-buffer)
717     (notmuch-tree-worker basic-query
718                          query-context
719                          target
720                          nil
721                          unthreaded)))
722
723 (defun notmuch-tree-thread-top ()
724   (when (notmuch-tree-get-message-properties)
725     (while (not (or (notmuch-tree-get-prop :first) (eobp)))
726       (forward-line -1))))
727
728 (defun notmuch-tree-prev-thread ()
729   (interactive)
730   (forward-line -1)
731   (notmuch-tree-thread-top))
732
733 (defun notmuch-tree-next-thread ()
734   "Get the next thread in the current tree. Returns t if a thread was
735 found or nil if not."
736   (interactive)
737   (forward-line 1)
738   (while (not (or (notmuch-tree-get-prop :first) (eobp)))
739     (forward-line 1))
740   (not (eobp)))
741
742 (defun notmuch-tree-thread-mapcar (function)
743   "Iterate through all messages in the current thread
744  and call FUNCTION for side effects."
745   (save-excursion
746     (notmuch-tree-thread-top)
747     (cl-loop collect (funcall function)
748              do (forward-line)
749              while (and (notmuch-tree-get-message-properties)
750                         (not (notmuch-tree-get-prop :first))))))
751
752 (defun notmuch-tree-get-messages-ids-thread-search ()
753   "Return a search string for all message ids of messages in the current thread."
754   (mapconcat 'identity
755              (notmuch-tree-thread-mapcar 'notmuch-tree-get-message-id)
756              " or "))
757
758 (defun notmuch-tree-tag-thread (tag-changes)
759   "Tag all messages in the current thread."
760   (interactive
761    (let ((tags (apply #'append (notmuch-tree-thread-mapcar
762                                 (lambda () (notmuch-tree-get-tags))))))
763      (list (notmuch-read-tag-changes tags "Tag thread"))))
764   (when (notmuch-tree-get-message-properties)
765     (notmuch-tag (notmuch-tree-get-messages-ids-thread-search) tag-changes)
766     (notmuch-tree-thread-mapcar
767      (lambda () (notmuch-tree-tag-update-display tag-changes)))))
768
769 (defun notmuch-tree-archive-thread (&optional unarchive)
770   "Archive each message in thread.
771
772 Archive each message currently shown by applying the tag changes
773 in `notmuch-archive-tags' to each. If a prefix argument is given,
774 the messages will be \"unarchived\", i.e. the tag changes in
775 `notmuch-archive-tags' will be reversed.
776
777 Note: This command is safe from any race condition of new messages
778 being delivered to the same thread. It does not archive the
779 entire thread, but only the messages shown in the current
780 buffer."
781   (interactive "P")
782   (when notmuch-archive-tags
783     (notmuch-tree-tag-thread
784      (notmuch-tag-change-list notmuch-archive-tags unarchive))))
785
786 ;; Functions below here display the tree buffer itself.
787
788 (defun notmuch-tree-clean-address (address)
789   "Try to clean a single email ADDRESS for display. Return
790 AUTHOR_NAME if present, otherwise return AUTHOR_EMAIL. Return
791 unchanged ADDRESS if parsing fails."
792   (let* ((clean-address (notmuch-clean-address address))
793          (p-address (car clean-address))
794          (p-name (cdr clean-address)))
795
796     ;; If we have a name return that otherwise return the address.
797     (or p-name p-address)))
798
799 (defun notmuch-tree-format-field (field format-string msg)
800   "Format a FIELD of MSG according to FORMAT-STRING and return string."
801   (let* ((headers (plist-get msg :headers))
802          (match (plist-get msg :match)))
803     (cond
804      ((listp field)
805       (format format-string (notmuch-tree-format-field-list field msg)))
806
807      ((string-equal field "date")
808       (let ((face (if match
809                       'notmuch-tree-match-date-face
810                     'notmuch-tree-no-match-date-face)))
811         (propertize (format format-string (plist-get msg :date_relative))
812                     'face face)))
813
814      ((string-equal field "tree")
815       (let ((tree-status (plist-get msg :tree-status))
816             (face (if match
817                       'notmuch-tree-match-tree-face
818                     'notmuch-tree-no-match-tree-face)))
819
820         (propertize (format format-string
821                             (mapconcat #'identity (reverse tree-status) ""))
822                     'face face)))
823
824      ((string-equal field "subject")
825       (let ((bare-subject (notmuch-show-strip-re (plist-get headers :Subject)))
826             (previous-subject notmuch-tree-previous-subject)
827             (face (if match
828                       'notmuch-tree-match-subject-face
829                     'notmuch-tree-no-match-subject-face)))
830
831         (setq notmuch-tree-previous-subject bare-subject)
832         (propertize (format format-string
833                             (if (string= previous-subject bare-subject)
834                                 " ..."
835                               bare-subject))
836                     'face face)))
837
838      ((string-equal field "authors")
839       (let ((author (notmuch-tree-clean-address (plist-get headers :From)))
840             (len (length (format format-string "")))
841             (face (if match
842                       'notmuch-tree-match-author-face
843                     'notmuch-tree-no-match-author-face)))
844         (when (> (length author) len)
845           (setq author (substring author 0 len)))
846         (propertize (format format-string author) 'face face)))
847
848      ((string-equal field "tags")
849       (let ((tags (plist-get msg :tags))
850             (orig-tags (plist-get msg :orig-tags))
851             (face (if match
852                       'notmuch-tree-match-tag-face
853                     'notmuch-tree-no-match-tag-face)))
854         (format format-string (notmuch-tag-format-tags tags orig-tags face)))))))
855
856 (defun notmuch-tree-format-field-list (field-list msg)
857   "Format fields of MSG according to FIELD-LIST and return string."
858   (let ((face (if (plist-get msg :match)
859                   'notmuch-tree-match-face
860                 'notmuch-tree-no-match-face))
861         (result-string))
862     (dolist (spec field-list result-string)
863       (let ((field-string (notmuch-tree-format-field (car spec) (cdr spec) msg)))
864         (setq result-string (concat result-string field-string))))
865     (notmuch-apply-face result-string face t)))
866
867 (defun notmuch-tree-insert-msg (msg)
868   "Insert the message MSG according to notmuch-tree-result-format."
869   ;; We need to save the previous subject as it will get overwritten
870   ;; by the insert-field calls.
871   (let ((previous-subject notmuch-tree-previous-subject))
872     (insert (notmuch-tree-format-field-list (notmuch-tree-result-format) msg))
873     (notmuch-tree-set-message-properties msg)
874     (notmuch-tree-set-prop :previous-subject previous-subject)
875     (insert "\n")))
876
877 (defun notmuch-tree-goto-and-insert-msg (msg)
878   "Insert msg at the end of the buffer. Move point to msg if it is the target."
879   (save-excursion
880     (goto-char (point-max))
881     (notmuch-tree-insert-msg msg))
882   (let ((msg-id (notmuch-id-to-query (plist-get msg :id)))
883         (target notmuch-tree-target-msg))
884     (when (or (and (not target) (plist-get msg :match))
885               (string= msg-id target))
886       (setq notmuch-tree-target-msg "found")
887       (goto-char (point-max))
888       (forward-line -1)
889       (when notmuch-tree-open-target
890         (notmuch-tree-show-message-in)))))
891
892 (defun notmuch-tree-insert-tree (tree depth tree-status first last)
893   "Insert the message tree TREE at depth DEPTH in the current thread.
894
895 A message tree is another name for a single sub-thread: i.e., a
896 message together with all its descendents."
897   (let ((msg (car tree))
898         (replies (cadr tree)))
899     (cond
900      ((and (< 0 depth) (not last))
901       (push "├" tree-status))
902      ((and (< 0 depth) last)
903       (push "╰" tree-status))
904      ((and (eq 0 depth) first last)
905       ;; Choice between these two variants is a matter of taste.
906       ;; (push "─" tree-status))
907       (push " " tree-status))
908      ((and (eq 0 depth) first (not last))
909       (push "┬" tree-status))
910      ((and (eq 0 depth) (not first) last)
911       (push "╰" tree-status))
912      ((and (eq 0 depth) (not first) (not last))
913       (push "├" tree-status)))
914     (push (concat (if replies "┬" "─") "►") tree-status)
915     (setq msg (plist-put msg :first (and first (eq 0 depth))))
916     (setq msg (plist-put msg :tree-status tree-status))
917     (setq msg (plist-put msg :orig-tags (plist-get msg :tags)))
918     (notmuch-tree-goto-and-insert-msg msg)
919     (pop tree-status)
920     (pop tree-status)
921     (if last
922         (push " " tree-status)
923       (push "│" tree-status))
924     (notmuch-tree-insert-thread replies (1+ depth) tree-status)))
925
926 (defun notmuch-tree-insert-thread (thread depth tree-status)
927   "Insert the collection of sibling sub-threads THREAD at depth DEPTH in the current forest."
928   (let ((n (length thread)))
929     (cl-loop for tree in thread
930              for count from 1 to n
931              do (notmuch-tree-insert-tree tree depth tree-status
932                                           (eq count 1)
933                                           (eq count n)))))
934
935 (defun notmuch-tree-insert-forest-thread (forest-thread)
936   "Insert a single complete thread."
937   (let (tree-status)
938     ;; Reset at the start of each main thread.
939     (setq notmuch-tree-previous-subject nil)
940     (notmuch-tree-insert-thread forest-thread 0 tree-status)))
941
942 (defun notmuch-tree-insert-forest (forest)
943   "Insert a forest of threads.
944
945 This function inserts a collection of several complete threads as
946 passed to it by notmuch-tree-process-filter."
947   (mapc 'notmuch-tree-insert-forest-thread forest))
948
949 (define-derived-mode notmuch-tree-mode fundamental-mode "notmuch-tree"
950   "Major mode displaying messages (as opposed to threads) of a notmuch search.
951
952 This buffer contains the results of a \"notmuch tree\" of your
953 email archives. Each line in the buffer represents a single
954 message giving the relative date, the author, subject, and any
955 tags.
956
957 Pressing \\[notmuch-tree-show-message] on any line displays that message.
958
959 Complete list of currently available key bindings:
960
961 \\{notmuch-tree-mode-map}"
962   (setq notmuch-buffer-refresh-function #'notmuch-tree-refresh-view)
963   (hl-line-mode 1)
964   (setq buffer-read-only t)
965   (setq truncate-lines t))
966
967 (defun notmuch-tree-process-sentinel (proc msg)
968   "Add a message to let user know when \"notmuch tree\" exits."
969   (let ((buffer (process-buffer proc))
970         (status (process-status proc))
971         (exit-status (process-exit-status proc))
972         (never-found-target-thread nil))
973     (when (memq status '(exit signal))
974       (kill-buffer (process-get proc 'parse-buf))
975       (when (buffer-live-p buffer)
976         (with-current-buffer buffer
977           (save-excursion
978             (let ((inhibit-read-only t)
979                   (atbob (bobp)))
980               (goto-char (point-max))
981               (when (eq status 'signal)
982                 (insert "Incomplete search results (tree view process was killed).\n"))
983               (when (eq status 'exit)
984                 (insert "End of search results.")
985                 (unless (= exit-status 0)
986                   (insert (format " (process returned %d)" exit-status)))
987                 (insert "\n")))))))))
988
989 (defun notmuch-tree-process-filter (proc string)
990   "Process and filter the output of \"notmuch show\" for tree view."
991   (let ((results-buf (process-buffer proc))
992         (parse-buf (process-get proc 'parse-buf))
993         (inhibit-read-only t)
994         done)
995     (if (not (buffer-live-p results-buf))
996         (delete-process proc)
997       (with-current-buffer parse-buf
998         ;; Insert new data
999         (save-excursion
1000           (goto-char (point-max))
1001           (insert string))
1002         (notmuch-sexp-parse-partial-list 'notmuch-tree-insert-forest-thread
1003                                          results-buf)))))
1004
1005 (defun notmuch-tree-worker (basic-query &optional query-context target open-target unthreaded)
1006   "Insert the tree view of the search in the current buffer.
1007
1008 This is is a helper function for notmuch-tree. The arguments are
1009 the same as for the function notmuch-tree."
1010   (interactive)
1011   (notmuch-tree-mode)
1012   (add-hook 'post-command-hook #'notmuch-tree-command-hook t t)
1013   (setq notmuch-tree-unthreaded unthreaded)
1014   (setq notmuch-tree-basic-query basic-query)
1015   (setq notmuch-tree-query-context (if (or (string= query-context "")
1016                                            (string= query-context "*"))
1017                                        nil
1018                                      query-context))
1019   (setq notmuch-tree-target-msg target)
1020   (setq notmuch-tree-open-target open-target)
1021   ;; Set the default value for `notmuch-show-process-crypto' in this
1022   ;; buffer. Although we don't use this some of the functions we call
1023   ;; (such as reply) do. It is a buffer local variable so setting it
1024   ;; will not affect genuine show buffers.
1025   (setq notmuch-show-process-crypto notmuch-crypto-process-mime)
1026   (erase-buffer)
1027   (goto-char (point-min))
1028   (let* ((search-args (concat basic-query
1029                               (and query-context
1030                                    (concat " and (" query-context ")"))))
1031          (message-arg (if unthreaded "--unthreaded" "--entire-thread")))
1032     (when (equal (car (process-lines notmuch-command "count" search-args)) "0")
1033       (setq search-args basic-query))
1034     (notmuch-tag-clear-cache)
1035     (let ((proc (notmuch-start-notmuch
1036                  "notmuch-tree" (current-buffer) #'notmuch-tree-process-sentinel
1037                  "show" "--body=false" "--format=sexp" "--format-version=4"
1038                  message-arg search-args))
1039           ;; Use a scratch buffer to accumulate partial output.
1040           ;; This buffer will be killed by the sentinel, which
1041           ;; should be called no matter how the process dies.
1042           (parse-buf (generate-new-buffer " *notmuch tree parse*")))
1043       (process-put proc 'parse-buf parse-buf)
1044       (set-process-filter proc 'notmuch-tree-process-filter)
1045       (set-process-query-on-exit-flag proc nil))))
1046
1047 (defun notmuch-tree-get-query ()
1048   "Return the current query in this tree buffer."
1049   (if notmuch-tree-query-context
1050       (concat notmuch-tree-basic-query
1051               " and ("
1052               notmuch-tree-query-context
1053               ")")
1054     notmuch-tree-basic-query))
1055
1056 (defun notmuch-tree (&optional query query-context target buffer-name open-target unthreaded parent-buffer)
1057   "Display threads matching QUERY in tree view.
1058
1059 The arguments are:
1060   QUERY: the main query. This can be any query but in many cases will be
1061       a single thread. If nil this is read interactively from the minibuffer.
1062   QUERY-CONTEXT: is an additional term for the query. The query used
1063       is QUERY and QUERY-CONTEXT unless that does not match any messages
1064       in which case we fall back to just QUERY.
1065   TARGET: A message ID (with the id: prefix) that will be made
1066       current if it appears in the tree view results.
1067   BUFFER-NAME: the name of the buffer to display the tree view. If
1068       it is nil \"*notmuch-tree\" followed by QUERY is used.
1069   OPEN-TARGET: If TRUE open the target message in the message pane.
1070   UNTHREADED: If TRUE only show matching messages in an unthreaded view."
1071   (interactive)
1072   (unless query
1073     (setq query (notmuch-read-query (concat "Notmuch "
1074                                             (if unthreaded "unthreaded " "tree ")
1075                                             "view search: "))))
1076   (let ((buffer (get-buffer-create (generate-new-buffer-name
1077                                     (or buffer-name
1078                                         (concat "*notmuch-"
1079                                                 (if unthreaded "unthreaded-" "tree-")
1080                                                 query "*")))))
1081         (inhibit-read-only t))
1082     (switch-to-buffer buffer))
1083   ;; Don't track undo information for this buffer
1084   (set 'buffer-undo-list t)
1085   (notmuch-tree-worker query query-context target open-target unthreaded)
1086   (setq notmuch-tree-parent-buffer parent-buffer)
1087   (setq truncate-lines t))
1088
1089 (defun notmuch-unthreaded (&optional query query-context target buffer-name open-target)
1090   (interactive)
1091   (notmuch-tree query query-context target buffer-name open-target t))
1092
1093 ;;
1094
1095 (provide 'notmuch-tree)
1096
1097 ;;; notmuch-tree.el ends here