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