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