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