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