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