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 :type '(alist :key-type (string) :value-type (string))
74 :group 'notmuch-search)
76 (defvar notmuch-query-history nil
77 "Variable to store minibuffer history for notmuch queries")
79 (defun notmuch-foreach-mime-part (function mm-handle)
80 (cond ((stringp (car mm-handle))
81 (dolist (part (cdr mm-handle))
82 (notmuch-foreach-mime-part function part)))
83 ((bufferp (car mm-handle))
84 (funcall function mm-handle))
85 (t (dolist (part mm-handle)
86 (notmuch-foreach-mime-part function part)))))
88 (defun notmuch-count-attachments (mm-handle)
90 (notmuch-foreach-mime-part
92 (let ((disposition (mm-handle-disposition p)))
93 (and (listp disposition)
94 (or (equal (car disposition) "attachment")
95 (and (equal (car disposition) "inline")
96 (assq 'filename disposition)))
101 (defun notmuch-save-attachments (mm-handle &optional queryp)
102 (notmuch-foreach-mime-part
104 (let ((disposition (mm-handle-disposition p)))
105 (and (listp disposition)
106 (or (equal (car disposition) "attachment")
107 (and (equal (car disposition) "inline")
108 (assq 'filename disposition)))
111 (concat "Save '" (cdr (assq 'filename disposition)) "' ")))
115 (defun notmuch-documentation-first-line (symbol)
116 "Return the first line of the documentation string for SYMBOL."
117 (let ((doc (documentation symbol)))
120 (insert (documentation symbol t))
121 (goto-char (point-min))
124 (buffer-substring beg (point))))
127 (defun notmuch-prefix-key-description (key)
128 "Given a prefix key code, return a human-readable string representation.
130 This is basically just `format-kbd-macro' but we also convert ESC to M-."
131 (let ((desc (format-kbd-macro (vector key))))
132 (if (string= desc "ESC")
136 ;; I would think that emacs would have code handy for walking a keymap
137 ;; and generating strings for each key, and I would prefer to just call
138 ;; that. But I couldn't find any (could be all implemented in C I
139 ;; suppose), so I wrote my own here.
140 (defun notmuch-substitute-one-command-key-with-prefix (prefix binding)
141 "For a key binding, return a string showing a human-readable
142 representation of the prefixed key as well as the first line of
143 documentation from the bound function.
145 For a mouse binding, return nil."
146 (let ((key (car binding))
147 (action (cdr binding)))
148 (if (mouse-event-p key)
151 (let ((substitute (apply-partially 'notmuch-substitute-one-command-key-with-prefix (notmuch-prefix-key-description key)))
153 (map-keymap (lambda (a b)
154 (push (cons a b) as-list))
156 (mapconcat substitute as-list "\n"))
157 (concat prefix (format-kbd-macro (vector key))
159 (notmuch-documentation-first-line action))))))
161 (defun notmuch-substitute-command-keys-one (key)
162 ;; A `keymap' key indicates inheritance from a parent keymap - the
163 ;; inherited mappings follow, so there is nothing to print for
165 (when (not (eq key 'keymap))
166 (notmuch-substitute-one-command-key-with-prefix nil key)))
168 (defun notmuch-substitute-command-keys (doc)
169 "Like `substitute-command-keys' but with documentation, not function names."
171 (while (string-match "\\\\{\\([^}[:space:]]*\\)}" doc beg)
172 (let* ((keymap-name (substring doc (match-beginning 1) (match-end 1)))
173 (keymap (symbol-value (intern keymap-name))))
174 (setq doc (replace-match
175 (mapconcat #'notmuch-substitute-command-keys-one
178 (setq beg (match-end 0)))
181 (defun notmuch-help ()
182 "Display help for the current notmuch mode."
184 (let* ((mode major-mode)
185 (doc (substitute-command-keys (notmuch-substitute-command-keys (documentation mode t)))))
186 (with-current-buffer (generate-new-buffer "*notmuch-help*")
188 (goto-char (point-min))
189 (set-buffer-modified-p nil)
190 (view-buffer (current-buffer) 'kill-buffer-if-not-modified))))
194 (defun notmuch-hl-line-mode ()
195 (prog1 (hl-line-mode)
196 (when hl-line-overlay
197 (overlay-put hl-line-overlay 'priority 1))))
199 (defcustom notmuch-search-hook '(notmuch-hl-line-mode)
200 "List of functions to call when notmuch displays the search results."
202 :options '(notmuch-hl-line-mode)
203 :group 'notmuch-search
204 :group 'notmuch-hooks)
206 (defvar notmuch-search-mode-map
207 (let ((map (make-sparse-keymap)))
208 (define-key map "?" 'notmuch-help)
209 (define-key map "q" 'notmuch-search-quit)
210 (define-key map "x" 'notmuch-search-quit)
211 (define-key map (kbd "<DEL>") 'notmuch-search-scroll-down)
212 (define-key map "b" 'notmuch-search-scroll-down)
213 (define-key map " " 'notmuch-search-scroll-up)
214 (define-key map "<" 'notmuch-search-first-thread)
215 (define-key map ">" 'notmuch-search-last-thread)
216 (define-key map "p" 'notmuch-search-previous-thread)
217 (define-key map "n" 'notmuch-search-next-thread)
218 (define-key map "r" 'notmuch-search-reply-to-thread-sender)
219 (define-key map "R" 'notmuch-search-reply-to-thread)
220 (define-key map "m" 'notmuch-mua-new-mail)
221 (define-key map "s" 'notmuch-search)
222 (define-key map "o" 'notmuch-search-toggle-order)
223 (define-key map "c" 'notmuch-search-stash-map)
224 (define-key map "=" 'notmuch-search-refresh-view)
225 (define-key map "G" 'notmuch-search-poll-and-refresh-view)
226 (define-key map "t" 'notmuch-search-filter-by-tag)
227 (define-key map "f" 'notmuch-search-filter)
228 (define-key map [mouse-1] 'notmuch-search-show-thread)
229 (define-key map "*" 'notmuch-search-tag-all)
230 (define-key map "a" 'notmuch-search-archive-thread)
231 (define-key map "-" 'notmuch-search-remove-tag)
232 (define-key map "+" 'notmuch-search-add-tag)
233 (define-key map (kbd "RET") 'notmuch-search-show-thread)
235 "Keymap for \"notmuch search\" buffers.")
236 (fset 'notmuch-search-mode-map notmuch-search-mode-map)
238 (defvar notmuch-search-stash-map
239 (let ((map (make-sparse-keymap)))
240 (define-key map "i" 'notmuch-search-stash-thread-id)
242 "Submap for stash commands")
243 (fset 'notmuch-search-stash-map notmuch-search-stash-map)
245 (defun notmuch-search-stash-thread-id ()
246 "Copy thread ID of current thread to kill-ring."
248 (notmuch-common-do-stash (notmuch-search-find-thread-id)))
250 (defvar notmuch-search-query-string)
251 (defvar notmuch-search-target-thread)
252 (defvar notmuch-search-target-line)
253 (defvar notmuch-search-continuation)
255 (defvar notmuch-search-disjunctive-regexp "\\<[oO][rR]\\>")
257 (defun notmuch-search-quit ()
258 "Exit the search buffer, calling any defined continuation function."
260 (let ((continuation notmuch-search-continuation))
261 (notmuch-kill-this-buffer)
263 (funcall continuation))))
265 (defun notmuch-search-scroll-up ()
266 "Move forward through search results by one window's worth."
270 ((end-of-buffer) (notmuch-search-last-thread))))
272 (defun notmuch-search-scroll-down ()
273 "Move backward through the search results by one window's worth."
275 ;; I don't know why scroll-down doesn't signal beginning-of-buffer
276 ;; the way that scroll-up signals end-of-buffer, but c'est la vie.
278 ;; So instead of trapping a signal we instead check whether the
279 ;; window begins on the first line of the buffer and if so, move
280 ;; directly to that position. (We have to count lines since the
281 ;; window-start position is not the same as point-min due to the
282 ;; invisible thread-ID characters on the first line.
283 (if (equal (count-lines (point-min) (window-start)) 0)
284 (goto-char (point-min))
287 (defun notmuch-search-next-thread ()
288 "Select the next thread in the search results."
292 (defun notmuch-search-previous-thread ()
293 "Select the previous thread in the search results."
297 (defun notmuch-search-last-thread ()
298 "Select the last thread in the search results."
300 (goto-char (point-max))
303 (defun notmuch-search-first-thread ()
304 "Select the first thread in the search results."
306 (goto-char (point-min)))
308 (defface notmuch-message-summary-face
309 '((((class color) (background light)) (:background "#f0f0f0"))
310 (((class color) (background dark)) (:background "#303030")))
311 "Face for the single-line message summary in notmuch-show-mode."
313 :group 'notmuch-faces)
315 (defface notmuch-search-date
316 '((t :inherit default))
317 "Face used in search mode for dates."
318 :group 'notmuch-search
319 :group 'notmuch-faces)
321 (defface notmuch-search-count
322 '((t :inherit default))
323 "Face used in search mode for the count matching the query."
324 :group 'notmuch-search
325 :group 'notmuch-faces)
327 (defface notmuch-search-subject
328 '((t :inherit default))
329 "Face used in search mode for subjects."
330 :group 'notmuch-search
331 :group 'notmuch-faces)
333 (defface notmuch-search-matching-authors
334 '((t :inherit default))
335 "Face used in search mode for authors matching the query."
336 :group 'notmuch-search
337 :group 'notmuch-faces)
339 (defface notmuch-search-non-matching-authors
342 (:foreground "grey30"))
345 (:foreground "grey60"))
348 "Face used in search mode for authors not matching the query."
349 :group 'notmuch-search
350 :group 'notmuch-faces)
352 (defface notmuch-tag-face
355 (:foreground "OliveDrab1"))
358 (:foreground "navy blue" :bold t))
361 "Face used in search mode face for tags."
362 :group 'notmuch-search
363 :group 'notmuch-faces)
365 (defun notmuch-search-mode ()
366 "Major mode displaying results of a notmuch search.
368 This buffer contains the results of a \"notmuch search\" of your
369 email archives. Each line in the buffer represents a single
370 thread giving a summary of the thread (a relative date, the
371 number of matched messages and total messages in the thread,
372 participants in the thread, a representative subject line, and
375 Pressing \\[notmuch-search-show-thread] on any line displays that thread. The '\\[notmuch-search-add-tag]' and '\\[notmuch-search-remove-tag]'
376 keys can be used to add or remove tags from a thread. The '\\[notmuch-search-archive-thread]' key
377 is a convenience for archiving a thread (removing the \"inbox\"
378 tag). The '\\[notmuch-search-tag-all]' key can be used to add or remove a tag from all
379 threads in the current buffer.
381 Other useful commands are '\\[notmuch-search-filter]' for filtering the current search
382 based on an additional query string, '\\[notmuch-search-filter-by-tag]' for filtering to include
383 only messages with a given tag, and '\\[notmuch-search]' to execute a new, global
386 Complete list of currently available key bindings:
388 \\{notmuch-search-mode-map}"
390 (kill-all-local-variables)
391 (make-local-variable 'notmuch-search-query-string)
392 (make-local-variable 'notmuch-search-oldest-first)
393 (make-local-variable 'notmuch-search-target-thread)
394 (make-local-variable 'notmuch-search-target-line)
395 (set (make-local-variable 'notmuch-search-continuation) nil)
396 (set (make-local-variable 'scroll-preserve-screen-position) t)
397 (add-to-invisibility-spec (cons 'ellipsis t))
398 (use-local-map notmuch-search-mode-map)
399 (setq truncate-lines t)
400 (setq major-mode 'notmuch-search-mode
401 mode-name "notmuch-search")
402 (setq buffer-read-only t))
404 (defun notmuch-search-get-result (&optional pos)
405 "Return the result object for the thread at POS (or point).
407 If there is no thread at POS (or point), returns nil."
408 (get-text-property (or pos (point)) 'notmuch-search-result))
410 (defun notmuch-search-result-beginning (&optional pos)
411 "Return the point at the beginning of the thread at POS (or point).
413 If there is no thread at POS (or point), returns nil."
414 (when (notmuch-search-get-result pos)
415 ;; We pass 1+point because previous-single-property-change starts
416 ;; searching one before the position we give it.
417 (previous-single-property-change (1+ (or pos (point)))
418 'notmuch-search-result nil (point-min))))
420 (defun notmuch-search-result-end (&optional pos)
421 "Return the point at the end of the thread at POS (or point).
423 The returned point will be just after the newline character that
424 ends the result line. If there is no thread at POS (or point),
426 (when (notmuch-search-get-result pos)
427 (next-single-property-change (or pos (point)) 'notmuch-search-result
430 (defun notmuch-search-properties-in-region (property beg end)
433 (last-line (line-number-at-pos end))
434 (max-line (- (line-number-at-pos (point-max)) 2)))
437 (while (<= (line-number-at-pos) (min last-line max-line))
438 (setq output (cons (get-text-property (point) property) output))
442 (defun notmuch-search-find-thread-id ()
443 "Return the thread for the current thread"
444 (get-text-property (point) 'notmuch-search-thread-id))
446 (defun notmuch-search-find-thread-id-region (beg end)
447 "Return a list of threads for the current region"
448 (notmuch-search-properties-in-region 'notmuch-search-thread-id beg end))
450 (defun notmuch-search-find-thread-id-region-search (beg end)
451 "Return a search string for threads for the current region"
452 (mapconcat 'identity (notmuch-search-find-thread-id-region beg end) " or "))
454 (defun notmuch-search-find-authors ()
455 "Return the authors for the current thread"
456 (get-text-property (point) 'notmuch-search-authors))
458 (defun notmuch-search-find-authors-region (beg end)
459 "Return a list of authors for the current region"
460 (notmuch-search-properties-in-region 'notmuch-search-authors beg end))
462 (defun notmuch-search-find-subject ()
463 "Return the subject for the current thread"
464 (get-text-property (point) 'notmuch-search-subject))
466 (defun notmuch-search-find-subject-region (beg end)
467 "Return a list of authors for the current region"
468 (notmuch-search-properties-in-region 'notmuch-search-subject beg end))
470 (defun notmuch-search-show-thread ()
471 "Display the currently selected thread."
473 (let ((thread-id (notmuch-search-find-thread-id))
474 (subject (notmuch-search-find-subject)))
475 (if (> (length thread-id) 0)
476 (notmuch-show thread-id
478 notmuch-search-query-string
479 ;; Name the buffer based on the subject.
480 (concat "*" (truncate-string-to-width subject 30 nil nil t) "*"))
481 (message "End of search results."))))
483 (defun notmuch-search-reply-to-thread (&optional prompt-for-sender)
484 "Begin composing a reply-all to the entire current thread in a new buffer."
486 (let ((message-id (notmuch-search-find-thread-id)))
487 (notmuch-mua-new-reply message-id prompt-for-sender t)))
489 (defun notmuch-search-reply-to-thread-sender (&optional prompt-for-sender)
490 "Begin composing a reply to the entire current thread in a new buffer."
492 (let ((message-id (notmuch-search-find-thread-id)))
493 (notmuch-mua-new-reply message-id prompt-for-sender nil)))
495 (defun notmuch-call-notmuch-process (&rest args)
496 "Synchronously invoke \"notmuch\" with the given list of arguments.
498 Output from the process will be presented to the user as an error
499 and will also appear in a buffer named \"*Notmuch errors*\"."
500 (let ((error-buffer (get-buffer-create "*Notmuch errors*")))
501 (with-current-buffer error-buffer
503 (if (eq (apply 'call-process notmuch-command nil error-buffer nil args) 0)
506 (with-current-buffer error-buffer
507 (let ((beg (point-min))
508 (end (- (point-max) 1)))
509 (error (buffer-substring beg end))
512 (defun notmuch-search-set-tags (tags &optional pos)
513 (let ((new-result (plist-put (notmuch-search-get-result pos) :tags tags)))
514 (notmuch-search-update-result new-result pos)))
516 (defun notmuch-search-get-tags (&optional pos)
517 (plist-get (notmuch-search-get-result pos) :tags))
519 (defun notmuch-search-get-tags-region (beg end)
522 (last-line (line-number-at-pos end))
523 (max-line (- (line-number-at-pos (point-max)) 2)))
525 (while (<= (line-number-at-pos) (min last-line max-line))
526 (setq output (append output (notmuch-search-get-tags)))
530 (defun notmuch-search-tag-region (beg end &optional tag-changes)
531 "Change tags for threads in the given region."
532 (let ((search-string (notmuch-search-find-thread-id-region-search beg end)))
533 (setq tag-changes (funcall 'notmuch-tag search-string tag-changes))
535 (let ((last-line (line-number-at-pos end))
536 (max-line (- (line-number-at-pos (point-max)) 2)))
538 (while (<= (line-number-at-pos) (min last-line max-line))
539 (notmuch-search-set-tags
540 (notmuch-update-tags (notmuch-search-get-tags) tag-changes))
543 (defun notmuch-search-tag (&optional tag-changes)
544 "Change tags for the currently selected thread or region.
546 See `notmuch-tag' for information on the format of TAG-CHANGES."
548 (let* ((beg (if (region-active-p) (region-beginning) (point)))
549 (end (if (region-active-p) (region-end) (point))))
550 (funcall 'notmuch-search-tag-region beg end tag-changes)))
552 (defun notmuch-search-add-tag ()
553 "Same as `notmuch-search-tag' but sets initial input to '+'."
555 (notmuch-search-tag "+"))
557 (defun notmuch-search-remove-tag ()
558 "Same as `notmuch-search-tag' but sets initial input to '-'."
560 (notmuch-search-tag "-"))
562 (defun notmuch-search-archive-thread ()
563 "Archive the currently selected thread (remove its \"inbox\" tag).
565 This function advances the next thread when finished."
567 (notmuch-search-tag '("-inbox"))
568 (notmuch-search-next-thread))
570 (defun notmuch-search-update-result (result &optional pos)
571 "Replace the result object of the thread at POS (or point) by
572 RESULT and redraw it.
574 This will keep point in a reasonable location. However, if there
575 are enclosing save-excursions and the saved point is in the
576 result being updated, the point will be restored to the beginning
578 (let ((start (notmuch-search-result-beginning pos))
579 (end (notmuch-search-result-end pos))
581 (inhibit-read-only t))
582 ;; Delete the current thread
583 (delete-region start end)
584 ;; Insert the updated thread
585 (notmuch-search-show-result result start)
586 ;; If point was inside the old result, make an educated guess
587 ;; about where to place it now. Unfortunately, this won't work
588 ;; with save-excursion (or any other markers that would be nice to
589 ;; preserve, such as the window start), but there's nothing we can
590 ;; do about that without a way to retrieve markers in a region.
591 (when (and (>= init-point start) (<= init-point end))
592 (let* ((new-end (notmuch-search-result-end start))
593 (new-point (if (= init-point end)
595 (min init-point (- new-end 1)))))
596 (goto-char new-point)))))
598 (defun notmuch-search-process-sentinel (proc msg)
599 "Add a message to let user know when \"notmuch search\" exits"
600 (let ((buffer (process-buffer proc))
601 (status (process-status proc))
602 (exit-status (process-exit-status proc))
603 (never-found-target-thread nil))
604 (when (memq status '(exit signal))
605 (kill-buffer (process-get proc 'parse-buf))
606 (if (buffer-live-p buffer)
607 (with-current-buffer buffer
609 (let ((inhibit-read-only t)
611 (goto-char (point-max))
612 (if (eq status 'signal)
613 (insert "Incomplete search results (search process was killed).\n"))
614 (when (eq status 'exit)
615 (insert "End of search results.")
616 (unless (= exit-status 0)
617 (insert (format " (process returned %d)" exit-status)))
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))))))))
627 (defcustom notmuch-search-line-faces '(("unread" :weight bold)
628 ("flagged" :foreground "blue"))
629 "Tag/face mapping for line highlighting in notmuch-search.
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):
634 (setq notmuch-search-line-faces '((\"deleted\" . (:foreground \"red\"
635 :background \"blue\"))
636 (\"unread\" . (:foreground \"green\"))))
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)
646 (defun notmuch-search-color-line (start end line-tag-list)
647 "Colorize lines in `notmuch-show' based on tags."
649 (let ((tag (car elem))
650 (attributes (cdr elem)))
651 (when (member tag line-tag-list)
652 (notmuch-combine-face-text-property start end attributes))))
653 ;; Reverse the list so earlier entries take precedence
654 (reverse notmuch-search-line-faces)))
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)))
667 (defun notmuch-search-insert-authors (format-string authors)
668 ;; Save the match data to avoid interfering with
669 ;; `notmuch-search-process-filter'.
671 (let* ((formatted-authors (format format-string authors))
672 (formatted-sample (format format-string ""))
673 (visible-string formatted-authors)
674 (invisible-string "")
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)
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)
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)
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)))
720 ;; If there is any invisible text, add it as a tooltip to the
722 (when (not (string= invisible-string ""))
723 (setq visible-string (propertize visible-string 'help-echo (concat "..." invisible-string))))
725 ;; Insert the visible and, if present, invisible author strings.
726 (insert visible-string)
727 (when (not (string= invisible-string ""))
728 (let ((start (point))
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)))
736 (defun notmuch-search-insert-field (field format-string result)
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 (plist-get result :subject))
748 'face 'notmuch-search-subject)))
750 ((string-equal field "authors")
751 (notmuch-search-insert-authors format-string (plist-get result :authors)))
753 ((string-equal field "tags")
754 ;; Ignore format-string here because notmuch-search-set-tags
755 ;; depends on the format of this
756 (insert (concat "(" (propertize
757 (mapconcat 'identity (plist-get result :tags) " ")
758 'font-lock-face 'notmuch-tag-face) ")")))))
760 (defun notmuch-search-show-result (result &optional pos)
761 "Insert RESULT at POS or the end of the buffer if POS is null."
762 ;; Ignore excluded matches
763 (unless (= (plist-get result :matched) 0)
764 (let ((beg (or pos (point-max))))
767 (dolist (spec notmuch-search-result-format)
768 (notmuch-search-insert-field (car spec) (cdr spec) result))
770 (notmuch-search-color-line beg (point) (plist-get result :tags))
771 (put-text-property beg (point) 'notmuch-search-result result)
772 (put-text-property beg (point) 'notmuch-search-thread-id
773 (concat "thread:" (plist-get result :thread)))
774 (put-text-property beg (point) 'notmuch-search-authors
775 (plist-get result :authors))
776 (put-text-property beg (point) 'notmuch-search-subject
777 (plist-get result :subject)))
778 (when (string= (plist-get result :thread) notmuch-search-target-thread)
779 (setq notmuch-search-target-thread "found")
782 (defun notmuch-search-show-error (string &rest objects)
784 (goto-char (point-max))
785 (insert "Error: Unexpected output from notmuch search:\n")
786 (insert (apply #'format string objects))
789 (defvar notmuch-search-process-state nil
790 "Parsing state of the search process filter.")
792 (defvar notmuch-search-json-parser nil
793 "Incremental JSON parser for the search process filter.")
795 (defun notmuch-search-process-filter (proc string)
796 "Process and filter the output of \"notmuch search\""
797 (let ((results-buf (process-buffer proc))
798 (parse-buf (process-get proc 'parse-buf))
799 (inhibit-read-only t)
801 (if (not (buffer-live-p results-buf))
802 (delete-process proc)
803 (with-current-buffer parse-buf
806 (goto-char (point-max))
808 (with-current-buffer results-buf
811 (case notmuch-search-process-state
813 ;; Enter the results list
814 (if (eq (notmuch-json-begin-compound
815 notmuch-search-json-parser) 'retry)
817 (setq notmuch-search-process-state 'result)))
820 (let ((result (notmuch-json-read notmuch-search-json-parser)))
822 ((retry) (setq done t))
823 ((end) (setq notmuch-search-process-state 'end))
824 (otherwise (notmuch-search-show-result result)))))
826 ;; Any trailing data is unexpected
827 (notmuch-json-eof notmuch-search-json-parser)
830 ;; Do our best to resynchronize and ensure forward
832 (notmuch-search-show-error
834 (with-current-buffer parse-buf
835 (let ((bad (buffer-substring (line-beginning-position)
836 (line-end-position))))
839 ;; Clear out what we've parsed
840 (with-current-buffer parse-buf
841 (delete-region (point-min) (point)))))))
843 (defun notmuch-search-tag-all (&optional tag-changes)
844 "Add/remove tags from all messages in current search buffer.
846 See `notmuch-tag' for information on the format of TAG-CHANGES."
848 (apply 'notmuch-tag notmuch-search-query-string tag-changes))
850 (defun notmuch-search-buffer-title (query)
851 "Returns the title for a buffer with notmuch search results."
855 (loop for tuple in notmuch-saved-searches
856 if (let ((quoted-query (regexp-quote (cdr tuple))))
857 (and (string-match (concat "^" quoted-query) query)
858 (> (length (match-string 0 query))
860 do (setq longest tuple))
862 (saved-search-name (car saved-search))
863 (saved-search-query (cdr saved-search)))
864 (cond ((and saved-search (equal saved-search-query query))
865 ;; Query is the same as saved search (ignoring case)
866 (concat "*notmuch-saved-search-" saved-search-name "*"))
868 (concat "*notmuch-search-"
869 (replace-regexp-in-string (concat "^" (regexp-quote saved-search-query))
870 (concat "[ " saved-search-name " ]")
874 (concat "*notmuch-search-" query "*"))
877 (defun notmuch-read-query (prompt)
878 "Read a notmuch-query from the minibuffer with completion.
880 PROMPT is the string to prompt with."
883 (append (list "folder:" "thread:" "id:" "date:" "from:" "to:"
884 "subject:" "attachment:")
885 (mapcar (lambda (tag)
887 (process-lines notmuch-command "search" "--output=tags" "*")))))
888 (let ((keymap (copy-keymap minibuffer-local-map))
889 (minibuffer-completion-table
890 (completion-table-dynamic
892 ;; generate a list of possible completions for the current input
894 ;; this ugly regexp is used to get the last word of the input
895 ;; possibly preceded by a '('
896 ((string-match "\\(^\\|.* (?\\)\\([^ ]*\\)$" string)
897 (mapcar (lambda (compl)
898 (concat (match-string-no-properties 1 string) compl))
899 (all-completions (match-string-no-properties 2 string)
901 (t (list string)))))))
902 ;; this was simpler than convincing completing-read to accept spaces:
903 (define-key keymap (kbd "TAB") 'minibuffer-complete)
904 (let ((history-delete-duplicates t))
905 (read-from-minibuffer prompt nil keymap nil
906 'notmuch-search-history nil nil)))))
909 (defun notmuch-search (&optional query oldest-first target-thread target-line continuation)
910 "Run \"notmuch search\" with the given `query' and display results.
912 If `query' is nil, it is read interactively from the minibuffer.
913 Other optional parameters are used as follows:
915 oldest-first: A Boolean controlling the sort order of returned threads
916 target-thread: A thread ID (with the thread: prefix) that will be made
917 current if it appears in the search results.
918 target-line: The line number to move to if the target thread does not
919 appear in the search results."
922 (setq query (notmuch-read-query "Notmuch search: ")))
923 (let ((buffer (get-buffer-create (notmuch-search-buffer-title query))))
924 (switch-to-buffer buffer)
925 (notmuch-search-mode)
926 ;; Don't track undo information for this buffer
927 (set 'buffer-undo-list t)
928 (set 'notmuch-search-query-string query)
929 (set 'notmuch-search-oldest-first oldest-first)
930 (set 'notmuch-search-target-thread target-thread)
931 (set 'notmuch-search-target-line target-line)
932 (set 'notmuch-search-continuation continuation)
933 (let ((proc (get-buffer-process (current-buffer)))
934 (inhibit-read-only t))
936 (error "notmuch search process already running for query `%s'" query)
939 (goto-char (point-min))
941 (let ((proc (start-process
942 "notmuch-search" buffer
943 notmuch-command "search"
946 "--sort=oldest-first"
947 "--sort=newest-first")
949 ;; Use a scratch buffer to accumulate partial output.
950 ;; This buffer will be killed by the sentinel, which
951 ;; should be called no matter how the process dies.
952 (parse-buf (generate-new-buffer " *notmuch search parse*")))
953 (set (make-local-variable 'notmuch-search-process-state) 'begin)
954 (set (make-local-variable 'notmuch-search-json-parser)
955 (notmuch-json-create-parser parse-buf))
956 (process-put proc 'parse-buf parse-buf)
957 (set-process-sentinel proc 'notmuch-search-process-sentinel)
958 (set-process-filter proc 'notmuch-search-process-filter)
959 (set-process-query-on-exit-flag proc nil))))
960 (run-hooks 'notmuch-search-hook)))
962 (defun notmuch-search-refresh-view ()
963 "Refresh the current view.
965 Kills the current buffer and runs a new search with the same
966 query string as the current search. If the current thread is in
967 the new search results, then point will be placed on the same
968 thread. Otherwise, point will be moved to attempt to be in the
969 same relative position within the new buffer."
971 (let ((target-line (line-number-at-pos))
972 (oldest-first notmuch-search-oldest-first)
973 (target-thread (notmuch-search-find-thread-id))
974 (query notmuch-search-query-string)
975 (continuation notmuch-search-continuation))
976 (notmuch-kill-this-buffer)
977 (notmuch-search query oldest-first target-thread target-line continuation)
978 (goto-char (point-min))))
980 (defcustom notmuch-poll-script nil
981 "An external script to incorporate new mail into the notmuch database.
983 This variable controls the action invoked by
984 `notmuch-search-poll-and-refresh-view' and
985 `notmuch-hello-poll-and-update' (each have a default keybinding
986 of 'G') to incorporate new mail into the notmuch database.
988 If set to nil (the default), new mail is processed by invoking
989 \"notmuch new\". Otherwise, this should be set to a string that
990 gives the name of an external script that processes new mail. If
991 set to the empty string, no command will be run.
993 The external script could do any of the following depending on
996 1. Invoke a program to transfer mail to the local mail store
997 2. Invoke \"notmuch new\" to incorporate the new mail
998 3. Invoke one or more \"notmuch tag\" commands to classify the mail
1000 Note that the recommended way of achieving the same is using
1001 \"notmuch new\" hooks."
1002 :type '(choice (const :tag "notmuch new" nil)
1003 (const :tag "Disabled" "")
1004 (string :tag "Custom script"))
1005 :group 'notmuch-external)
1007 (defun notmuch-poll ()
1008 "Run \"notmuch new\" or an external script to import mail.
1010 Invokes `notmuch-poll-script', \"notmuch new\", or does nothing
1011 depending on the value of `notmuch-poll-script'."
1013 (if (stringp notmuch-poll-script)
1014 (unless (string= notmuch-poll-script "")
1015 (call-process notmuch-poll-script nil nil))
1016 (call-process notmuch-command nil nil nil "new")))
1018 (defun notmuch-search-poll-and-refresh-view ()
1019 "Invoke `notmuch-poll' to import mail, then refresh the current view."
1022 (notmuch-search-refresh-view))
1024 (defun notmuch-search-toggle-order ()
1025 "Toggle the current search order.
1027 By default, the \"inbox\" view created by `notmuch' is displayed
1028 in chronological order (oldest thread at the beginning of the
1029 buffer), while any global searches created by `notmuch-search'
1030 are displayed in reverse-chronological order (newest thread at
1031 the beginning of the buffer).
1033 This command toggles the sort order for the current search.
1035 Note that any filtered searches created by
1036 `notmuch-search-filter' retain the search order of the parent
1039 (set 'notmuch-search-oldest-first (not notmuch-search-oldest-first))
1040 (notmuch-search-refresh-view))
1042 (defun notmuch-search-filter (query)
1043 "Filter the current search results based on an additional query string.
1045 Runs a new search matching only messages that match both the
1046 current search results AND the additional query string provided."
1047 (interactive (list (notmuch-read-query "Filter search: ")))
1048 (let ((grouped-query (if (string-match-p notmuch-search-disjunctive-regexp query)
1049 (concat "( " query " )")
1051 (notmuch-search (if (string= notmuch-search-query-string "*")
1053 (concat notmuch-search-query-string " and " grouped-query)) notmuch-search-oldest-first)))
1055 (defun notmuch-search-filter-by-tag (tag)
1056 "Filter the current search results based on a single tag.
1058 Runs a new search matching only messages that match both the
1059 current search results AND that are tagged with the given tag."
1061 (list (notmuch-select-tag-with-completion "Filter by tag: ")))
1062 (notmuch-search (concat notmuch-search-query-string " and tag:" tag) notmuch-search-oldest-first))
1066 "Run notmuch and display saved searches, known tags, etc."
1070 (defun notmuch-interesting-buffer (b)
1071 "Is the current buffer of interest to a notmuch user?"
1072 (with-current-buffer b
1073 (memq major-mode '(notmuch-show-mode
1079 (defun notmuch-cycle-notmuch-buffers ()
1080 "Cycle through any existing notmuch buffers (search, show or hello).
1082 If the current buffer is the only notmuch buffer, bury it. If no
1083 notmuch buffers exist, run `notmuch'."
1087 ;; If the current buffer is a notmuch buffer, remember it and then
1089 (when (notmuch-interesting-buffer (current-buffer))
1090 (setq start (current-buffer))
1093 ;; Find the first notmuch buffer.
1094 (setq first (loop for buffer in (buffer-list)
1095 if (notmuch-interesting-buffer buffer)
1099 ;; If the first one we found is any other than the starting
1100 ;; buffer, switch to it.
1101 (unless (eq first start)
1102 (switch-to-buffer first))
1105 (setq mail-user-agent 'notmuch-user-agent)