]> git.notmuchmail.org Git - notmuch/blob - contrib/notmuch-pick/notmuch-pick.el
pick: Use list form of tag-changes in test
[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))))
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))))
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     (notmuch-pick-tag (notmuch-tag-change-list notmuch-archive-tags unarchive))))
546
547 (defun notmuch-pick-archive-message-then-next (&optional unarchive)
548   "Archive the current message and move to next matching message."
549   (interactive "P")
550   (notmuch-pick-archive-message unarchive)
551   (notmuch-pick-next-matching-message))
552
553 (defun notmuch-pick-next-message ()
554   "Move to next message."
555   (interactive)
556   (forward-line)
557   (when (window-live-p notmuch-pick-message-window)
558     (notmuch-pick-show-message-in)))
559
560 (defun notmuch-pick-prev-message ()
561   "Move to previous message."
562   (interactive)
563   (forward-line -1)
564   (when (window-live-p notmuch-pick-message-window)
565     (notmuch-pick-show-message-in)))
566
567 (defun notmuch-pick-prev-matching-message ()
568   "Move to previous matching message."
569   (interactive)
570   (forward-line -1)
571   (while (and (not (bobp)) (not (notmuch-pick-get-match)))
572     (forward-line -1))
573   (when (window-live-p notmuch-pick-message-window)
574     (notmuch-pick-show-message-in)))
575
576 (defun notmuch-pick-next-matching-message ()
577   "Move to next matching message."
578   (interactive)
579   (forward-line)
580   (while (and (not (eobp)) (not (notmuch-pick-get-match)))
581     (forward-line))
582   (when (window-live-p notmuch-pick-message-window)
583     (notmuch-pick-show-message-in)))
584
585 (defun notmuch-pick-refresh-view ()
586   "Refresh view."
587   (interactive)
588   (let ((inhibit-read-only t)
589         (basic-query notmuch-pick-basic-query)
590         (query-context notmuch-pick-query-context)
591         (target (notmuch-pick-get-message-id)))
592     (erase-buffer)
593     (notmuch-pick-worker basic-query
594                          query-context
595                          target)))
596
597 (defun notmuch-pick-thread-top ()
598   (when (notmuch-pick-get-message-properties)
599     (while (not (or (notmuch-pick-get-prop :first) (eobp)))
600       (forward-line -1))))
601
602 (defun notmuch-pick-prev-thread ()
603   (interactive)
604   (forward-line -1)
605   (notmuch-pick-thread-top))
606
607 (defun notmuch-pick-next-thread ()
608   (interactive)
609   (forward-line 1)
610   (while (not (or (notmuch-pick-get-prop :first) (eobp)))
611     (forward-line 1)))
612
613 (defun notmuch-pick-thread-mapcar (function)
614   "Iterate through all messages in the current thread
615  and call FUNCTION for side effects."
616   (save-excursion
617     (notmuch-pick-thread-top)
618     (loop collect (funcall function)
619           do (forward-line)
620           while (and (notmuch-pick-get-message-properties)
621                      (not (notmuch-pick-get-prop :first))))))
622
623 (defun notmuch-pick-get-messages-ids-thread-search ()
624   "Return a search string for all message ids of messages in the current thread."
625   (mapconcat 'identity
626              (notmuch-pick-thread-mapcar 'notmuch-pick-get-message-id)
627              " or "))
628
629 (defun notmuch-pick-tag-thread (&optional tag-changes)
630   "Tag all messages in the current thread"
631   (interactive)
632   (when (notmuch-pick-get-message-properties)
633     (let ((tag-changes (notmuch-tag (notmuch-pick-get-messages-ids-thread-search) tag-changes)))
634       (notmuch-pick-thread-mapcar
635        (lambda () (notmuch-pick-tag-update-display tag-changes))))))
636
637 (defun notmuch-pick-archive-thread (&optional unarchive)
638   "Archive each message in thread.
639
640 Archive each message currently shown by applying the tag changes
641 in `notmuch-archive-tags' to each. If a prefix argument is given,
642 the messages will be \"unarchived\", i.e. the tag changes in
643 `notmuch-archive-tags' will be reversed.
644
645 Note: This command is safe from any race condition of new messages
646 being delivered to the same thread. It does not archive the
647 entire thread, but only the messages shown in the current
648 buffer."
649   (interactive "P")
650   (when notmuch-archive-tags
651     (notmuch-pick-tag-thread
652      (notmuch-tag-change-list notmuch-archive-tags unarchive))))
653
654 ;; Functions below here display the pick buffer itself.
655
656 (defun notmuch-pick-clean-address (address)
657   "Try to clean a single email ADDRESS for display. Return
658 AUTHOR_NAME if present, otherwise return AUTHOR_EMAIL. Return
659 unchanged ADDRESS if parsing fails."
660   (let* ((clean-address (notmuch-clean-address address))
661          (p-address (car clean-address))
662          (p-name (cdr clean-address)))
663
664     ;; If we have a name return that otherwise return the address.
665     (or p-name p-address)))
666
667 (defun notmuch-pick-format-field (field format-string msg)
668   "Format a FIELD of MSG according to FORMAT-STRING and return string"
669   (let* ((headers (plist-get msg :headers))
670          (match (plist-get msg :match)))
671     (cond
672      ((listp field)
673       (format format-string (notmuch-pick-format-field-list field msg)))
674
675      ((string-equal field "date")
676       (let ((face (if match
677                       'notmuch-pick-match-date-face
678                     'notmuch-pick-no-match-date-face)))
679         (propertize (format format-string (plist-get msg :date_relative)) 'face face)))
680
681      ((string-equal field "tree")
682       (let ((tree-status (plist-get msg :tree-status))
683             (face (if match
684                       'notmuch-pick-match-tree-face
685                     'notmuch-pick-no-match-tree-face)))
686
687         (propertize (format format-string
688                             (mapconcat #'identity (reverse tree-status) ""))
689                     'face face)))
690
691      ((string-equal field "subject")
692       (let ((bare-subject (notmuch-show-strip-re (plist-get headers :Subject)))
693             (previous-subject notmuch-pick-previous-subject)
694             (face (if match
695                       'notmuch-pick-match-subject-face
696                     'notmuch-pick-no-match-subject-face)))
697
698         (setq notmuch-pick-previous-subject bare-subject)
699         (propertize (format format-string
700                             (if (string= previous-subject bare-subject)
701                                 " ..."
702                               bare-subject))
703                     'face face)))
704
705      ((string-equal field "authors")
706       (let ((author (notmuch-pick-clean-address (plist-get headers :From)))
707             (len (length (format format-string "")))
708             (face (if match
709                       'notmuch-pick-match-author-face
710                     'notmuch-pick-no-match-author-face)))
711         (when (> (length author) len)
712           (setq author (substring author 0 len)))
713         (propertize (format format-string author) 'face face)))
714
715      ((string-equal field "tags")
716       (let ((tags (plist-get msg :tags))
717             (face (if match
718                       'notmuch-pick-match-tag-face
719                     'notmuch-pick-no-match-tag-face)))
720         (propertize (format format-string
721                             (mapconcat #'identity tags ", "))
722                     'face face))))))
723
724
725 (defun notmuch-pick-format-field-list (field-list msg)
726   "Format fields of MSG according to FIELD-LIST and return string"
727   (let (result-string)
728     (dolist (spec field-list result-string)
729       (let ((field-string (notmuch-pick-format-field (car spec) (cdr spec) msg)))
730         (setq result-string (concat result-string field-string))))))
731
732 (defun notmuch-pick-insert-msg (msg)
733   "Insert the message MSG according to notmuch-pick-result-format"
734   ;; We need to save the previous subject as it will get overwritten
735   ;; by the insert-field calls.
736   (let ((previous-subject notmuch-pick-previous-subject))
737     (insert (notmuch-pick-format-field-list notmuch-pick-result-format msg))
738     (notmuch-pick-set-message-properties msg)
739     (notmuch-pick-set-prop :previous-subject previous-subject)
740     (insert "\n")))
741
742 (defun notmuch-pick-goto-and-insert-msg (msg)
743   "Insert msg at the end of the buffer. Move point to msg if it is the target"
744   (save-excursion
745     (goto-char (point-max))
746     (notmuch-pick-insert-msg msg))
747   (let ((msg-id (notmuch-id-to-query (plist-get msg :id)))
748         (target notmuch-pick-target-msg))
749     (when (or (and (not target) (plist-get msg :match))
750               (string= msg-id target))
751       (setq notmuch-pick-target-msg "found")
752       (goto-char (point-max))
753       (forward-line -1)
754       (when notmuch-pick-open-target
755         (notmuch-pick-show-message-in)))))
756
757 (defun notmuch-pick-insert-tree (tree depth tree-status first last)
758   "Insert the message tree TREE at depth DEPTH in the current thread.
759
760 A message tree is another name for a single sub-thread: i.e., a
761 message together with all its descendents."
762   (let ((msg (car tree))
763         (replies (cadr tree)))
764
765       (cond
766        ((and (< 0 depth) (not last))
767         (push "├" tree-status))
768        ((and (< 0 depth) last)
769         (push "╰" tree-status))
770        ((and (eq 0 depth) first last)
771 ;;        (push "─" tree-status)) choice between this and next line is matter of taste.
772         (push " " tree-status))
773        ((and (eq 0 depth) first (not last))
774           (push "┬" tree-status))
775        ((and (eq 0 depth) (not first) last)
776         (push "╰" tree-status))
777        ((and (eq 0 depth) (not first) (not last))
778         (push "├" tree-status)))
779
780       (push (concat (if replies "┬" "─") "►") tree-status)
781       (plist-put msg :first (and first (eq 0 depth)))
782       (notmuch-pick-goto-and-insert-msg (plist-put msg :tree-status tree-status))
783       (pop tree-status)
784       (pop tree-status)
785
786       (if last
787           (push " " tree-status)
788         (push "│" tree-status))
789
790     (notmuch-pick-insert-thread replies (1+ depth) tree-status)))
791
792 (defun notmuch-pick-insert-thread (thread depth tree-status)
793   "Insert the collection of sibling sub-threads THREAD at depth DEPTH in the current forest."
794   (let ((n (length thread)))
795     (loop for tree in thread
796           for count from 1 to n
797
798           do (notmuch-pick-insert-tree tree depth tree-status (eq count 1) (eq count n)))))
799
800 (defun notmuch-pick-insert-forest-thread (forest-thread)
801   "Insert a single complete thread."
802   (let (tree-status)
803     ;; Reset at the start of each main thread.
804     (setq notmuch-pick-previous-subject nil)
805     (notmuch-pick-insert-thread forest-thread 0 tree-status)))
806
807 (defun notmuch-pick-insert-forest (forest)
808   "Insert a forest of threads.
809
810 This function inserts a collection of several complete threads as
811 passed to it by notmuch-pick-process-filter."
812   (mapc 'notmuch-pick-insert-forest-thread forest))
813
814 (defun notmuch-pick-mode ()
815   "Major mode displaying messages (as opposed to threads) of of a notmuch search.
816
817 This buffer contains the results of a \"notmuch pick\" of your
818 email archives. Each line in the buffer represents a single
819 message giving the relative date, the author, subject, and any
820 tags.
821
822 Pressing \\[notmuch-pick-show-message] on any line displays that message.
823
824 Complete list of currently available key bindings:
825
826 \\{notmuch-pick-mode-map}"
827
828   (interactive)
829   (kill-all-local-variables)
830   (setq notmuch-buffer-refresh-function #'notmuch-pick-refresh-view)
831   (use-local-map notmuch-pick-mode-map)
832   (setq major-mode 'notmuch-pick-mode
833         mode-name "notmuch-pick")
834   (hl-line-mode 1)
835   (setq buffer-read-only t
836         truncate-lines t))
837
838 (defun notmuch-pick-process-sentinel (proc msg)
839   "Add a message to let user know when \"notmuch pick\" exits"
840   (let ((buffer (process-buffer proc))
841         (status (process-status proc))
842         (exit-status (process-exit-status proc))
843         (never-found-target-thread nil))
844     (when (memq status '(exit signal))
845         (kill-buffer (process-get proc 'parse-buf))
846         (if (buffer-live-p buffer)
847             (with-current-buffer buffer
848               (save-excursion
849                 (let ((inhibit-read-only t)
850                       (atbob (bobp)))
851                   (goto-char (point-max))
852                   (if (eq status 'signal)
853                       (insert "Incomplete search results (pick process was killed).\n"))
854                   (when (eq status 'exit)
855                     (insert "End of search results.")
856                     (unless (= exit-status 0)
857                       (insert (format " (process returned %d)" exit-status)))
858                     (insert "\n")))))))))
859
860 (defun notmuch-pick-process-filter (proc string)
861   "Process and filter the output of \"notmuch show\" (for pick)"
862   (let ((results-buf (process-buffer proc))
863         (parse-buf (process-get proc 'parse-buf))
864         (inhibit-read-only t)
865         done)
866     (if (not (buffer-live-p results-buf))
867         (delete-process proc)
868       (with-current-buffer parse-buf
869         ;; Insert new data
870         (save-excursion
871           (goto-char (point-max))
872           (insert string))
873         (notmuch-sexp-parse-partial-list 'notmuch-pick-insert-forest-thread
874                                          results-buf)))))
875
876 (defun notmuch-pick-worker (basic-query &optional query-context target open-target)
877   "Insert the actual pick search in the current buffer.
878
879 This is is a helper function for notmuch-pick. The arguments are
880 the same as for the function notmuch-pick."
881   (interactive)
882   (notmuch-pick-mode)
883   (setq notmuch-pick-basic-query basic-query)
884   (setq notmuch-pick-query-context query-context)
885   (setq notmuch-pick-target-msg target)
886   (setq notmuch-pick-open-target open-target)
887
888   (erase-buffer)
889   (goto-char (point-min))
890   (let* ((search-args (concat basic-query
891                        (if query-context (concat " and (" query-context ")"))
892                        ))
893          (message-arg "--entire-thread"))
894     (if (equal (car (process-lines notmuch-command "count" search-args)) "0")
895         (setq search-args basic-query))
896     (let ((proc (notmuch-start-notmuch
897                  "notmuch-pick" (current-buffer) #'notmuch-pick-process-sentinel
898                  "show" "--body=false" "--format=sexp"
899                  message-arg search-args))
900           ;; Use a scratch buffer to accumulate partial output.
901           ;; This buffer will be killed by the sentinel, which
902           ;; should be called no matter how the process dies.
903           (parse-buf (generate-new-buffer " *notmuch pick parse*")))
904       (process-put proc 'parse-buf parse-buf)
905       (set-process-filter proc 'notmuch-pick-process-filter)
906       (set-process-query-on-exit-flag proc nil))))
907
908 (defun notmuch-pick (&optional query query-context target buffer-name open-target)
909   "Run notmuch pick with the given `query' and display the results.
910
911 The arguments are:
912   QUERY: the main query. This can be any query but in many cases will be
913       a single thread. If nil this is read interactively from the minibuffer.
914   QUERY-CONTEXT: is an additional term for the query. The query used
915       is QUERY and QUERY-CONTEXT unless that does not match any messages
916       in which case we fall back to just QUERY.
917   TARGET: A message ID (with the id: prefix) that will be made
918       current if it appears in the pick results.
919   BUFFER-NAME: the name of the buffer to show the pick tree. If
920       it is nil \"*notmuch-pick\" followed by QUERY is used.
921   OPEN-TARGET: If TRUE open the target message in the message pane."
922   (interactive)
923   (if (null query)
924       (setq query (notmuch-read-query "Notmuch pick: ")))
925   (let ((buffer (get-buffer-create (generate-new-buffer-name
926                                     (or buffer-name
927                                         (concat "*notmuch-pick-" query "*")))))
928         (inhibit-read-only t))
929
930     (switch-to-buffer buffer))
931   ;; Don't track undo information for this buffer
932   (set 'buffer-undo-list t)
933
934   (notmuch-pick-worker query query-context target open-target)
935
936   (setq truncate-lines t))
937
938
939 ;; Set up key bindings from the rest of notmuch.
940 (define-key notmuch-common-keymap "z" 'notmuch-pick)
941 (define-key notmuch-search-mode-map "Z" 'notmuch-pick-from-search-current-query)
942 (define-key notmuch-show-mode-map "Z" 'notmuch-pick-from-show-current-query)
943 (message "Initialised notmuch-pick")
944
945 (provide 'notmuch-pick)