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