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