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