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