]> git.notmuchmail.org Git - notmuch/blob - contrib/notmuch-pick/notmuch-pick.el
contrib: pick: remove sync parser
[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-clean-address (address)
598   "Try to clean a single email ADDRESS for display. Return
599 AUTHOR_NAME if present, otherwise return AUTHOR_EMAIL. Return
600 unchanged ADDRESS if parsing fails."
601   (let* ((clean-address (notmuch-clean-address address))
602          (p-address (car clean-address))
603          (p-name (cdr clean-address)))
604
605     ;; If we have a name return that otherwise return the address.
606     (or p-name p-address)))
607
608 (defun notmuch-pick-insert-field (field format-string msg)
609   (let* ((headers (plist-get msg :headers))
610         (match (plist-get msg :match)))
611     (cond
612      ((string-equal field "date")
613       (let ((face (if match
614                       'notmuch-pick-match-date-face
615                     'notmuch-pick-no-match-date-face)))
616         (insert (propertize (format format-string (plist-get msg :date_relative))
617                             'face face))))
618
619      ((string-equal field "subject")
620       (let ((tree-status (plist-get msg :tree-status))
621             (bare-subject (notmuch-show-strip-re (plist-get headers :Subject)))
622             (face (if match
623                       'notmuch-pick-match-subject-face
624                     'notmuch-pick-no-match-subject-face)))
625         (insert (propertize (format format-string
626                                     (concat
627                                      (mapconcat #'identity (reverse tree-status) "")
628                                      (if (string= notmuch-pick-previous-subject bare-subject)
629                                          " ..."
630                                        bare-subject)))
631                             'face face))
632         (setq notmuch-pick-previous-subject bare-subject)))
633
634      ((string-equal field "authors")
635       (let ((author (notmuch-pick-clean-address (plist-get headers :From)))
636             (len (length (format format-string "")))
637             (face (if match
638                       'notmuch-pick-match-author-face
639                     'notmuch-pick-no-match-author-face)))
640         (when (> (length author) len)
641           (setq author (substring author 0 len)))
642         (insert (propertize (format format-string author)
643                             'face face))))
644
645      ((string-equal field "tags")
646       (let ((tags (plist-get msg :tags))
647             (face (if match
648                           'notmuch-pick-match-tag-face
649                         'notmuch-pick-no-match-tag-face)))
650         (when tags
651           (insert (propertize (format format-string
652                                       (mapconcat #'identity tags ", "))
653                               'face face))))))))
654
655 (defun notmuch-pick-insert-msg (msg)
656   "Insert the message MSG according to notmuch-pick-result-format"
657   ;; We need to save the previous subject as it will get overwritten
658   ;; by the insert-field calls.
659   (let ((previous-subject notmuch-pick-previous-subject))
660     (dolist (spec notmuch-pick-result-format)
661       (notmuch-pick-insert-field (car spec) (cdr spec) msg))
662     (notmuch-pick-set-message-properties msg)
663     (notmuch-pick-set-prop :previous-subject previous-subject)
664     (insert "\n")))
665
666 (defun notmuch-pick-goto-and-insert-msg (msg)
667   "Insert msg at the end of the buffer. Move point to msg if it is the target"
668   (save-excursion
669     (goto-char (point-max))
670     (notmuch-pick-insert-msg msg))
671   (let ((msg-id (notmuch-id-to-query (plist-get msg :id)))
672         (target notmuch-pick-target-msg))
673     (when (or (and (not target) (plist-get msg :match))
674               (string= msg-id target))
675       (setq notmuch-pick-target-msg "found")
676       (goto-char (point-max))
677       (forward-line -1)
678       (when notmuch-pick-open-target
679         (notmuch-pick-show-message)))))
680
681 (defun notmuch-pick-insert-tree (tree depth tree-status first last)
682   "Insert the message tree TREE at depth DEPTH in the current thread.
683
684 A message tree is another name for a single sub-thread: i.e., a
685 message together with all its descendents."
686   (let ((msg (car tree))
687         (replies (cadr tree)))
688
689       (cond
690        ((and (< 0 depth) (not last))
691         (push "├" tree-status))
692        ((and (< 0 depth) last)
693         (push "╰" tree-status))
694        ((and (eq 0 depth) first last)
695 ;;        (push "─" tree-status)) choice between this and next line is matter of taste.
696         (push " " tree-status))
697        ((and (eq 0 depth) first (not last))
698           (push "┬" tree-status))
699        ((and (eq 0 depth) (not first) last)
700         (push "╰" tree-status))
701        ((and (eq 0 depth) (not first) (not last))
702         (push "├" tree-status)))
703
704       (push (concat (if replies "┬" "─") "►") tree-status)
705       (notmuch-pick-goto-and-insert-msg (plist-put msg :tree-status tree-status))
706       (pop tree-status)
707       (pop tree-status)
708
709       (if last
710           (push " " tree-status)
711         (push "│" tree-status))
712
713     (notmuch-pick-insert-thread replies (1+ depth) tree-status)))
714
715 (defun notmuch-pick-insert-thread (thread depth tree-status)
716   "Insert the collection of sibling sub-threads THREAD at depth DEPTH in the current forest."
717   (let ((n (length thread)))
718     (loop for tree in thread
719           for count from 1 to n
720
721           do (notmuch-pick-insert-tree tree depth tree-status (eq count 1) (eq count n)))))
722
723 (defun notmuch-pick-insert-forest-thread (forest-thread)
724   "Insert a single complete thread."
725   (let (tree-status)
726     ;; Reset at the start of each main thread.
727     (setq notmuch-pick-previous-subject nil)
728     (notmuch-pick-insert-thread forest-thread 0 tree-status)))
729
730 (defun notmuch-pick-insert-forest (forest)
731   "Insert a forest of threads.
732
733 This function inserts a collection of several complete threads as
734 passed to it by notmuch-pick-process-filter."
735   (mapc 'notmuch-pick-insert-forest-thread forest))
736
737 (defun notmuch-pick-mode ()
738   "Major mode displaying messages (as opposed to threads) of of a notmuch search.
739
740 This buffer contains the results of a \"notmuch pick\" of your
741 email archives. Each line in the buffer represents a single
742 message giving the relative date, the author, subject, and any
743 tags.
744
745 Pressing \\[notmuch-pick-show-message] on any line displays that message.
746
747 Complete list of currently available key bindings:
748
749 \\{notmuch-pick-mode-map}"
750
751   (interactive)
752   (kill-all-local-variables)
753   (use-local-map notmuch-pick-mode-map)
754   (setq major-mode 'notmuch-pick-mode
755         mode-name "notmuch-pick")
756   (hl-line-mode 1)
757   (setq buffer-read-only t
758         truncate-lines t))
759
760 (defun notmuch-pick-process-sentinel (proc msg)
761   "Add a message to let user know when \"notmuch pick\" exits"
762   (let ((buffer (process-buffer proc))
763         (status (process-status proc))
764         (exit-status (process-exit-status proc))
765         (never-found-target-thread nil))
766     (when (memq status '(exit signal))
767         (kill-buffer (process-get proc 'parse-buf))
768         (if (buffer-live-p buffer)
769             (with-current-buffer buffer
770               (save-excursion
771                 (let ((inhibit-read-only t)
772                       (atbob (bobp)))
773                   (goto-char (point-max))
774                   (if (eq status 'signal)
775                       (insert "Incomplete search results (pick process was killed).\n"))
776                   (when (eq status 'exit)
777                     (insert "End of search results.")
778                     (unless (= exit-status 0)
779                       (insert (format " (process returned %d)" exit-status)))
780                     (insert "\n")))))))))
781
782 (defun notmuch-pick-process-filter (proc string)
783   "Process and filter the output of \"notmuch show\" (for pick)"
784   (let ((results-buf (process-buffer proc))
785         (parse-buf (process-get proc 'parse-buf))
786         (inhibit-read-only t)
787         done)
788     (if (not (buffer-live-p results-buf))
789         (delete-process proc)
790       (with-current-buffer parse-buf
791         ;; Insert new data
792         (save-excursion
793           (goto-char (point-max))
794           (insert string))
795         (notmuch-sexp-parse-partial-list 'notmuch-pick-insert-forest-thread
796                                          results-buf)))))
797
798 (defun notmuch-pick-worker (basic-query &optional query-context target buffer open-target)
799   (interactive)
800   (notmuch-pick-mode)
801   (setq notmuch-pick-basic-query basic-query)
802   (setq notmuch-pick-query-context query-context)
803   (setq notmuch-pick-buffer-name (buffer-name buffer))
804   (setq notmuch-pick-target-msg target)
805   (setq notmuch-pick-open-target open-target)
806
807   (erase-buffer)
808   (goto-char (point-min))
809   (let* ((search-args (concat basic-query
810                        (if query-context (concat " and (" query-context ")"))
811                        ))
812          (message-arg "--entire-thread"))
813     (if (equal (car (process-lines notmuch-command "count" search-args)) "0")
814         (setq search-args basic-query))
815     (let ((proc (notmuch-start-notmuch
816                  "notmuch-pick" buffer #'notmuch-pick-process-sentinel
817                  "show" "--body=false" "--format=sexp"
818                  message-arg search-args))
819           ;; Use a scratch buffer to accumulate partial output.
820           ;; This buffer will be killed by the sentinel, which
821           ;; should be called no matter how the process dies.
822           (parse-buf (generate-new-buffer " *notmuch pick parse*")))
823       (process-put proc 'parse-buf parse-buf)
824       (set-process-filter proc 'notmuch-pick-process-filter)
825       (set-process-query-on-exit-flag proc nil))))
826
827 (defun notmuch-pick (&optional query query-context target buffer-name open-target)
828   "Run notmuch pick with the given `query' and display the results.
829
830 The arguments are:
831   QUERY: the main query. This can be any query but in many cases will be
832       a single thread. If nil this is read interactively from the minibuffer.
833   QUERY-CONTEXT: is an additional term for the query. The query used
834       is QUERY and QUERY-CONTEXT unless that does not match any messages
835       in which case we fall back to just QUERY.
836   TARGET: A message ID (with the id: prefix) that will be made
837       current if it appears in the pick results.
838   BUFFER-NAME: the name of the buffer to show the pick tree. If
839       it is nil \"*notmuch-pick\" followed by QUERY is used.
840   OPEN-TARGET: If TRUE open the target message in the message pane."
841   (interactive "sNotmuch pick: ")
842   (if (null query)
843       (setq query (notmuch-read-query "Notmuch pick: ")))
844   (let ((buffer (get-buffer-create (generate-new-buffer-name
845                                     (or buffer-name
846                                         (concat "*notmuch-pick-" query "*")))))
847         (inhibit-read-only t))
848
849     (switch-to-buffer buffer)
850     ;; Don't track undo information for this buffer
851     (set 'buffer-undo-list t)
852
853     (notmuch-pick-worker query query-context target buffer open-target)
854
855     (setq truncate-lines t)))
856
857
858 ;; Set up key bindings from the rest of notmuch.
859 (define-key 'notmuch-search-mode-map "z" 'notmuch-pick)
860 (define-key 'notmuch-search-mode-map "Z" 'notmuch-pick-from-search-current-query)
861 (define-key 'notmuch-search-mode-map (kbd "M-RET") 'notmuch-pick-from-search-thread)
862 (define-key 'notmuch-hello-mode-map "z" 'notmuch-pick-from-hello)
863 (define-key 'notmuch-show-mode-map "z" 'notmuch-pick)
864 (define-key 'notmuch-show-mode-map "Z" 'notmuch-pick-from-show-current-query)
865 (notmuch-pick-setup-show-out)
866 (message "Initialised notmuch-pick")
867
868 (provide 'notmuch-pick)