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