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