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