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