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