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