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