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