]> git.notmuchmail.org Git - notmuch/blob - contrib/notmuch-pick/notmuch-pick.el
contrib: pick: move M-RET to prefix-arg RET
[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 (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 (&optional tag-changes)
376   "Change tags for the current message"
377   (interactive)
378   (setq tag-changes (notmuch-tag (notmuch-pick-get-message-id) tag-changes))
379   (notmuch-pick-tag-update-display tag-changes))
380
381 (defun notmuch-pick-add-tag ()
382   "Same as `notmuch-pick-tag' but sets initial input to '+'."
383   (interactive)
384   (notmuch-pick-tag "+"))
385
386 (defun notmuch-pick-remove-tag ()
387   "Same as `notmuch-pick-tag' but sets initial input to '-'."
388   (interactive)
389   (notmuch-pick-tag "-"))
390
391 ;; The next two functions close the message window before searching or
392 ;; picking but they do so after the user has entered the query (in
393 ;; case the user was basing the query on something in the message
394 ;; window).
395
396 (defun notmuch-pick-to-search ()
397   "Run \"notmuch search\" with the given `query' and display results."
398   (interactive)
399   (let ((query (notmuch-read-query "Notmuch search: ")))
400     (notmuch-pick-close-message-window)
401     (notmuch-search query)))
402
403 (defun notmuch-pick-to-pick ()
404   "Run a query and display results in experimental notmuch-pick mode"
405   (interactive)
406   (let ((query (notmuch-read-query "Notmuch pick: ")))
407     (notmuch-pick-close-message-window)
408     (notmuch-pick query)))
409
410 ;; This function should be in notmuch-show.el but be we trying to
411 ;; minimise impact on the rest of the codebase.
412 (defun notmuch-pick-from-show-current-query ()
413   "Call notmuch pick with the current query"
414   (interactive)
415   (notmuch-pick notmuch-show-thread-id
416                 notmuch-show-query-context
417                 (notmuch-show-get-message-id)))
418
419 ;; This function should be in notmuch.el but be we trying to minimise
420 ;; impact on the rest of the codebase.
421 (defun notmuch-pick-from-search-current-query ()
422   "Call notmuch pick with the current query"
423   (interactive)
424   (notmuch-pick notmuch-search-query-string))
425
426 ;; This function should be in notmuch.el but be we trying to minimise
427 ;; impact on the rest of the codebase.
428 (defun notmuch-pick-from-search-thread ()
429   "Show the selected thread with notmuch-pick"
430   (interactive)
431   (notmuch-pick (notmuch-search-find-thread-id)
432                 notmuch-search-query-string
433                 nil
434                 (notmuch-prettify-subject (notmuch-search-find-subject))
435                 t))
436
437 (defun notmuch-pick-message-window-kill-hook ()
438   "Close the message pane when exiting the show buffer."
439   (let ((buffer (current-buffer)))
440     (when (and (window-live-p notmuch-pick-message-window)
441                (eq (window-buffer notmuch-pick-message-window) buffer))
442       ;; We do not want an error if this is the sole window in the
443       ;; frame and I do not know how to test for that in emacs pre
444       ;; 24. Hence we just ignore-errors.
445       (ignore-errors
446         (delete-window notmuch-pick-message-window)))))
447
448 (defun notmuch-pick-show-message-in ()
449   "Show the current message (in split-pane)."
450   (interactive)
451   (let ((id (notmuch-pick-get-message-id))
452         (inhibit-read-only t)
453         buffer)
454     (when id
455       ;; We close and reopen the window to kill off un-needed buffers
456       ;; this might cause flickering but seems ok.
457       (notmuch-pick-close-message-window)
458       (setq notmuch-pick-message-window
459             (split-window-vertically (/ (window-height) 4)))
460       (with-selected-window notmuch-pick-message-window
461         ;; Since we are only displaying one message do not indent.
462         (let ((notmuch-show-indent-messages-width 0)
463               (notmuch-show-only-matching-messages t))
464           (setq buffer (notmuch-show id nil nil nil))))
465       ;; We need the `let' as notmuch-pick-message-window is buffer local.
466       (let ((window notmuch-pick-message-window))
467         (with-current-buffer buffer
468           (setq notmuch-pick-message-window window)
469           (add-hook 'kill-buffer-hook 'notmuch-pick-message-window-kill-hook)))
470       (when notmuch-show-mark-read-tags
471         (notmuch-pick-tag-update-display notmuch-show-mark-read-tags))
472       (setq notmuch-pick-message-buffer buffer))))
473
474 (defun notmuch-pick-show-message-out ()
475   "Show the current message (in whole window)."
476   (interactive)
477   (let ((id (notmuch-pick-get-message-id))
478         (inhibit-read-only t)
479         buffer)
480     (when id
481       ;; We close the window to kill off un-needed buffers.
482       (notmuch-pick-close-message-window)
483       (notmuch-show id nil nil nil))))
484
485 (defun notmuch-pick-show-message (arg)
486   "Show the current message.
487
488 Shows in split pane or whole window according to value of
489 `notmuch-pick-show-out'. A prefix argument reverses the choice."
490   (interactive "P")
491   (if (or (and notmuch-pick-show-out  (not arg))
492           (and (not notmuch-pick-show-out) arg))
493       (notmuch-pick-show-message-out)
494     (notmuch-pick-show-message-in)))
495
496 (defun notmuch-pick-scroll-message-window ()
497   "Scroll the message window (if it exists)"
498   (interactive)
499   (when (window-live-p notmuch-pick-message-window)
500     (with-selected-window notmuch-pick-message-window
501       (if (pos-visible-in-window-p (point-max))
502           t
503         (scroll-up)))))
504
505 (defun notmuch-pick-scroll-message-window-back ()
506   "Scroll the message window back(if it exists)"
507   (interactive)
508   (when (window-live-p notmuch-pick-message-window)
509     (with-selected-window notmuch-pick-message-window
510       (if (pos-visible-in-window-p (point-min))
511           t
512         (scroll-down)))))
513
514 (defun notmuch-pick-scroll-or-next ()
515   "Scroll the message window. If it at end go to next message."
516   (interactive)
517   (when (notmuch-pick-scroll-message-window)
518     (notmuch-pick-next-matching-message)))
519
520 (defun notmuch-pick-quit ()
521   "Close the split view or exit pick."
522   (interactive)
523   (unless (notmuch-pick-close-message-window)
524     (kill-buffer (current-buffer))))
525
526 (defun notmuch-pick-close-message-window ()
527   "Close the message-window. Return t if close succeeds."
528   (interactive)
529   (when (and (window-live-p notmuch-pick-message-window)
530              (eq (window-buffer notmuch-pick-message-window) notmuch-pick-message-buffer))
531     (delete-window notmuch-pick-message-window)
532     (unless (get-buffer-window-list notmuch-pick-message-buffer)
533       (kill-buffer notmuch-pick-message-buffer))
534     t))
535
536 (defun notmuch-pick-archive-message (&optional unarchive)
537   "Archive the current message.
538
539 Archive the current message by applying the tag changes in
540 `notmuch-archive-tags' to it. If a prefix argument is given, the
541 message will be \"unarchived\", i.e. the tag changes in
542 `notmuch-archive-tags' will be reversed."
543   (interactive "P")
544   (when notmuch-archive-tags
545     (apply 'notmuch-pick-tag
546            (notmuch-tag-change-list notmuch-archive-tags unarchive))))
547
548 (defun notmuch-pick-archive-message-then-next (&optional unarchive)
549   "Archive the current message and move to next matching message."
550   (interactive "P")
551   (notmuch-pick-archive-message unarchive)
552   (notmuch-pick-next-matching-message))
553
554 (defun notmuch-pick-next-message ()
555   "Move to next message."
556   (interactive)
557   (forward-line)
558   (when (window-live-p notmuch-pick-message-window)
559     (notmuch-pick-show-message-in)))
560
561 (defun notmuch-pick-prev-message ()
562   "Move to previous message."
563   (interactive)
564   (forward-line -1)
565   (when (window-live-p notmuch-pick-message-window)
566     (notmuch-pick-show-message-in)))
567
568 (defun notmuch-pick-prev-matching-message ()
569   "Move to previous matching message."
570   (interactive)
571   (forward-line -1)
572   (while (and (not (bobp)) (not (notmuch-pick-get-match)))
573     (forward-line -1))
574   (when (window-live-p notmuch-pick-message-window)
575     (notmuch-pick-show-message-in)))
576
577 (defun notmuch-pick-next-matching-message ()
578   "Move to next matching message."
579   (interactive)
580   (forward-line)
581   (while (and (not (eobp)) (not (notmuch-pick-get-match)))
582     (forward-line))
583   (when (window-live-p notmuch-pick-message-window)
584     (notmuch-pick-show-message-in)))
585
586 (defun notmuch-pick-refresh-view ()
587   "Refresh view."
588   (interactive)
589   (let ((inhibit-read-only t)
590         (basic-query notmuch-pick-basic-query)
591         (query-context notmuch-pick-query-context)
592         (target (notmuch-pick-get-message-id)))
593     (erase-buffer)
594     (notmuch-pick-worker basic-query
595                          query-context
596                          target)))
597
598 (defun notmuch-pick-thread-top ()
599   (when (notmuch-pick-get-message-properties)
600     (while (not (or (notmuch-pick-get-prop :first) (eobp)))
601       (forward-line -1))))
602
603 (defun notmuch-pick-prev-thread ()
604   (interactive)
605   (forward-line -1)
606   (notmuch-pick-thread-top))
607
608 (defun notmuch-pick-next-thread ()
609   (interactive)
610   (forward-line 1)
611   (while (not (or (notmuch-pick-get-prop :first) (eobp)))
612     (forward-line 1)))
613
614 (defun notmuch-pick-thread-mapcar (function)
615   "Iterate through all messages in the current thread
616  and call FUNCTION for side effects."
617   (save-excursion
618     (notmuch-pick-thread-top)
619     (loop collect (funcall function)
620           do (forward-line)
621           while (and (notmuch-pick-get-message-properties)
622                      (not (notmuch-pick-get-prop :first))))))
623
624 (defun notmuch-pick-get-messages-ids-thread-search ()
625   "Return a search string for all message ids of messages in the current thread."
626   (mapconcat 'identity
627              (notmuch-pick-thread-mapcar 'notmuch-pick-get-message-id)
628              " or "))
629
630 (defun notmuch-pick-tag-thread (&optional tag-changes)
631   "Tag all messages in the current thread"
632   (interactive)
633   (when (notmuch-pick-get-message-properties)
634     (let ((tag-changes (notmuch-tag (notmuch-pick-get-messages-ids-thread-search) tag-changes)))
635       (notmuch-pick-thread-mapcar
636        (lambda () (notmuch-pick-tag-update-display tag-changes))))))
637
638 (defun notmuch-pick-archive-thread (&optional unarchive)
639   "Archive each message in thread.
640
641 Archive each message currently shown by applying the tag changes
642 in `notmuch-archive-tags' to each. If a prefix argument is given,
643 the messages will be \"unarchived\", i.e. the tag changes in
644 `notmuch-archive-tags' will be reversed.
645
646 Note: This command is safe from any race condition of new messages
647 being delivered to the same thread. It does not archive the
648 entire thread, but only the messages shown in the current
649 buffer."
650   (interactive "P")
651   (when notmuch-archive-tags
652     (notmuch-pick-tag-thread
653      (notmuch-tag-change-list notmuch-archive-tags unarchive))))
654
655 ;; Functions below here display the pick buffer itself.
656
657 (defun notmuch-pick-clean-address (address)
658   "Try to clean a single email ADDRESS for display. Return
659 AUTHOR_NAME if present, otherwise return AUTHOR_EMAIL. Return
660 unchanged ADDRESS if parsing fails."
661   (let* ((clean-address (notmuch-clean-address address))
662          (p-address (car clean-address))
663          (p-name (cdr clean-address)))
664
665     ;; If we have a name return that otherwise return the address.
666     (or p-name p-address)))
667
668 (defun notmuch-pick-format-field (field format-string msg)
669   "Format a FIELD of MSG according to FORMAT-STRING and return string"
670   (let* ((headers (plist-get msg :headers))
671          (match (plist-get msg :match)))
672     (cond
673      ((listp field)
674       (format format-string (notmuch-pick-format-field-list field msg)))
675
676      ((string-equal field "date")
677       (let ((face (if match
678                       'notmuch-pick-match-date-face
679                     'notmuch-pick-no-match-date-face)))
680         (propertize (format format-string (plist-get msg :date_relative)) 'face face)))
681
682      ((string-equal field "tree")
683       (let ((tree-status (plist-get msg :tree-status))
684             (face (if match
685                       'notmuch-pick-match-tree-face
686                     'notmuch-pick-no-match-tree-face)))
687
688         (propertize (format format-string
689                             (mapconcat #'identity (reverse tree-status) ""))
690                     'face face)))
691
692      ((string-equal field "subject")
693       (let ((bare-subject (notmuch-show-strip-re (plist-get headers :Subject)))
694             (previous-subject notmuch-pick-previous-subject)
695             (face (if match
696                       'notmuch-pick-match-subject-face
697                     'notmuch-pick-no-match-subject-face)))
698
699         (setq notmuch-pick-previous-subject bare-subject)
700         (propertize (format format-string
701                             (if (string= previous-subject bare-subject)
702                                 " ..."
703                               bare-subject))
704                     'face face)))
705
706      ((string-equal field "authors")
707       (let ((author (notmuch-pick-clean-address (plist-get headers :From)))
708             (len (length (format format-string "")))
709             (face (if match
710                       'notmuch-pick-match-author-face
711                     'notmuch-pick-no-match-author-face)))
712         (when (> (length author) len)
713           (setq author (substring author 0 len)))
714         (propertize (format format-string author) 'face face)))
715
716      ((string-equal field "tags")
717       (let ((tags (plist-get msg :tags))
718             (face (if match
719                       'notmuch-pick-match-tag-face
720                     'notmuch-pick-no-match-tag-face)))
721         (propertize (format format-string
722                             (mapconcat #'identity tags ", "))
723                     'face face))))))
724
725
726 (defun notmuch-pick-format-field-list (field-list msg)
727   "Format fields of MSG according to FIELD-LIST and return string"
728   (let (result-string)
729     (dolist (spec field-list result-string)
730       (let ((field-string (notmuch-pick-format-field (car spec) (cdr spec) msg)))
731         (setq result-string (concat result-string field-string))))))
732
733 (defun notmuch-pick-insert-msg (msg)
734   "Insert the message MSG according to notmuch-pick-result-format"
735   ;; We need to save the previous subject as it will get overwritten
736   ;; by the insert-field calls.
737   (let ((previous-subject notmuch-pick-previous-subject))
738     (insert (notmuch-pick-format-field-list notmuch-pick-result-format msg))
739     (notmuch-pick-set-message-properties msg)
740     (notmuch-pick-set-prop :previous-subject previous-subject)
741     (insert "\n")))
742
743 (defun notmuch-pick-goto-and-insert-msg (msg)
744   "Insert msg at the end of the buffer. Move point to msg if it is the target"
745   (save-excursion
746     (goto-char (point-max))
747     (notmuch-pick-insert-msg msg))
748   (let ((msg-id (notmuch-id-to-query (plist-get msg :id)))
749         (target notmuch-pick-target-msg))
750     (when (or (and (not target) (plist-get msg :match))
751               (string= msg-id target))
752       (setq notmuch-pick-target-msg "found")
753       (goto-char (point-max))
754       (forward-line -1)
755       (when notmuch-pick-open-target
756         (notmuch-pick-show-message-in)))))
757
758 (defun notmuch-pick-insert-tree (tree depth tree-status first last)
759   "Insert the message tree TREE at depth DEPTH in the current thread.
760
761 A message tree is another name for a single sub-thread: i.e., a
762 message together with all its descendents."
763   (let ((msg (car tree))
764         (replies (cadr tree)))
765
766       (cond
767        ((and (< 0 depth) (not last))
768         (push "├" tree-status))
769        ((and (< 0 depth) last)
770         (push "╰" tree-status))
771        ((and (eq 0 depth) first last)
772 ;;        (push "─" tree-status)) choice between this and next line is matter of taste.
773         (push " " tree-status))
774        ((and (eq 0 depth) first (not last))
775           (push "┬" tree-status))
776        ((and (eq 0 depth) (not first) last)
777         (push "╰" tree-status))
778        ((and (eq 0 depth) (not first) (not last))
779         (push "├" tree-status)))
780
781       (push (concat (if replies "┬" "─") "►") tree-status)
782       (plist-put msg :first (and first (eq 0 depth)))
783       (notmuch-pick-goto-and-insert-msg (plist-put msg :tree-status tree-status))
784       (pop tree-status)
785       (pop tree-status)
786
787       (if last
788           (push " " tree-status)
789         (push "│" tree-status))
790
791     (notmuch-pick-insert-thread replies (1+ depth) tree-status)))
792
793 (defun notmuch-pick-insert-thread (thread depth tree-status)
794   "Insert the collection of sibling sub-threads THREAD at depth DEPTH in the current forest."
795   (let ((n (length thread)))
796     (loop for tree in thread
797           for count from 1 to n
798
799           do (notmuch-pick-insert-tree tree depth tree-status (eq count 1) (eq count n)))))
800
801 (defun notmuch-pick-insert-forest-thread (forest-thread)
802   "Insert a single complete thread."
803   (let (tree-status)
804     ;; Reset at the start of each main thread.
805     (setq notmuch-pick-previous-subject nil)
806     (notmuch-pick-insert-thread forest-thread 0 tree-status)))
807
808 (defun notmuch-pick-insert-forest (forest)
809   "Insert a forest of threads.
810
811 This function inserts a collection of several complete threads as
812 passed to it by notmuch-pick-process-filter."
813   (mapc 'notmuch-pick-insert-forest-thread forest))
814
815 (defun notmuch-pick-mode ()
816   "Major mode displaying messages (as opposed to threads) of of a notmuch search.
817
818 This buffer contains the results of a \"notmuch pick\" of your
819 email archives. Each line in the buffer represents a single
820 message giving the relative date, the author, subject, and any
821 tags.
822
823 Pressing \\[notmuch-pick-show-message] on any line displays that message.
824
825 Complete list of currently available key bindings:
826
827 \\{notmuch-pick-mode-map}"
828
829   (interactive)
830   (kill-all-local-variables)
831   (setq notmuch-buffer-refresh-function #'notmuch-pick-refresh-view)
832   (use-local-map notmuch-pick-mode-map)
833   (setq major-mode 'notmuch-pick-mode
834         mode-name "notmuch-pick")
835   (hl-line-mode 1)
836   (setq buffer-read-only t
837         truncate-lines t))
838
839 (defun notmuch-pick-process-sentinel (proc msg)
840   "Add a message to let user know when \"notmuch pick\" exits"
841   (let ((buffer (process-buffer proc))
842         (status (process-status proc))
843         (exit-status (process-exit-status proc))
844         (never-found-target-thread nil))
845     (when (memq status '(exit signal))
846         (kill-buffer (process-get proc 'parse-buf))
847         (if (buffer-live-p buffer)
848             (with-current-buffer buffer
849               (save-excursion
850                 (let ((inhibit-read-only t)
851                       (atbob (bobp)))
852                   (goto-char (point-max))
853                   (if (eq status 'signal)
854                       (insert "Incomplete search results (pick process was killed).\n"))
855                   (when (eq status 'exit)
856                     (insert "End of search results.")
857                     (unless (= exit-status 0)
858                       (insert (format " (process returned %d)" exit-status)))
859                     (insert "\n")))))))))
860
861 (defun notmuch-pick-process-filter (proc string)
862   "Process and filter the output of \"notmuch show\" (for pick)"
863   (let ((results-buf (process-buffer proc))
864         (parse-buf (process-get proc 'parse-buf))
865         (inhibit-read-only t)
866         done)
867     (if (not (buffer-live-p results-buf))
868         (delete-process proc)
869       (with-current-buffer parse-buf
870         ;; Insert new data
871         (save-excursion
872           (goto-char (point-max))
873           (insert string))
874         (notmuch-sexp-parse-partial-list 'notmuch-pick-insert-forest-thread
875                                          results-buf)))))
876
877 (defun notmuch-pick-worker (basic-query &optional query-context target open-target)
878   "Insert the actual pick search in the current buffer.
879
880 This is is a helper function for notmuch-pick. The arguments are
881 the same as for the function notmuch-pick."
882   (interactive)
883   (notmuch-pick-mode)
884   (setq notmuch-pick-basic-query basic-query)
885   (setq notmuch-pick-query-context query-context)
886   (setq notmuch-pick-target-msg target)
887   (setq notmuch-pick-open-target open-target)
888
889   (erase-buffer)
890   (goto-char (point-min))
891   (let* ((search-args (concat basic-query
892                        (if query-context (concat " and (" query-context ")"))
893                        ))
894          (message-arg "--entire-thread"))
895     (if (equal (car (process-lines notmuch-command "count" search-args)) "0")
896         (setq search-args basic-query))
897     (let ((proc (notmuch-start-notmuch
898                  "notmuch-pick" (current-buffer) #'notmuch-pick-process-sentinel
899                  "show" "--body=false" "--format=sexp"
900                  message-arg search-args))
901           ;; Use a scratch buffer to accumulate partial output.
902           ;; This buffer will be killed by the sentinel, which
903           ;; should be called no matter how the process dies.
904           (parse-buf (generate-new-buffer " *notmuch pick parse*")))
905       (process-put proc 'parse-buf parse-buf)
906       (set-process-filter proc 'notmuch-pick-process-filter)
907       (set-process-query-on-exit-flag proc nil))))
908
909 (defun notmuch-pick (&optional query query-context target buffer-name open-target)
910   "Run notmuch pick with the given `query' and display the results.
911
912 The arguments are:
913   QUERY: the main query. This can be any query but in many cases will be
914       a single thread. If nil this is read interactively from the minibuffer.
915   QUERY-CONTEXT: is an additional term for the query. The query used
916       is QUERY and QUERY-CONTEXT unless that does not match any messages
917       in which case we fall back to just QUERY.
918   TARGET: A message ID (with the id: prefix) that will be made
919       current if it appears in the pick results.
920   BUFFER-NAME: the name of the buffer to show the pick tree. If
921       it is nil \"*notmuch-pick\" followed by QUERY is used.
922   OPEN-TARGET: If TRUE open the target message in the message pane."
923   (interactive)
924   (if (null query)
925       (setq query (notmuch-read-query "Notmuch pick: ")))
926   (let ((buffer (get-buffer-create (generate-new-buffer-name
927                                     (or buffer-name
928                                         (concat "*notmuch-pick-" query "*")))))
929         (inhibit-read-only t))
930
931     (switch-to-buffer buffer))
932   ;; Don't track undo information for this buffer
933   (set 'buffer-undo-list t)
934
935   (notmuch-pick-worker query query-context target open-target)
936
937   (setq truncate-lines t))
938
939
940 ;; Set up key bindings from the rest of notmuch.
941 (define-key notmuch-common-keymap "z" 'notmuch-pick)
942 (define-key notmuch-search-mode-map "Z" 'notmuch-pick-from-search-current-query)
943 (define-key notmuch-search-mode-map (kbd "M-RET") 'notmuch-pick-from-search-thread)
944 (define-key notmuch-show-mode-map "Z" 'notmuch-pick-from-show-current-query)
945 (message "Initialised notmuch-pick")
946
947 (provide 'notmuch-pick)