]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-tree.el
emacs: add z to common keymap
[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-date-face
74   '((t :inherit default))
75   "Face used in tree mode for the date in messages matching the query."
76   :group 'notmuch-tree
77   :group 'notmuch-faces)
78
79 (defface notmuch-tree-match-author-face
80   '((((class color)
81       (background dark))
82      (:foreground "OliveDrab1"))
83     (((class color)
84       (background light))
85      (:foreground "dark blue"))
86     (t
87      (:bold t)))
88   "Face used in tree mode for the date in messages matching the query."
89   :group 'notmuch-tree
90   :group 'notmuch-faces)
91
92 (defface notmuch-tree-match-subject-face
93   '((t :inherit default))
94   "Face used in tree mode for the subject in messages matching the query."
95   :group 'notmuch-tree
96   :group 'notmuch-faces)
97
98 (defface notmuch-tree-match-tree-face
99   '((t :inherit default))
100   "Face used in tree mode for the thread tree block graphics in messages matching the query."
101   :group 'notmuch-tree
102   :group 'notmuch-faces)
103
104 (defface notmuch-tree-match-tag-face
105   '((((class color)
106       (background dark))
107      (:foreground "OliveDrab1"))
108     (((class color)
109       (background light))
110      (:foreground "navy blue" :bold t))
111     (t
112      (:bold t)))
113   "Face used in tree mode for tags in messages matching the query."
114   :group 'notmuch-tree
115   :group 'notmuch-faces)
116
117 ;; Faces for messages that do not match the query.
118 (defface notmuch-tree-no-match-date-face
119   '((t (:foreground "gray")))
120   "Face used in tree mode for non-matching dates."
121   :group 'notmuch-tree
122   :group 'notmuch-faces)
123
124 (defface notmuch-tree-no-match-subject-face
125   '((t (:foreground "gray")))
126   "Face used in tree mode for non-matching subjects."
127   :group 'notmuch-tree
128   :group 'notmuch-faces)
129
130 (defface notmuch-tree-no-match-tree-face
131   '((t (:foreground "gray")))
132   "Face used in tree mode for the thread tree block graphics in messages matching the query."
133   :group 'notmuch-tree
134   :group 'notmuch-faces)
135
136 (defface notmuch-tree-no-match-author-face
137   '((t (:foreground "gray")))
138   "Face used in tree mode for the date in messages matching the query."
139   :group 'notmuch-tree
140   :group 'notmuch-faces)
141
142 (defface notmuch-tree-no-match-tag-face
143   '((t (:foreground "gray")))
144   "Face used in tree mode face for non-matching tags."
145   :group 'notmuch-tree
146   :group 'notmuch-faces)
147
148 (defvar notmuch-tree-previous-subject
149   "The subject of the most recent result shown during the async display")
150 (make-variable-buffer-local 'notmuch-tree-previous-subject)
151
152 (defvar notmuch-tree-basic-query nil
153   "A buffer local copy of argument query to the function notmuch-tree")
154 (make-variable-buffer-local 'notmuch-tree-basic-query)
155
156 (defvar notmuch-tree-query-context nil
157   "A buffer local copy of argument query-context to the function notmuch-tree")
158 (make-variable-buffer-local 'notmuch-tree-query-context)
159
160 (defvar notmuch-tree-target-msg nil
161   "A buffer local copy of argument target to the function notmuch-tree")
162 (make-variable-buffer-local 'notmuch-tree-target-msg)
163
164 (defvar notmuch-tree-open-target nil
165   "A buffer local copy of argument open-target to the function notmuch-tree")
166 (make-variable-buffer-local 'notmuch-tree-open-target)
167
168 (defvar notmuch-tree-message-window nil
169   "The window of the message pane.
170
171 It is set in both the tree buffer and the child show buffer. It
172 is used to try and close the message pane when quitting tree view
173 or the child show buffer.")
174 (make-variable-buffer-local 'notmuch-tree-message-window)
175 (put 'notmuch-tree-message-window 'permanent-local t)
176
177 (defvar notmuch-tree-message-buffer nil
178   "The buffer name of the show buffer in the message pane.
179
180 This is used to try and make sure we don't close the message pane
181 if the user has loaded a different buffer in that window.")
182 (make-variable-buffer-local 'notmuch-tree-message-buffer)
183 (put 'notmuch-tree-message-buffer 'permanent-local t)
184
185 (defun notmuch-tree-to-message-pane (func)
186   "Execute FUNC in message pane.
187
188 This function returns a function (so can be used as a keybinding)
189 which executes function FUNC in the message pane if it is
190 open (if the message pane is closed it does nothing)."
191   `(lambda ()
192       ,(concat "(In message pane) " (documentation func t))
193      (interactive)
194      (when (window-live-p notmuch-tree-message-window)
195        (with-selected-window notmuch-tree-message-window
196          (call-interactively #',func)))))
197
198 (defun notmuch-tree-button-activate (&optional button)
199   "Activate BUTTON or button at point
200
201 This function does not give an error if there is no button."
202   (interactive)
203   (let ((button (or button (button-at (point)))))
204     (when button (button-activate button))))
205
206 (defun notmuch-tree-close-message-pane-and (func)
207   "Close message pane and execute FUNC.
208
209 This function returns a function (so can be used as a keybinding)
210 which closes the message pane if open and then executes function
211 FUNC."
212   `(lambda ()
213       ,(concat "(Close message pane and) " (documentation func t))
214      (interactive)
215      (notmuch-tree-close-message-window)
216      (call-interactively #',func)))
217
218 (defvar notmuch-tree-mode-map
219   (let ((map (make-sparse-keymap)))
220     (set-keymap-parent map notmuch-common-keymap)
221     ;; The following override the global keymap.
222     ;; Override because we want to close message pane first.
223     (define-key map "?" (notmuch-tree-close-message-pane-and #'notmuch-help))
224     ;; Override because we first close message pane and then close tree buffer.
225     (define-key map "q" 'notmuch-tree-quit)
226     ;; Override because we close message pane after the search query is entered.
227     (define-key map "s" 'notmuch-tree-to-search)
228     ;; Override because we want to close message pane first.
229     (define-key map "m" (notmuch-tree-close-message-pane-and #'notmuch-mua-new-mail))
230
231     ;; these use notmuch-show functions directly
232     (define-key map "|" 'notmuch-show-pipe-message)
233     (define-key map "w" 'notmuch-show-save-attachments)
234     (define-key map "v" 'notmuch-show-view-all-mime-parts)
235     (define-key map "c" 'notmuch-show-stash-map)
236
237     ;; these apply to the message pane
238     (define-key map (kbd "M-TAB") (notmuch-tree-to-message-pane #'notmuch-show-previous-button))
239     (define-key map (kbd "<backtab>")  (notmuch-tree-to-message-pane #'notmuch-show-previous-button))
240     (define-key map (kbd "TAB") (notmuch-tree-to-message-pane #'notmuch-show-next-button))
241     (define-key map "e" (notmuch-tree-to-message-pane #'notmuch-tree-button-activate))
242
243     ;; bindings from show (or elsewhere) but we close the message pane first.
244     (define-key map "f" (notmuch-tree-close-message-pane-and #'notmuch-show-forward-message))
245     (define-key map "r" (notmuch-tree-close-message-pane-and #'notmuch-show-reply-sender))
246     (define-key map "R" (notmuch-tree-close-message-pane-and #'notmuch-show-reply))
247     (define-key map "V" (notmuch-tree-close-message-pane-and #'notmuch-show-view-raw-message))
248
249     ;; The main tree view bindings
250     (define-key map (kbd "RET") 'notmuch-tree-show-message)
251     (define-key map [mouse-1] 'notmuch-tree-show-message)
252     (define-key map "x" 'notmuch-tree-quit)
253     (define-key map "A" 'notmuch-tree-archive-thread)
254     (define-key map "a" 'notmuch-tree-archive-message-then-next)
255     (define-key map "=" 'notmuch-tree-refresh-view)
256     (define-key map "z" 'notmuch-tree-to-tree)
257     (define-key map "n" 'notmuch-tree-next-matching-message)
258     (define-key map "p" 'notmuch-tree-prev-matching-message)
259     (define-key map "N" 'notmuch-tree-next-message)
260     (define-key map "P" 'notmuch-tree-prev-message)
261     (define-key map (kbd "M-p") 'notmuch-tree-prev-thread)
262     (define-key map (kbd "M-n") 'notmuch-tree-next-thread)
263     (define-key map "-" 'notmuch-tree-remove-tag)
264     (define-key map "+" 'notmuch-tree-add-tag)
265     (define-key map "*" 'notmuch-tree-tag-thread)
266     (define-key map " " 'notmuch-tree-scroll-or-next)
267     (define-key map "b" 'notmuch-tree-scroll-message-window-back)
268     map))
269 (fset 'notmuch-tree-mode-map notmuch-tree-mode-map)
270
271 (defun notmuch-tree-get-message-properties ()
272   "Return the properties of the current message as a plist.
273
274 Some useful entries are:
275 :headers - Property list containing the headers :Date, :Subject, :From, etc.
276 :tags - Tags for this message"
277   (save-excursion
278     (beginning-of-line)
279     (get-text-property (point) :notmuch-message-properties)))
280
281 ;; XXX This should really be a lib function but we are trying to
282 ;; reduce impact on the code base.
283 (defun notmuch-show-get-prop (prop &optional props)
284   "This is a tree view overridden version of notmuch-show-get-prop
285
286 It gets property PROP from PROPS or, if PROPS is nil, the current
287 message in either tree or show. This means that several functions
288 in notmuch-show now work unchanged in tree as they just need the
289 correct message properties."
290   (let ((props (or props
291                    (cond ((eq major-mode 'notmuch-show-mode)
292                           (notmuch-show-get-message-properties))
293                          ((eq major-mode 'notmuch-tree-mode)
294                           (notmuch-tree-get-message-properties))))))
295     (plist-get props prop)))
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 ()
323   "Return the message id of the current message."
324   (let ((id (notmuch-tree-get-prop :id)))
325     (if id
326         (notmuch-id-to-query id)
327       nil)))
328
329 (defun notmuch-tree-get-match ()
330   "Return whether the current message is a match."
331   (interactive)
332   (notmuch-tree-get-prop :match))
333
334 (defun notmuch-tree-refresh-result ()
335   "Redisplay the current message line.
336
337 This redisplays the current line based on the messages
338 properties (as they are now). This is used when tags are
339 updated."
340   (let ((init-point (point))
341         (end (line-end-position))
342         (msg (notmuch-tree-get-message-properties))
343         (inhibit-read-only t))
344     (beginning-of-line)
345     ;; This is a little tricky: we override
346     ;; notmuch-tree-previous-subject to get the decision between
347     ;; ... and a subject right and it stops notmuch-tree-insert-msg
348     ;; from overwriting the buffer local copy of
349     ;; notmuch-tree-previous-subject if this is called while the
350     ;; buffer is displaying.
351     (let ((notmuch-tree-previous-subject (notmuch-tree-get-prop :previous-subject)))
352       (delete-region (point) (1+ (line-end-position)))
353       (notmuch-tree-insert-msg msg))
354     (let ((new-end (line-end-position)))
355       (goto-char (if (= init-point end)
356                      new-end
357                    (min init-point (- new-end 1)))))))
358
359 (defun notmuch-tree-tag-update-display (&optional tag-changes)
360   "Update display for TAG-CHANGES to current message.
361
362 Does NOT change the database."
363   (let* ((current-tags (notmuch-tree-get-tags))
364          (new-tags (notmuch-update-tags current-tags tag-changes)))
365     (unless (equal current-tags new-tags)
366       (notmuch-tree-set-tags new-tags)
367       (notmuch-tree-refresh-result))))
368
369 (defun notmuch-tree-tag (tag-changes)
370   "Change tags for the current message"
371   (interactive
372    (list (notmuch-read-tag-changes (notmuch-tree-get-tags) "Tag message")))
373   (notmuch-tag (notmuch-tree-get-message-id) tag-changes)
374   (notmuch-tree-tag-update-display tag-changes))
375
376 (defun notmuch-tree-add-tag (tag-changes)
377   "Same as `notmuch-tree-tag' but sets initial input to '+'."
378   (interactive
379    (list (notmuch-read-tag-changes (notmuch-tree-get-tags) "Tag message" "+")))
380   (notmuch-tree-tag tag-changes))
381
382 (defun notmuch-tree-remove-tag (tag-changes)
383   "Same as `notmuch-tree-tag' but sets initial input to '-'."
384   (interactive
385    (list (notmuch-read-tag-changes (notmuch-tree-get-tags) "Tag message" "-")))
386   (notmuch-tree-tag tag-changes))
387
388 ;; The next two functions close the message window before calling
389 ;; notmuch-search or notmuch-tree but they do so after the user has
390 ;; entered the query (in case the user was basing the query on
391 ;; something in the message window).
392
393 (defun notmuch-tree-to-search ()
394   "Run \"notmuch search\" with the given `query' and display results."
395   (interactive)
396   (let ((query (notmuch-read-query "Notmuch search: ")))
397     (notmuch-tree-close-message-window)
398     (notmuch-search query)))
399
400 (defun notmuch-tree-to-tree ()
401   "Run a query and display results in Tree view"
402   (interactive)
403   (let ((query (notmuch-read-query "Notmuch tree view search: ")))
404     (notmuch-tree-close-message-window)
405     (notmuch-tree query)))
406
407 ;; This function should be in notmuch-show.el but be we trying to
408 ;; minimise impact on the rest of the codebase.
409 (defun notmuch-tree-from-show-current-query ()
410   "Call notmuch tree with the current query"
411   (interactive)
412   (notmuch-tree notmuch-show-thread-id
413                 notmuch-show-query-context
414                 (notmuch-show-get-message-id)))
415
416 (defun notmuch-tree-message-window-kill-hook ()
417   "Close the message pane when exiting the show buffer."
418   (let ((buffer (current-buffer)))
419     (when (and (window-live-p notmuch-tree-message-window)
420                (eq (window-buffer notmuch-tree-message-window) buffer))
421       ;; We do not want an error if this is the sole window in the
422       ;; frame and I do not know how to test for that in emacs pre
423       ;; 24. Hence we just ignore-errors.
424       (ignore-errors
425         (delete-window notmuch-tree-message-window)))))
426
427 (defun notmuch-tree-show-message-in ()
428   "Show the current message (in split-pane)."
429   (interactive)
430   (let ((id (notmuch-tree-get-message-id))
431         (inhibit-read-only t)
432         buffer)
433     (when id
434       ;; We close and reopen the window to kill off un-needed buffers
435       ;; this might cause flickering but seems ok.
436       (notmuch-tree-close-message-window)
437       (setq notmuch-tree-message-window
438             (split-window-vertically (/ (window-height) 4)))
439       (with-selected-window notmuch-tree-message-window
440         ;; Since we are only displaying one message do not indent.
441         (let ((notmuch-show-indent-messages-width 0)
442               (notmuch-show-only-matching-messages t))
443           (setq buffer (notmuch-show id))))
444       ;; We need the `let' as notmuch-tree-message-window is buffer local.
445       (let ((window notmuch-tree-message-window))
446         (with-current-buffer buffer
447           (setq notmuch-tree-message-window window)
448           (add-hook 'kill-buffer-hook 'notmuch-tree-message-window-kill-hook)))
449       (when notmuch-show-mark-read-tags
450         (notmuch-tree-tag-update-display notmuch-show-mark-read-tags))
451       (setq notmuch-tree-message-buffer buffer))))
452
453 (defun notmuch-tree-show-message-out ()
454   "Show the current message (in whole window)."
455   (interactive)
456   (let ((id (notmuch-tree-get-message-id))
457         (inhibit-read-only t)
458         buffer)
459     (when id
460       ;; We close the window to kill off un-needed buffers.
461       (notmuch-tree-close-message-window)
462       (notmuch-show id))))
463
464 (defun notmuch-tree-show-message (arg)
465   "Show the current message.
466
467 Shows in split pane or whole window according to value of
468 `notmuch-tree-show-out'. A prefix argument reverses the choice."
469   (interactive "P")
470   (if (or (and notmuch-tree-show-out  (not arg))
471           (and (not notmuch-tree-show-out) arg))
472       (notmuch-tree-show-message-out)
473     (notmuch-tree-show-message-in)))
474
475 (defun notmuch-tree-scroll-message-window ()
476   "Scroll the message window (if it exists)"
477   (interactive)
478   (when (window-live-p notmuch-tree-message-window)
479     (with-selected-window notmuch-tree-message-window
480       (if (pos-visible-in-window-p (point-max))
481           t
482         (scroll-up)))))
483
484 (defun notmuch-tree-scroll-message-window-back ()
485   "Scroll the message window back(if it exists)"
486   (interactive)
487   (when (window-live-p notmuch-tree-message-window)
488     (with-selected-window notmuch-tree-message-window
489       (if (pos-visible-in-window-p (point-min))
490           t
491         (scroll-down)))))
492
493 (defun notmuch-tree-scroll-or-next ()
494   "Scroll the message window. If it at end go to next message."
495   (interactive)
496   (when (notmuch-tree-scroll-message-window)
497     (notmuch-tree-next-matching-message)))
498
499 (defun notmuch-tree-quit ()
500   "Close the split view or exit tree."
501   (interactive)
502   (unless (notmuch-tree-close-message-window)
503     (kill-buffer (current-buffer))))
504
505 (defun notmuch-tree-close-message-window ()
506   "Close the message-window. Return t if close succeeds."
507   (interactive)
508   (when (and (window-live-p notmuch-tree-message-window)
509              (eq (window-buffer notmuch-tree-message-window) notmuch-tree-message-buffer))
510     (delete-window notmuch-tree-message-window)
511     (unless (get-buffer-window-list notmuch-tree-message-buffer)
512       (kill-buffer notmuch-tree-message-buffer))
513     t))
514
515 (defun notmuch-tree-archive-message (&optional unarchive)
516   "Archive the current message.
517
518 Archive the current message by applying the tag changes in
519 `notmuch-archive-tags' to it. If a prefix argument is given, the
520 message will be \"unarchived\", i.e. the tag changes in
521 `notmuch-archive-tags' will be reversed."
522   (interactive "P")
523   (when notmuch-archive-tags
524     (notmuch-tree-tag (notmuch-tag-change-list notmuch-archive-tags unarchive))))
525
526 (defun notmuch-tree-archive-message-then-next (&optional unarchive)
527   "Archive the current message and move to next matching message."
528   (interactive "P")
529   (notmuch-tree-archive-message unarchive)
530   (notmuch-tree-next-matching-message))
531
532 (defun notmuch-tree-next-message ()
533   "Move to next message."
534   (interactive)
535   (forward-line)
536   (when (window-live-p notmuch-tree-message-window)
537     (notmuch-tree-show-message-in)))
538
539 (defun notmuch-tree-prev-message ()
540   "Move to previous message."
541   (interactive)
542   (forward-line -1)
543   (when (window-live-p notmuch-tree-message-window)
544     (notmuch-tree-show-message-in)))
545
546 (defun notmuch-tree-prev-matching-message ()
547   "Move to previous matching message."
548   (interactive)
549   (forward-line -1)
550   (while (and (not (bobp)) (not (notmuch-tree-get-match)))
551     (forward-line -1))
552   (when (window-live-p notmuch-tree-message-window)
553     (notmuch-tree-show-message-in)))
554
555 (defun notmuch-tree-next-matching-message ()
556   "Move to next matching message."
557   (interactive)
558   (forward-line)
559   (while (and (not (eobp)) (not (notmuch-tree-get-match)))
560     (forward-line))
561   (when (window-live-p notmuch-tree-message-window)
562     (notmuch-tree-show-message-in)))
563
564 (defun notmuch-tree-refresh-view ()
565   "Refresh view."
566   (interactive)
567   (let ((inhibit-read-only t)
568         (basic-query notmuch-tree-basic-query)
569         (query-context notmuch-tree-query-context)
570         (target (notmuch-tree-get-message-id)))
571     (erase-buffer)
572     (notmuch-tree-worker basic-query
573                          query-context
574                          target)))
575
576 (defun notmuch-tree-thread-top ()
577   (when (notmuch-tree-get-message-properties)
578     (while (not (or (notmuch-tree-get-prop :first) (eobp)))
579       (forward-line -1))))
580
581 (defun notmuch-tree-prev-thread ()
582   (interactive)
583   (forward-line -1)
584   (notmuch-tree-thread-top))
585
586 (defun notmuch-tree-next-thread ()
587   (interactive)
588   (forward-line 1)
589   (while (not (or (notmuch-tree-get-prop :first) (eobp)))
590     (forward-line 1)))
591
592 (defun notmuch-tree-thread-mapcar (function)
593   "Iterate through all messages in the current thread
594  and call FUNCTION for side effects."
595   (save-excursion
596     (notmuch-tree-thread-top)
597     (loop collect (funcall function)
598           do (forward-line)
599           while (and (notmuch-tree-get-message-properties)
600                      (not (notmuch-tree-get-prop :first))))))
601
602 (defun notmuch-tree-get-messages-ids-thread-search ()
603   "Return a search string for all message ids of messages in the current thread."
604   (mapconcat 'identity
605              (notmuch-tree-thread-mapcar 'notmuch-tree-get-message-id)
606              " or "))
607
608 (defun notmuch-tree-tag-thread (tag-changes)
609   "Tag all messages in the current thread"
610   (interactive
611    (let ((tags (apply #'append (notmuch-tree-thread-mapcar
612                                 (lambda () (notmuch-tree-get-tags))))))
613      (list (notmuch-read-tag-changes tags "Tag thread"))))
614   (when (notmuch-tree-get-message-properties)
615     (notmuch-tag (notmuch-tree-get-messages-ids-thread-search) tag-changes)
616     (notmuch-tree-thread-mapcar
617      (lambda () (notmuch-tree-tag-update-display tag-changes)))))
618
619 (defun notmuch-tree-archive-thread (&optional unarchive)
620   "Archive each message in thread.
621
622 Archive each message currently shown by applying the tag changes
623 in `notmuch-archive-tags' to each. If a prefix argument is given,
624 the messages will be \"unarchived\", i.e. the tag changes in
625 `notmuch-archive-tags' will be reversed.
626
627 Note: This command is safe from any race condition of new messages
628 being delivered to the same thread. It does not archive the
629 entire thread, but only the messages shown in the current
630 buffer."
631   (interactive "P")
632   (when notmuch-archive-tags
633     (notmuch-tree-tag-thread
634      (notmuch-tag-change-list notmuch-archive-tags unarchive))))
635
636 ;; Functions below here display the tree buffer itself.
637
638 (defun notmuch-tree-clean-address (address)
639   "Try to clean a single email ADDRESS for display. Return
640 AUTHOR_NAME if present, otherwise return AUTHOR_EMAIL. Return
641 unchanged ADDRESS if parsing fails."
642   (let* ((clean-address (notmuch-clean-address address))
643          (p-address (car clean-address))
644          (p-name (cdr clean-address)))
645
646     ;; If we have a name return that otherwise return the address.
647     (or p-name p-address)))
648
649 (defun notmuch-tree-format-field (field format-string msg)
650   "Format a FIELD of MSG according to FORMAT-STRING and return string"
651   (let* ((headers (plist-get msg :headers))
652          (match (plist-get msg :match)))
653     (cond
654      ((listp field)
655       (format format-string (notmuch-tree-format-field-list field msg)))
656
657      ((string-equal field "date")
658       (let ((face (if match
659                       'notmuch-tree-match-date-face
660                     'notmuch-tree-no-match-date-face)))
661         (propertize (format format-string (plist-get msg :date_relative)) 'face face)))
662
663      ((string-equal field "tree")
664       (let ((tree-status (plist-get msg :tree-status))
665             (face (if match
666                       'notmuch-tree-match-tree-face
667                     'notmuch-tree-no-match-tree-face)))
668
669         (propertize (format format-string
670                             (mapconcat #'identity (reverse tree-status) ""))
671                     'face face)))
672
673      ((string-equal field "subject")
674       (let ((bare-subject (notmuch-show-strip-re (plist-get headers :Subject)))
675             (previous-subject notmuch-tree-previous-subject)
676             (face (if match
677                       'notmuch-tree-match-subject-face
678                     'notmuch-tree-no-match-subject-face)))
679
680         (setq notmuch-tree-previous-subject bare-subject)
681         (propertize (format format-string
682                             (if (string= previous-subject bare-subject)
683                                 " ..."
684                               bare-subject))
685                     'face face)))
686
687      ((string-equal field "authors")
688       (let ((author (notmuch-tree-clean-address (plist-get headers :From)))
689             (len (length (format format-string "")))
690             (face (if match
691                       'notmuch-tree-match-author-face
692                     'notmuch-tree-no-match-author-face)))
693         (when (> (length author) len)
694           (setq author (substring author 0 len)))
695         (propertize (format format-string author) 'face face)))
696
697      ((string-equal field "tags")
698       (let ((tags (plist-get msg :tags))
699             (face (if match
700                       'notmuch-tree-match-tag-face
701                     'notmuch-tree-no-match-tag-face)))
702         (propertize (format format-string
703                             (mapconcat #'identity tags ", "))
704                     'face face))))))
705
706
707 (defun notmuch-tree-format-field-list (field-list msg)
708   "Format fields of MSG according to FIELD-LIST and return string"
709   (let (result-string)
710     (dolist (spec field-list result-string)
711       (let ((field-string (notmuch-tree-format-field (car spec) (cdr spec) msg)))
712         (setq result-string (concat result-string field-string))))))
713
714 (defun notmuch-tree-insert-msg (msg)
715   "Insert the message MSG according to notmuch-tree-result-format"
716   ;; We need to save the previous subject as it will get overwritten
717   ;; by the insert-field calls.
718   (let ((previous-subject notmuch-tree-previous-subject))
719     (insert (notmuch-tree-format-field-list notmuch-tree-result-format msg))
720     (notmuch-tree-set-message-properties msg)
721     (notmuch-tree-set-prop :previous-subject previous-subject)
722     (insert "\n")))
723
724 (defun notmuch-tree-goto-and-insert-msg (msg)
725   "Insert msg at the end of the buffer. Move point to msg if it is the target"
726   (save-excursion
727     (goto-char (point-max))
728     (notmuch-tree-insert-msg msg))
729   (let ((msg-id (notmuch-id-to-query (plist-get msg :id)))
730         (target notmuch-tree-target-msg))
731     (when (or (and (not target) (plist-get msg :match))
732               (string= msg-id target))
733       (setq notmuch-tree-target-msg "found")
734       (goto-char (point-max))
735       (forward-line -1)
736       (when notmuch-tree-open-target
737         (notmuch-tree-show-message-in)))))
738
739 (defun notmuch-tree-insert-tree (tree depth tree-status first last)
740   "Insert the message tree TREE at depth DEPTH in the current thread.
741
742 A message tree is another name for a single sub-thread: i.e., a
743 message together with all its descendents."
744   (let ((msg (car tree))
745         (replies (cadr tree)))
746
747       (cond
748        ((and (< 0 depth) (not last))
749         (push "├" tree-status))
750        ((and (< 0 depth) last)
751         (push "╰" tree-status))
752        ((and (eq 0 depth) first last)
753 ;;        (push "─" tree-status)) choice between this and next line is matter of taste.
754         (push " " tree-status))
755        ((and (eq 0 depth) first (not last))
756           (push "┬" tree-status))
757        ((and (eq 0 depth) (not first) last)
758         (push "╰" tree-status))
759        ((and (eq 0 depth) (not first) (not last))
760         (push "├" tree-status)))
761
762       (push (concat (if replies "┬" "─") "►") tree-status)
763       (plist-put msg :first (and first (eq 0 depth)))
764       (notmuch-tree-goto-and-insert-msg (plist-put msg :tree-status tree-status))
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   (setq notmuch-tree-basic-query basic-query)
866   (setq notmuch-tree-query-context query-context)
867   (setq notmuch-tree-target-msg target)
868   (setq notmuch-tree-open-target open-target)
869
870   (erase-buffer)
871   (goto-char (point-min))
872   (let* ((search-args (concat basic-query
873                        (if query-context (concat " and (" query-context ")"))
874                        ))
875          (message-arg "--entire-thread"))
876     (if (equal (car (process-lines notmuch-command "count" search-args)) "0")
877         (setq search-args basic-query))
878     (let ((proc (notmuch-start-notmuch
879                  "notmuch-tree" (current-buffer) #'notmuch-tree-process-sentinel
880                  "show" "--body=false" "--format=sexp"
881                  message-arg search-args))
882           ;; Use a scratch buffer to accumulate partial output.
883           ;; This buffer will be killed by the sentinel, which
884           ;; should be called no matter how the process dies.
885           (parse-buf (generate-new-buffer " *notmuch tree parse*")))
886       (process-put proc 'parse-buf parse-buf)
887       (set-process-filter proc 'notmuch-tree-process-filter)
888       (set-process-query-on-exit-flag proc nil))))
889
890 (defun notmuch-tree (&optional query query-context target buffer-name open-target)
891   "Display threads matching QUERY in Tree View.
892
893 The arguments are:
894   QUERY: the main query. This can be any query but in many cases will be
895       a single thread. If nil this is read interactively from the minibuffer.
896   QUERY-CONTEXT: is an additional term for the query. The query used
897       is QUERY and QUERY-CONTEXT unless that does not match any messages
898       in which case we fall back to just QUERY.
899   TARGET: A message ID (with the id: prefix) that will be made
900       current if it appears in the tree view results.
901   BUFFER-NAME: the name of the buffer to display the tree view. If
902       it is nil \"*notmuch-tree\" followed by QUERY is used.
903   OPEN-TARGET: If TRUE open the target message in the message pane."
904   (interactive)
905   (if (null query)
906       (setq query (notmuch-read-query "Notmuch tree view search: ")))
907   (let ((buffer (get-buffer-create (generate-new-buffer-name
908                                     (or buffer-name
909                                         (concat "*notmuch-tree-" query "*")))))
910         (inhibit-read-only t))
911
912     (switch-to-buffer buffer))
913   ;; Don't track undo information for this buffer
914   (set 'buffer-undo-list t)
915
916   (notmuch-tree-worker query query-context target open-target)
917
918   (setq truncate-lines t))
919
920
921 ;; Set up key bindings from the rest of notmuch.
922 (define-key notmuch-show-mode-map "Z" 'notmuch-tree-from-show-current-query)
923
924 (provide 'notmuch-tree)