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