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