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