]> git.notmuchmail.org Git - notmuch/blob - contrib/notmuch-pick/notmuch-pick.el
contrib: pick: use async parser from lib
[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-clean-address "notmuch-show" (parsed-address))
39 (declare-function notmuch-show-spaces-n "notmuch-show" (n))
40 (declare-function notmuch-read-query "notmuch" (prompt))
41 (declare-function notmuch-read-tag-changes "notmuch" (&optional initial-input &rest search-terms))
42 (declare-function notmuch-update-tags "notmuch" (current-tags tag-changes))
43 (declare-function notmuch-hello-trim "notmuch-hello" (search))
44 (declare-function notmuch-search-find-thread-id "notmuch" ())
45 (declare-function notmuch-search-find-subject "notmuch" ())
46
47 ;; the following variable is defined in notmuch.el
48 (defvar notmuch-search-query-string)
49
50 (defgroup notmuch-pick nil
51   "Showing message and thread structure."
52   :group 'notmuch)
53
54 ;; This is ugly. We can't run setup-show-out until it has been defined
55 ;; which needs the keymap to be defined. So we defer setting up to
56 ;; notmuch-pick-init.
57 (defcustom notmuch-pick-show-out nil
58   "View selected messages in new window rather than split-pane."
59   :type 'boolean
60   :group 'notmuch-pick
61   :set (lambda (symbol value)
62          (set-default symbol value)
63          (when (fboundp 'notmuch-pick-setup-show-out)
64            (notmuch-pick-setup-show-out))))
65
66 (defcustom notmuch-pick-result-format
67   `(("date" . "%12s  ")
68     ("authors" . "%-20s")
69     ("subject" . " %-54s ")
70     ("tags" . "(%s)"))
71   "Result formatting for Pick. Supported fields are: date,
72         authors, subject, tags Note: subject includes the tree
73         structure graphics, and the author string should not
74         contain whitespace (put it in the neighbouring fields
75         instead).  For example:
76         (setq notmuch-pick-result-format \(\(\"authors\" . \"%-40s\"\)
77                                              \(\"subject\" . \"%s\"\)\)\)"
78   :type '(alist :key-type (string) :value-type (string))
79   :group 'notmuch-pick)
80
81 (defcustom notmuch-pick-asynchronous-parser t
82   "Use the asynchronous parser."
83   :type 'boolean
84   :group 'notmuch-pick)
85
86 ;; Faces for messages that match the query.
87 (defface notmuch-pick-match-date-face
88   '((t :inherit default))
89   "Face used in pick mode for the date in messages matching the query."
90   :group 'notmuch-pick
91   :group 'notmuch-faces)
92
93 (defface notmuch-pick-match-author-face
94   '((((class color)
95       (background dark))
96      (:foreground "OliveDrab1"))
97     (((class color)
98       (background light))
99      (:foreground "dark blue"))
100     (t
101      (:bold t)))
102   "Face used in pick mode for the date in messages matching the query."
103   :group 'notmuch-pick
104   :group 'notmuch-faces)
105
106 (defface notmuch-pick-match-subject-face
107   '((t :inherit default))
108   "Face used in pick mode for the subject in messages matching the query."
109   :group 'notmuch-pick
110   :group 'notmuch-faces)
111
112 (defface notmuch-pick-match-tag-face
113   '((((class color)
114       (background dark))
115      (:foreground "OliveDrab1"))
116     (((class color)
117       (background light))
118      (:foreground "navy blue" :bold t))
119     (t
120      (:bold t)))
121   "Face used in pick mode for tags in messages matching the query."
122   :group 'notmuch-pick
123   :group 'notmuch-faces)
124
125 ;; Faces for messages that do not match the query.
126 (defface notmuch-pick-no-match-date-face
127   '((t (:foreground "gray")))
128   "Face used in pick mode for non-matching dates."
129   :group 'notmuch-pick
130   :group 'notmuch-faces)
131
132 (defface notmuch-pick-no-match-subject-face
133   '((t (:foreground "gray")))
134   "Face used in pick mode for non-matching subjects."
135   :group 'notmuch-pick
136   :group 'notmuch-faces)
137
138 (defface notmuch-pick-no-match-author-face
139   '((t (:foreground "gray")))
140   "Face used in pick mode for the date in messages matching the query."
141   :group 'notmuch-pick
142   :group 'notmuch-faces)
143
144 (defface notmuch-pick-no-match-tag-face
145   '((t (:foreground "gray")))
146   "Face used in pick mode face for non-matching tags."
147   :group 'notmuch-pick
148   :group 'notmuch-faces)
149
150 (defvar notmuch-pick-previous-subject "")
151 (make-variable-buffer-local 'notmuch-pick-previous-subject)
152
153 ;; The basic query i.e. the key part of the search request.
154 (defvar notmuch-pick-basic-query nil)
155 (make-variable-buffer-local 'notmuch-pick-basic-query)
156 ;; The context of the search: i.e., useful but can be dropped.
157 (defvar notmuch-pick-query-context nil)
158 (make-variable-buffer-local 'notmuch-pick-query-context)
159 (defvar notmuch-pick-buffer-name nil)
160 (make-variable-buffer-local 'notmuch-pick-buffer-name)
161 (defvar notmuch-pick-message-window nil)
162 (make-variable-buffer-local 'notmuch-pick-message-window)
163 (put 'notmuch-pick-message-window 'permanent-local t)
164 (defvar notmuch-pick-message-buffer nil)
165 (make-variable-buffer-local 'notmuch-pick-message-buffer-name)
166 (put 'notmuch-pick-message-buffer-name 'permanent-local t)
167 (defvar notmuch-pick-process-state nil
168   "Parsing state of the search process filter.")
169
170
171 (defvar notmuch-pick-mode-map
172   (let ((map (make-sparse-keymap)))
173     (define-key map [mouse-1] 'notmuch-pick-show-message)
174     (define-key map "q" 'notmuch-pick-quit)
175     (define-key map "x" 'notmuch-pick-quit)
176     (define-key map "?" 'notmuch-help)
177     (define-key map "a" 'notmuch-pick-archive-message)
178     (define-key map "=" 'notmuch-pick-refresh-view)
179     (define-key map "s" 'notmuch-search)
180     (define-key map "z" 'notmuch-pick)
181     (define-key map "m" 'notmuch-pick-new-mail)
182     (define-key map "f" 'notmuch-pick-forward-message)
183     (define-key map "r" 'notmuch-pick-reply-sender)
184     (define-key map "R" 'notmuch-pick-reply)
185     (define-key map "n" 'notmuch-pick-next-matching-message)
186     (define-key map "p" 'notmuch-pick-prev-matching-message)
187     (define-key map "N" 'notmuch-pick-next-message)
188     (define-key map "P" 'notmuch-pick-prev-message)
189     (define-key map "|" 'notmuch-pick-pipe-message)
190     (define-key map "-" 'notmuch-pick-remove-tag)
191     (define-key map "+" 'notmuch-pick-add-tag)
192     (define-key map " " 'notmuch-pick-scroll-or-next)
193     (define-key map "b" 'notmuch-pick-scroll-message-window-back)
194     map))
195 (fset 'notmuch-pick-mode-map notmuch-pick-mode-map)
196
197 (defun notmuch-pick-setup-show-out ()
198   (let ((map notmuch-pick-mode-map))
199     (if notmuch-pick-show-out
200         (progn
201           (define-key map (kbd "M-RET") 'notmuch-pick-show-message)
202           (define-key map (kbd "RET") 'notmuch-pick-show-message-out))
203       (progn
204         (define-key map (kbd "RET") 'notmuch-pick-show-message)
205         (define-key map (kbd "M-RET") 'notmuch-pick-show-message-out)))))
206
207 (defun notmuch-pick-get-message-properties ()
208   "Return the properties of the current message as a plist.
209
210 Some useful entries are:
211 :headers - Property list containing the headers :Date, :Subject, :From, etc.
212 :tags - Tags for this message"
213   (save-excursion
214     (beginning-of-line)
215     (get-text-property (point) :notmuch-message-properties)))
216
217 (defun notmuch-pick-set-message-properties (props)
218   (save-excursion
219     (beginning-of-line)
220     (put-text-property (point) (+ (point) 1) :notmuch-message-properties props)))
221
222 (defun notmuch-pick-set-prop (prop val &optional props)
223   (let ((inhibit-read-only t)
224         (props (or props
225                    (notmuch-pick-get-message-properties))))
226     (plist-put props prop val)
227     (notmuch-pick-set-message-properties props)))
228
229 (defun notmuch-pick-get-prop (prop &optional props)
230   (let ((props (or props
231                    (notmuch-pick-get-message-properties))))
232     (plist-get props prop)))
233
234 (defun notmuch-pick-set-tags (tags)
235   "Set the tags of the current message."
236   (notmuch-pick-set-prop :tags tags))
237
238 (defun notmuch-pick-get-tags ()
239   "Return the tags of the current message."
240   (notmuch-pick-get-prop :tags))
241
242 (defun notmuch-pick-get-message-id ()
243   "Return the message id of the current message."
244   (let ((id (notmuch-pick-get-prop :id)))
245     (if id
246         (notmuch-id-to-query id)
247       nil)))
248
249 (defun notmuch-pick-get-match ()
250   "Return whether the current message is a match."
251   (interactive)
252   (notmuch-pick-get-prop :match))
253
254 (defun notmuch-pick-refresh-result ()
255   (let ((init-point (point))
256         (end (line-end-position))
257         (msg (notmuch-pick-get-message-properties))
258         (inhibit-read-only t))
259     (beginning-of-line)
260     (delete-region (point) (1+ (line-end-position)))
261     (notmuch-pick-insert-msg msg)
262     (let ((new-end (line-end-position)))
263       (goto-char (if (= init-point end)
264                      new-end
265                    (min init-point (- new-end 1)))))))
266
267 (defun notmuch-pick-tag-update-display (&optional tag-changes)
268   "Update display for TAG-CHANGES to current message.
269
270 Does NOT change the database."
271   (let* ((current-tags (notmuch-pick-get-tags))
272          (new-tags (notmuch-update-tags current-tags tag-changes)))
273     (unless (equal current-tags new-tags)
274       (notmuch-pick-set-tags new-tags)
275       (notmuch-pick-refresh-result))))
276
277 (defun notmuch-pick-tag (&optional tag-changes)
278   "Change tags for the current message"
279   (interactive)
280   (setq tag-changes (funcall 'notmuch-tag (notmuch-pick-get-message-id) tag-changes))
281   (notmuch-pick-tag-update-display tag-changes))
282
283 (defun notmuch-pick-add-tag ()
284   "Same as `notmuch-pick-tag' but sets initial input to '+'."
285   (interactive)
286   (notmuch-pick-tag "+"))
287
288 (defun notmuch-pick-remove-tag ()
289   "Same as `notmuch-pick-tag' but sets initial input to '-'."
290   (interactive)
291   (notmuch-pick-tag "-"))
292
293 ;; This function should be in notmuch-hello.el but we are trying to
294 ;; minimise impact on the rest of the codebase.
295 (defun notmuch-pick-from-hello (&optional search)
296   "Run a query and display results in experimental notmuch-pick mode"
297   (interactive)
298   (unless (null search)
299     (setq search (notmuch-hello-trim search))
300     (let ((history-delete-duplicates t))
301       (add-to-history 'notmuch-search-history search)))
302   (notmuch-pick search))
303
304 ;; This function should be in notmuch-show.el but be we trying to
305 ;; minimise impact on the rest of the codebase.
306 (defun notmuch-pick-from-show-current-query ()
307   "Call notmuch pick with the current query"
308   (interactive)
309   (notmuch-pick notmuch-show-thread-id notmuch-show-query-context))
310
311 ;; This function should be in notmuch.el but be we trying to minimise
312 ;; impact on the rest of the codebase.
313 (defun notmuch-pick-from-search-current-query ()
314   "Call notmuch pick with the current query"
315   (interactive)
316   (notmuch-pick notmuch-search-query-string))
317
318 ;; This function should be in notmuch.el but be we trying to minimise
319 ;; impact on the rest of the codebase.
320 (defun notmuch-pick-from-search-thread ()
321   "Show the selected thread with notmuch-pick"
322   (interactive)
323   (notmuch-pick (notmuch-search-find-thread-id)
324                 notmuch-search-query-string
325                 (notmuch-prettify-subject (notmuch-search-find-subject)))
326   (notmuch-pick-show-match-message-with-wait))
327
328 (defun notmuch-pick-show-message ()
329   "Show the current message (in split-pane)."
330   (interactive)
331   (let ((id (notmuch-pick-get-message-id))
332         (inhibit-read-only t)
333         buffer)
334     (when id
335       ;; We close and reopen the window to kill off un-needed buffers
336       ;; this might cause flickering but seems ok.
337       (notmuch-pick-close-message-window)
338       (setq notmuch-pick-message-window
339             (split-window-vertically (/ (window-height) 4)))
340       (with-selected-window notmuch-pick-message-window
341         (setq current-prefix-arg '(4))
342         (setq buffer (notmuch-show id nil nil nil)))
343       (notmuch-pick-tag-update-display (list "-unread")))
344     (setq notmuch-pick-message-buffer buffer)))
345
346 (defun notmuch-pick-show-message-out ()
347   "Show the current message (in whole window)."
348   (interactive)
349   (let ((id (notmuch-pick-get-message-id))
350         (inhibit-read-only t)
351         buffer)
352     (when id
353       ;; We close the window to kill off un-needed buffers.
354       (notmuch-pick-close-message-window)
355       (notmuch-show id nil nil nil))))
356
357 (defun notmuch-pick-scroll-message-window ()
358   "Scroll the message window (if it exists)"
359   (interactive)
360   (when (window-live-p notmuch-pick-message-window)
361     (with-selected-window notmuch-pick-message-window
362       (if (pos-visible-in-window-p (point-max))
363           t
364         (scroll-up)))))
365
366 (defun notmuch-pick-scroll-message-window-back ()
367   "Scroll the message window back(if it exists)"
368   (interactive)
369   (when (window-live-p notmuch-pick-message-window)
370     (with-selected-window notmuch-pick-message-window
371       (if (pos-visible-in-window-p (point-min))
372           t
373         (scroll-down)))))
374
375 (defun notmuch-pick-scroll-or-next ()
376   "Scroll the message window. If it at end go to next message."
377   (interactive)
378   (when (notmuch-pick-scroll-message-window)
379     (notmuch-pick-next-matching-message)))
380
381 (defun notmuch-pick-quit ()
382   "Close the split view or exit pick."
383   (interactive)
384   (unless (notmuch-pick-close-message-window)
385     (kill-buffer (current-buffer))))
386
387 (defun notmuch-pick-close-message-window ()
388   "Close the message-window. Return t if close succeeds."
389   (interactive)
390   (when (and (window-live-p notmuch-pick-message-window)
391              (eq (window-buffer notmuch-pick-message-window) notmuch-pick-message-buffer))
392     (delete-window notmuch-pick-message-window)
393     (unless (get-buffer-window-list notmuch-pick-message-buffer)
394       (kill-buffer notmuch-pick-message-buffer))
395     t))
396
397 (defun notmuch-pick-archive-message ()
398   "Archive the current message and move to next matching message."
399   (interactive)
400   (notmuch-pick-tag "-inbox")
401   (notmuch-pick-next-matching-message))
402
403 (defun notmuch-pick-next-message ()
404   "Move to next message."
405   (interactive)
406   (forward-line)
407   (when (window-live-p notmuch-pick-message-window)
408     (notmuch-pick-show-message)))
409
410 (defun notmuch-pick-prev-message ()
411   "Move to previous message."
412   (interactive)
413   (forward-line -1)
414   (when (window-live-p notmuch-pick-message-window)
415     (notmuch-pick-show-message)))
416
417 (defun notmuch-pick-prev-matching-message ()
418   "Move to previous matching message."
419   (interactive)
420   (forward-line -1)
421   (while (and (not (bobp)) (not (notmuch-pick-get-match)))
422     (forward-line -1))
423   (when (window-live-p notmuch-pick-message-window)
424     (notmuch-pick-show-message)))
425
426 (defun notmuch-pick-next-matching-message ()
427   "Move to next matching message."
428   (interactive)
429   (forward-line)
430   (while (and (not (eobp)) (not (notmuch-pick-get-match)))
431     (forward-line))
432   (when (window-live-p notmuch-pick-message-window)
433     (notmuch-pick-show-message)))
434
435 (defun notmuch-pick-show-match-message-with-wait ()
436   "Show the first matching message but wait for it to appear or search to finish."
437   (interactive)
438   (unless (notmuch-pick-get-match)
439     (notmuch-pick-next-matching-message))
440   (while (and (not (notmuch-pick-get-match))
441               (get-buffer-process (current-buffer)))
442     (message "waiting for message")
443     (sit-for 0.1)
444     (goto-char (point-min))
445     (unless (notmuch-pick-get-match)
446       (notmuch-pick-next-matching-message)))
447   (message nil)
448   (when (notmuch-pick-get-match)
449     (notmuch-pick-show-message)))
450
451 (defun notmuch-pick-refresh-view ()
452   "Refresh view."
453   (interactive)
454   (let ((inhibit-read-only t)
455         (basic-query notmuch-pick-basic-query)
456         (query-context notmuch-pick-query-context)
457         (buffer-name notmuch-pick-buffer-name))
458     (erase-buffer)
459     (notmuch-pick-worker basic-query query-context (get-buffer buffer-name))))
460
461 (defmacro with-current-notmuch-pick-message (&rest body)
462   "Evaluate body with current buffer set to the text of current message"
463   `(save-excursion
464      (let ((id (notmuch-pick-get-message-id)))
465        (let ((buf (generate-new-buffer (concat "*notmuch-msg-" id "*"))))
466          (with-current-buffer buf
467             (call-process notmuch-command nil t nil "show" "--format=raw" id)
468            ,@body)
469          (kill-buffer buf)))))
470
471 (defun notmuch-pick-new-mail (&optional prompt-for-sender)
472   "Compose new mail."
473   (interactive "P")
474   (notmuch-pick-close-message-window)
475   (notmuch-mua-new-mail prompt-for-sender ))
476
477 (defun notmuch-pick-forward-message (&optional prompt-for-sender)
478   "Forward the current message."
479   (interactive "P")
480   (notmuch-pick-close-message-window)
481   (with-current-notmuch-pick-message
482    (notmuch-mua-new-forward-message prompt-for-sender)))
483
484 (defun notmuch-pick-reply (&optional prompt-for-sender)
485   "Reply to the sender and all recipients of the current message."
486   (interactive "P")
487   (notmuch-pick-close-message-window)
488   (notmuch-mua-new-reply (notmuch-pick-get-message-id) prompt-for-sender t))
489
490 (defun notmuch-pick-reply-sender (&optional prompt-for-sender)
491   "Reply to the sender of the current message."
492   (interactive "P")
493   (notmuch-pick-close-message-window)
494   (notmuch-mua-new-reply (notmuch-pick-get-message-id) prompt-for-sender nil))
495
496 ;; Shamelessly stolen from notmuch-show.el: maybe should be unified.
497 (defun notmuch-pick-pipe-message (command)
498   "Pipe the contents of the current message to the given command.
499
500 The given command will be executed with the raw contents of the
501 current email message as stdin. Anything printed by the command
502 to stdout or stderr will appear in the *notmuch-pipe* buffer.
503
504 When invoked with a prefix argument, the command will receive all
505 open messages in the current thread (formatted as an mbox) rather
506 than only the current message."
507   (interactive "sPipe message to command: ")
508   (let ((shell-command
509          (concat notmuch-command " show --format=raw "
510                  (shell-quote-argument (notmuch-pick-get-message-id)) " | " command))
511          (buf (get-buffer-create (concat "*notmuch-pipe*"))))
512     (with-current-buffer buf
513       (setq buffer-read-only nil)
514       (erase-buffer)
515       (let ((exit-code (call-process-shell-command shell-command nil buf)))
516         (goto-char (point-max))
517         (set-buffer-modified-p nil)
518         (setq buffer-read-only t)
519         (unless (zerop exit-code)
520           (switch-to-buffer-other-window buf)
521           (message (format "Command '%s' exited abnormally with code %d"
522                            shell-command exit-code)))))))
523
524 ;; Shamelessly stolen from notmuch-show.el: should be unified.
525 (defun notmuch-pick-clean-address (address)
526   "Try to clean a single email ADDRESS for display.  Return
527 unchanged ADDRESS if parsing fails."
528   (condition-case nil
529     (let (p-name p-address)
530       ;; It would be convenient to use `mail-header-parse-address',
531       ;; but that expects un-decoded mailbox parts, whereas our
532       ;; mailbox parts are already decoded (and hence may contain
533       ;; UTF-8). Given that notmuch should handle most of the awkward
534       ;; cases, some simple string deconstruction should be sufficient
535       ;; here.
536       (cond
537        ;; "User <user@dom.ain>" style.
538        ((string-match "\\(.*\\) <\\(.*\\)>" address)
539         (setq p-name (match-string 1 address)
540               p-address (match-string 2 address)))
541
542        ;; "<user@dom.ain>" style.
543        ((string-match "<\\(.*\\)>" address)
544         (setq p-address (match-string 1 address)))
545
546        ;; Everything else.
547        (t
548         (setq p-address address)))
549
550       (when p-name
551         ;; Remove elements of the mailbox part that are not relevant for
552         ;; display, even if they are required during transport:
553         ;;
554         ;; Backslashes.
555         (setq p-name (replace-regexp-in-string "\\\\" "" p-name))
556
557         ;; Outer single and double quotes, which might be nested.
558         (loop
559          with start-of-loop
560          do (setq start-of-loop p-name)
561
562          when (string-match "^\"\\(.*\\)\"$" p-name)
563          do (setq p-name (match-string 1 p-name))
564
565          when (string-match "^'\\(.*\\)'$" p-name)
566          do (setq p-name (match-string 1 p-name))
567
568          until (string= start-of-loop p-name)))
569
570       ;; If the address is 'foo@bar.com <foo@bar.com>' then show just
571       ;; 'foo@bar.com'.
572       (when (string= p-name p-address)
573         (setq p-name nil))
574
575       ;; If we have a name return that otherwise return the address.
576       (if (not p-name)
577           p-address
578         p-name))
579     (error address)))
580
581 (defun notmuch-pick-insert-field (field format-string msg)
582   (let* ((headers (plist-get msg :headers))
583         (match (plist-get msg :match)))
584     (cond
585      ((string-equal field "date")
586       (let ((face (if match
587                       'notmuch-pick-match-date-face
588                     'notmuch-pick-no-match-date-face)))
589         (insert (propertize (format format-string (plist-get msg :date_relative))
590                             'face face))))
591
592      ((string-equal field "subject")
593       (let ((tree-status (plist-get msg :tree-status))
594             (bare-subject (notmuch-show-strip-re (plist-get headers :Subject)))
595             (face (if match
596                       'notmuch-pick-match-subject-face
597                     'notmuch-pick-no-match-subject-face)))
598         (insert (propertize (format format-string
599                                     (concat
600                                      (mapconcat #'identity (reverse tree-status) "")
601                                      (if (string= notmuch-pick-previous-subject bare-subject)
602                                          " ..."
603                                        bare-subject)))
604                             'face face))
605         (setq notmuch-pick-previous-subject bare-subject)))
606
607      ((string-equal field "authors")
608       (let ((author (notmuch-pick-clean-address (plist-get headers :From)))
609             (len (length (format format-string "")))
610             (face (if match
611                       'notmuch-pick-match-author-face
612                     'notmuch-pick-no-match-author-face)))
613         (when (> (length author) len)
614           (setq author (substring author 0 len)))
615         (insert (propertize (format format-string author)
616                             'face face))))
617
618      ((string-equal field "tags")
619       (let ((tags (plist-get msg :tags))
620             (face (if match
621                           'notmuch-pick-match-tag-face
622                         'notmuch-pick-no-match-tag-face)))
623         (when tags
624           (insert (propertize (format format-string
625                                       (mapconcat #'identity tags ", "))
626                               'face face))))))))
627
628 (defun notmuch-pick-insert-msg (msg)
629   "Insert the message MSG according to notmuch-pick-result-format"
630   (dolist (spec notmuch-pick-result-format)
631     (notmuch-pick-insert-field (car spec) (cdr spec) msg))
632   (notmuch-pick-set-message-properties msg)
633   (insert "\n"))
634
635 (defun notmuch-pick-insert-tree (tree depth tree-status first last)
636   "Insert the message tree TREE at depth DEPTH in the current thread."
637   (let ((msg (car tree))
638         (replies (cadr tree)))
639
640       (cond
641        ((and (< 0 depth) (not last))
642         (push "├" tree-status))
643        ((and (< 0 depth) last)
644         (push "╰" tree-status))
645        ((and (eq 0 depth) first last)
646 ;;        (push "─" tree-status)) choice between this and next line is matter of taste.
647         (push " " tree-status))
648        ((and (eq 0 depth) first (not last))
649           (push "┬" tree-status))
650        ((and (eq 0 depth) (not first) last)
651         (push "╰" tree-status))
652        ((and (eq 0 depth) (not first) (not last))
653         (push "├" tree-status)))
654
655       (push (concat (if replies "┬" "─") "►") tree-status)
656       (notmuch-pick-insert-msg (plist-put msg :tree-status tree-status))
657       (pop tree-status)
658       (pop tree-status)
659
660       (if last
661           (push " " tree-status)
662         (push "│" tree-status))
663
664     (notmuch-pick-insert-thread replies (1+ depth) tree-status)))
665
666 (defun notmuch-pick-insert-thread (thread depth tree-status)
667   "Insert the thread THREAD at depth DEPTH >= 1 in the current forest."
668   (let ((n (length thread)))
669     (loop for tree in thread
670           for count from 1 to n
671
672           do (notmuch-pick-insert-tree tree depth tree-status (eq count 1) (eq count n)))))
673
674 (defun notmuch-pick-insert-forest-thread (forest-thread)
675   (save-excursion
676     (goto-char (point-max))
677     (let (tree-status)
678       ;; Reset at the start of each main thread.
679       (setq notmuch-pick-previous-subject nil)
680       (notmuch-pick-insert-thread forest-thread 0 tree-status))))
681
682 (defun notmuch-pick-insert-forest (forest)
683   (mapc 'notmuch-pick-insert-forest-thread forest))
684
685 (defun notmuch-pick-mode ()
686   "Major mode displaying messages (as opposed to threads) of of a notmuch search.
687
688 This buffer contains the results of a \"notmuch pick\" of your
689 email archives. Each line in the buffer represents a single
690 message giving the relative date, the author, subject, and any
691 tags.
692
693 Pressing \\[notmuch-pick-show-message] on any line displays that message.
694
695 Complete list of currently available key bindings:
696
697 \\{notmuch-pick-mode-map}"
698
699   (interactive)
700   (kill-all-local-variables)
701   (use-local-map notmuch-pick-mode-map)
702   (setq major-mode 'notmuch-pick-mode
703         mode-name "notmuch-pick")
704   (hl-line-mode 1)
705   (setq buffer-read-only t
706         truncate-lines t))
707
708 (defun notmuch-pick-process-sentinel (proc msg)
709   "Add a message to let user know when \"notmuch pick\" exits"
710   (let ((buffer (process-buffer proc))
711         (status (process-status proc))
712         (exit-status (process-exit-status proc))
713         (never-found-target-thread nil))
714     (when (memq status '(exit signal))
715         (kill-buffer (process-get proc 'parse-buf))
716         (if (buffer-live-p buffer)
717             (with-current-buffer buffer
718               (save-excursion
719                 (let ((inhibit-read-only t)
720                       (atbob (bobp)))
721                   (goto-char (point-max))
722                   (if (eq status 'signal)
723                       (insert "Incomplete search results (pick process was killed).\n"))
724                   (when (eq status 'exit)
725                     (insert "End of search results.")
726                     (unless (= exit-status 0)
727                       (insert (format " (process returned %d)" exit-status)))
728                     (insert "\n")))))))))
729
730
731 (defun notmuch-pick-show-error (string &rest objects)
732   (save-excursion
733     (goto-char (point-max))
734     (insert "Error: Unexpected output from notmuch search:\n")
735     (insert (apply #'format string objects))
736     (insert "\n")))
737
738
739 (defun notmuch-pick-process-filter (proc string)
740   "Process and filter the output of \"notmuch show\" (for pick)"
741   (let ((results-buf (process-buffer proc))
742         (parse-buf (process-get proc 'parse-buf))
743         (inhibit-read-only t)
744         done)
745     (if (not (buffer-live-p results-buf))
746         (delete-process proc)
747       (with-current-buffer parse-buf
748         ;; Insert new data
749         (save-excursion
750           (goto-char (point-max))
751           (insert string))
752         (notmuch-json-parse-partial-list 'notmuch-pick-insert-forest-thread
753                                          'notmuch-pick-show-error
754                                          results-buf)))))
755
756 (defun notmuch-pick-worker (basic-query &optional query-context buffer)
757   (interactive)
758   (notmuch-pick-mode)
759   (setq notmuch-pick-basic-query basic-query)
760   (setq notmuch-pick-query-context query-context)
761   (setq notmuch-pick-buffer-name (buffer-name buffer))
762
763   (erase-buffer)
764   (goto-char (point-min))
765   (let* ((search-args (concat basic-query
766                        (if query-context (concat " and (" query-context ")"))
767                        ))
768          (message-arg "--entire-thread"))
769     (if (equal (car (process-lines notmuch-command "count" search-args)) "0")
770         (setq search-args basic-query))
771     (if notmuch-pick-asynchronous-parser
772         (let ((proc (start-process
773                      "notmuch-pick" buffer
774                      notmuch-command "show" "--body=false" "--format=json"
775                      message-arg search-args))
776               ;; Use a scratch buffer to accumulate partial output.
777               ;; This buffer will be killed by the sentinel, which
778               ;; should be called no matter how the process dies.
779               (parse-buf (generate-new-buffer " *notmuch pick parse*")))
780           (process-put proc 'parse-buf parse-buf)
781           (set-process-sentinel proc 'notmuch-pick-process-sentinel)
782           (set-process-filter proc 'notmuch-pick-process-filter)
783           (set-process-query-on-exit-flag proc nil))
784       (progn
785         (notmuch-pick-insert-forest
786          (notmuch-query-get-threads
787           (list "--body=false" message-arg search-args)))
788         (save-excursion
789           (goto-char (point-max))
790           (insert "End of search results.\n"))))))
791
792
793 (defun notmuch-pick (&optional query query-context buffer-name show-first-match)
794   "Run notmuch pick with the given `query' and display the results"
795   (interactive "sNotmuch pick: ")
796   (if (null query)
797       (setq query (notmuch-read-query "Notmuch pick: ")))
798   (let ((buffer (get-buffer-create (generate-new-buffer-name
799                                     (or buffer-name
800                                         (concat "*notmuch-pick-" query "*")))))
801         (inhibit-read-only t))
802
803     (switch-to-buffer buffer)
804     ;; Don't track undo information for this buffer
805     (set 'buffer-undo-list t)
806
807     (notmuch-pick-worker query query-context buffer)
808
809     (setq truncate-lines t)
810     (when show-first-match
811       (notmuch-pick-show-match-message-with-wait))))
812
813
814 ;; Set up key bindings from the rest of notmuch.
815 (define-key 'notmuch-search-mode-map "z" 'notmuch-pick)
816 (define-key 'notmuch-search-mode-map "Z" 'notmuch-pick-from-search-current-query)
817 (define-key 'notmuch-search-mode-map (kbd "M-RET") 'notmuch-pick-from-search-thread)
818 (define-key 'notmuch-hello-mode-map "z" 'notmuch-pick-from-hello)
819 (define-key 'notmuch-show-mode-map "z" 'notmuch-pick)
820 (define-key 'notmuch-show-mode-map "Z" 'notmuch-pick-from-show-current-query)
821 (notmuch-pick-setup-show-out)
822 (message "Initialised notmuch-pick")
823
824 (provide 'notmuch-pick)