]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-tree.el
Merge tag 'debian/0.18.1-2'
[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-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     ;; these use notmuch-show functions directly
244     (define-key map "|" 'notmuch-show-pipe-message)
245     (define-key map "w" 'notmuch-show-save-attachments)
246     (define-key map "v" 'notmuch-show-view-all-mime-parts)
247     (define-key map "c" 'notmuch-show-stash-map)
248
249     ;; these apply to the message pane
250     (define-key map (kbd "M-TAB") (notmuch-tree-to-message-pane #'notmuch-show-previous-button))
251     (define-key map (kbd "<backtab>")  (notmuch-tree-to-message-pane #'notmuch-show-previous-button))
252     (define-key map (kbd "TAB") (notmuch-tree-to-message-pane #'notmuch-show-next-button))
253     (define-key map "e" (notmuch-tree-to-message-pane #'notmuch-tree-button-activate))
254
255     ;; bindings from show (or elsewhere) but we close the message pane first.
256     (define-key map "f" (notmuch-tree-close-message-pane-and #'notmuch-show-forward-message))
257     (define-key map "r" (notmuch-tree-close-message-pane-and #'notmuch-show-reply-sender))
258     (define-key map "R" (notmuch-tree-close-message-pane-and #'notmuch-show-reply))
259     (define-key map "V" (notmuch-tree-close-message-pane-and #'notmuch-show-view-raw-message))
260
261     ;; The main tree view bindings
262     (define-key map (kbd "RET") 'notmuch-tree-show-message)
263     (define-key map [mouse-1] 'notmuch-tree-show-message)
264     (define-key map "x" 'notmuch-tree-quit)
265     (define-key map "A" 'notmuch-tree-archive-thread)
266     (define-key map "a" 'notmuch-tree-archive-message-then-next)
267     (define-key map "=" 'notmuch-tree-refresh-view)
268     (define-key map "z" 'notmuch-tree-to-tree)
269     (define-key map "n" 'notmuch-tree-next-matching-message)
270     (define-key map "p" 'notmuch-tree-prev-matching-message)
271     (define-key map "N" 'notmuch-tree-next-message)
272     (define-key map "P" 'notmuch-tree-prev-message)
273     (define-key map (kbd "M-p") 'notmuch-tree-prev-thread)
274     (define-key map (kbd "M-n") 'notmuch-tree-next-thread)
275     (define-key map "-" 'notmuch-tree-remove-tag)
276     (define-key map "+" 'notmuch-tree-add-tag)
277     (define-key map "*" 'notmuch-tree-tag-thread)
278     (define-key map " " 'notmuch-tree-scroll-or-next)
279     (define-key map "b" 'notmuch-tree-scroll-message-window-back)
280     map))
281 (fset 'notmuch-tree-mode-map notmuch-tree-mode-map)
282
283 (defun notmuch-tree-get-message-properties ()
284   "Return the properties of the current message as a plist.
285
286 Some useful entries are:
287 :headers - Property list containing the headers :Date, :Subject, :From, etc.
288 :tags - Tags for this message"
289   (save-excursion
290     (beginning-of-line)
291     (get-text-property (point) :notmuch-message-properties)))
292
293 (defun notmuch-tree-set-message-properties (props)
294   (save-excursion
295     (beginning-of-line)
296     (put-text-property (point) (+ (point) 1) :notmuch-message-properties props)))
297
298 (defun notmuch-tree-set-prop (prop val &optional props)
299   (let ((inhibit-read-only t)
300         (props (or props
301                    (notmuch-tree-get-message-properties))))
302     (plist-put props prop val)
303     (notmuch-tree-set-message-properties props)))
304
305 (defun notmuch-tree-get-prop (prop &optional props)
306   (let ((props (or props
307                    (notmuch-tree-get-message-properties))))
308     (plist-get props prop)))
309
310 (defun notmuch-tree-set-tags (tags)
311   "Set the tags of the current message."
312   (notmuch-tree-set-prop :tags tags))
313
314 (defun notmuch-tree-get-tags ()
315   "Return the tags of the current message."
316   (notmuch-tree-get-prop :tags))
317
318 (defun notmuch-tree-get-message-id (&optional bare)
319   "Return the message id of the current message."
320   (let ((id (notmuch-tree-get-prop :id)))
321     (if id
322         (if bare
323             id
324           (notmuch-id-to-query id))
325       nil)))
326
327 (defun notmuch-tree-get-match ()
328   "Return whether the current message is a match."
329   (interactive)
330   (notmuch-tree-get-prop :match))
331
332 (defun notmuch-tree-refresh-result ()
333   "Redisplay the current message line.
334
335 This redisplays the current line based on the messages
336 properties (as they are now). This is used when tags are
337 updated."
338   (let ((init-point (point))
339         (end (line-end-position))
340         (msg (notmuch-tree-get-message-properties))
341         (inhibit-read-only t))
342     (beginning-of-line)
343     ;; This is a little tricky: we override
344     ;; notmuch-tree-previous-subject to get the decision between
345     ;; ... and a subject right and it stops notmuch-tree-insert-msg
346     ;; from overwriting the buffer local copy of
347     ;; notmuch-tree-previous-subject if this is called while the
348     ;; buffer is displaying.
349     (let ((notmuch-tree-previous-subject (notmuch-tree-get-prop :previous-subject)))
350       (delete-region (point) (1+ (line-end-position)))
351       (notmuch-tree-insert-msg msg))
352     (let ((new-end (line-end-position)))
353       (goto-char (if (= init-point end)
354                      new-end
355                    (min init-point (- new-end 1)))))))
356
357 (defun notmuch-tree-tag-update-display (&optional tag-changes)
358   "Update display for TAG-CHANGES to current message.
359
360 Does NOT change the database."
361   (let* ((current-tags (notmuch-tree-get-tags))
362          (new-tags (notmuch-update-tags current-tags tag-changes)))
363     (unless (equal current-tags new-tags)
364       (notmuch-tree-set-tags new-tags)
365       (notmuch-tree-refresh-result))))
366
367 (defun notmuch-tree-tag (tag-changes)
368   "Change tags for the current message"
369   (interactive
370    (list (notmuch-read-tag-changes (notmuch-tree-get-tags) "Tag message")))
371   (notmuch-tag (notmuch-tree-get-message-id) tag-changes)
372   (notmuch-tree-tag-update-display tag-changes))
373
374 (defun notmuch-tree-add-tag (tag-changes)
375   "Same as `notmuch-tree-tag' but sets initial input to '+'."
376   (interactive
377    (list (notmuch-read-tag-changes (notmuch-tree-get-tags) "Tag message" "+")))
378   (notmuch-tree-tag tag-changes))
379
380 (defun notmuch-tree-remove-tag (tag-changes)
381   "Same as `notmuch-tree-tag' but sets initial input to '-'."
382   (interactive
383    (list (notmuch-read-tag-changes (notmuch-tree-get-tags) "Tag message" "-")))
384   (notmuch-tree-tag tag-changes))
385
386 ;; The next two functions close the message window before calling
387 ;; notmuch-search or notmuch-tree but they do so after the user has
388 ;; entered the query (in case the user was basing the query on
389 ;; something in the message window).
390
391 (defun notmuch-tree-to-search ()
392   "Run \"notmuch search\" with the given `query' and display results."
393   (interactive)
394   (let ((query (notmuch-read-query "Notmuch search: ")))
395     (notmuch-tree-close-message-window)
396     (notmuch-search query)))
397
398 (defun notmuch-tree-to-tree ()
399   "Run a query and display results in Tree view"
400   (interactive)
401   (let ((query (notmuch-read-query "Notmuch tree view search: ")))
402     (notmuch-tree-close-message-window)
403     (notmuch-tree query)))
404
405 (defun notmuch-tree-message-window-kill-hook ()
406   "Close the message pane when exiting the show buffer."
407   (let ((buffer (current-buffer)))
408     (when (and (window-live-p notmuch-tree-message-window)
409                (eq (window-buffer notmuch-tree-message-window) buffer))
410       ;; We do not want an error if this is the sole window in the
411       ;; frame and I do not know how to test for that in emacs pre
412       ;; 24. Hence we just ignore-errors.
413       (ignore-errors
414         (delete-window notmuch-tree-message-window)))))
415
416 (defun notmuch-tree-show-message-in ()
417   "Show the current message (in split-pane)."
418   (interactive)
419   (let ((id (notmuch-tree-get-message-id))
420         (inhibit-read-only t)
421         buffer)
422     (when id
423       ;; We close and reopen the window to kill off un-needed buffers
424       ;; this might cause flickering but seems ok.
425       (notmuch-tree-close-message-window)
426       (setq notmuch-tree-message-window
427             (split-window-vertically (/ (window-height) 4)))
428       (with-selected-window notmuch-tree-message-window
429         ;; Since we are only displaying one message do not indent.
430         (let ((notmuch-show-indent-messages-width 0)
431               (notmuch-show-only-matching-messages t))
432           (setq buffer (notmuch-show id))))
433       ;; We need the `let' as notmuch-tree-message-window is buffer local.
434       (let ((window notmuch-tree-message-window))
435         (with-current-buffer buffer
436           (setq notmuch-tree-message-window window)
437           (add-hook 'kill-buffer-hook 'notmuch-tree-message-window-kill-hook)))
438       (when notmuch-show-mark-read-tags
439         (notmuch-tree-tag-update-display notmuch-show-mark-read-tags))
440       (setq notmuch-tree-message-buffer buffer))))
441
442 (defun notmuch-tree-show-message-out ()
443   "Show the current message (in whole window)."
444   (interactive)
445   (let ((id (notmuch-tree-get-message-id))
446         (inhibit-read-only t)
447         buffer)
448     (when id
449       ;; We close the window to kill off un-needed buffers.
450       (notmuch-tree-close-message-window)
451       (notmuch-show id))))
452
453 (defun notmuch-tree-show-message (arg)
454   "Show the current message.
455
456 Shows in split pane or whole window according to value of
457 `notmuch-tree-show-out'. A prefix argument reverses the choice."
458   (interactive "P")
459   (if (or (and notmuch-tree-show-out  (not arg))
460           (and (not notmuch-tree-show-out) arg))
461       (notmuch-tree-show-message-out)
462     (notmuch-tree-show-message-in)))
463
464 (defun notmuch-tree-scroll-message-window ()
465   "Scroll the message window (if it exists)"
466   (interactive)
467   (when (window-live-p notmuch-tree-message-window)
468     (with-selected-window notmuch-tree-message-window
469       (if (pos-visible-in-window-p (point-max))
470           t
471         (scroll-up)))))
472
473 (defun notmuch-tree-scroll-message-window-back ()
474   "Scroll the message window back(if it exists)"
475   (interactive)
476   (when (window-live-p notmuch-tree-message-window)
477     (with-selected-window notmuch-tree-message-window
478       (if (pos-visible-in-window-p (point-min))
479           t
480         (scroll-down)))))
481
482 (defun notmuch-tree-scroll-or-next ()
483   "Scroll the message window. If it at end go to next message."
484   (interactive)
485   (when (notmuch-tree-scroll-message-window)
486     (notmuch-tree-next-matching-message)))
487
488 (defun notmuch-tree-quit ()
489   "Close the split view or exit tree."
490   (interactive)
491   (unless (notmuch-tree-close-message-window)
492     (kill-buffer (current-buffer))))
493
494 (defun notmuch-tree-close-message-window ()
495   "Close the message-window. Return t if close succeeds."
496   (interactive)
497   (when (and (window-live-p notmuch-tree-message-window)
498              (eq (window-buffer notmuch-tree-message-window) notmuch-tree-message-buffer))
499     (delete-window notmuch-tree-message-window)
500     (unless (get-buffer-window-list notmuch-tree-message-buffer)
501       (kill-buffer notmuch-tree-message-buffer))
502     t))
503
504 (defun notmuch-tree-archive-message (&optional unarchive)
505   "Archive the current message.
506
507 Archive the current message by applying the tag changes in
508 `notmuch-archive-tags' to it. If a prefix argument is given, the
509 message will be \"unarchived\", i.e. the tag changes in
510 `notmuch-archive-tags' will be reversed."
511   (interactive "P")
512   (when notmuch-archive-tags
513     (notmuch-tree-tag (notmuch-tag-change-list notmuch-archive-tags unarchive))))
514
515 (defun notmuch-tree-archive-message-then-next (&optional unarchive)
516   "Archive the current message and move to next matching message."
517   (interactive "P")
518   (notmuch-tree-archive-message unarchive)
519   (notmuch-tree-next-matching-message))
520
521 (defun notmuch-tree-next-message ()
522   "Move to next message."
523   (interactive)
524   (forward-line)
525   (when (window-live-p notmuch-tree-message-window)
526     (notmuch-tree-show-message-in)))
527
528 (defun notmuch-tree-prev-message ()
529   "Move to previous message."
530   (interactive)
531   (forward-line -1)
532   (when (window-live-p notmuch-tree-message-window)
533     (notmuch-tree-show-message-in)))
534
535 (defun notmuch-tree-prev-matching-message ()
536   "Move to previous matching message."
537   (interactive)
538   (forward-line -1)
539   (while (and (not (bobp)) (not (notmuch-tree-get-match)))
540     (forward-line -1))
541   (when (window-live-p notmuch-tree-message-window)
542     (notmuch-tree-show-message-in)))
543
544 (defun notmuch-tree-next-matching-message ()
545   "Move to next matching message."
546   (interactive)
547   (forward-line)
548   (while (and (not (eobp)) (not (notmuch-tree-get-match)))
549     (forward-line))
550   (when (window-live-p notmuch-tree-message-window)
551     (notmuch-tree-show-message-in)))
552
553 (defun notmuch-tree-refresh-view ()
554   "Refresh view."
555   (interactive)
556   (let ((inhibit-read-only t)
557         (basic-query notmuch-tree-basic-query)
558         (query-context notmuch-tree-query-context)
559         (target (notmuch-tree-get-message-id)))
560     (erase-buffer)
561     (notmuch-tree-worker basic-query
562                          query-context
563                          target)))
564
565 (defun notmuch-tree-thread-top ()
566   (when (notmuch-tree-get-message-properties)
567     (while (not (or (notmuch-tree-get-prop :first) (eobp)))
568       (forward-line -1))))
569
570 (defun notmuch-tree-prev-thread ()
571   (interactive)
572   (forward-line -1)
573   (notmuch-tree-thread-top))
574
575 (defun notmuch-tree-next-thread ()
576   (interactive)
577   (forward-line 1)
578   (while (not (or (notmuch-tree-get-prop :first) (eobp)))
579     (forward-line 1)))
580
581 (defun notmuch-tree-thread-mapcar (function)
582   "Iterate through all messages in the current thread
583  and call FUNCTION for side effects."
584   (save-excursion
585     (notmuch-tree-thread-top)
586     (loop collect (funcall function)
587           do (forward-line)
588           while (and (notmuch-tree-get-message-properties)
589                      (not (notmuch-tree-get-prop :first))))))
590
591 (defun notmuch-tree-get-messages-ids-thread-search ()
592   "Return a search string for all message ids of messages in the current thread."
593   (mapconcat 'identity
594              (notmuch-tree-thread-mapcar 'notmuch-tree-get-message-id)
595              " or "))
596
597 (defun notmuch-tree-tag-thread (tag-changes)
598   "Tag all messages in the current thread"
599   (interactive
600    (let ((tags (apply #'append (notmuch-tree-thread-mapcar
601                                 (lambda () (notmuch-tree-get-tags))))))
602      (list (notmuch-read-tag-changes tags "Tag thread"))))
603   (when (notmuch-tree-get-message-properties)
604     (notmuch-tag (notmuch-tree-get-messages-ids-thread-search) tag-changes)
605     (notmuch-tree-thread-mapcar
606      (lambda () (notmuch-tree-tag-update-display tag-changes)))))
607
608 (defun notmuch-tree-archive-thread (&optional unarchive)
609   "Archive each message in thread.
610
611 Archive each message currently shown by applying the tag changes
612 in `notmuch-archive-tags' to each. If a prefix argument is given,
613 the messages will be \"unarchived\", i.e. the tag changes in
614 `notmuch-archive-tags' will be reversed.
615
616 Note: This command is safe from any race condition of new messages
617 being delivered to the same thread. It does not archive the
618 entire thread, but only the messages shown in the current
619 buffer."
620   (interactive "P")
621   (when notmuch-archive-tags
622     (notmuch-tree-tag-thread
623      (notmuch-tag-change-list notmuch-archive-tags unarchive))))
624
625 ;; Functions below here display the tree buffer itself.
626
627 (defun notmuch-tree-clean-address (address)
628   "Try to clean a single email ADDRESS for display. Return
629 AUTHOR_NAME if present, otherwise return AUTHOR_EMAIL. Return
630 unchanged ADDRESS if parsing fails."
631   (let* ((clean-address (notmuch-clean-address address))
632          (p-address (car clean-address))
633          (p-name (cdr clean-address)))
634
635     ;; If we have a name return that otherwise return the address.
636     (or p-name p-address)))
637
638 (defun notmuch-tree-format-field (field format-string msg)
639   "Format a FIELD of MSG according to FORMAT-STRING and return string"
640   (let* ((headers (plist-get msg :headers))
641          (match (plist-get msg :match)))
642     (cond
643      ((listp field)
644       (format format-string (notmuch-tree-format-field-list field msg)))
645
646      ((string-equal field "date")
647       (let ((face (if match
648                       'notmuch-tree-match-date-face
649                     'notmuch-tree-no-match-date-face)))
650         (propertize (format format-string (plist-get msg :date_relative)) 'face face)))
651
652      ((string-equal field "tree")
653       (let ((tree-status (plist-get msg :tree-status))
654             (face (if match
655                       'notmuch-tree-match-tree-face
656                     'notmuch-tree-no-match-tree-face)))
657
658         (propertize (format format-string
659                             (mapconcat #'identity (reverse tree-status) ""))
660                     'face face)))
661
662      ((string-equal field "subject")
663       (let ((bare-subject (notmuch-show-strip-re (plist-get headers :Subject)))
664             (previous-subject notmuch-tree-previous-subject)
665             (face (if match
666                       'notmuch-tree-match-subject-face
667                     'notmuch-tree-no-match-subject-face)))
668
669         (setq notmuch-tree-previous-subject bare-subject)
670         (propertize (format format-string
671                             (if (string= previous-subject bare-subject)
672                                 " ..."
673                               bare-subject))
674                     'face face)))
675
676      ((string-equal field "authors")
677       (let ((author (notmuch-tree-clean-address (plist-get headers :From)))
678             (len (length (format format-string "")))
679             (face (if match
680                       'notmuch-tree-match-author-face
681                     'notmuch-tree-no-match-author-face)))
682         (when (> (length author) len)
683           (setq author (substring author 0 len)))
684         (propertize (format format-string author) 'face face)))
685
686      ((string-equal field "tags")
687       (let ((tags (plist-get msg :tags))
688             (orig-tags (plist-get msg :orig-tags))
689             (face (if match
690                       'notmuch-tree-match-tag-face
691                     'notmuch-tree-no-match-tag-face)))
692         (format format-string (notmuch-tag-format-tags tags orig-tags face)))))))
693
694 (defun notmuch-tree-format-field-list (field-list msg)
695   "Format fields of MSG according to FIELD-LIST and return string"
696   (let ((face (if (plist-get msg :match)
697                   'notmuch-tree-match-face
698                 'notmuch-tree-no-match-face))
699         (result-string))
700     (dolist (spec field-list result-string)
701       (let ((field-string (notmuch-tree-format-field (car spec) (cdr spec) msg)))
702         (setq result-string (concat result-string field-string))))
703     (notmuch-apply-face result-string face t)))
704
705 (defun notmuch-tree-insert-msg (msg)
706   "Insert the message MSG according to notmuch-tree-result-format"
707   ;; We need to save the previous subject as it will get overwritten
708   ;; by the insert-field calls.
709   (let ((previous-subject notmuch-tree-previous-subject))
710     (insert (notmuch-tree-format-field-list notmuch-tree-result-format msg))
711     (notmuch-tree-set-message-properties msg)
712     (notmuch-tree-set-prop :previous-subject previous-subject)
713     (insert "\n")))
714
715 (defun notmuch-tree-goto-and-insert-msg (msg)
716   "Insert msg at the end of the buffer. Move point to msg if it is the target"
717   (save-excursion
718     (goto-char (point-max))
719     (notmuch-tree-insert-msg msg))
720   (let ((msg-id (notmuch-id-to-query (plist-get msg :id)))
721         (target notmuch-tree-target-msg))
722     (when (or (and (not target) (plist-get msg :match))
723               (string= msg-id target))
724       (setq notmuch-tree-target-msg "found")
725       (goto-char (point-max))
726       (forward-line -1)
727       (when notmuch-tree-open-target
728         (notmuch-tree-show-message-in)))))
729
730 (defun notmuch-tree-insert-tree (tree depth tree-status first last)
731   "Insert the message tree TREE at depth DEPTH in the current thread.
732
733 A message tree is another name for a single sub-thread: i.e., a
734 message together with all its descendents."
735   (let ((msg (car tree))
736         (replies (cadr tree)))
737
738       (cond
739        ((and (< 0 depth) (not last))
740         (push "├" tree-status))
741        ((and (< 0 depth) last)
742         (push "╰" tree-status))
743        ((and (eq 0 depth) first last)
744 ;;        (push "─" tree-status)) choice between this and next line is matter of taste.
745         (push " " tree-status))
746        ((and (eq 0 depth) first (not last))
747           (push "┬" tree-status))
748        ((and (eq 0 depth) (not first) last)
749         (push "╰" tree-status))
750        ((and (eq 0 depth) (not first) (not last))
751         (push "├" tree-status)))
752
753       (push (concat (if replies "┬" "─") "►") tree-status)
754       (setq msg (plist-put msg :first (and first (eq 0 depth))))
755       (setq msg (plist-put msg :tree-status tree-status))
756       (setq msg (plist-put msg :orig-tags (plist-get msg :tags)))
757       (notmuch-tree-goto-and-insert-msg msg)
758       (pop tree-status)
759       (pop tree-status)
760
761       (if last
762           (push " " tree-status)
763         (push "│" tree-status))
764
765     (notmuch-tree-insert-thread replies (1+ depth) tree-status)))
766
767 (defun notmuch-tree-insert-thread (thread depth tree-status)
768   "Insert the collection of sibling sub-threads THREAD at depth DEPTH in the current forest."
769   (let ((n (length thread)))
770     (loop for tree in thread
771           for count from 1 to n
772
773           do (notmuch-tree-insert-tree tree depth tree-status (eq count 1) (eq count n)))))
774
775 (defun notmuch-tree-insert-forest-thread (forest-thread)
776   "Insert a single complete thread."
777   (let (tree-status)
778     ;; Reset at the start of each main thread.
779     (setq notmuch-tree-previous-subject nil)
780     (notmuch-tree-insert-thread forest-thread 0 tree-status)))
781
782 (defun notmuch-tree-insert-forest (forest)
783   "Insert a forest of threads.
784
785 This function inserts a collection of several complete threads as
786 passed to it by notmuch-tree-process-filter."
787   (mapc 'notmuch-tree-insert-forest-thread forest))
788
789 (defun notmuch-tree-mode ()
790   "Major mode displaying messages (as opposed to threads) of of a notmuch search.
791
792 This buffer contains the results of a \"notmuch tree\" of your
793 email archives. Each line in the buffer represents a single
794 message giving the relative date, the author, subject, and any
795 tags.
796
797 Pressing \\[notmuch-tree-show-message] on any line displays that message.
798
799 Complete list of currently available key bindings:
800
801 \\{notmuch-tree-mode-map}"
802
803   (interactive)
804   (kill-all-local-variables)
805   (setq notmuch-buffer-refresh-function #'notmuch-tree-refresh-view)
806   (use-local-map notmuch-tree-mode-map)
807   (setq major-mode 'notmuch-tree-mode
808         mode-name "notmuch-tree")
809   (hl-line-mode 1)
810   (setq buffer-read-only t
811         truncate-lines t))
812
813 (defun notmuch-tree-process-sentinel (proc msg)
814   "Add a message to let user know when \"notmuch tree\" exits"
815   (let ((buffer (process-buffer proc))
816         (status (process-status proc))
817         (exit-status (process-exit-status proc))
818         (never-found-target-thread nil))
819     (when (memq status '(exit signal))
820         (kill-buffer (process-get proc 'parse-buf))
821         (if (buffer-live-p buffer)
822             (with-current-buffer buffer
823               (save-excursion
824                 (let ((inhibit-read-only t)
825                       (atbob (bobp)))
826                   (goto-char (point-max))
827                   (if (eq status 'signal)
828                       (insert "Incomplete search results (tree view process was killed).\n"))
829                   (when (eq status 'exit)
830                     (insert "End of search results.")
831                     (unless (= exit-status 0)
832                       (insert (format " (process returned %d)" exit-status)))
833                     (insert "\n")))))))))
834
835 (defun notmuch-tree-process-filter (proc string)
836   "Process and filter the output of \"notmuch show\" for tree view"
837   (let ((results-buf (process-buffer proc))
838         (parse-buf (process-get proc 'parse-buf))
839         (inhibit-read-only t)
840         done)
841     (if (not (buffer-live-p results-buf))
842         (delete-process proc)
843       (with-current-buffer parse-buf
844         ;; Insert new data
845         (save-excursion
846           (goto-char (point-max))
847           (insert string))
848         (notmuch-sexp-parse-partial-list 'notmuch-tree-insert-forest-thread
849                                          results-buf)))))
850
851 (defun notmuch-tree-worker (basic-query &optional query-context target open-target)
852   "Insert the tree view of the search in the current buffer.
853
854 This is is a helper function for notmuch-tree. The arguments are
855 the same as for the function notmuch-tree."
856   (interactive)
857   (notmuch-tree-mode)
858   (setq notmuch-tree-basic-query basic-query)
859   (setq notmuch-tree-query-context query-context)
860   (setq notmuch-tree-target-msg target)
861   (setq notmuch-tree-open-target open-target)
862
863   (erase-buffer)
864   (goto-char (point-min))
865   (let* ((search-args (concat basic-query
866                        (if query-context (concat " and (" query-context ")"))
867                        ))
868          (message-arg "--entire-thread"))
869     (if (equal (car (process-lines notmuch-command "count" search-args)) "0")
870         (setq search-args basic-query))
871     (notmuch-tag-clear-cache)
872     (let ((proc (notmuch-start-notmuch
873                  "notmuch-tree" (current-buffer) #'notmuch-tree-process-sentinel
874                  "show" "--body=false" "--format=sexp"
875                  message-arg search-args))
876           ;; Use a scratch buffer to accumulate partial output.
877           ;; This buffer will be killed by the sentinel, which
878           ;; should be called no matter how the process dies.
879           (parse-buf (generate-new-buffer " *notmuch tree parse*")))
880       (process-put proc 'parse-buf parse-buf)
881       (set-process-filter proc 'notmuch-tree-process-filter)
882       (set-process-query-on-exit-flag proc nil))))
883
884 (defun notmuch-tree-get-query ()
885   "Return the current query in this tree buffer"
886   (if notmuch-tree-query-context
887       (concat notmuch-tree-basic-query
888               " and ("
889               notmuch-tree-query-context
890               ")")
891     notmuch-tree-basic-query))
892
893 (defun notmuch-tree (&optional query query-context target buffer-name open-target)
894   "Display threads matching QUERY in Tree View.
895
896 The arguments are:
897   QUERY: the main query. This can be any query but in many cases will be
898       a single thread. If nil this is read interactively from the minibuffer.
899   QUERY-CONTEXT: is an additional term for the query. The query used
900       is QUERY and QUERY-CONTEXT unless that does not match any messages
901       in which case we fall back to just QUERY.
902   TARGET: A message ID (with the id: prefix) that will be made
903       current if it appears in the tree view results.
904   BUFFER-NAME: the name of the buffer to display the tree view. If
905       it is nil \"*notmuch-tree\" followed by QUERY is used.
906   OPEN-TARGET: If TRUE open the target message in the message pane."
907   (interactive)
908   (if (null query)
909       (setq query (notmuch-read-query "Notmuch tree view search: ")))
910   (let ((buffer (get-buffer-create (generate-new-buffer-name
911                                     (or buffer-name
912                                         (concat "*notmuch-tree-" query "*")))))
913         (inhibit-read-only t))
914
915     (switch-to-buffer buffer))
916   ;; Don't track undo information for this buffer
917   (set 'buffer-undo-list t)
918
919   (notmuch-tree-worker query query-context target open-target)
920
921   (setq truncate-lines t))
922
923
924 ;;
925
926 (provide 'notmuch-tree)