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