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