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