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