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