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))
55 (require 'notmuch-lib)
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-tag-completions (&optional search-terms)
81 (with-output-to-string
82 (with-current-buffer standard-output
83 (apply 'call-process notmuch-command nil t
84 nil "search-tags" search-terms)))
87 (defun notmuch-select-tag-with-completion (prompt &rest search-terms)
88 (let ((tag-list (notmuch-tag-completions search-terms)))
89 (completing-read prompt tag-list)))
91 (defun notmuch-read-tag-changes (&optional initial-input &rest search-terms)
92 (let* ((all-tag-list (notmuch-tag-completions))
93 (add-tag-list (mapcar (apply-partially 'concat "+") all-tag-list))
94 (remove-tag-list (mapcar (apply-partially 'concat "-")
95 (if (null search-terms)
97 (notmuch-tag-completions search-terms))))
98 (tag-list (append add-tag-list remove-tag-list))
100 ;; By default, space is bound to "complete word" function.
101 ;; Re-bind it to insert a space instead. Note that <tab>
102 ;; still does the completion.
103 (crm-local-completion-map
104 (let ((map (make-sparse-keymap)))
105 (set-keymap-parent map crm-local-completion-map)
106 (define-key map " " 'self-insert-command)
108 (delete "" (completing-read-multiple "Tags (+add -drop): "
109 tag-list nil nil initial-input))))
111 (defun notmuch-update-tags (tags tag-changes)
112 "Return a copy of TAGS with additions and removals from TAG-CHANGES.
114 TAG-CHANGES must be a list of tags names, each prefixed with
115 either a \"+\" to indicate the tag should be added to TAGS if not
116 present or a \"-\" to indicate that the tag should be removed
117 from TAGS if present."
118 (let ((result-tags (copy-sequence tags)))
119 (dolist (tag-change tag-changes)
120 (let ((op (string-to-char tag-change))
121 (tag (unless (string= tag-change "") (substring tag-change 1))))
123 (?+ (unless (member tag result-tags)
124 (push tag result-tags)))
125 (?- (setq result-tags (delete tag result-tags)))
127 (error "Changed tag must be of the form `+this_tag' or `-that_tag'")))))
128 (sort result-tags 'string<)))
130 (defun notmuch-foreach-mime-part (function mm-handle)
131 (cond ((stringp (car mm-handle))
132 (dolist (part (cdr mm-handle))
133 (notmuch-foreach-mime-part function part)))
134 ((bufferp (car mm-handle))
135 (funcall function mm-handle))
136 (t (dolist (part mm-handle)
137 (notmuch-foreach-mime-part function part)))))
139 (defun notmuch-count-attachments (mm-handle)
141 (notmuch-foreach-mime-part
143 (let ((disposition (mm-handle-disposition p)))
144 (and (listp disposition)
145 (or (equal (car disposition) "attachment")
146 (and (equal (car disposition) "inline")
147 (assq 'filename disposition)))
152 (defun notmuch-save-attachments (mm-handle &optional queryp)
153 (notmuch-foreach-mime-part
155 (let ((disposition (mm-handle-disposition p)))
156 (and (listp disposition)
157 (or (equal (car disposition) "attachment")
158 (and (equal (car disposition) "inline")
159 (assq 'filename disposition)))
162 (concat "Save '" (cdr (assq 'filename disposition)) "' ")))
166 (defun notmuch-documentation-first-line (symbol)
167 "Return the first line of the documentation string for SYMBOL."
168 (let ((doc (documentation symbol)))
171 (insert (documentation symbol t))
172 (goto-char (point-min))
175 (buffer-substring beg (point))))
178 (defun notmuch-prefix-key-description (key)
179 "Given a prefix key code, return a human-readable string representation.
181 This is basically just `format-kbd-macro' but we also convert ESC to M-."
182 (let ((desc (format-kbd-macro (vector key))))
183 (if (string= desc "ESC")
187 ;; I would think that emacs would have code handy for walking a keymap
188 ;; and generating strings for each key, and I would prefer to just call
189 ;; that. But I couldn't find any (could be all implemented in C I
190 ;; suppose), so I wrote my own here.
191 (defun notmuch-substitute-one-command-key-with-prefix (prefix binding)
192 "For a key binding, return a string showing a human-readable
193 representation of the prefixed key as well as the first line of
194 documentation from the bound function.
196 For a mouse binding, return nil."
197 (let ((key (car binding))
198 (action (cdr binding)))
199 (if (mouse-event-p key)
202 (let ((substitute (apply-partially 'notmuch-substitute-one-command-key-with-prefix (notmuch-prefix-key-description key)))
204 (map-keymap (lambda (a b)
205 (push (cons a b) as-list))
207 (mapconcat substitute as-list "\n"))
208 (concat prefix (format-kbd-macro (vector key))
210 (notmuch-documentation-first-line action))))))
212 (defun notmuch-substitute-command-keys-one (key)
213 ;; A `keymap' key indicates inheritance from a parent keymap - the
214 ;; inherited mappings follow, so there is nothing to print for
216 (when (not (eq key 'keymap))
217 (notmuch-substitute-one-command-key-with-prefix nil key)))
219 (defun notmuch-substitute-command-keys (doc)
220 "Like `substitute-command-keys' but with documentation, not function names."
222 (while (string-match "\\\\{\\([^}[:space:]]*\\)}" doc beg)
223 (let* ((keymap-name (substring doc (match-beginning 1) (match-end 1)))
224 (keymap (symbol-value (intern keymap-name))))
225 (setq doc (replace-match
226 (mapconcat #'notmuch-substitute-command-keys-one
229 (setq beg (match-end 0)))
232 (defun notmuch-help ()
233 "Display help for the current notmuch mode."
235 (let* ((mode major-mode)
236 (doc (substitute-command-keys (notmuch-substitute-command-keys (documentation mode t)))))
237 (with-current-buffer (generate-new-buffer "*notmuch-help*")
239 (goto-char (point-min))
240 (set-buffer-modified-p nil)
241 (view-buffer (current-buffer) 'kill-buffer-if-not-modified))))
243 (defcustom notmuch-search-hook '(hl-line-mode)
244 "List of functions to call when notmuch displays the search results."
246 :options '(hl-line-mode)
247 :group 'notmuch-search
248 :group 'notmuch-hooks)
250 (defvar notmuch-search-mode-map
251 (let ((map (make-sparse-keymap)))
252 (define-key map "?" 'notmuch-help)
253 (define-key map "q" 'notmuch-search-quit)
254 (define-key map "x" 'notmuch-search-quit)
255 (define-key map (kbd "<DEL>") 'notmuch-search-scroll-down)
256 (define-key map "b" 'notmuch-search-scroll-down)
257 (define-key map " " 'notmuch-search-scroll-up)
258 (define-key map "<" 'notmuch-search-first-thread)
259 (define-key map ">" 'notmuch-search-last-thread)
260 (define-key map "p" 'notmuch-search-previous-thread)
261 (define-key map "n" 'notmuch-search-next-thread)
262 (define-key map "r" 'notmuch-search-reply-to-thread-sender)
263 (define-key map "R" 'notmuch-search-reply-to-thread)
264 (define-key map "m" 'notmuch-mua-new-mail)
265 (define-key map "s" 'notmuch-search)
266 (define-key map "o" 'notmuch-search-toggle-order)
267 (define-key map "c" 'notmuch-search-stash-map)
268 (define-key map "=" 'notmuch-search-refresh-view)
269 (define-key map "G" 'notmuch-search-poll-and-refresh-view)
270 (define-key map "t" 'notmuch-search-filter-by-tag)
271 (define-key map "f" 'notmuch-search-filter)
272 (define-key map [mouse-1] 'notmuch-search-show-thread)
273 (define-key map "*" 'notmuch-search-operate-all)
274 (define-key map "a" 'notmuch-search-archive-thread)
275 (define-key map "-" 'notmuch-search-remove-tag)
276 (define-key map "+" 'notmuch-search-add-tag)
277 (define-key map (kbd "RET") 'notmuch-search-show-thread)
279 "Keymap for \"notmuch search\" buffers.")
280 (fset 'notmuch-search-mode-map notmuch-search-mode-map)
282 (defvar notmuch-search-stash-map
283 (let ((map (make-sparse-keymap)))
284 (define-key map "i" 'notmuch-search-stash-thread-id)
286 "Submap for stash commands")
287 (fset 'notmuch-search-stash-map notmuch-search-stash-map)
289 (defun notmuch-search-stash-thread-id ()
290 "Copy thread ID of current thread to kill-ring."
292 (notmuch-common-do-stash (notmuch-search-find-thread-id)))
294 (defvar notmuch-search-query-string)
295 (defvar notmuch-search-target-thread)
296 (defvar notmuch-search-target-line)
297 (defvar notmuch-search-continuation)
299 (defvar notmuch-search-disjunctive-regexp "\\<[oO][rR]\\>")
301 (defun notmuch-search-quit ()
302 "Exit the search buffer, calling any defined continuation function."
304 (let ((continuation notmuch-search-continuation))
305 (notmuch-kill-this-buffer)
307 (funcall continuation))))
309 (defun notmuch-search-scroll-up ()
310 "Move forward through search results by one window's worth."
314 ((end-of-buffer) (notmuch-search-last-thread))))
316 (defun notmuch-search-scroll-down ()
317 "Move backward through the search results by one window's worth."
319 ;; I don't know why scroll-down doesn't signal beginning-of-buffer
320 ;; the way that scroll-up signals end-of-buffer, but c'est la vie.
322 ;; So instead of trapping a signal we instead check whether the
323 ;; window begins on the first line of the buffer and if so, move
324 ;; directly to that position. (We have to count lines since the
325 ;; window-start position is not the same as point-min due to the
326 ;; invisible thread-ID characters on the first line.
327 (if (equal (count-lines (point-min) (window-start)) 0)
328 (goto-char (point-min))
331 (defun notmuch-search-next-thread ()
332 "Select the next thread in the search results."
336 (defun notmuch-search-previous-thread ()
337 "Select the previous thread in the search results."
341 (defun notmuch-search-last-thread ()
342 "Select the last thread in the search results."
344 (goto-char (point-max))
347 (defun notmuch-search-first-thread ()
348 "Select the first thread in the search results."
350 (goto-char (point-min)))
352 (defface notmuch-message-summary-face
353 '((((class color) (background light)) (:background "#f0f0f0"))
354 (((class color) (background dark)) (:background "#303030")))
355 "Face for the single-line message summary in notmuch-show-mode."
357 :group 'notmuch-faces)
359 (defface notmuch-search-date
360 '((t :inherit default))
361 "Face used in search mode for dates."
362 :group 'notmuch-search
363 :group 'notmuch-faces)
365 (defface notmuch-search-count
366 '((t :inherit default))
367 "Face used in search mode for the count matching the query."
368 :group 'notmuch-search
369 :group 'notmuch-faces)
371 (defface notmuch-search-subject
372 '((t :inherit default))
373 "Face used in search mode for subjects."
374 :group 'notmuch-search
375 :group 'notmuch-faces)
377 (defface notmuch-search-matching-authors
378 '((t :inherit default))
379 "Face used in search mode for authors matching the query."
380 :group 'notmuch-search
381 :group 'notmuch-faces)
383 (defface notmuch-search-non-matching-authors
386 (:foreground "grey30"))
389 (:foreground "grey60"))
392 "Face used in search mode for authors not matching the query."
393 :group 'notmuch-search
394 :group 'notmuch-faces)
396 (defface notmuch-tag-face
399 (:foreground "OliveDrab1"))
402 (:foreground "navy blue" :bold t))
405 "Face used in search mode face for tags."
406 :group 'notmuch-search
407 :group 'notmuch-faces)
409 (defun notmuch-search-mode ()
410 "Major mode displaying results of a notmuch search.
412 This buffer contains the results of a \"notmuch search\" of your
413 email archives. Each line in the buffer represents a single
414 thread giving a summary of the thread (a relative date, the
415 number of matched messages and total messages in the thread,
416 participants in the thread, a representative subject line, and
419 Pressing \\[notmuch-search-show-thread] on any line displays that thread. The '\\[notmuch-search-add-tag]' and '\\[notmuch-search-remove-tag]'
420 keys can be used to add or remove tags from a thread. The '\\[notmuch-search-archive-thread]' key
421 is a convenience for archiving a thread (removing the \"inbox\"
422 tag). The '\\[notmuch-search-operate-all]' key can be used to add or remove a tag from all
423 threads in the current buffer.
425 Other useful commands are '\\[notmuch-search-filter]' for filtering the current search
426 based on an additional query string, '\\[notmuch-search-filter-by-tag]' for filtering to include
427 only messages with a given tag, and '\\[notmuch-search]' to execute a new, global
430 Complete list of currently available key bindings:
432 \\{notmuch-search-mode-map}"
434 (kill-all-local-variables)
435 (make-local-variable 'notmuch-search-query-string)
436 (make-local-variable 'notmuch-search-oldest-first)
437 (make-local-variable 'notmuch-search-target-thread)
438 (make-local-variable 'notmuch-search-target-line)
439 (set (make-local-variable 'notmuch-search-continuation) nil)
440 (set (make-local-variable 'scroll-preserve-screen-position) t)
441 (add-to-invisibility-spec (cons 'ellipsis t))
442 (use-local-map notmuch-search-mode-map)
443 (setq truncate-lines t)
444 (setq major-mode 'notmuch-search-mode
445 mode-name "notmuch-search")
446 (setq buffer-read-only t))
448 (defun notmuch-search-properties-in-region (property beg end)
451 (last-line (line-number-at-pos end))
452 (max-line (- (line-number-at-pos (point-max)) 2)))
455 (while (<= (line-number-at-pos) (min last-line max-line))
456 (setq output (cons (get-text-property (point) property) output))
460 (defun notmuch-search-find-thread-id ()
461 "Return the thread for the current thread"
462 (get-text-property (point) 'notmuch-search-thread-id))
464 (defun notmuch-search-find-thread-id-region (beg end)
465 "Return a list of threads for the current region"
466 (notmuch-search-properties-in-region 'notmuch-search-thread-id beg end))
468 (defun notmuch-search-find-thread-id-region-search (beg end)
469 "Return a search string for threads for the current region"
470 (mapconcat 'identity (notmuch-search-find-thread-id-region beg end) " or "))
472 (defun notmuch-search-find-authors ()
473 "Return the authors for the current thread"
474 (get-text-property (point) 'notmuch-search-authors))
476 (defun notmuch-search-find-authors-region (beg end)
477 "Return a list of authors for the current region"
478 (notmuch-search-properties-in-region 'notmuch-search-authors beg end))
480 (defun notmuch-search-find-subject ()
481 "Return the subject for the current thread"
482 (get-text-property (point) 'notmuch-search-subject))
484 (defun notmuch-search-find-subject-region (beg end)
485 "Return a list of authors for the current region"
486 (notmuch-search-properties-in-region 'notmuch-search-subject beg end))
488 (defun notmuch-search-show-thread (&optional crypto-switch)
489 "Display the currently selected thread."
491 (let ((thread-id (notmuch-search-find-thread-id))
492 (subject (notmuch-prettify-subject (notmuch-search-find-subject))))
493 (if (> (length thread-id) 0)
494 (notmuch-show thread-id
496 notmuch-search-query-string
497 ;; Name the buffer based on the subject.
498 (concat "*" (truncate-string-to-width subject 30 nil nil t) "*")
500 (message "End of search results."))))
502 (defun notmuch-search-reply-to-thread (&optional prompt-for-sender)
503 "Begin composing a reply-all to the entire current thread in a new buffer."
505 (let ((message-id (notmuch-search-find-thread-id)))
506 (notmuch-mua-new-reply message-id prompt-for-sender t)))
508 (defun notmuch-search-reply-to-thread-sender (&optional prompt-for-sender)
509 "Begin composing a reply to the entire current thread in a new buffer."
511 (let ((message-id (notmuch-search-find-thread-id)))
512 (notmuch-mua-new-reply message-id prompt-for-sender nil)))
514 (defun notmuch-call-notmuch-process (&rest args)
515 "Synchronously invoke \"notmuch\" with the given list of arguments.
517 Output from the process will be presented to the user as an error
518 and will also appear in a buffer named \"*Notmuch errors*\"."
519 (let ((error-buffer (get-buffer-create "*Notmuch errors*")))
520 (with-current-buffer error-buffer
522 (if (eq (apply 'call-process notmuch-command nil error-buffer nil args) 0)
525 (with-current-buffer error-buffer
526 (let ((beg (point-min))
527 (end (- (point-max) 1)))
528 (error (buffer-substring beg end))
531 (defun notmuch-tag (query &rest tags)
532 "Add/remove tags in TAGS to messages matching QUERY.
534 TAGS should be a list of strings of the form \"+TAG\" or \"-TAG\" and
535 QUERY should be a string containing the search-query.
537 Note: Other code should always use this function alter tags of
538 messages instead of running (notmuch-call-notmuch-process \"tag\" ..)
539 directly, so that hooks specified in notmuch-before-tag-hook and
540 notmuch-after-tag-hook will be run."
541 ;; Perform some validation
542 (when (null tags) (error "No tags given"))
544 (unless (string-match-p "^[-+][-+_.[:word:]]+$" tag)
545 (error "Tag must be of the form `+this_tag' or `-that_tag'")))
547 (run-hooks 'notmuch-before-tag-hook)
548 (apply 'notmuch-call-notmuch-process
549 (append (list "tag") tags (list "--" query)))
550 (run-hooks 'notmuch-after-tag-hook))
552 (defcustom notmuch-before-tag-hook nil
553 "Hooks that are run before tags of a message are modified.
555 'tags' will contain the tags that are about to be added or removed as
556 a list of strings of the form \"+TAG\" or \"-TAG\".
557 'query' will be a string containing the search query that determines
558 the messages that are about to be tagged"
561 :options '(hl-line-mode)
562 :group 'notmuch-hooks)
564 (defcustom notmuch-after-tag-hook nil
565 "Hooks that are run after tags of a message are modified.
567 'tags' will contain the tags that were added or removed as
568 a list of strings of the form \"+TAG\" or \"-TAG\".
569 'query' will be a string containing the search query that determines
570 the messages that were tagged"
572 :options '(hl-line-mode)
573 :group 'notmuch-hooks)
575 (defun notmuch-search-set-tags (tags)
578 (re-search-backward "(")
581 (inhibit-read-only t))
582 (re-search-forward ")")
585 (delete-region beg end)
586 (insert (propertize (mapconcat 'identity tags " ")
587 'face 'notmuch-tag-face))))))
589 (defun notmuch-search-get-tags ()
592 (re-search-backward "(")
593 (let ((beg (+ (point) 1)))
594 (re-search-forward ")")
595 (let ((end (- (point) 1)))
596 (split-string (buffer-substring-no-properties beg end))))))
598 (defun notmuch-search-get-tags-region (beg end)
601 (last-line (line-number-at-pos end))
602 (max-line (- (line-number-at-pos (point-max)) 2)))
604 (while (<= (line-number-at-pos) (min last-line max-line))
605 (setq output (append output (notmuch-search-get-tags)))
609 (defun notmuch-search-tag-thread (&rest tags)
610 "Change tags for the currently selected thread.
612 See `notmuch-search-tag-region' for details."
613 (apply 'notmuch-search-tag-region (point) (point) tags))
615 (defun notmuch-search-tag-region (beg end &rest tags)
616 "Change tags for threads in the given region.
618 TAGS is a list of tag operations for `notmuch-tag'. The tags are
619 added or removed for all threads in the region from BEG to END."
620 (let ((search-string (notmuch-search-find-thread-id-region-search beg end)))
621 (apply 'notmuch-tag search-string tags)
623 (let ((last-line (line-number-at-pos end))
624 (max-line (- (line-number-at-pos (point-max)) 2)))
626 (while (<= (line-number-at-pos) (min last-line max-line))
627 (notmuch-search-set-tags
628 (notmuch-update-tags (notmuch-search-get-tags) tags))
631 (defun notmuch-search-tag (&optional initial-input)
632 "Change tags for the currently selected thread or region."
634 (let* ((beg (if (region-active-p) (region-beginning) (point)))
635 (end (if (region-active-p) (region-end) (point)))
636 (search-string (notmuch-search-find-thread-id-region-search beg end))
637 (tags (notmuch-read-tag-changes initial-input search-string)))
638 (apply 'notmuch-search-tag-region beg end tags)))
640 (defun notmuch-search-add-tag ()
641 "Same as `notmuch-search-tag' but sets initial input to '+'."
643 (notmuch-search-tag "+"))
645 (defun notmuch-search-remove-tag ()
646 "Same as `notmuch-search-tag' but sets initial input to '-'."
648 (notmuch-search-tag "-"))
650 (defun notmuch-search-archive-thread ()
651 "Archive the currently selected thread (remove its \"inbox\" tag).
653 This function advances the next thread when finished."
655 (notmuch-search-tag-thread "-inbox")
656 (notmuch-search-next-thread))
658 (defvar notmuch-search-process-filter-data nil
659 "Data that has not yet been processed.")
660 (make-variable-buffer-local 'notmuch-search-process-filter-data)
662 (defun notmuch-search-process-sentinel (proc msg)
663 "Add a message to let user know when \"notmuch search\" exits"
664 (let ((buffer (process-buffer proc))
665 (status (process-status proc))
666 (exit-status (process-exit-status proc))
667 (never-found-target-thread nil))
668 (if (memq status '(exit signal))
669 (if (buffer-live-p buffer)
670 (with-current-buffer buffer
672 (let ((inhibit-read-only t)
674 (goto-char (point-max))
675 (if (eq status 'signal)
676 (insert "Incomplete search results (search process was killed).\n"))
677 (when (eq status 'exit)
678 (if notmuch-search-process-filter-data
679 (insert (concat "Error: Unexpected output from notmuch search:\n" notmuch-search-process-filter-data)))
680 (insert "End of search results.")
681 (unless (= exit-status 0)
682 (insert (format " (process returned %d)" exit-status)))
685 (not (string= notmuch-search-target-thread "found")))
686 (set 'never-found-target-thread t)))))
687 (when (and never-found-target-thread
688 notmuch-search-target-line)
689 (goto-char (point-min))
690 (forward-line (1- notmuch-search-target-line))))))))
692 (defcustom notmuch-search-line-faces nil
693 "Tag/face mapping for line highlighting in notmuch-search.
695 Here is an example of how to color search results based on tags.
696 (the following text would be placed in your ~/.emacs file):
698 (setq notmuch-search-line-faces '((\"delete\" . (:foreground \"red\"
699 :background \"blue\"))
700 (\"unread\" . (:foreground \"green\"))))
702 The attributes defined for matching tags are merged, with later
703 attributes overriding earlier. A message having both \"delete\"
704 and \"unread\" tags with the above settings would have a green
705 foreground and blue background."
706 :type '(alist :key-type (string) :value-type (custom-face-edit))
707 :group 'notmuch-search
708 :group 'notmuch-faces)
710 (defun notmuch-search-color-line (start end line-tag-list)
711 "Colorize lines in `notmuch-show' based on tags."
712 ;; Create the overlay only if the message has tags which match one
713 ;; of those specified in `notmuch-search-line-faces'.
716 (let ((tag (car elem))
717 (attributes (cdr elem)))
718 (when (member tag line-tag-list)
720 (setq overlay (make-overlay start end)))
721 ;; Merge the specified properties with any already
722 ;; applied from an earlier match.
723 (overlay-put overlay 'face
724 (append (overlay-get overlay 'face) attributes)))))
725 notmuch-search-line-faces)))
727 (defun notmuch-search-author-propertize (authors)
728 "Split `authors' into matching and non-matching authors and
729 propertize appropriately. If no boundary between authors and
730 non-authors is found, assume that all of the authors match."
731 (if (string-match "\\(.*\\)|\\(.*\\)" authors)
732 (concat (propertize (concat (match-string 1 authors) ",")
733 'face 'notmuch-search-matching-authors)
734 (propertize (match-string 2 authors)
735 'face 'notmuch-search-non-matching-authors))
736 (propertize authors 'face 'notmuch-search-matching-authors)))
738 (defun notmuch-search-insert-authors (format-string authors)
739 ;; Save the match data to avoid interfering with
740 ;; `notmuch-search-process-filter'.
742 (let* ((formatted-authors (format format-string authors))
743 (formatted-sample (format format-string ""))
744 (visible-string formatted-authors)
745 (invisible-string "")
748 ;; Truncate the author string to fit the specification.
749 (if (> (length formatted-authors)
750 (length formatted-sample))
751 (let ((visible-length (- (length formatted-sample)
753 ;; Truncate the visible string according to the width of
754 ;; the display string.
755 (setq visible-string (substring formatted-authors 0 visible-length)
756 invisible-string (substring formatted-authors visible-length))
757 ;; If possible, truncate the visible string at a natural
758 ;; break (comma or pipe), as incremental search doesn't
759 ;; match across the visible/invisible border.
760 (when (string-match "\\(.*\\)\\([,|] \\)\\([^,|]*\\)" visible-string)
761 ;; Second clause is destructive on `visible-string', so
762 ;; order is important.
763 (setq invisible-string (concat (match-string 3 visible-string)
765 visible-string (concat (match-string 1 visible-string)
766 (match-string 2 visible-string))))
767 ;; `visible-string' may be shorter than the space allowed
768 ;; by `format-string'. If so we must insert some padding
769 ;; after `invisible-string'.
770 (setq padding (make-string (- (length formatted-sample)
771 (length visible-string)
775 ;; Use different faces to show matching and non-matching authors.
776 (if (string-match "\\(.*\\)|\\(.*\\)" visible-string)
777 ;; The visible string contains both matching and
778 ;; non-matching authors.
779 (setq visible-string (notmuch-search-author-propertize visible-string)
780 ;; The invisible string must contain only non-matching
781 ;; authors, as the visible-string contains both.
782 invisible-string (propertize invisible-string
783 'face 'notmuch-search-non-matching-authors))
784 ;; The visible string contains only matching authors.
785 (setq visible-string (propertize visible-string
786 'face 'notmuch-search-matching-authors)
787 ;; The invisible string may contain both matching and
788 ;; non-matching authors.
789 invisible-string (notmuch-search-author-propertize invisible-string)))
791 ;; If there is any invisible text, add it as a tooltip to the
793 (when (not (string= invisible-string ""))
794 (setq visible-string (propertize visible-string 'help-echo (concat "..." invisible-string))))
796 ;; Insert the visible and, if present, invisible author strings.
797 (insert visible-string)
798 (when (not (string= invisible-string ""))
799 (let ((start (point))
801 (insert invisible-string)
802 (setq overlay (make-overlay start (point)))
803 (overlay-put overlay 'invisible 'ellipsis)
804 (overlay-put overlay 'isearch-open-invisible #'delete-overlay)))
807 (defun notmuch-search-insert-field (field date count authors subject tags)
809 ((string-equal field "date")
810 (insert (propertize (format (cdr (assoc field notmuch-search-result-format)) date)
811 'face 'notmuch-search-date)))
812 ((string-equal field "count")
813 (insert (propertize (format (cdr (assoc field notmuch-search-result-format)) count)
814 'face 'notmuch-search-count)))
815 ((string-equal field "subject")
816 (insert (propertize (format (cdr (assoc field notmuch-search-result-format)) subject)
817 'face 'notmuch-search-subject)))
819 ((string-equal field "authors")
820 (notmuch-search-insert-authors (cdr (assoc field notmuch-search-result-format)) authors))
822 ((string-equal field "tags")
823 (insert (concat "(" (propertize tags 'font-lock-face 'notmuch-tag-face) ")")))))
825 (defun notmuch-search-show-result (date count authors subject tags)
826 (let ((fields) (field))
827 (setq fields (mapcar 'car notmuch-search-result-format))
828 (loop for field in fields
829 do (notmuch-search-insert-field field date count authors subject tags)))
832 (defun notmuch-search-process-filter (proc string)
833 "Process and filter the output of \"notmuch search\""
834 (let ((buffer (process-buffer proc))
836 (if (buffer-live-p buffer)
837 (with-current-buffer buffer
841 (inhibit-read-only t)
842 (string (concat notmuch-search-process-filter-data string)))
843 (setq notmuch-search-process-filter-data nil)
845 (while (and (< line (length string)) (= (elt string line) ?\n))
846 (setq line (1+ line)))
847 (if (string-match "^\\(thread:[0-9A-Fa-f]*\\) \\([^][]*\\) \\(\\[[0-9/]*\\]\\) \\([^;]*\\); \\(.*\\) (\\([^()]*\\))$" string line)
848 (let* ((thread-id (match-string 1 string))
849 (date (match-string 2 string))
850 (count (match-string 3 string))
851 (authors (match-string 4 string))
852 (subject (match-string 5 string))
853 (tags (match-string 6 string))
854 (tag-list (if tags (save-match-data (split-string tags)))))
855 (goto-char (point-max))
856 (if (/= (match-beginning 1) line)
857 (insert (concat "Error: Unexpected output from notmuch search:\n" (substring string line (match-beginning 1)) "\n")))
859 (notmuch-search-show-result date count authors
860 (notmuch-prettify-subject subject) tags)
861 (notmuch-search-color-line beg (point) tag-list)
862 (put-text-property beg (point) 'notmuch-search-thread-id thread-id)
863 (put-text-property beg (point) 'notmuch-search-authors authors)
864 (put-text-property beg (point) 'notmuch-search-subject subject)
865 (when (string= thread-id notmuch-search-target-thread)
866 (set 'found-target beg)
867 (set 'notmuch-search-target-thread "found")))
868 (set 'line (match-end 0)))
870 (while (and (< line (length string)) (= (elt string line) ?\n))
871 (setq line (1+ line)))
872 (if (< line (length string))
873 (setq notmuch-search-process-filter-data (substring string line)))
876 (goto-char found-target)))
877 (delete-process proc))))
879 (defun notmuch-search-operate-all (&rest actions)
880 "Add/remove tags from all matching messages.
882 This command adds or removes tags from all messages matching the
883 current search terms. When called interactively, this command
884 will prompt for tags to be added or removed. Tags prefixed with
885 '+' will be added and tags prefixed with '-' will be removed.
887 Each character of the tag name may consist of alphanumeric
888 characters as well as `_.+-'.
890 (interactive (notmuch-read-tag-changes))
891 (apply 'notmuch-tag notmuch-search-query-string actions))
893 (defun notmuch-search-buffer-title (query)
894 "Returns the title for a buffer with notmuch search results."
898 (loop for tuple in notmuch-saved-searches
899 if (let ((quoted-query (regexp-quote (cdr tuple))))
900 (and (string-match (concat "^" quoted-query) query)
901 (> (length (match-string 0 query))
903 do (setq longest tuple))
905 (saved-search-name (car saved-search))
906 (saved-search-query (cdr saved-search)))
907 (cond ((and saved-search (equal saved-search-query query))
908 ;; Query is the same as saved search (ignoring case)
909 (concat "*notmuch-saved-search-" saved-search-name "*"))
911 (concat "*notmuch-search-"
912 (replace-regexp-in-string (concat "^" (regexp-quote saved-search-query))
913 (concat "[ " saved-search-name " ]")
917 (concat "*notmuch-search-" query "*"))
920 (defun notmuch-read-query (prompt)
921 "Read a notmuch-query from the minibuffer with completion.
923 PROMPT is the string to prompt with."
926 (append (list "folder:" "thread:" "id:" "date:" "from:" "to:"
927 "subject:" "attachment:")
928 (mapcar (lambda (tag)
930 (process-lines notmuch-command "search" "--output=tags" "*")))))
931 (let ((keymap (copy-keymap minibuffer-local-map))
932 (minibuffer-completion-table
933 (completion-table-dynamic
935 ;; generate a list of possible completions for the current input
937 ;; this ugly regexp is used to get the last word of the input
938 ;; possibly preceded by a '('
939 ((string-match "\\(^\\|.* (?\\)\\([^ ]*\\)$" string)
940 (mapcar (lambda (compl)
941 (concat (match-string-no-properties 1 string) compl))
942 (all-completions (match-string-no-properties 2 string)
944 (t (list string)))))))
945 ;; this was simpler than convincing completing-read to accept spaces:
946 (define-key keymap (kbd "<tab>") 'minibuffer-complete)
947 (let ((history-delete-duplicates t))
948 (read-from-minibuffer prompt nil keymap nil
949 'notmuch-search-history nil nil)))))
952 (defun notmuch-search (&optional query oldest-first target-thread target-line continuation)
953 "Run \"notmuch search\" with the given `query' and display results.
955 If `query' is nil, it is read interactively from the minibuffer.
956 Other optional parameters are used as follows:
958 oldest-first: A Boolean controlling the sort order of returned threads
959 target-thread: A thread ID (with the thread: prefix) that will be made
960 current if it appears in the search results.
961 target-line: The line number to move to if the target thread does not
962 appear in the search results."
965 (setq query (notmuch-read-query "Notmuch search: ")))
966 (let ((buffer (get-buffer-create (notmuch-search-buffer-title query))))
967 (switch-to-buffer buffer)
968 (notmuch-search-mode)
969 ;; Don't track undo information for this buffer
970 (set 'buffer-undo-list t)
971 (set 'notmuch-search-query-string query)
972 (set 'notmuch-search-oldest-first oldest-first)
973 (set 'notmuch-search-target-thread target-thread)
974 (set 'notmuch-search-target-line target-line)
975 (set 'notmuch-search-continuation continuation)
976 (let ((proc (get-buffer-process (current-buffer)))
977 (inhibit-read-only t))
979 (error "notmuch search process already running for query `%s'" query)
982 (goto-char (point-min))
984 (let ((proc (start-process
985 "notmuch-search" buffer
986 notmuch-command "search"
988 "--sort=oldest-first"
989 "--sort=newest-first")
991 (set-process-sentinel proc 'notmuch-search-process-sentinel)
992 (set-process-filter proc 'notmuch-search-process-filter)
993 (set-process-query-on-exit-flag proc nil))))
994 (run-hooks 'notmuch-search-hook)))
996 (defun notmuch-search-refresh-view ()
997 "Refresh the current view.
999 Kills the current buffer and runs a new search with the same
1000 query string as the current search. If the current thread is in
1001 the new search results, then point will be placed on the same
1002 thread. Otherwise, point will be moved to attempt to be in the
1003 same relative position within the new buffer."
1005 (let ((target-line (line-number-at-pos))
1006 (oldest-first notmuch-search-oldest-first)
1007 (target-thread (notmuch-search-find-thread-id))
1008 (query notmuch-search-query-string)
1009 (continuation notmuch-search-continuation))
1010 (notmuch-kill-this-buffer)
1011 (notmuch-search query oldest-first target-thread target-line continuation)
1012 (goto-char (point-min))))
1014 (defcustom notmuch-poll-script nil
1015 "An external script to incorporate new mail into the notmuch database.
1017 This variable controls the action invoked by
1018 `notmuch-search-poll-and-refresh-view' and
1019 `notmuch-hello-poll-and-update' (each have a default keybinding
1020 of 'G') to incorporate new mail into the notmuch database.
1022 If set to nil (the default), new mail is processed by invoking
1023 \"notmuch new\". Otherwise, this should be set to a string that
1024 gives the name of an external script that processes new mail. If
1025 set to the empty string, no command will be run.
1027 The external script could do any of the following depending on
1030 1. Invoke a program to transfer mail to the local mail store
1031 2. Invoke \"notmuch new\" to incorporate the new mail
1032 3. Invoke one or more \"notmuch tag\" commands to classify the mail
1034 Note that the recommended way of achieving the same is using
1035 \"notmuch new\" hooks."
1036 :type '(choice (const :tag "notmuch new" nil)
1037 (const :tag "Disabled" "")
1038 (string :tag "Custom script"))
1039 :group 'notmuch-external)
1041 (defun notmuch-poll ()
1042 "Run \"notmuch new\" or an external script to import mail.
1044 Invokes `notmuch-poll-script', \"notmuch new\", or does nothing
1045 depending on the value of `notmuch-poll-script'."
1047 (if (stringp notmuch-poll-script)
1048 (unless (string= notmuch-poll-script "")
1049 (call-process notmuch-poll-script nil nil))
1050 (call-process notmuch-command nil nil nil "new")))
1052 (defun notmuch-search-poll-and-refresh-view ()
1053 "Invoke `notmuch-poll' to import mail, then refresh the current view."
1056 (notmuch-search-refresh-view))
1058 (defun notmuch-search-toggle-order ()
1059 "Toggle the current search order.
1061 By default, the \"inbox\" view created by `notmuch' is displayed
1062 in chronological order (oldest thread at the beginning of the
1063 buffer), while any global searches created by `notmuch-search'
1064 are displayed in reverse-chronological order (newest thread at
1065 the beginning of the buffer).
1067 This command toggles the sort order for the current search.
1069 Note that any filtered searches created by
1070 `notmuch-search-filter' retain the search order of the parent
1073 (set 'notmuch-search-oldest-first (not notmuch-search-oldest-first))
1074 (notmuch-search-refresh-view))
1076 (defun notmuch-search-filter (query)
1077 "Filter the current search results based on an additional query string.
1079 Runs a new search matching only messages that match both the
1080 current search results AND the additional query string provided."
1081 (interactive (list (notmuch-read-query "Filter search: ")))
1082 (let ((grouped-query (if (string-match-p notmuch-search-disjunctive-regexp query)
1083 (concat "( " query " )")
1085 (notmuch-search (if (string= notmuch-search-query-string "*")
1087 (concat notmuch-search-query-string " and " grouped-query)) notmuch-search-oldest-first)))
1089 (defun notmuch-search-filter-by-tag (tag)
1090 "Filter the current search results based on a single tag.
1092 Runs a new search matching only messages that match both the
1093 current search results AND that are tagged with the given tag."
1095 (list (notmuch-select-tag-with-completion "Filter by tag: ")))
1096 (notmuch-search (concat notmuch-search-query-string " and tag:" tag) notmuch-search-oldest-first))
1100 "Run notmuch and display saved searches, known tags, etc."
1104 (defun notmuch-interesting-buffer (b)
1105 "Is the current buffer of interest to a notmuch user?"
1106 (with-current-buffer b
1107 (memq major-mode '(notmuch-show-mode
1113 (defun notmuch-cycle-notmuch-buffers ()
1114 "Cycle through any existing notmuch buffers (search, show or hello).
1116 If the current buffer is the only notmuch buffer, bury it. If no
1117 notmuch buffers exist, run `notmuch'."
1121 ;; If the current buffer is a notmuch buffer, remember it and then
1123 (when (notmuch-interesting-buffer (current-buffer))
1124 (setq start (current-buffer))
1127 ;; Find the first notmuch buffer.
1128 (setq first (loop for buffer in (buffer-list)
1129 if (notmuch-interesting-buffer buffer)
1133 ;; If the first one we found is any other than the starting
1134 ;; buffer, switch to it.
1135 (unless (eq first start)
1136 (switch-to-buffer first))
1139 (setq mail-user-agent 'notmuch-user-agent)