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