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