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