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