]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch.el
e646aa5ba6143c389a615790896a55b6df44acea
[notmuch] / emacs / notmuch.el
1 ;; notmuch.el --- run notmuch within emacs
2 ;;
3 ;; Copyright © Carl Worth
4 ;;
5 ;; This file is part of Notmuch.
6 ;;
7 ;; Notmuch is free software: you can redistribute it and/or modify it
8 ;; under the terms of the GNU General Public License as published by
9 ;; the Free Software Foundation, either version 3 of the License, or
10 ;; (at your option) any later version.
11 ;;
12 ;; Notmuch is distributed in the hope that it will be useful, but
13 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 ;; General Public License for more details.
16 ;;
17 ;; You should have received a copy of the GNU General Public License
18 ;; along with Notmuch.  If not, see <http://www.gnu.org/licenses/>.
19 ;;
20 ;; Authors: Carl Worth <cworth@cworth.org>
21
22 ;; This is an emacs-based interface to the notmuch mail system.
23 ;;
24 ;; You will first need to have the notmuch program installed and have a
25 ;; notmuch database built in order to use this. See
26 ;; http://notmuchmail.org for details.
27 ;;
28 ;; To install this software, copy it to a directory that is on the
29 ;; `load-path' variable within emacs (a good candidate is
30 ;; /usr/local/share/emacs/site-lisp). If you are viewing this from the
31 ;; notmuch source distribution then you can simply run:
32 ;;
33 ;;      sudo make install-emacs
34 ;;
35 ;; to install it.
36 ;;
37 ;; Then, to actually run it, add:
38 ;;
39 ;;      (autoload 'notmuch "notmuch" "Notmuch mail" t)
40 ;;
41 ;; to your ~/.emacs file, and then run "M-x notmuch" from within emacs,
42 ;; or run:
43 ;;
44 ;;      emacs -f notmuch
45 ;;
46 ;; Have fun, and let us know if you have any comment, questions, or
47 ;; kudos: Notmuch list <notmuch@notmuchmail.org> (subscription is not
48 ;; required, but is available from http://notmuchmail.org).
49
50 (eval-when-compile (require 'cl))
51 (require 'mm-view)
52 (require 'message)
53
54 (require 'notmuch-lib)
55 (require 'notmuch-tag)
56 (require 'notmuch-show)
57 (require 'notmuch-tree)
58 (require 'notmuch-mua)
59 (require 'notmuch-hello)
60 (require 'notmuch-maildir-fcc)
61 (require 'notmuch-message)
62 (require 'notmuch-parser)
63
64 (defcustom notmuch-search-result-format
65   `(("date" . "%12s ")
66     ("count" . "%-7s ")
67     ("authors" . "%-20s ")
68     ("subject" . "%s ")
69     ("tags" . "(%s)"))
70   "Search result formatting. Supported fields are:
71         date, count, authors, subject, tags
72 For example:
73         (setq notmuch-search-result-format \(\(\"authors\" . \"%-40s\"\)
74                                              \(\"subject\" . \"%s\"\)\)\)
75 Line breaks are permitted in format strings (though this is
76 currently experimental).  Note that a line break at the end of an
77 \"authors\" field will get elided if the authors list is long;
78 place it instead at the beginning of the following field.  To
79 enter a line break when setting this variable with setq, use \\n.
80 To enter a line break in customize, press \\[quoted-insert] C-j."
81   :type '(alist :key-type (string) :value-type (string))
82   :group 'notmuch-search)
83
84 (defvar notmuch-query-history nil
85   "Variable to store minibuffer history for notmuch queries")
86
87 (defun notmuch-foreach-mime-part (function mm-handle)
88   (cond ((stringp (car mm-handle))
89          (dolist (part (cdr mm-handle))
90            (notmuch-foreach-mime-part function part)))
91         ((bufferp (car mm-handle))
92          (funcall function mm-handle))
93         (t (dolist (part mm-handle)
94              (notmuch-foreach-mime-part function part)))))
95
96 (defun notmuch-count-attachments (mm-handle)
97   (let ((count 0))
98     (notmuch-foreach-mime-part
99      (lambda (p)
100        (let ((disposition (mm-handle-disposition p)))
101          (and (listp disposition)
102               (or (equal (car disposition) "attachment")
103                   (and (equal (car disposition) "inline")
104                        (assq 'filename disposition)))
105               (incf count))))
106      mm-handle)
107     count))
108
109 (defun notmuch-save-attachments (mm-handle &optional queryp)
110   (notmuch-foreach-mime-part
111    (lambda (p)
112      (let ((disposition (mm-handle-disposition p)))
113        (and (listp disposition)
114             (or (equal (car disposition) "attachment")
115                 (and (equal (car disposition) "inline")
116                      (assq 'filename disposition)))
117             (or (not queryp)
118                 (y-or-n-p
119                  (concat "Save '" (cdr (assq 'filename disposition)) "' ")))
120             (mm-save-part p))))
121    mm-handle))
122
123 (require 'hl-line)
124
125 (defun notmuch-hl-line-mode ()
126   (prog1 (hl-line-mode)
127     (when hl-line-overlay
128       (overlay-put hl-line-overlay 'priority 1))))
129
130 (defcustom notmuch-search-hook '(notmuch-hl-line-mode)
131   "List of functions to call when notmuch displays the search results."
132   :type 'hook
133   :options '(notmuch-hl-line-mode)
134   :group 'notmuch-search
135   :group 'notmuch-hooks)
136
137 (defvar notmuch-search-mode-map
138   (let ((map (make-sparse-keymap)))
139     (set-keymap-parent map notmuch-common-keymap)
140     (define-key map "x" 'notmuch-kill-this-buffer)
141     (define-key map (kbd "<DEL>") 'notmuch-search-scroll-down)
142     (define-key map "b" 'notmuch-search-scroll-down)
143     (define-key map " " 'notmuch-search-scroll-up)
144     (define-key map "<" 'notmuch-search-first-thread)
145     (define-key map ">" 'notmuch-search-last-thread)
146     (define-key map "p" 'notmuch-search-previous-thread)
147     (define-key map "n" 'notmuch-search-next-thread)
148     (define-key map "r" 'notmuch-search-reply-to-thread-sender)
149     (define-key map "R" 'notmuch-search-reply-to-thread)
150     (define-key map "o" 'notmuch-search-toggle-order)
151     (define-key map "c" 'notmuch-search-stash-map)
152     (define-key map "t" 'notmuch-search-filter-by-tag)
153     (define-key map "f" 'notmuch-search-filter)
154     (define-key map [mouse-1] 'notmuch-search-show-thread)
155     (define-key map "*" 'notmuch-search-tag-all)
156     (define-key map "a" 'notmuch-search-archive-thread)
157     (define-key map "-" 'notmuch-search-remove-tag)
158     (define-key map "+" 'notmuch-search-add-tag)
159     (define-key map (kbd "RET") 'notmuch-search-show-thread)
160     (define-key map "Z" 'notmuch-tree-from-search-current-query)
161     map)
162   "Keymap for \"notmuch search\" buffers.")
163 (fset 'notmuch-search-mode-map notmuch-search-mode-map)
164
165 (defvar notmuch-search-stash-map
166   (let ((map (make-sparse-keymap)))
167     (define-key map "i" 'notmuch-search-stash-thread-id)
168     (define-key map "?" 'notmuch-subkeymap-help)
169     map)
170   "Submap for stash commands")
171 (fset 'notmuch-search-stash-map notmuch-search-stash-map)
172
173 (defun notmuch-search-stash-thread-id ()
174   "Copy thread ID of current thread to kill-ring."
175   (interactive)
176   (notmuch-common-do-stash (notmuch-search-find-thread-id)))
177
178 (defvar notmuch-search-query-string)
179 (defvar notmuch-search-target-thread)
180 (defvar notmuch-search-target-line)
181
182 (defvar notmuch-search-disjunctive-regexp      "\\<[oO][rR]\\>")
183
184 (defun notmuch-search-scroll-up ()
185   "Move forward through search results by one window's worth."
186   (interactive)
187   (condition-case nil
188       (scroll-up nil)
189     ((end-of-buffer) (notmuch-search-last-thread))))
190
191 (defun notmuch-search-scroll-down ()
192   "Move backward through the search results by one window's worth."
193   (interactive)
194   ;; I don't know why scroll-down doesn't signal beginning-of-buffer
195   ;; the way that scroll-up signals end-of-buffer, but c'est la vie.
196   ;;
197   ;; So instead of trapping a signal we instead check whether the
198   ;; window begins on the first line of the buffer and if so, move
199   ;; directly to that position. (We have to count lines since the
200   ;; window-start position is not the same as point-min due to the
201   ;; invisible thread-ID characters on the first line.
202   (if (equal (count-lines (point-min) (window-start)) 0)
203       (goto-char (point-min))
204     (scroll-down nil)))
205
206 (defun notmuch-search-next-thread ()
207   "Select the next thread in the search results."
208   (interactive)
209   (when (notmuch-search-get-result)
210     (goto-char (notmuch-search-result-end))))
211
212 (defun notmuch-search-previous-thread ()
213   "Select the previous thread in the search results."
214   (interactive)
215   (if (notmuch-search-get-result)
216       (unless (bobp)
217         (goto-char (notmuch-search-result-beginning (- (point) 1))))
218     ;; We must be past the end; jump to the last result
219     (notmuch-search-last-thread)))
220
221 (defun notmuch-search-last-thread ()
222   "Select the last thread in the search results."
223   (interactive)
224   (goto-char (point-max))
225   (forward-line -2)
226   (let ((beg (notmuch-search-result-beginning)))
227     (when beg (goto-char beg))))
228
229 (defun notmuch-search-first-thread ()
230   "Select the first thread in the search results."
231   (interactive)
232   (goto-char (point-min)))
233
234 (defface notmuch-message-summary-face
235  '((((class color) (background light)) (:background "#f0f0f0"))
236    (((class color) (background dark)) (:background "#303030")))
237  "Face for the single-line message summary in notmuch-show-mode."
238  :group 'notmuch-show
239  :group 'notmuch-faces)
240
241 (defface notmuch-search-date
242   '((t :inherit default))
243   "Face used in search mode for dates."
244   :group 'notmuch-search
245   :group 'notmuch-faces)
246
247 (defface notmuch-search-count
248   '((t :inherit default))
249   "Face used in search mode for the count matching the query."
250   :group 'notmuch-search
251   :group 'notmuch-faces)
252
253 (defface notmuch-search-subject
254   '((t :inherit default))
255   "Face used in search mode for subjects."
256   :group 'notmuch-search
257   :group 'notmuch-faces)
258
259 (defface notmuch-search-matching-authors
260   '((t :inherit default))
261   "Face used in search mode for authors matching the query."
262   :group 'notmuch-search
263   :group 'notmuch-faces)
264
265 (defface notmuch-search-non-matching-authors
266   '((((class color)
267       (background dark))
268      (:foreground "grey30"))
269     (((class color)
270       (background light))
271      (:foreground "grey60"))
272     (t
273      (:italic t)))
274   "Face used in search mode for authors not matching the query."
275   :group 'notmuch-search
276   :group 'notmuch-faces)
277
278 (defface notmuch-tag-face
279   '((((class color)
280       (background dark))
281      (:foreground "OliveDrab1"))
282     (((class color)
283       (background light))
284      (:foreground "navy blue" :bold t))
285     (t
286      (:bold t)))
287   "Face used in search mode face for tags."
288   :group 'notmuch-search
289   :group 'notmuch-faces)
290
291 (defun notmuch-search-mode ()
292   "Major mode displaying results of a notmuch search.
293
294 This buffer contains the results of a \"notmuch search\" of your
295 email archives. Each line in the buffer represents a single
296 thread giving a summary of the thread (a relative date, the
297 number of matched messages and total messages in the thread,
298 participants in the thread, a representative subject line, and
299 any tags).
300
301 Pressing \\[notmuch-search-show-thread] on any line displays that
302 thread. The '\\[notmuch-search-add-tag]' and
303 '\\[notmuch-search-remove-tag]' keys can be used to add or remove
304 tags from a thread. The '\\[notmuch-search-archive-thread]' key
305 is a convenience for archiving a thread (applying changes in
306 `notmuch-archive-tags'). The '\\[notmuch-search-tag-all]' key can
307 be used to add and/or remove tags from all messages (as opposed
308 to threads) that match the current query.  Use with caution, as
309 this will also tag matching messages that arrived *after*
310 constructing the buffer.
311
312 Other useful commands are '\\[notmuch-search-filter]' for
313 filtering the current search based on an additional query string,
314 '\\[notmuch-search-filter-by-tag]' for filtering to include only
315 messages with a given tag, and '\\[notmuch-search]' to execute a
316 new, global search.
317
318 Complete list of currently available key bindings:
319
320 \\{notmuch-search-mode-map}"
321   (interactive)
322   (kill-all-local-variables)
323   (make-local-variable 'notmuch-search-query-string)
324   (make-local-variable 'notmuch-search-oldest-first)
325   (make-local-variable 'notmuch-search-target-thread)
326   (make-local-variable 'notmuch-search-target-line)
327   (setq notmuch-buffer-refresh-function #'notmuch-search-refresh-view)
328   (set (make-local-variable 'scroll-preserve-screen-position) t)
329   (add-to-invisibility-spec (cons 'ellipsis t))
330   (use-local-map notmuch-search-mode-map)
331   (setq truncate-lines t)
332   (setq major-mode 'notmuch-search-mode
333         mode-name "notmuch-search")
334   (setq buffer-read-only t))
335
336 (defun notmuch-search-get-result (&optional pos)
337   "Return the result object for the thread at POS (or point).
338
339 If there is no thread at POS (or point), returns nil."
340   (get-text-property (or pos (point)) 'notmuch-search-result))
341
342 (defun notmuch-search-result-beginning (&optional pos)
343   "Return the point at the beginning of the thread at POS (or point).
344
345 If there is no thread at POS (or point), returns nil."
346   (when (notmuch-search-get-result pos)
347     ;; We pass 1+point because previous-single-property-change starts
348     ;; searching one before the position we give it.
349     (previous-single-property-change (1+ (or pos (point)))
350                                      'notmuch-search-result nil (point-min))))
351
352 (defun notmuch-search-result-end (&optional pos)
353   "Return the point at the end of the thread at POS (or point).
354
355 The returned point will be just after the newline character that
356 ends the result line.  If there is no thread at POS (or point),
357 returns nil"
358   (when (notmuch-search-get-result pos)
359     (next-single-property-change (or pos (point)) 'notmuch-search-result
360                                  nil (point-max))))
361
362 (defun notmuch-search-foreach-result (beg end function)
363   "Invoke FUNCTION for each result between BEG and END.
364
365 FUNCTION should take one argument.  It will be applied to the
366 character position of the beginning of each result that overlaps
367 the region between points BEG and END.  As a special case, if (=
368 BEG END), FUNCTION will be applied to the result containing point
369 BEG."
370
371   (lexical-let ((pos (notmuch-search-result-beginning beg))
372                 ;; End must be a marker in case function changes the
373                 ;; text.
374                 (end (copy-marker end))
375                 ;; Make sure we examine at least one result, even if
376                 ;; (= beg end).
377                 (first t))
378     ;; We have to be careful if the region extends beyond the results.
379     ;; In this case, pos could be null or there could be no result at
380     ;; pos.
381     (while (and pos (or (< pos end) first))
382       (when (notmuch-search-get-result pos)
383         (funcall function pos))
384       (setq pos (notmuch-search-result-end pos)
385             first nil))))
386 ;; Unindent the function argument of notmuch-search-foreach-result so
387 ;; the indentation of callers doesn't get out of hand.
388 (put 'notmuch-search-foreach-result 'lisp-indent-function 2)
389
390 (defun notmuch-search-properties-in-region (property beg end)
391   (let (output)
392     (notmuch-search-foreach-result beg end
393       (lambda (pos)
394         (push (plist-get (notmuch-search-get-result pos) property) output)))
395     output))
396
397 (defun notmuch-search-find-thread-id (&optional bare)
398   "Return the thread for the current thread
399
400 If BARE is set then do not prefix with \"thread:\""
401   (let ((thread (plist-get (notmuch-search-get-result) :thread)))
402     (when thread (concat (unless bare "thread:") thread))))
403
404 (defun notmuch-search-find-stable-query ()
405   "Return the stable queries for the current thread.
406
407 This returns a list (MATCHED-QUERY UNMATCHED-QUERY) for the
408 matched and unmatched messages in the current thread."
409   (plist-get (notmuch-search-get-result) :query))
410
411 (defun notmuch-search-find-stable-query-region (beg end &optional only-matched)
412   "Return the stable query for the current region.
413
414 If ONLY-MATCHED is non-nil, include only matched messages.  If it
415 is nil, include both matched and unmatched messages."
416   (let ((query-list nil) (all (not only-matched)))
417     (dolist (queries (notmuch-search-properties-in-region :query beg end))
418       (when (first queries)
419         (push (first queries) query-list))
420       (when (and all (second queries))
421         (push (second queries) query-list)))
422     (concat "(" (mapconcat 'identity query-list ") or (") ")")))
423
424 (defun notmuch-search-find-authors ()
425   "Return the authors for the current thread"
426   (plist-get (notmuch-search-get-result) :authors))
427
428 (defun notmuch-search-find-authors-region (beg end)
429   "Return a list of authors for the current region"
430   (notmuch-search-properties-in-region :authors beg end))
431
432 (defun notmuch-search-find-subject ()
433   "Return the subject for the current thread"
434   (plist-get (notmuch-search-get-result) :subject))
435
436 (defun notmuch-search-find-subject-region (beg end)
437   "Return a list of authors for the current region"
438   (notmuch-search-properties-in-region :subject beg end))
439
440 (defun notmuch-search-show-thread (&optional elide-toggle)
441   "Display the currently selected thread."
442   (interactive "P")
443   (let ((thread-id (notmuch-search-find-thread-id))
444         (subject (notmuch-search-find-subject)))
445     (if (> (length thread-id) 0)
446         (notmuch-show thread-id
447                       elide-toggle
448                       (current-buffer)
449                       notmuch-search-query-string
450                       ;; Name the buffer based on the subject.
451                       (concat "*" (truncate-string-to-width subject 30 nil nil t) "*"))
452       (message "End of search results."))))
453
454 (defun notmuch-tree-from-search-current-query ()
455   "Call notmuch tree with the current query"
456   (interactive)
457   (notmuch-tree notmuch-search-query-string))
458
459 (defun notmuch-tree-from-search-thread ()
460   "Show the selected thread with notmuch-tree"
461   (interactive)
462   (notmuch-tree (notmuch-search-find-thread-id)
463                 notmuch-search-query-string
464                 nil
465                 (notmuch-prettify-subject (notmuch-search-find-subject))
466                 t))
467
468 (defun notmuch-search-reply-to-thread (&optional prompt-for-sender)
469   "Begin composing a reply-all to the entire current thread in a new buffer."
470   (interactive "P")
471   (let ((message-id (notmuch-search-find-thread-id)))
472     (notmuch-mua-new-reply message-id prompt-for-sender t)))
473
474 (defun notmuch-search-reply-to-thread-sender (&optional prompt-for-sender)
475   "Begin composing a reply to the entire current thread in a new buffer."
476   (interactive "P")
477   (let ((message-id (notmuch-search-find-thread-id)))
478     (notmuch-mua-new-reply message-id prompt-for-sender nil)))
479
480 (defun notmuch-search-set-tags (tags &optional pos)
481   (let ((new-result (plist-put (notmuch-search-get-result pos) :tags tags)))
482     (notmuch-search-update-result new-result pos)))
483
484 (defun notmuch-search-get-tags (&optional pos)
485   (plist-get (notmuch-search-get-result pos) :tags))
486
487 (defun notmuch-search-get-tags-region (beg end)
488   (let (output)
489     (notmuch-search-foreach-result beg end
490       (lambda (pos)
491         (setq output (append output (notmuch-search-get-tags pos)))))
492     output))
493
494 (defun notmuch-search-interactive-region ()
495   "Return the bounds of the current interactive region.
496
497 This returns (BEG END), where BEG and END are the bounds of the
498 region if the region is active, or both `point' otherwise."
499   (if (region-active-p)
500       (list (region-beginning) (region-end))
501     (list (point) (point))))
502
503 (defun notmuch-search-interactive-tag-changes (&optional initial-input)
504   "Prompt for tag changes for the current thread or region.
505
506 Returns (TAG-CHANGES REGION-BEGIN REGION-END)."
507   (let* ((region (notmuch-search-interactive-region))
508          (beg (first region)) (end (second region))
509          (prompt (if (= beg end) "Tag thread" "Tag region")))
510     (cons (notmuch-read-tag-changes
511            (notmuch-search-get-tags-region beg end) prompt initial-input)
512           region)))
513
514 (defun notmuch-search-tag (tag-changes &optional beg end only-matched)
515   "Change tags for the currently selected thread or region.
516
517 See `notmuch-tag' for information on the format of TAG-CHANGES.
518 When called interactively, this uses the region if the region is
519 active.  When called directly, BEG and END provide the region.
520 If these are nil or not provided, this applies to the thread at
521 point.
522
523 If ONLY-MATCHED is non-nil, only tag matched messages."
524   (interactive (notmuch-search-interactive-tag-changes))
525   (unless (and beg end) (setq beg (point) end (point)))
526   (let ((search-string (notmuch-search-find-stable-query-region
527                         beg end only-matched)))
528     (notmuch-tag search-string tag-changes)
529     (notmuch-search-foreach-result beg end
530       (lambda (pos)
531         (notmuch-search-set-tags
532          (notmuch-update-tags (notmuch-search-get-tags pos) tag-changes)
533          pos)))))
534
535 (defun notmuch-search-add-tag (tag-changes &optional beg end)
536   "Change tags for the current thread or region (defaulting to add).
537
538 Same as `notmuch-search-tag' but sets initial input to '+'."
539   (interactive (notmuch-search-interactive-tag-changes "+"))
540   (notmuch-search-tag tag-changes beg end))
541
542 (defun notmuch-search-remove-tag (tag-changes &optional beg end)
543   "Change tags for the current thread or region (defaulting to remove).
544
545 Same as `notmuch-search-tag' but sets initial input to '-'."
546   (interactive (notmuch-search-interactive-tag-changes "-"))
547   (notmuch-search-tag tag-changes beg end))
548
549 (put 'notmuch-search-archive-thread 'notmuch-prefix-doc
550      "Un-archive the currently selected thread.")
551 (defun notmuch-search-archive-thread (&optional unarchive beg end)
552   "Archive the currently selected thread or region.
553
554 Archive each message in the currently selected thread by applying
555 the tag changes in `notmuch-archive-tags' to each (remove the
556 \"inbox\" tag by default). If a prefix argument is given, the
557 messages will be \"unarchived\" (i.e. the tag changes in
558 `notmuch-archive-tags' will be reversed).
559
560 This function advances the next thread when finished."
561   (interactive (cons current-prefix-arg (notmuch-search-interactive-region)))
562   (when notmuch-archive-tags
563     (notmuch-search-tag
564      (notmuch-tag-change-list notmuch-archive-tags unarchive) beg end))
565   (notmuch-search-next-thread))
566
567 (defun notmuch-search-update-result (result &optional pos)
568   "Replace the result object of the thread at POS (or point) by
569 RESULT and redraw it.
570
571 This will keep point in a reasonable location.  However, if there
572 are enclosing save-excursions and the saved point is in the
573 result being updated, the point will be restored to the beginning
574 of the result."
575   (let ((start (notmuch-search-result-beginning pos))
576         (end (notmuch-search-result-end pos))
577         (init-point (point))
578         (inhibit-read-only t))
579     ;; Delete the current thread
580     (delete-region start end)
581     ;; Insert the updated thread
582     (notmuch-search-show-result result start)
583     ;; If point was inside the old result, make an educated guess
584     ;; about where to place it now.  Unfortunately, this won't work
585     ;; with save-excursion (or any other markers that would be nice to
586     ;; preserve, such as the window start), but there's nothing we can
587     ;; do about that without a way to retrieve markers in a region.
588     (when (and (>= init-point start) (<= init-point end))
589       (let* ((new-end (notmuch-search-result-end start))
590              (new-point (if (= init-point end)
591                             new-end
592                           (min init-point (- new-end 1)))))
593         (goto-char new-point)))))
594
595 (defun notmuch-search-process-sentinel (proc msg)
596   "Add a message to let user know when \"notmuch search\" exits"
597   (let ((buffer (process-buffer proc))
598         (status (process-status proc))
599         (exit-status (process-exit-status proc))
600         (never-found-target-thread nil))
601     (when (memq status '(exit signal))
602       (catch 'return
603         (kill-buffer (process-get proc 'parse-buf))
604         (if (buffer-live-p buffer)
605             (with-current-buffer buffer
606               (save-excursion
607                 (let ((inhibit-read-only t)
608                       (atbob (bobp)))
609                   (goto-char (point-max))
610                   (if (eq status 'signal)
611                       (insert "Incomplete search results (search process was killed).\n"))
612                   (when (eq status 'exit)
613                     (insert "End of search results.\n")
614                     ;; For version mismatch, there's no point in
615                     ;; showing the search buffer
616                     (when (or (= exit-status 20) (= exit-status 21))
617                       (kill-buffer)
618                       (throw 'return nil))
619                     (if (and atbob
620                              (not (string= notmuch-search-target-thread "found")))
621                         (set 'never-found-target-thread t)))))
622               (when (and never-found-target-thread
623                        notmuch-search-target-line)
624                   (goto-char (point-min))
625                   (forward-line (1- notmuch-search-target-line)))))))))
626
627 (defcustom notmuch-search-line-faces '(("unread" :weight bold)
628                                        ("flagged" :foreground "blue"))
629   "Tag/face mapping for line highlighting in notmuch-search.
630
631 Here is an example of how to color search results based on tags.
632  (the following text would be placed in your ~/.emacs file):
633
634  (setq notmuch-search-line-faces '((\"deleted\" . (:foreground \"red\"
635                                                   :background \"blue\"))
636                                    (\"unread\" . (:foreground \"green\"))))
637
638 The attributes defined for matching tags are merged, with later
639 attributes overriding earlier. A message having both \"deleted\"
640 and \"unread\" tags with the above settings would have a green
641 foreground and blue background."
642   :type '(alist :key-type (string) :value-type (custom-face-edit))
643   :group 'notmuch-search
644   :group 'notmuch-faces)
645
646 (defun notmuch-search-color-line (start end line-tag-list)
647   "Colorize lines in `notmuch-show' based on tags."
648   (mapc (lambda (elem)
649           (let ((tag (car elem))
650                 (attributes (cdr elem)))
651             (when (member tag line-tag-list)
652               (notmuch-apply-face nil attributes nil start end))))
653         ;; Reverse the list so earlier entries take precedence
654         (reverse notmuch-search-line-faces)))
655
656 (defun notmuch-search-author-propertize (authors)
657   "Split `authors' into matching and non-matching authors and
658 propertize appropriately. If no boundary between authors and
659 non-authors is found, assume that all of the authors match."
660   (if (string-match "\\(.*\\)|\\(.*\\)" authors)
661       (concat (propertize (concat (match-string 1 authors) ",")
662                           'face 'notmuch-search-matching-authors)
663               (propertize (match-string 2 authors)
664                           'face 'notmuch-search-non-matching-authors))
665     (propertize authors 'face 'notmuch-search-matching-authors)))
666
667 (defun notmuch-search-insert-authors (format-string authors)
668   ;; Save the match data to avoid interfering with
669   ;; `notmuch-search-process-filter'.
670   (save-match-data
671     (let* ((formatted-authors (format format-string authors))
672            (formatted-sample (format format-string ""))
673            (visible-string formatted-authors)
674            (invisible-string "")
675            (padding ""))
676
677       ;; Truncate the author string to fit the specification.
678       (if (> (length formatted-authors)
679              (length formatted-sample))
680           (let ((visible-length (- (length formatted-sample)
681                                    (length "... "))))
682             ;; Truncate the visible string according to the width of
683             ;; the display string.
684             (setq visible-string (substring formatted-authors 0 visible-length)
685                   invisible-string (substring formatted-authors visible-length))
686             ;; If possible, truncate the visible string at a natural
687             ;; break (comma or pipe), as incremental search doesn't
688             ;; match across the visible/invisible border.
689             (when (string-match "\\(.*\\)\\([,|] \\)\\([^,|]*\\)" visible-string)
690               ;; Second clause is destructive on `visible-string', so
691               ;; order is important.
692               (setq invisible-string (concat (match-string 3 visible-string)
693                                              invisible-string)
694                     visible-string (concat (match-string 1 visible-string)
695                                            (match-string 2 visible-string))))
696             ;; `visible-string' may be shorter than the space allowed
697             ;; by `format-string'. If so we must insert some padding
698             ;; after `invisible-string'.
699             (setq padding (make-string (- (length formatted-sample)
700                                           (length visible-string)
701                                           (length "..."))
702                                        ? ))))
703
704       ;; Use different faces to show matching and non-matching authors.
705       (if (string-match "\\(.*\\)|\\(.*\\)" visible-string)
706           ;; The visible string contains both matching and
707           ;; non-matching authors.
708           (setq visible-string (notmuch-search-author-propertize visible-string)
709                 ;; The invisible string must contain only non-matching
710                 ;; authors, as the visible-string contains both.
711                 invisible-string (propertize invisible-string
712                                              'face 'notmuch-search-non-matching-authors))
713         ;; The visible string contains only matching authors.
714         (setq visible-string (propertize visible-string
715                                          'face 'notmuch-search-matching-authors)
716               ;; The invisible string may contain both matching and
717               ;; non-matching authors.
718               invisible-string (notmuch-search-author-propertize invisible-string)))
719
720       ;; If there is any invisible text, add it as a tooltip to the
721       ;; visible text.
722       (when (not (string= invisible-string ""))
723         (setq visible-string (propertize visible-string 'help-echo (concat "..." invisible-string))))
724
725       ;; Insert the visible and, if present, invisible author strings.
726       (insert visible-string)
727       (when (not (string= invisible-string ""))
728         (let ((start (point))
729               overlay)
730           (insert invisible-string)
731           (setq overlay (make-overlay start (point)))
732           (overlay-put overlay 'invisible 'ellipsis)
733           (overlay-put overlay 'isearch-open-invisible #'delete-overlay)))
734       (insert padding))))
735
736 (defun notmuch-search-insert-field (field format-string result)
737   (cond
738    ((string-equal field "date")
739     (insert (propertize (format format-string (plist-get result :date_relative))
740                         'face 'notmuch-search-date)))
741    ((string-equal field "count")
742     (insert (propertize (format format-string
743                                 (format "[%s/%s]" (plist-get result :matched)
744                                         (plist-get result :total)))
745                         'face 'notmuch-search-count)))
746    ((string-equal field "subject")
747     (insert (propertize (format format-string
748                                 (notmuch-sanitize (plist-get result :subject)))
749                         'face 'notmuch-search-subject)))
750
751    ((string-equal field "authors")
752     (notmuch-search-insert-authors
753      format-string (notmuch-sanitize (plist-get result :authors))))
754
755    ((string-equal field "tags")
756     (let ((tags (plist-get result :tags))
757           (orig-tags (plist-get result :orig-tags)))
758       (insert (format format-string (notmuch-tag-format-tags tags orig-tags)))))))
759
760 (defun notmuch-search-show-result (result pos)
761   "Insert RESULT at POS."
762   ;; Ignore excluded matches
763   (unless (= (plist-get result :matched) 0)
764     (save-excursion
765       (goto-char pos)
766       (dolist (spec notmuch-search-result-format)
767         (notmuch-search-insert-field (car spec) (cdr spec) result))
768       (insert "\n")
769       (notmuch-search-color-line pos (point) (plist-get result :tags))
770       (put-text-property pos (point) 'notmuch-search-result result))))
771
772 (defun notmuch-search-append-result (result)
773   "Insert RESULT at the end of the buffer.
774
775 This is only called when a result is first inserted so it also
776 sets the :orig-tag property."
777   (let ((new-result (plist-put result :orig-tags (plist-get result :tags)))
778         (pos (point-max)))
779     (notmuch-search-show-result new-result pos)
780     (when (string= (plist-get result :thread) notmuch-search-target-thread)
781       (setq notmuch-search-target-thread "found")
782       (goto-char pos))))
783
784 (defun notmuch-search-process-filter (proc string)
785   "Process and filter the output of \"notmuch search\""
786   (let ((results-buf (process-buffer proc))
787         (parse-buf (process-get proc 'parse-buf))
788         (inhibit-read-only t)
789         done)
790     (when (buffer-live-p results-buf)
791       (with-current-buffer parse-buf
792         ;; Insert new data
793         (save-excursion
794           (goto-char (point-max))
795           (insert string))
796         (notmuch-sexp-parse-partial-list 'notmuch-search-append-result
797                                          results-buf)))))
798
799 (defun notmuch-search-tag-all (tag-changes)
800   "Add/remove tags from all messages in current search buffer.
801
802 See `notmuch-tag' for information on the format of TAG-CHANGES."
803   (interactive
804    (list (notmuch-read-tag-changes
805           (notmuch-search-get-tags-region (point-min) (point-max)) "Tag all")))
806   (notmuch-search-tag tag-changes (point-min) (point-max) t))
807
808 (defun notmuch-search-buffer-title (query)
809   "Returns the title for a buffer with notmuch search results."
810   (let* ((saved-search
811           (let (longest
812                 (longest-length 0))
813             (loop for tuple in notmuch-saved-searches
814                   if (let ((quoted-query (regexp-quote (cdr tuple))))
815                        (and (string-match (concat "^" quoted-query) query)
816                             (> (length (match-string 0 query))
817                                longest-length)))
818                   do (setq longest tuple))
819             longest))
820          (saved-search-name (car saved-search))
821          (saved-search-query (cdr saved-search)))
822     (cond ((and saved-search (equal saved-search-query query))
823            ;; Query is the same as saved search (ignoring case)
824            (concat "*notmuch-saved-search-" saved-search-name "*"))
825           (saved-search
826            (concat "*notmuch-search-"
827                    (replace-regexp-in-string (concat "^" (regexp-quote saved-search-query))
828                                              (concat "[ " saved-search-name " ]")
829                                              query)
830                    "*"))
831           (t
832            (concat "*notmuch-search-" query "*"))
833           )))
834
835 (defun notmuch-read-query (prompt)
836   "Read a notmuch-query from the minibuffer with completion.
837
838 PROMPT is the string to prompt with."
839   (lexical-let
840       ((completions
841         (append (list "folder:" "path:" "thread:" "id:" "date:" "from:" "to:"
842                       "subject:" "attachment:")
843                 (mapcar (lambda (tag)
844                           (concat "tag:" (notmuch-escape-boolean-term tag)))
845                         (process-lines notmuch-command "search" "--output=tags" "*")))))
846     (let ((keymap (copy-keymap minibuffer-local-map))
847           (minibuffer-completion-table
848            (completion-table-dynamic
849             (lambda (string)
850               ;; generate a list of possible completions for the current input
851               (cond
852                ;; this ugly regexp is used to get the last word of the input
853                ;; possibly preceded by a '('
854                ((string-match "\\(^\\|.* (?\\)\\([^ ]*\\)$" string)
855                 (mapcar (lambda (compl)
856                           (concat (match-string-no-properties 1 string) compl))
857                         (all-completions (match-string-no-properties 2 string)
858                                          completions)))
859                (t (list string)))))))
860       ;; this was simpler than convincing completing-read to accept spaces:
861       (define-key keymap (kbd "TAB") 'minibuffer-complete)
862       (let ((history-delete-duplicates t))
863         (read-from-minibuffer prompt nil keymap nil
864                               'notmuch-search-history nil nil)))))
865
866 ;;;###autoload
867 (put 'notmuch-search 'notmuch-doc "Search for messages.")
868 (defun notmuch-search (&optional query oldest-first target-thread target-line)
869   "Display threads matching QUERY in a notmuch-search buffer.
870
871 If QUERY is nil, it is read interactively from the minibuffer.
872 Other optional parameters are used as follows:
873
874   OLDEST-FIRST: A Boolean controlling the sort order of returned threads
875   TARGET-THREAD: A thread ID (without the thread: prefix) that will be made
876                  current if it appears in the search results.
877   TARGET-LINE: The line number to move to if the target thread does not
878                appear in the search results.
879
880 When called interactively, this will prompt for a query and use
881 the configured default sort order."
882   (interactive
883    (list
884     ;; Prompt for a query
885     nil
886     ;; Use the default search order (if we're doing a search from a
887     ;; search buffer, ignore any buffer-local overrides)
888     (default-value 'notmuch-search-oldest-first)))
889
890   (let* ((query (or query (notmuch-read-query "Notmuch search: ")))
891          (buffer (get-buffer-create (notmuch-search-buffer-title query))))
892     (switch-to-buffer buffer)
893     (notmuch-search-mode)
894     ;; Don't track undo information for this buffer
895     (set 'buffer-undo-list t)
896     (set 'notmuch-search-query-string query)
897     (set 'notmuch-search-oldest-first oldest-first)
898     (set 'notmuch-search-target-thread target-thread)
899     (set 'notmuch-search-target-line target-line)
900     (notmuch-tag-clear-cache)
901     (let ((proc (get-buffer-process (current-buffer)))
902           (inhibit-read-only t))
903       (if proc
904           (error "notmuch search process already running for query `%s'" query)
905         )
906       (erase-buffer)
907       (goto-char (point-min))
908       (save-excursion
909         (let ((proc (notmuch-start-notmuch
910                      "notmuch-search" buffer #'notmuch-search-process-sentinel
911                      "search" "--format=sexp" "--format-version=2"
912                      (if oldest-first
913                          "--sort=oldest-first"
914                        "--sort=newest-first")
915                      query))
916               ;; Use a scratch buffer to accumulate partial output.
917               ;; This buffer will be killed by the sentinel, which
918               ;; should be called no matter how the process dies.
919               (parse-buf (generate-new-buffer " *notmuch search parse*")))
920           (process-put proc 'parse-buf parse-buf)
921           (set-process-filter proc 'notmuch-search-process-filter)
922           (set-process-query-on-exit-flag proc nil))))
923     (run-hooks 'notmuch-search-hook)))
924
925 (defun notmuch-search-refresh-view ()
926   "Refresh the current view.
927
928 Kills the current buffer and runs a new search with the same
929 query string as the current search. If the current thread is in
930 the new search results, then point will be placed on the same
931 thread. Otherwise, point will be moved to attempt to be in the
932 same relative position within the new buffer."
933   (let ((target-line (line-number-at-pos))
934         (oldest-first notmuch-search-oldest-first)
935         (target-thread (notmuch-search-find-thread-id 'bare))
936         (query notmuch-search-query-string))
937     (notmuch-kill-this-buffer)
938     (notmuch-search query oldest-first target-thread target-line)
939     (goto-char (point-min))))
940
941 (defun notmuch-search-toggle-order ()
942   "Toggle the current search order.
943
944 This command toggles the sort order for the current search. The
945 default sort order is defined by `notmuch-search-oldest-first'."
946   (interactive)
947   (set 'notmuch-search-oldest-first (not notmuch-search-oldest-first))
948   (notmuch-search-refresh-view))
949
950 (defun notmuch-search-filter (query)
951   "Filter the current search results based on an additional query string.
952
953 Runs a new search matching only messages that match both the
954 current search results AND the additional query string provided."
955   (interactive (list (notmuch-read-query "Filter search: ")))
956   (let ((grouped-query (if (string-match-p notmuch-search-disjunctive-regexp query)
957                            (concat "( " query " )")
958                          query)))
959     (notmuch-search (if (string= notmuch-search-query-string "*")
960                         grouped-query
961                       (concat notmuch-search-query-string " and " grouped-query)) notmuch-search-oldest-first)))
962
963 (defun notmuch-search-filter-by-tag (tag)
964   "Filter the current search results based on a single tag.
965
966 Runs a new search matching only messages that match both the
967 current search results AND that are tagged with the given tag."
968   (interactive
969    (list (notmuch-select-tag-with-completion "Filter by tag: ")))
970   (notmuch-search (concat notmuch-search-query-string " and tag:" tag) notmuch-search-oldest-first))
971
972 ;;;###autoload
973 (defun notmuch ()
974   "Run notmuch and display saved searches, known tags, etc."
975   (interactive)
976   (notmuch-hello))
977
978 (defun notmuch-interesting-buffer (b)
979   "Is the current buffer of interest to a notmuch user?"
980   (with-current-buffer b
981     (memq major-mode '(notmuch-show-mode
982                        notmuch-search-mode
983                        notmuch-hello-mode
984                        message-mode))))
985
986 ;;;###autoload
987 (defun notmuch-cycle-notmuch-buffers ()
988   "Cycle through any existing notmuch buffers (search, show or hello).
989
990 If the current buffer is the only notmuch buffer, bury it. If no
991 notmuch buffers exist, run `notmuch'."
992   (interactive)
993
994   (let (start first)
995     ;; If the current buffer is a notmuch buffer, remember it and then
996     ;; bury it.
997     (when (notmuch-interesting-buffer (current-buffer))
998       (setq start (current-buffer))
999       (bury-buffer))
1000
1001     ;; Find the first notmuch buffer.
1002     (setq first (loop for buffer in (buffer-list)
1003                      if (notmuch-interesting-buffer buffer)
1004                      return buffer))
1005
1006     (if first
1007         ;; If the first one we found is any other than the starting
1008         ;; buffer, switch to it.
1009         (unless (eq first start)
1010           (switch-to-buffer first))
1011       (notmuch))))
1012
1013 (setq mail-user-agent 'notmuch-user-agent)
1014
1015 (provide 'notmuch)