1 ;; notmuch.el --- run notmuch within emacs
3 ;; Copyright © Carl Worth
5 ;; This file is part of Notmuch.
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.
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.
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/>.
20 ;; Authors: Carl Worth <cworth@cworth.org>
22 ;; This is an emacs-based interface to the notmuch mail system.
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.
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:
33 ;; sudo make install-emacs
37 ;; Then, to actually run it, add:
41 ;; to your ~/.emacs file, and then run "M-x notmuch" from within emacs,
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).
50 (eval-when-compile (require 'cl))
54 (require 'notmuch-lib)
55 (require 'notmuch-tag)
56 (require 'notmuch-show)
57 (require 'notmuch-mua)
58 (require 'notmuch-hello)
59 (require 'notmuch-maildir-fcc)
60 (require 'notmuch-message)
62 (defcustom notmuch-search-result-format
65 ("authors" . "%-20s ")
68 "Search result formatting. Supported fields are:
69 date, count, authors, subject, tags
71 (setq notmuch-search-result-format \(\(\"authors\" . \"%-40s\"\)
72 \(\"subject\" . \"%s\"\)\)\)
73 Line breaks are permitted in format strings (though this is
74 currently experimental). Note that a line break at the end of an
75 \"authors\" field will get elided if the authors list is long;
76 place it instead at the beginning of the following field. To
77 enter a line break when setting this variable with setq, use \\n.
78 To enter a line break in customize, press \\[quoted-insert] C-j."
79 :type '(alist :key-type (string) :value-type (string))
80 :group 'notmuch-search)
82 (defvar notmuch-query-history nil
83 "Variable to store minibuffer history for notmuch queries")
85 (defun notmuch-foreach-mime-part (function mm-handle)
86 (cond ((stringp (car mm-handle))
87 (dolist (part (cdr mm-handle))
88 (notmuch-foreach-mime-part function part)))
89 ((bufferp (car mm-handle))
90 (funcall function mm-handle))
91 (t (dolist (part mm-handle)
92 (notmuch-foreach-mime-part function part)))))
94 (defun notmuch-count-attachments (mm-handle)
96 (notmuch-foreach-mime-part
98 (let ((disposition (mm-handle-disposition p)))
99 (and (listp disposition)
100 (or (equal (car disposition) "attachment")
101 (and (equal (car disposition) "inline")
102 (assq 'filename disposition)))
107 (defun notmuch-save-attachments (mm-handle &optional queryp)
108 (notmuch-foreach-mime-part
110 (let ((disposition (mm-handle-disposition p)))
111 (and (listp disposition)
112 (or (equal (car disposition) "attachment")
113 (and (equal (car disposition) "inline")
114 (assq 'filename disposition)))
117 (concat "Save '" (cdr (assq 'filename disposition)) "' ")))
121 (defun notmuch-documentation-first-line (symbol)
122 "Return the first line of the documentation string for SYMBOL."
123 (let ((doc (documentation symbol)))
126 (insert (documentation symbol t))
127 (goto-char (point-min))
130 (buffer-substring beg (point))))
133 (defun notmuch-prefix-key-description (key)
134 "Given a prefix key code, return a human-readable string representation.
136 This is basically just `format-kbd-macro' but we also convert ESC to M-."
137 (let ((desc (format-kbd-macro (vector key))))
138 (if (string= desc "ESC")
142 ;; I would think that emacs would have code handy for walking a keymap
143 ;; and generating strings for each key, and I would prefer to just call
144 ;; that. But I couldn't find any (could be all implemented in C I
145 ;; suppose), so I wrote my own here.
146 (defun notmuch-substitute-one-command-key-with-prefix (prefix binding)
147 "For a key binding, return a string showing a human-readable
148 representation of the prefixed key as well as the first line of
149 documentation from the bound function.
151 For a mouse binding, return nil."
152 (let ((key (car binding))
153 (action (cdr binding)))
154 (if (mouse-event-p key)
157 (let ((substitute (apply-partially 'notmuch-substitute-one-command-key-with-prefix (notmuch-prefix-key-description key)))
159 (map-keymap (lambda (a b)
160 (push (cons a b) as-list))
162 (mapconcat substitute as-list "\n"))
163 (concat prefix (format-kbd-macro (vector key))
165 (notmuch-documentation-first-line action))))))
167 (defun notmuch-substitute-command-keys-one (key)
168 ;; A `keymap' key indicates inheritance from a parent keymap - the
169 ;; inherited mappings follow, so there is nothing to print for
171 (when (not (eq key 'keymap))
172 (notmuch-substitute-one-command-key-with-prefix nil key)))
174 (defun notmuch-substitute-command-keys (doc)
175 "Like `substitute-command-keys' but with documentation, not function names."
177 (while (string-match "\\\\{\\([^}[:space:]]*\\)}" doc beg)
178 (let* ((keymap-name (substring doc (match-beginning 1) (match-end 1)))
179 (keymap (symbol-value (intern keymap-name))))
180 (setq doc (replace-match
181 (mapconcat #'notmuch-substitute-command-keys-one
184 (setq beg (match-end 0)))
187 (defun notmuch-help ()
188 "Display help for the current notmuch mode."
190 (let* ((mode major-mode)
191 (doc (substitute-command-keys (notmuch-substitute-command-keys (documentation mode t)))))
192 (with-current-buffer (generate-new-buffer "*notmuch-help*")
194 (goto-char (point-min))
195 (set-buffer-modified-p nil)
196 (view-buffer (current-buffer) 'kill-buffer-if-not-modified))))
200 (defun notmuch-hl-line-mode ()
201 (prog1 (hl-line-mode)
202 (when hl-line-overlay
203 (overlay-put hl-line-overlay 'priority 1))))
205 (defcustom notmuch-search-hook '(notmuch-hl-line-mode)
206 "List of functions to call when notmuch displays the search results."
208 :options '(notmuch-hl-line-mode)
209 :group 'notmuch-search
210 :group 'notmuch-hooks)
212 (defvar notmuch-search-mode-map
213 (let ((map (make-sparse-keymap)))
214 (define-key map "?" 'notmuch-help)
215 (define-key map "q" 'notmuch-search-quit)
216 (define-key map "x" 'notmuch-search-quit)
217 (define-key map (kbd "<DEL>") 'notmuch-search-scroll-down)
218 (define-key map "b" 'notmuch-search-scroll-down)
219 (define-key map " " 'notmuch-search-scroll-up)
220 (define-key map "<" 'notmuch-search-first-thread)
221 (define-key map ">" 'notmuch-search-last-thread)
222 (define-key map "p" 'notmuch-search-previous-thread)
223 (define-key map "n" 'notmuch-search-next-thread)
224 (define-key map "r" 'notmuch-search-reply-to-thread-sender)
225 (define-key map "R" 'notmuch-search-reply-to-thread)
226 (define-key map "m" 'notmuch-mua-new-mail)
227 (define-key map "s" 'notmuch-search)
228 (define-key map "o" 'notmuch-search-toggle-order)
229 (define-key map "c" 'notmuch-search-stash-map)
230 (define-key map "=" 'notmuch-search-refresh-view)
231 (define-key map "G" 'notmuch-search-poll-and-refresh-view)
232 (define-key map "t" 'notmuch-search-filter-by-tag)
233 (define-key map "f" 'notmuch-search-filter)
234 (define-key map [mouse-1] 'notmuch-search-show-thread)
235 (define-key map "*" 'notmuch-search-tag-all)
236 (define-key map "a" 'notmuch-search-archive-thread)
237 (define-key map "-" 'notmuch-search-remove-tag)
238 (define-key map "+" 'notmuch-search-add-tag)
239 (define-key map (kbd "RET") 'notmuch-search-show-thread)
241 "Keymap for \"notmuch search\" buffers.")
242 (fset 'notmuch-search-mode-map notmuch-search-mode-map)
244 (defvar notmuch-search-stash-map
245 (let ((map (make-sparse-keymap)))
246 (define-key map "i" 'notmuch-search-stash-thread-id)
248 "Submap for stash commands")
249 (fset 'notmuch-search-stash-map notmuch-search-stash-map)
251 (defun notmuch-search-stash-thread-id ()
252 "Copy thread ID of current thread to kill-ring."
254 (notmuch-common-do-stash (notmuch-search-find-thread-id)))
256 (defvar notmuch-search-query-string)
257 (defvar notmuch-search-target-thread)
258 (defvar notmuch-search-target-line)
259 (defvar notmuch-search-continuation)
261 (defvar notmuch-search-disjunctive-regexp "\\<[oO][rR]\\>")
263 (defun notmuch-search-quit ()
264 "Exit the search buffer, calling any defined continuation function."
266 (let ((continuation notmuch-search-continuation))
267 (notmuch-kill-this-buffer)
269 (funcall continuation))))
271 (defun notmuch-search-scroll-up ()
272 "Move forward through search results by one window's worth."
276 ((end-of-buffer) (notmuch-search-last-thread))))
278 (defun notmuch-search-scroll-down ()
279 "Move backward through the search results by one window's worth."
281 ;; I don't know why scroll-down doesn't signal beginning-of-buffer
282 ;; the way that scroll-up signals end-of-buffer, but c'est la vie.
284 ;; So instead of trapping a signal we instead check whether the
285 ;; window begins on the first line of the buffer and if so, move
286 ;; directly to that position. (We have to count lines since the
287 ;; window-start position is not the same as point-min due to the
288 ;; invisible thread-ID characters on the first line.
289 (if (equal (count-lines (point-min) (window-start)) 0)
290 (goto-char (point-min))
293 (defun notmuch-search-next-thread ()
294 "Select the next thread in the search results."
296 (when (notmuch-search-get-result)
297 (goto-char (notmuch-search-result-end))))
299 (defun notmuch-search-previous-thread ()
300 "Select the previous thread in the search results."
302 (if (notmuch-search-get-result)
304 (goto-char (notmuch-search-result-beginning (- (point) 1))))
305 ;; We must be past the end; jump to the last result
306 (notmuch-search-last-thread)))
308 (defun notmuch-search-last-thread ()
309 "Select the last thread in the search results."
311 (goto-char (point-max))
313 (let ((beg (notmuch-search-result-beginning)))
314 (when beg (goto-char beg))))
316 (defun notmuch-search-first-thread ()
317 "Select the first thread in the search results."
319 (goto-char (point-min)))
321 (defface notmuch-message-summary-face
322 '((((class color) (background light)) (:background "#f0f0f0"))
323 (((class color) (background dark)) (:background "#303030")))
324 "Face for the single-line message summary in notmuch-show-mode."
326 :group 'notmuch-faces)
328 (defface notmuch-search-date
329 '((t :inherit default))
330 "Face used in search mode for dates."
331 :group 'notmuch-search
332 :group 'notmuch-faces)
334 (defface notmuch-search-count
335 '((t :inherit default))
336 "Face used in search mode for the count matching the query."
337 :group 'notmuch-search
338 :group 'notmuch-faces)
340 (defface notmuch-search-subject
341 '((t :inherit default))
342 "Face used in search mode for subjects."
343 :group 'notmuch-search
344 :group 'notmuch-faces)
346 (defface notmuch-search-matching-authors
347 '((t :inherit default))
348 "Face used in search mode for authors matching the query."
349 :group 'notmuch-search
350 :group 'notmuch-faces)
352 (defface notmuch-search-non-matching-authors
355 (:foreground "grey30"))
358 (:foreground "grey60"))
361 "Face used in search mode for authors not matching the query."
362 :group 'notmuch-search
363 :group 'notmuch-faces)
365 (defface notmuch-tag-face
368 (:foreground "OliveDrab1"))
371 (:foreground "navy blue" :bold t))
374 "Face used in search mode face for tags."
375 :group 'notmuch-search
376 :group 'notmuch-faces)
378 (defun notmuch-search-mode ()
379 "Major mode displaying results of a notmuch search.
381 This buffer contains the results of a \"notmuch search\" of your
382 email archives. Each line in the buffer represents a single
383 thread giving a summary of the thread (a relative date, the
384 number of matched messages and total messages in the thread,
385 participants in the thread, a representative subject line, and
388 Pressing \\[notmuch-search-show-thread] on any line displays that thread. The '\\[notmuch-search-add-tag]' and '\\[notmuch-search-remove-tag]'
389 keys can be used to add or remove tags from a thread. The '\\[notmuch-search-archive-thread]' key
390 is a convenience for archiving a thread (removing the \"inbox\"
391 tag). The '\\[notmuch-search-tag-all]' key can be used to add or remove a tag from all
392 threads in the current buffer.
394 Other useful commands are '\\[notmuch-search-filter]' for filtering the current search
395 based on an additional query string, '\\[notmuch-search-filter-by-tag]' for filtering to include
396 only messages with a given tag, and '\\[notmuch-search]' to execute a new, global
399 Complete list of currently available key bindings:
401 \\{notmuch-search-mode-map}"
403 (kill-all-local-variables)
404 (make-local-variable 'notmuch-search-query-string)
405 (make-local-variable 'notmuch-search-oldest-first)
406 (make-local-variable 'notmuch-search-target-thread)
407 (make-local-variable 'notmuch-search-target-line)
408 (set (make-local-variable 'notmuch-search-continuation) nil)
409 (set (make-local-variable 'scroll-preserve-screen-position) t)
410 (add-to-invisibility-spec (cons 'ellipsis t))
411 (use-local-map notmuch-search-mode-map)
412 (setq truncate-lines t)
413 (setq major-mode 'notmuch-search-mode
414 mode-name "notmuch-search")
415 (setq buffer-read-only t))
417 (defun notmuch-search-get-result (&optional pos)
418 "Return the result object for the thread at POS (or point).
420 If there is no thread at POS (or point), returns nil."
421 (get-text-property (or pos (point)) 'notmuch-search-result))
423 (defun notmuch-search-result-beginning (&optional pos)
424 "Return the point at the beginning of the thread at POS (or point).
426 If there is no thread at POS (or point), returns nil."
427 (when (notmuch-search-get-result pos)
428 ;; We pass 1+point because previous-single-property-change starts
429 ;; searching one before the position we give it.
430 (previous-single-property-change (1+ (or pos (point)))
431 'notmuch-search-result nil (point-min))))
433 (defun notmuch-search-result-end (&optional pos)
434 "Return the point at the end of the thread at POS (or point).
436 The returned point will be just after the newline character that
437 ends the result line. If there is no thread at POS (or point),
439 (when (notmuch-search-get-result pos)
440 (next-single-property-change (or pos (point)) 'notmuch-search-result
443 (defun notmuch-search-foreach-result (beg end function)
444 "Invoke FUNCTION for each result between BEG and END.
446 FUNCTION should take one argument. It will be applied to the
447 character position of the beginning of each result that overlaps
448 the region between points BEG and END. As a special case, if (=
449 BEG END), FUNCTION will be applied to the result containing point
452 (lexical-let ((pos (notmuch-search-result-beginning beg))
453 ;; End must be a marker in case function changes the
455 (end (copy-marker end))
456 ;; Make sure we examine at least one result, even if
459 ;; We have to be careful if the region extends beyond the results.
460 ;; In this case, pos could be null or there could be no result at
462 (while (and pos (or (< pos end) first))
463 (when (notmuch-search-get-result pos)
464 (funcall function pos))
465 (setq pos (notmuch-search-result-end pos)
467 ;; Unindent the function argument of notmuch-search-foreach-result so
468 ;; the indentation of callers doesn't get out of hand.
469 (put 'notmuch-search-foreach-result 'lisp-indent-function 2)
471 (defun notmuch-search-properties-in-region (property beg end)
473 (notmuch-search-foreach-result beg end
475 (push (plist-get (notmuch-search-get-result pos) property) output)))
478 (defun notmuch-search-find-thread-id (&optional bare)
479 "Return the thread for the current thread
481 If BARE is set then do not prefix with \"thread:\""
482 (let ((thread (plist-get (notmuch-search-get-result) :thread)))
483 (when thread (concat (unless bare "thread:") thread))))
485 (defun notmuch-search-find-thread-id-region (beg end)
486 "Return a list of threads for the current region"
487 (mapcar (lambda (thread) (concat "thread:" thread))
488 (notmuch-search-properties-in-region :thread beg end)))
490 (defun notmuch-search-find-thread-id-region-search (beg end)
491 "Return a search string for threads for the current region"
492 (mapconcat 'identity (notmuch-search-find-thread-id-region beg end) " or "))
494 (defun notmuch-search-find-authors ()
495 "Return the authors for the current thread"
496 (plist-get (notmuch-search-get-result) :authors))
498 (defun notmuch-search-find-authors-region (beg end)
499 "Return a list of authors for the current region"
500 (notmuch-search-properties-in-region :authors beg end))
502 (defun notmuch-search-find-subject ()
503 "Return the subject for the current thread"
504 (plist-get (notmuch-search-get-result) :subject))
506 (defun notmuch-search-find-subject-region (beg end)
507 "Return a list of authors for the current region"
508 (notmuch-search-properties-in-region :subject beg end))
510 (defun notmuch-search-show-thread ()
511 "Display the currently selected thread."
513 (let ((thread-id (notmuch-search-find-thread-id))
514 (subject (notmuch-search-find-subject)))
515 (if (> (length thread-id) 0)
516 (notmuch-show thread-id
518 notmuch-search-query-string
519 ;; Name the buffer based on the subject.
520 (concat "*" (truncate-string-to-width subject 30 nil nil t) "*"))
521 (message "End of search results."))))
523 (defun notmuch-search-reply-to-thread (&optional prompt-for-sender)
524 "Begin composing a reply-all to the entire current thread in a new buffer."
526 (let ((message-id (notmuch-search-find-thread-id)))
527 (notmuch-mua-new-reply message-id prompt-for-sender t)))
529 (defun notmuch-search-reply-to-thread-sender (&optional prompt-for-sender)
530 "Begin composing a reply to the entire current thread in a new buffer."
532 (let ((message-id (notmuch-search-find-thread-id)))
533 (notmuch-mua-new-reply message-id prompt-for-sender nil)))
535 (defun notmuch-call-notmuch-process (&rest args)
536 "Synchronously invoke \"notmuch\" with the given list of arguments.
538 Output from the process will be presented to the user as an error
539 and will also appear in a buffer named \"*Notmuch errors*\"."
540 (let ((error-buffer (get-buffer-create "*Notmuch errors*")))
541 (with-current-buffer error-buffer
543 (if (eq (apply 'call-process notmuch-command nil error-buffer nil args) 0)
546 (with-current-buffer error-buffer
547 (let ((beg (point-min))
548 (end (- (point-max) 1)))
549 (error (buffer-substring beg end))
552 (defun notmuch-search-set-tags (tags &optional pos)
553 (let ((new-result (plist-put (notmuch-search-get-result pos) :tags tags)))
554 (notmuch-search-update-result new-result pos)))
556 (defun notmuch-search-get-tags (&optional pos)
557 (plist-get (notmuch-search-get-result pos) :tags))
559 (defun notmuch-search-get-tags-region (beg end)
561 (notmuch-search-foreach-result beg end
563 (setq output (append output (notmuch-search-get-tags pos)))))
566 (defun notmuch-search-tag-region (beg end &optional tag-changes)
567 "Change tags for threads in the given region."
568 (let ((search-string (notmuch-search-find-thread-id-region-search beg end)))
569 (setq tag-changes (funcall 'notmuch-tag search-string tag-changes))
570 (notmuch-search-foreach-result beg end
572 (notmuch-search-set-tags
573 (notmuch-update-tags (notmuch-search-get-tags pos) tag-changes)
576 (defun notmuch-search-tag (&optional tag-changes)
577 "Change tags for the currently selected thread or region.
579 See `notmuch-tag' for information on the format of TAG-CHANGES."
581 (let* ((beg (if (region-active-p) (region-beginning) (point)))
582 (end (if (region-active-p) (region-end) (point))))
583 (funcall 'notmuch-search-tag-region beg end tag-changes)))
585 (defun notmuch-search-add-tag ()
586 "Same as `notmuch-search-tag' but sets initial input to '+'."
588 (notmuch-search-tag "+"))
590 (defun notmuch-search-remove-tag ()
591 "Same as `notmuch-search-tag' but sets initial input to '-'."
593 (notmuch-search-tag "-"))
595 (defun notmuch-search-archive-thread ()
596 "Archive the currently selected thread (remove its \"inbox\" tag).
598 This function advances the next thread when finished."
600 (notmuch-search-tag '("-inbox"))
601 (notmuch-search-next-thread))
603 (defun notmuch-search-update-result (result &optional pos)
604 "Replace the result object of the thread at POS (or point) by
605 RESULT and redraw it.
607 This will keep point in a reasonable location. However, if there
608 are enclosing save-excursions and the saved point is in the
609 result being updated, the point will be restored to the beginning
611 (let ((start (notmuch-search-result-beginning pos))
612 (end (notmuch-search-result-end pos))
614 (inhibit-read-only t))
615 ;; Delete the current thread
616 (delete-region start end)
617 ;; Insert the updated thread
618 (notmuch-search-show-result result start)
619 ;; If point was inside the old result, make an educated guess
620 ;; about where to place it now. Unfortunately, this won't work
621 ;; with save-excursion (or any other markers that would be nice to
622 ;; preserve, such as the window start), but there's nothing we can
623 ;; do about that without a way to retrieve markers in a region.
624 (when (and (>= init-point start) (<= init-point end))
625 (let* ((new-end (notmuch-search-result-end start))
626 (new-point (if (= init-point end)
628 (min init-point (- new-end 1)))))
629 (goto-char new-point)))))
631 (defun notmuch-search-process-sentinel (proc msg)
632 "Add a message to let user know when \"notmuch search\" exits"
633 (let ((buffer (process-buffer proc))
634 (status (process-status proc))
635 (exit-status (process-exit-status proc))
636 (never-found-target-thread nil))
637 (when (memq status '(exit signal))
638 (kill-buffer (process-get proc 'parse-buf))
639 (if (buffer-live-p buffer)
640 (with-current-buffer buffer
642 (let ((inhibit-read-only t)
644 (goto-char (point-max))
645 (if (eq status 'signal)
646 (insert "Incomplete search results (search process was killed).\n"))
647 (when (eq status 'exit)
648 (insert "End of search results.")
649 (unless (= exit-status 0)
650 (insert (format " (process returned %d)" exit-status)))
653 (not (string= notmuch-search-target-thread "found")))
654 (set 'never-found-target-thread t)))))
655 (when (and never-found-target-thread
656 notmuch-search-target-line)
657 (goto-char (point-min))
658 (forward-line (1- notmuch-search-target-line))))))))
660 (defcustom notmuch-search-line-faces '(("unread" :weight bold)
661 ("flagged" :foreground "blue"))
662 "Tag/face mapping for line highlighting in notmuch-search.
664 Here is an example of how to color search results based on tags.
665 (the following text would be placed in your ~/.emacs file):
667 (setq notmuch-search-line-faces '((\"deleted\" . (:foreground \"red\"
668 :background \"blue\"))
669 (\"unread\" . (:foreground \"green\"))))
671 The attributes defined for matching tags are merged, with later
672 attributes overriding earlier. A message having both \"deleted\"
673 and \"unread\" tags with the above settings would have a green
674 foreground and blue background."
675 :type '(alist :key-type (string) :value-type (custom-face-edit))
676 :group 'notmuch-search
677 :group 'notmuch-faces)
679 (defun notmuch-search-color-line (start end line-tag-list)
680 "Colorize lines in `notmuch-show' based on tags."
682 (let ((tag (car elem))
683 (attributes (cdr elem)))
684 (when (member tag line-tag-list)
685 (notmuch-combine-face-text-property start end attributes))))
686 ;; Reverse the list so earlier entries take precedence
687 (reverse notmuch-search-line-faces)))
689 (defun notmuch-search-author-propertize (authors)
690 "Split `authors' into matching and non-matching authors and
691 propertize appropriately. If no boundary between authors and
692 non-authors is found, assume that all of the authors match."
693 (if (string-match "\\(.*\\)|\\(.*\\)" authors)
694 (concat (propertize (concat (match-string 1 authors) ",")
695 'face 'notmuch-search-matching-authors)
696 (propertize (match-string 2 authors)
697 'face 'notmuch-search-non-matching-authors))
698 (propertize authors 'face 'notmuch-search-matching-authors)))
700 (defun notmuch-search-insert-authors (format-string authors)
701 ;; Save the match data to avoid interfering with
702 ;; `notmuch-search-process-filter'.
704 (let* ((formatted-authors (format format-string authors))
705 (formatted-sample (format format-string ""))
706 (visible-string formatted-authors)
707 (invisible-string "")
710 ;; Truncate the author string to fit the specification.
711 (if (> (length formatted-authors)
712 (length formatted-sample))
713 (let ((visible-length (- (length formatted-sample)
715 ;; Truncate the visible string according to the width of
716 ;; the display string.
717 (setq visible-string (substring formatted-authors 0 visible-length)
718 invisible-string (substring formatted-authors visible-length))
719 ;; If possible, truncate the visible string at a natural
720 ;; break (comma or pipe), as incremental search doesn't
721 ;; match across the visible/invisible border.
722 (when (string-match "\\(.*\\)\\([,|] \\)\\([^,|]*\\)" visible-string)
723 ;; Second clause is destructive on `visible-string', so
724 ;; order is important.
725 (setq invisible-string (concat (match-string 3 visible-string)
727 visible-string (concat (match-string 1 visible-string)
728 (match-string 2 visible-string))))
729 ;; `visible-string' may be shorter than the space allowed
730 ;; by `format-string'. If so we must insert some padding
731 ;; after `invisible-string'.
732 (setq padding (make-string (- (length formatted-sample)
733 (length visible-string)
737 ;; Use different faces to show matching and non-matching authors.
738 (if (string-match "\\(.*\\)|\\(.*\\)" visible-string)
739 ;; The visible string contains both matching and
740 ;; non-matching authors.
741 (setq visible-string (notmuch-search-author-propertize visible-string)
742 ;; The invisible string must contain only non-matching
743 ;; authors, as the visible-string contains both.
744 invisible-string (propertize invisible-string
745 'face 'notmuch-search-non-matching-authors))
746 ;; The visible string contains only matching authors.
747 (setq visible-string (propertize visible-string
748 'face 'notmuch-search-matching-authors)
749 ;; The invisible string may contain both matching and
750 ;; non-matching authors.
751 invisible-string (notmuch-search-author-propertize invisible-string)))
753 ;; If there is any invisible text, add it as a tooltip to the
755 (when (not (string= invisible-string ""))
756 (setq visible-string (propertize visible-string 'help-echo (concat "..." invisible-string))))
758 ;; Insert the visible and, if present, invisible author strings.
759 (insert visible-string)
760 (when (not (string= invisible-string ""))
761 (let ((start (point))
763 (insert invisible-string)
764 (setq overlay (make-overlay start (point)))
765 (overlay-put overlay 'invisible 'ellipsis)
766 (overlay-put overlay 'isearch-open-invisible #'delete-overlay)))
769 (defun notmuch-search-insert-field (field format-string result)
771 ((string-equal field "date")
772 (insert (propertize (format format-string (plist-get result :date_relative))
773 'face 'notmuch-search-date)))
774 ((string-equal field "count")
775 (insert (propertize (format format-string
776 (format "[%s/%s]" (plist-get result :matched)
777 (plist-get result :total)))
778 'face 'notmuch-search-count)))
779 ((string-equal field "subject")
780 (insert (propertize (format format-string (plist-get result :subject))
781 'face 'notmuch-search-subject)))
783 ((string-equal field "authors")
784 (notmuch-search-insert-authors format-string (plist-get result :authors)))
786 ((string-equal field "tags")
787 (let ((tags-str (mapconcat 'identity (plist-get result :tags) " ")))
788 (insert (propertize (format format-string tags-str)
789 'face 'notmuch-tag-face))))))
791 (defun notmuch-search-show-result (result &optional pos)
792 "Insert RESULT at POS or the end of the buffer if POS is null."
793 ;; Ignore excluded matches
794 (unless (= (plist-get result :matched) 0)
795 (let ((beg (or pos (point-max))))
798 (dolist (spec notmuch-search-result-format)
799 (notmuch-search-insert-field (car spec) (cdr spec) result))
801 (notmuch-search-color-line beg (point) (plist-get result :tags))
802 (put-text-property beg (point) 'notmuch-search-result result))
803 (when (string= (plist-get result :thread) notmuch-search-target-thread)
804 (setq notmuch-search-target-thread "found")
807 (defun notmuch-search-show-error (string &rest objects)
809 (goto-char (point-max))
810 (insert "Error: Unexpected output from notmuch search:\n")
811 (insert (apply #'format string objects))
814 (defvar notmuch-search-process-state nil
815 "Parsing state of the search process filter.")
817 (defvar notmuch-search-json-parser nil
818 "Incremental JSON parser for the search process filter.")
820 (defun notmuch-search-process-filter (proc string)
821 "Process and filter the output of \"notmuch search\""
822 (let ((results-buf (process-buffer proc))
823 (parse-buf (process-get proc 'parse-buf))
824 (inhibit-read-only t)
826 (if (not (buffer-live-p results-buf))
827 (delete-process proc)
828 (with-current-buffer parse-buf
831 (goto-char (point-max))
833 (with-current-buffer results-buf
836 (case notmuch-search-process-state
838 ;; Enter the results list
839 (if (eq (notmuch-json-begin-compound
840 notmuch-search-json-parser) 'retry)
842 (setq notmuch-search-process-state 'result)))
845 (let ((result (notmuch-json-read notmuch-search-json-parser)))
847 ((retry) (setq done t))
848 ((end) (setq notmuch-search-process-state 'end))
849 (otherwise (notmuch-search-show-result result)))))
851 ;; Any trailing data is unexpected
852 (notmuch-json-eof notmuch-search-json-parser)
855 ;; Do our best to resynchronize and ensure forward
857 (notmuch-search-show-error
859 (with-current-buffer parse-buf
860 (let ((bad (buffer-substring (line-beginning-position)
861 (line-end-position))))
864 ;; Clear out what we've parsed
865 (with-current-buffer parse-buf
866 (delete-region (point-min) (point)))))))
868 (defun notmuch-search-tag-all (&optional tag-changes)
869 "Add/remove tags from all messages in current search buffer.
871 See `notmuch-tag' for information on the format of TAG-CHANGES."
873 (apply 'notmuch-tag notmuch-search-query-string tag-changes))
875 (defun notmuch-search-buffer-title (query)
876 "Returns the title for a buffer with notmuch search results."
880 (loop for tuple in notmuch-saved-searches
881 if (let ((quoted-query (regexp-quote (cdr tuple))))
882 (and (string-match (concat "^" quoted-query) query)
883 (> (length (match-string 0 query))
885 do (setq longest tuple))
887 (saved-search-name (car saved-search))
888 (saved-search-query (cdr saved-search)))
889 (cond ((and saved-search (equal saved-search-query query))
890 ;; Query is the same as saved search (ignoring case)
891 (concat "*notmuch-saved-search-" saved-search-name "*"))
893 (concat "*notmuch-search-"
894 (replace-regexp-in-string (concat "^" (regexp-quote saved-search-query))
895 (concat "[ " saved-search-name " ]")
899 (concat "*notmuch-search-" query "*"))
902 (defun notmuch-read-query (prompt)
903 "Read a notmuch-query from the minibuffer with completion.
905 PROMPT is the string to prompt with."
908 (append (list "folder:" "thread:" "id:" "date:" "from:" "to:"
909 "subject:" "attachment:")
910 (mapcar (lambda (tag)
912 (process-lines notmuch-command "search" "--output=tags" "*")))))
913 (let ((keymap (copy-keymap minibuffer-local-map))
914 (minibuffer-completion-table
915 (completion-table-dynamic
917 ;; generate a list of possible completions for the current input
919 ;; this ugly regexp is used to get the last word of the input
920 ;; possibly preceded by a '('
921 ((string-match "\\(^\\|.* (?\\)\\([^ ]*\\)$" string)
922 (mapcar (lambda (compl)
923 (concat (match-string-no-properties 1 string) compl))
924 (all-completions (match-string-no-properties 2 string)
926 (t (list string)))))))
927 ;; this was simpler than convincing completing-read to accept spaces:
928 (define-key keymap (kbd "TAB") 'minibuffer-complete)
929 (let ((history-delete-duplicates t))
930 (read-from-minibuffer prompt nil keymap nil
931 'notmuch-search-history nil nil)))))
934 (defun notmuch-search (&optional query oldest-first target-thread target-line continuation)
935 "Run \"notmuch search\" with the given `query' and display results.
937 If `query' is nil, it is read interactively from the minibuffer.
938 Other optional parameters are used as follows:
940 oldest-first: A Boolean controlling the sort order of returned threads
941 target-thread: A thread ID (without the thread: prefix) that will be made
942 current if it appears in the search results.
943 target-line: The line number to move to if the target thread does not
944 appear in the search results."
947 (setq query (notmuch-read-query "Notmuch search: ")))
948 (let ((buffer (get-buffer-create (notmuch-search-buffer-title query))))
949 (switch-to-buffer buffer)
950 (notmuch-search-mode)
951 ;; Don't track undo information for this buffer
952 (set 'buffer-undo-list t)
953 (set 'notmuch-search-query-string query)
954 (set 'notmuch-search-oldest-first oldest-first)
955 (set 'notmuch-search-target-thread target-thread)
956 (set 'notmuch-search-target-line target-line)
957 (set 'notmuch-search-continuation continuation)
958 (let ((proc (get-buffer-process (current-buffer)))
959 (inhibit-read-only t))
961 (error "notmuch search process already running for query `%s'" query)
964 (goto-char (point-min))
966 (let ((proc (start-process
967 "notmuch-search" buffer
968 notmuch-command "search"
971 "--sort=oldest-first"
972 "--sort=newest-first")
974 ;; Use a scratch buffer to accumulate partial output.
975 ;; This buffer will be killed by the sentinel, which
976 ;; should be called no matter how the process dies.
977 (parse-buf (generate-new-buffer " *notmuch search parse*")))
978 (set (make-local-variable 'notmuch-search-process-state) 'begin)
979 (set (make-local-variable 'notmuch-search-json-parser)
980 (notmuch-json-create-parser parse-buf))
981 (process-put proc 'parse-buf parse-buf)
982 (set-process-sentinel proc 'notmuch-search-process-sentinel)
983 (set-process-filter proc 'notmuch-search-process-filter)
984 (set-process-query-on-exit-flag proc nil))))
985 (run-hooks 'notmuch-search-hook)))
987 (defun notmuch-search-refresh-view ()
988 "Refresh the current view.
990 Kills the current buffer and runs a new search with the same
991 query string as the current search. If the current thread is in
992 the new search results, then point will be placed on the same
993 thread. Otherwise, point will be moved to attempt to be in the
994 same relative position within the new buffer."
996 (let ((target-line (line-number-at-pos))
997 (oldest-first notmuch-search-oldest-first)
998 (target-thread (notmuch-search-find-thread-id 'bare))
999 (query notmuch-search-query-string)
1000 (continuation notmuch-search-continuation))
1001 (notmuch-kill-this-buffer)
1002 (notmuch-search query oldest-first target-thread target-line continuation)
1003 (goto-char (point-min))))
1005 (defcustom notmuch-poll-script nil
1006 "An external script to incorporate new mail into the notmuch database.
1008 This variable controls the action invoked by
1009 `notmuch-search-poll-and-refresh-view' and
1010 `notmuch-hello-poll-and-update' (each have a default keybinding
1011 of 'G') to incorporate new mail into the notmuch database.
1013 If set to nil (the default), new mail is processed by invoking
1014 \"notmuch new\". Otherwise, this should be set to a string that
1015 gives the name of an external script that processes new mail. If
1016 set to the empty string, no command will be run.
1018 The external script could do any of the following depending on
1021 1. Invoke a program to transfer mail to the local mail store
1022 2. Invoke \"notmuch new\" to incorporate the new mail
1023 3. Invoke one or more \"notmuch tag\" commands to classify the mail
1025 Note that the recommended way of achieving the same is using
1026 \"notmuch new\" hooks."
1027 :type '(choice (const :tag "notmuch new" nil)
1028 (const :tag "Disabled" "")
1029 (string :tag "Custom script"))
1030 :group 'notmuch-external)
1032 (defun notmuch-poll ()
1033 "Run \"notmuch new\" or an external script to import mail.
1035 Invokes `notmuch-poll-script', \"notmuch new\", or does nothing
1036 depending on the value of `notmuch-poll-script'."
1038 (if (stringp notmuch-poll-script)
1039 (unless (string= notmuch-poll-script "")
1040 (call-process notmuch-poll-script nil nil))
1041 (call-process notmuch-command nil nil nil "new")))
1043 (defun notmuch-search-poll-and-refresh-view ()
1044 "Invoke `notmuch-poll' to import mail, then refresh the current view."
1047 (notmuch-search-refresh-view))
1049 (defun notmuch-search-toggle-order ()
1050 "Toggle the current search order.
1052 By default, the \"inbox\" view created by `notmuch' is displayed
1053 in chronological order (oldest thread at the beginning of the
1054 buffer), while any global searches created by `notmuch-search'
1055 are displayed in reverse-chronological order (newest thread at
1056 the beginning of the buffer).
1058 This command toggles the sort order for the current search.
1060 Note that any filtered searches created by
1061 `notmuch-search-filter' retain the search order of the parent
1064 (set 'notmuch-search-oldest-first (not notmuch-search-oldest-first))
1065 (notmuch-search-refresh-view))
1067 (defun notmuch-search-filter (query)
1068 "Filter the current search results based on an additional query string.
1070 Runs a new search matching only messages that match both the
1071 current search results AND the additional query string provided."
1072 (interactive (list (notmuch-read-query "Filter search: ")))
1073 (let ((grouped-query (if (string-match-p notmuch-search-disjunctive-regexp query)
1074 (concat "( " query " )")
1076 (notmuch-search (if (string= notmuch-search-query-string "*")
1078 (concat notmuch-search-query-string " and " grouped-query)) notmuch-search-oldest-first)))
1080 (defun notmuch-search-filter-by-tag (tag)
1081 "Filter the current search results based on a single tag.
1083 Runs a new search matching only messages that match both the
1084 current search results AND that are tagged with the given tag."
1086 (list (notmuch-select-tag-with-completion "Filter by tag: ")))
1087 (notmuch-search (concat notmuch-search-query-string " and tag:" tag) notmuch-search-oldest-first))
1091 "Run notmuch and display saved searches, known tags, etc."
1095 (defun notmuch-interesting-buffer (b)
1096 "Is the current buffer of interest to a notmuch user?"
1097 (with-current-buffer b
1098 (memq major-mode '(notmuch-show-mode
1104 (defun notmuch-cycle-notmuch-buffers ()
1105 "Cycle through any existing notmuch buffers (search, show or hello).
1107 If the current buffer is the only notmuch buffer, bury it. If no
1108 notmuch buffers exist, run `notmuch'."
1112 ;; If the current buffer is a notmuch buffer, remember it and then
1114 (when (notmuch-interesting-buffer (current-buffer))
1115 (setq start (current-buffer))
1118 ;; Find the first notmuch buffer.
1119 (setq first (loop for buffer in (buffer-list)
1120 if (notmuch-interesting-buffer buffer)
1124 ;; If the first one we found is any other than the starting
1125 ;; buffer, switch to it.
1126 (unless (eq first start)
1127 (switch-to-buffer first))
1130 (setq mail-user-agent 'notmuch-user-agent)