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