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