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 (defvar notmuch-select-tag-history nil
80 "Variable to store minibuffer history for
81 `notmuch-select-tag-with-completion' function.")
83 (defvar notmuch-read-tag-changes-history nil
84 "Variable to store minibuffer history for
85 `notmuch-read-tag-changes' function.")
87 (defun notmuch-tag-completions (&optional search-terms)
88 (if (null search-terms)
89 (setq search-terms (list "*")))
91 (with-output-to-string
92 (with-current-buffer standard-output
93 (apply 'call-process notmuch-command nil t
94 nil "search" "--output=tags" "--exclude=false" search-terms)))
97 (defun notmuch-select-tag-with-completion (prompt &rest search-terms)
98 (let ((tag-list (notmuch-tag-completions search-terms)))
99 (completing-read prompt tag-list nil nil nil 'notmuch-select-tag-history)))
101 (defun notmuch-read-tag-changes (&optional initial-input &rest search-terms)
102 (let* ((all-tag-list (notmuch-tag-completions))
103 (add-tag-list (mapcar (apply-partially 'concat "+") all-tag-list))
104 (remove-tag-list (mapcar (apply-partially 'concat "-")
105 (if (null search-terms)
107 (notmuch-tag-completions search-terms))))
108 (tag-list (append add-tag-list remove-tag-list))
110 ;; By default, space is bound to "complete word" function.
111 ;; Re-bind it to insert a space instead. Note that <tab>
112 ;; still does the completion.
113 (crm-local-completion-map
114 (let ((map (make-sparse-keymap)))
115 (set-keymap-parent map crm-local-completion-map)
116 (define-key map " " 'self-insert-command)
118 (delete "" (completing-read-multiple "Tags (+add -drop): "
119 tag-list nil nil initial-input
120 'notmuch-read-tag-changes-history))))
122 (defun notmuch-update-tags (tags tag-changes)
123 "Return a copy of TAGS with additions and removals from TAG-CHANGES.
125 TAG-CHANGES must be a list of tags names, each prefixed with
126 either a \"+\" to indicate the tag should be added to TAGS if not
127 present or a \"-\" to indicate that the tag should be removed
128 from TAGS if present."
129 (let ((result-tags (copy-sequence tags)))
130 (dolist (tag-change tag-changes)
131 (let ((op (string-to-char tag-change))
132 (tag (unless (string= tag-change "") (substring tag-change 1))))
134 (?+ (unless (member tag result-tags)
135 (push tag result-tags)))
136 (?- (setq result-tags (delete tag result-tags)))
138 (error "Changed tag must be of the form `+this_tag' or `-that_tag'")))))
139 (sort result-tags 'string<)))
141 (defun notmuch-foreach-mime-part (function mm-handle)
142 (cond ((stringp (car mm-handle))
143 (dolist (part (cdr mm-handle))
144 (notmuch-foreach-mime-part function part)))
145 ((bufferp (car mm-handle))
146 (funcall function mm-handle))
147 (t (dolist (part mm-handle)
148 (notmuch-foreach-mime-part function part)))))
150 (defun notmuch-count-attachments (mm-handle)
152 (notmuch-foreach-mime-part
154 (let ((disposition (mm-handle-disposition p)))
155 (and (listp disposition)
156 (or (equal (car disposition) "attachment")
157 (and (equal (car disposition) "inline")
158 (assq 'filename disposition)))
163 (defun notmuch-save-attachments (mm-handle &optional queryp)
164 (notmuch-foreach-mime-part
166 (let ((disposition (mm-handle-disposition p)))
167 (and (listp disposition)
168 (or (equal (car disposition) "attachment")
169 (and (equal (car disposition) "inline")
170 (assq 'filename disposition)))
173 (concat "Save '" (cdr (assq 'filename disposition)) "' ")))
177 (defun notmuch-documentation-first-line (symbol)
178 "Return the first line of the documentation string for SYMBOL."
179 (let ((doc (documentation symbol)))
182 (insert (documentation symbol t))
183 (goto-char (point-min))
186 (buffer-substring beg (point))))
189 (defun notmuch-prefix-key-description (key)
190 "Given a prefix key code, return a human-readable string representation.
192 This is basically just `format-kbd-macro' but we also convert ESC to M-."
193 (let ((desc (format-kbd-macro (vector key))))
194 (if (string= desc "ESC")
198 ;; I would think that emacs would have code handy for walking a keymap
199 ;; and generating strings for each key, and I would prefer to just call
200 ;; that. But I couldn't find any (could be all implemented in C I
201 ;; suppose), so I wrote my own here.
202 (defun notmuch-substitute-one-command-key-with-prefix (prefix binding)
203 "For a key binding, return a string showing a human-readable
204 representation of the prefixed key as well as the first line of
205 documentation from the bound function.
207 For a mouse binding, return nil."
208 (let ((key (car binding))
209 (action (cdr binding)))
210 (if (mouse-event-p key)
213 (let ((substitute (apply-partially 'notmuch-substitute-one-command-key-with-prefix (notmuch-prefix-key-description key)))
215 (map-keymap (lambda (a b)
216 (push (cons a b) as-list))
218 (mapconcat substitute as-list "\n"))
219 (concat prefix (format-kbd-macro (vector key))
221 (notmuch-documentation-first-line action))))))
223 (defun notmuch-substitute-command-keys-one (key)
224 ;; A `keymap' key indicates inheritance from a parent keymap - the
225 ;; inherited mappings follow, so there is nothing to print for
227 (when (not (eq key 'keymap))
228 (notmuch-substitute-one-command-key-with-prefix nil key)))
230 (defun notmuch-substitute-command-keys (doc)
231 "Like `substitute-command-keys' but with documentation, not function names."
233 (while (string-match "\\\\{\\([^}[:space:]]*\\)}" doc beg)
234 (let* ((keymap-name (substring doc (match-beginning 1) (match-end 1)))
235 (keymap (symbol-value (intern keymap-name))))
236 (setq doc (replace-match
237 (mapconcat #'notmuch-substitute-command-keys-one
240 (setq beg (match-end 0)))
243 (defun notmuch-help ()
244 "Display help for the current notmuch mode."
246 (let* ((mode major-mode)
247 (doc (substitute-command-keys (notmuch-substitute-command-keys (documentation mode t)))))
248 (with-current-buffer (generate-new-buffer "*notmuch-help*")
250 (goto-char (point-min))
251 (set-buffer-modified-p nil)
252 (view-buffer (current-buffer) 'kill-buffer-if-not-modified))))
256 (defun notmuch-hl-line-mode ()
257 (prog1 (hl-line-mode)
258 (when hl-line-overlay
259 (overlay-put hl-line-overlay 'priority 1))))
261 (defcustom notmuch-search-hook '(notmuch-hl-line-mode)
262 "List of functions to call when notmuch displays the search results."
264 :options '(notmuch-hl-line-mode)
265 :group 'notmuch-search
266 :group 'notmuch-hooks)
268 (defvar notmuch-search-mode-map
269 (let ((map (make-sparse-keymap)))
270 (define-key map "?" 'notmuch-help)
271 (define-key map "q" 'notmuch-search-quit)
272 (define-key map "x" 'notmuch-search-quit)
273 (define-key map (kbd "<DEL>") 'notmuch-search-scroll-down)
274 (define-key map "b" 'notmuch-search-scroll-down)
275 (define-key map " " 'notmuch-search-scroll-up)
276 (define-key map "<" 'notmuch-search-first-thread)
277 (define-key map ">" 'notmuch-search-last-thread)
278 (define-key map "p" 'notmuch-search-previous-thread)
279 (define-key map "n" 'notmuch-search-next-thread)
280 (define-key map "r" 'notmuch-search-reply-to-thread-sender)
281 (define-key map "R" 'notmuch-search-reply-to-thread)
282 (define-key map "m" 'notmuch-mua-new-mail)
283 (define-key map "s" 'notmuch-search)
284 (define-key map "o" 'notmuch-search-toggle-order)
285 (define-key map "c" 'notmuch-search-stash-map)
286 (define-key map "=" 'notmuch-search-refresh-view)
287 (define-key map "G" 'notmuch-search-poll-and-refresh-view)
288 (define-key map "t" 'notmuch-search-filter-by-tag)
289 (define-key map "f" 'notmuch-search-filter)
290 (define-key map [mouse-1] 'notmuch-search-show-thread)
291 (define-key map "*" 'notmuch-search-tag-all)
292 (define-key map "a" 'notmuch-search-archive-thread)
293 (define-key map "-" 'notmuch-search-remove-tag)
294 (define-key map "+" 'notmuch-search-add-tag)
295 (define-key map (kbd "RET") 'notmuch-search-show-thread)
297 "Keymap for \"notmuch search\" buffers.")
298 (fset 'notmuch-search-mode-map notmuch-search-mode-map)
300 (defvar notmuch-search-stash-map
301 (let ((map (make-sparse-keymap)))
302 (define-key map "i" 'notmuch-search-stash-thread-id)
304 "Submap for stash commands")
305 (fset 'notmuch-search-stash-map notmuch-search-stash-map)
307 (defun notmuch-search-stash-thread-id ()
308 "Copy thread ID of current thread to kill-ring."
310 (notmuch-common-do-stash (notmuch-search-find-thread-id)))
312 (defvar notmuch-search-query-string)
313 (defvar notmuch-search-target-thread)
314 (defvar notmuch-search-target-line)
315 (defvar notmuch-search-continuation)
317 (defvar notmuch-search-disjunctive-regexp "\\<[oO][rR]\\>")
319 (defun notmuch-search-quit ()
320 "Exit the search buffer, calling any defined continuation function."
322 (let ((continuation notmuch-search-continuation))
323 (notmuch-kill-this-buffer)
325 (funcall continuation))))
327 (defun notmuch-search-scroll-up ()
328 "Move forward through search results by one window's worth."
332 ((end-of-buffer) (notmuch-search-last-thread))))
334 (defun notmuch-search-scroll-down ()
335 "Move backward through the search results by one window's worth."
337 ;; I don't know why scroll-down doesn't signal beginning-of-buffer
338 ;; the way that scroll-up signals end-of-buffer, but c'est la vie.
340 ;; So instead of trapping a signal we instead check whether the
341 ;; window begins on the first line of the buffer and if so, move
342 ;; directly to that position. (We have to count lines since the
343 ;; window-start position is not the same as point-min due to the
344 ;; invisible thread-ID characters on the first line.
345 (if (equal (count-lines (point-min) (window-start)) 0)
346 (goto-char (point-min))
349 (defun notmuch-search-next-thread ()
350 "Select the next thread in the search results."
354 (defun notmuch-search-previous-thread ()
355 "Select the previous thread in the search results."
359 (defun notmuch-search-last-thread ()
360 "Select the last thread in the search results."
362 (goto-char (point-max))
365 (defun notmuch-search-first-thread ()
366 "Select the first thread in the search results."
368 (goto-char (point-min)))
370 (defface notmuch-message-summary-face
371 '((((class color) (background light)) (:background "#f0f0f0"))
372 (((class color) (background dark)) (:background "#303030")))
373 "Face for the single-line message summary in notmuch-show-mode."
375 :group 'notmuch-faces)
377 (defface notmuch-search-date
378 '((t :inherit default))
379 "Face used in search mode for dates."
380 :group 'notmuch-search
381 :group 'notmuch-faces)
383 (defface notmuch-search-count
384 '((t :inherit default))
385 "Face used in search mode for the count matching the query."
386 :group 'notmuch-search
387 :group 'notmuch-faces)
389 (defface notmuch-search-subject
390 '((t :inherit default))
391 "Face used in search mode for subjects."
392 :group 'notmuch-search
393 :group 'notmuch-faces)
395 (defface notmuch-search-matching-authors
396 '((t :inherit default))
397 "Face used in search mode for authors matching the query."
398 :group 'notmuch-search
399 :group 'notmuch-faces)
401 (defface notmuch-search-non-matching-authors
404 (:foreground "grey30"))
407 (:foreground "grey60"))
410 "Face used in search mode for authors not matching the query."
411 :group 'notmuch-search
412 :group 'notmuch-faces)
414 (defface notmuch-tag-face
417 (:foreground "OliveDrab1"))
420 (:foreground "navy blue" :bold t))
423 "Face used in search mode face for tags."
424 :group 'notmuch-search
425 :group 'notmuch-faces)
427 (defun notmuch-search-mode ()
428 "Major mode displaying results of a notmuch search.
430 This buffer contains the results of a \"notmuch search\" of your
431 email archives. Each line in the buffer represents a single
432 thread giving a summary of the thread (a relative date, the
433 number of matched messages and total messages in the thread,
434 participants in the thread, a representative subject line, and
437 Pressing \\[notmuch-search-show-thread] on any line displays that thread. The '\\[notmuch-search-add-tag]' and '\\[notmuch-search-remove-tag]'
438 keys can be used to add or remove tags from a thread. The '\\[notmuch-search-archive-thread]' key
439 is a convenience for archiving a thread (removing the \"inbox\"
440 tag). The '\\[notmuch-search-tag-all]' key can be used to add or remove a tag from all
441 threads in the current buffer.
443 Other useful commands are '\\[notmuch-search-filter]' for filtering the current search
444 based on an additional query string, '\\[notmuch-search-filter-by-tag]' for filtering to include
445 only messages with a given tag, and '\\[notmuch-search]' to execute a new, global
448 Complete list of currently available key bindings:
450 \\{notmuch-search-mode-map}"
452 (kill-all-local-variables)
453 (make-local-variable 'notmuch-search-query-string)
454 (make-local-variable 'notmuch-search-oldest-first)
455 (make-local-variable 'notmuch-search-target-thread)
456 (make-local-variable 'notmuch-search-target-line)
457 (set (make-local-variable 'notmuch-search-continuation) nil)
458 (set (make-local-variable 'scroll-preserve-screen-position) t)
459 (add-to-invisibility-spec (cons 'ellipsis t))
460 (use-local-map notmuch-search-mode-map)
461 (setq truncate-lines t)
462 (setq major-mode 'notmuch-search-mode
463 mode-name "notmuch-search")
464 (setq buffer-read-only t))
466 (defun notmuch-search-properties-in-region (property beg end)
469 (last-line (line-number-at-pos end))
470 (max-line (- (line-number-at-pos (point-max)) 2)))
473 (while (<= (line-number-at-pos) (min last-line max-line))
474 (setq output (cons (get-text-property (point) property) output))
478 (defun notmuch-search-find-thread-id ()
479 "Return the thread for the current thread"
480 (get-text-property (point) 'notmuch-search-thread-id))
482 (defun notmuch-search-find-thread-id-region (beg end)
483 "Return a list of threads for the current region"
484 (notmuch-search-properties-in-region 'notmuch-search-thread-id beg end))
486 (defun notmuch-search-find-thread-id-region-search (beg end)
487 "Return a search string for threads for the current region"
488 (mapconcat 'identity (notmuch-search-find-thread-id-region beg end) " or "))
490 (defun notmuch-search-find-authors ()
491 "Return the authors for the current thread"
492 (get-text-property (point) 'notmuch-search-authors))
494 (defun notmuch-search-find-authors-region (beg end)
495 "Return a list of authors for the current region"
496 (notmuch-search-properties-in-region 'notmuch-search-authors beg end))
498 (defun notmuch-search-find-subject ()
499 "Return the subject for the current thread"
500 (get-text-property (point) 'notmuch-search-subject))
502 (defun notmuch-search-find-subject-region (beg end)
503 "Return a list of authors for the current region"
504 (notmuch-search-properties-in-region 'notmuch-search-subject beg end))
506 (defun notmuch-search-show-thread ()
507 "Display the currently selected thread."
509 (let ((thread-id (notmuch-search-find-thread-id))
510 (subject (notmuch-prettify-subject (notmuch-search-find-subject))))
511 (if (> (length thread-id) 0)
512 (notmuch-show thread-id
514 notmuch-search-query-string
515 ;; Name the buffer based on the subject.
516 (concat "*" (truncate-string-to-width subject 30 nil nil t) "*"))
517 (message "End of search results."))))
519 (defun notmuch-search-reply-to-thread (&optional prompt-for-sender)
520 "Begin composing a reply-all to the entire current thread in a new buffer."
522 (let ((message-id (notmuch-search-find-thread-id)))
523 (notmuch-mua-new-reply message-id prompt-for-sender t)))
525 (defun notmuch-search-reply-to-thread-sender (&optional prompt-for-sender)
526 "Begin composing a reply to the entire current thread in a new buffer."
528 (let ((message-id (notmuch-search-find-thread-id)))
529 (notmuch-mua-new-reply message-id prompt-for-sender nil)))
531 (defun notmuch-call-notmuch-process (&rest args)
532 "Synchronously invoke \"notmuch\" with the given list of arguments.
534 Output from the process will be presented to the user as an error
535 and will also appear in a buffer named \"*Notmuch errors*\"."
536 (let ((error-buffer (get-buffer-create "*Notmuch errors*")))
537 (with-current-buffer error-buffer
539 (if (eq (apply 'call-process notmuch-command nil error-buffer nil args) 0)
542 (with-current-buffer error-buffer
543 (let ((beg (point-min))
544 (end (- (point-max) 1)))
545 (error (buffer-substring beg end))
548 (defun notmuch-tag (query &rest tag-changes)
549 "Add/remove tags in TAG-CHANGES to messages matching QUERY.
551 TAG-CHANGES should be a list of strings of the form \"+tag\" or
552 \"-tag\" and QUERY should be a string containing the
555 Note: Other code should always use this function alter tags of
556 messages instead of running (notmuch-call-notmuch-process \"tag\" ..)
557 directly, so that hooks specified in notmuch-before-tag-hook and
558 notmuch-after-tag-hook will be run."
559 ;; Perform some validation
560 (mapc (lambda (tag-change)
561 (unless (string-match-p "^[-+]\\S-+$" tag-change)
562 (error "Tag must be of the form `+this_tag' or `-that_tag'")))
564 (unless (null tag-changes)
565 (run-hooks 'notmuch-before-tag-hook)
566 (apply 'notmuch-call-notmuch-process "tag"
567 (append tag-changes (list "--" query)))
568 (run-hooks 'notmuch-after-tag-hook)))
570 (defcustom notmuch-before-tag-hook nil
571 "Hooks that are run before tags of a message are modified.
573 'tags' will contain the tags that are about to be added or removed as
574 a list of strings of the form \"+TAG\" or \"-TAG\".
575 'query' will be a string containing the search query that determines
576 the messages that are about to be tagged"
579 :options '(notmuch-hl-line-mode)
580 :group 'notmuch-hooks)
582 (defcustom notmuch-after-tag-hook nil
583 "Hooks that are run after tags of a message are modified.
585 'tags' will contain the tags that were added or removed as
586 a list of strings of the form \"+TAG\" or \"-TAG\".
587 'query' will be a string containing the search query that determines
588 the messages that were tagged"
590 :options '(notmuch-hl-line-mode)
591 :group 'notmuch-hooks)
593 (defun notmuch-search-set-tags (tags)
596 (re-search-backward "(")
599 (inhibit-read-only t))
600 (re-search-forward ")")
603 (delete-region beg end)
604 (insert (propertize (mapconcat 'identity tags " ")
605 'face 'notmuch-tag-face))))))
607 (defun notmuch-search-get-tags ()
610 (re-search-backward "(")
611 (let ((beg (+ (point) 1)))
612 (re-search-forward ")")
613 (let ((end (- (point) 1)))
614 (split-string (buffer-substring-no-properties beg end))))))
616 (defun notmuch-search-get-tags-region (beg end)
619 (last-line (line-number-at-pos end))
620 (max-line (- (line-number-at-pos (point-max)) 2)))
622 (while (<= (line-number-at-pos) (min last-line max-line))
623 (setq output (append output (notmuch-search-get-tags)))
627 (defun notmuch-search-tag-thread (&rest tag-changes)
628 "Change tags for the currently selected thread.
630 See `notmuch-search-tag-region' for details."
631 (apply 'notmuch-search-tag-region (point) (point) tag-changes))
633 (defun notmuch-search-tag-region (beg end &rest tag-changes)
634 "Change tags for threads in the given region.
636 TAGS is a list of tag operations for `notmuch-tag'. The tags are
637 added or removed for all threads in the region from BEG to END."
638 (let ((search-string (notmuch-search-find-thread-id-region-search beg end)))
639 (apply 'notmuch-tag search-string tag-changes)
641 (let ((last-line (line-number-at-pos end))
642 (max-line (- (line-number-at-pos (point-max)) 2)))
644 (while (<= (line-number-at-pos) (min last-line max-line))
645 (notmuch-search-set-tags
646 (notmuch-update-tags (notmuch-search-get-tags) tag-changes))
649 (defun notmuch-search-tag (&optional initial-input)
650 "Change tags for the currently selected thread or region."
652 (let* ((beg (if (region-active-p) (region-beginning) (point)))
653 (end (if (region-active-p) (region-end) (point)))
654 (search-string (notmuch-search-find-thread-id-region-search beg end))
655 (tags (notmuch-read-tag-changes initial-input search-string)))
656 (apply 'notmuch-search-tag-region beg end tags)))
658 (defun notmuch-search-add-tag ()
659 "Same as `notmuch-search-tag' but sets initial input to '+'."
661 (notmuch-search-tag "+"))
663 (defun notmuch-search-remove-tag ()
664 "Same as `notmuch-search-tag' but sets initial input to '-'."
666 (notmuch-search-tag "-"))
668 (defun notmuch-search-archive-thread ()
669 "Archive the currently selected thread (remove its \"inbox\" tag).
671 This function advances the next thread when finished."
673 (notmuch-search-tag-thread "-inbox")
674 (notmuch-search-next-thread))
676 (defvar notmuch-search-process-filter-data nil
677 "Data that has not yet been processed.")
678 (make-variable-buffer-local 'notmuch-search-process-filter-data)
680 (defun notmuch-search-process-sentinel (proc msg)
681 "Add a message to let user know when \"notmuch search\" exits"
682 (let ((buffer (process-buffer proc))
683 (status (process-status proc))
684 (exit-status (process-exit-status proc))
685 (never-found-target-thread nil))
686 (if (memq status '(exit signal))
687 (if (buffer-live-p buffer)
688 (with-current-buffer buffer
690 (let ((inhibit-read-only t)
692 (goto-char (point-max))
693 (if (eq status 'signal)
694 (insert "Incomplete search results (search process was killed).\n"))
695 (when (eq status 'exit)
696 (if notmuch-search-process-filter-data
697 (insert (concat "Error: Unexpected output from notmuch search:\n" notmuch-search-process-filter-data)))
698 (insert "End of search results.")
699 (unless (= exit-status 0)
700 (insert (format " (process returned %d)" exit-status)))
703 (not (string= notmuch-search-target-thread "found")))
704 (set 'never-found-target-thread t)))))
705 (when (and never-found-target-thread
706 notmuch-search-target-line)
707 (goto-char (point-min))
708 (forward-line (1- notmuch-search-target-line))))))))
710 (defcustom notmuch-search-line-faces '(("unread" :weight bold)
711 ("flagged" :foreground "blue"))
712 "Tag/face mapping for line highlighting in notmuch-search.
714 Here is an example of how to color search results based on tags.
715 (the following text would be placed in your ~/.emacs file):
717 (setq notmuch-search-line-faces '((\"deleted\" . (:foreground \"red\"
718 :background \"blue\"))
719 (\"unread\" . (:foreground \"green\"))))
721 The attributes defined for matching tags are merged, with later
722 attributes overriding earlier. A message having both \"deleted\"
723 and \"unread\" tags with the above settings would have a green
724 foreground and blue background."
725 :type '(alist :key-type (string) :value-type (custom-face-edit))
726 :group 'notmuch-search
727 :group 'notmuch-faces)
729 (defun notmuch-search-color-line (start end line-tag-list)
730 "Colorize lines in `notmuch-show' based on tags."
731 ;; Create the overlay only if the message has tags which match one
732 ;; of those specified in `notmuch-search-line-faces'.
735 (let ((tag (car elem))
736 (attributes (cdr elem)))
737 (when (member tag line-tag-list)
739 (setq overlay (make-overlay start end)))
740 ;; Merge the specified properties with any already
741 ;; applied from an earlier match.
742 (overlay-put overlay 'face
743 (append (overlay-get overlay 'face) attributes)))))
744 notmuch-search-line-faces)))
746 (defun notmuch-search-author-propertize (authors)
747 "Split `authors' into matching and non-matching authors and
748 propertize appropriately. If no boundary between authors and
749 non-authors is found, assume that all of the authors match."
750 (if (string-match "\\(.*\\)|\\(.*\\)" authors)
751 (concat (propertize (concat (match-string 1 authors) ",")
752 'face 'notmuch-search-matching-authors)
753 (propertize (match-string 2 authors)
754 'face 'notmuch-search-non-matching-authors))
755 (propertize authors 'face 'notmuch-search-matching-authors)))
757 (defun notmuch-search-insert-authors (format-string authors)
758 ;; Save the match data to avoid interfering with
759 ;; `notmuch-search-process-filter'.
761 (let* ((formatted-authors (format format-string authors))
762 (formatted-sample (format format-string ""))
763 (visible-string formatted-authors)
764 (invisible-string "")
767 ;; Truncate the author string to fit the specification.
768 (if (> (length formatted-authors)
769 (length formatted-sample))
770 (let ((visible-length (- (length formatted-sample)
772 ;; Truncate the visible string according to the width of
773 ;; the display string.
774 (setq visible-string (substring formatted-authors 0 visible-length)
775 invisible-string (substring formatted-authors visible-length))
776 ;; If possible, truncate the visible string at a natural
777 ;; break (comma or pipe), as incremental search doesn't
778 ;; match across the visible/invisible border.
779 (when (string-match "\\(.*\\)\\([,|] \\)\\([^,|]*\\)" visible-string)
780 ;; Second clause is destructive on `visible-string', so
781 ;; order is important.
782 (setq invisible-string (concat (match-string 3 visible-string)
784 visible-string (concat (match-string 1 visible-string)
785 (match-string 2 visible-string))))
786 ;; `visible-string' may be shorter than the space allowed
787 ;; by `format-string'. If so we must insert some padding
788 ;; after `invisible-string'.
789 (setq padding (make-string (- (length formatted-sample)
790 (length visible-string)
794 ;; Use different faces to show matching and non-matching authors.
795 (if (string-match "\\(.*\\)|\\(.*\\)" visible-string)
796 ;; The visible string contains both matching and
797 ;; non-matching authors.
798 (setq visible-string (notmuch-search-author-propertize visible-string)
799 ;; The invisible string must contain only non-matching
800 ;; authors, as the visible-string contains both.
801 invisible-string (propertize invisible-string
802 'face 'notmuch-search-non-matching-authors))
803 ;; The visible string contains only matching authors.
804 (setq visible-string (propertize visible-string
805 'face 'notmuch-search-matching-authors)
806 ;; The invisible string may contain both matching and
807 ;; non-matching authors.
808 invisible-string (notmuch-search-author-propertize invisible-string)))
810 ;; If there is any invisible text, add it as a tooltip to the
812 (when (not (string= invisible-string ""))
813 (setq visible-string (propertize visible-string 'help-echo (concat "..." invisible-string))))
815 ;; Insert the visible and, if present, invisible author strings.
816 (insert visible-string)
817 (when (not (string= invisible-string ""))
818 (let ((start (point))
820 (insert invisible-string)
821 (setq overlay (make-overlay start (point)))
822 (overlay-put overlay 'invisible 'ellipsis)
823 (overlay-put overlay 'isearch-open-invisible #'delete-overlay)))
826 (defun notmuch-search-insert-field (field date count authors subject tags)
828 ((string-equal field "date")
829 (insert (propertize (format (cdr (assoc field notmuch-search-result-format)) date)
830 'face 'notmuch-search-date)))
831 ((string-equal field "count")
832 (insert (propertize (format (cdr (assoc field notmuch-search-result-format)) count)
833 'face 'notmuch-search-count)))
834 ((string-equal field "subject")
835 (insert (propertize (format (cdr (assoc field notmuch-search-result-format)) subject)
836 'face 'notmuch-search-subject)))
838 ((string-equal field "authors")
839 (notmuch-search-insert-authors (cdr (assoc field notmuch-search-result-format)) authors))
841 ((string-equal field "tags")
842 (insert (concat "(" (propertize tags 'font-lock-face 'notmuch-tag-face) ")")))))
844 (defun notmuch-search-show-result (date count authors subject tags)
845 (let ((fields) (field))
846 (setq fields (mapcar 'car notmuch-search-result-format))
847 (loop for field in fields
848 do (notmuch-search-insert-field field date count authors subject tags)))
851 (defun notmuch-search-process-filter (proc string)
852 "Process and filter the output of \"notmuch search\""
853 (let ((buffer (process-buffer proc))
855 (if (buffer-live-p buffer)
856 (with-current-buffer buffer
860 (inhibit-read-only t)
861 (string (concat notmuch-search-process-filter-data string)))
862 (setq notmuch-search-process-filter-data nil)
864 (while (and (< line (length string)) (= (elt string line) ?\n))
865 (setq line (1+ line)))
866 (if (string-match "^\\(thread:[0-9A-Fa-f]*\\) \\([^][]*\\) \\(\\[[0-9/]*\\]\\) \\([^;]*\\); \\(.*\\) (\\([^()]*\\))$" string line)
867 (let* ((thread-id (match-string 1 string))
868 (date (match-string 2 string))
869 (count (match-string 3 string))
870 (authors (match-string 4 string))
871 (subject (match-string 5 string))
872 (tags (match-string 6 string))
873 (tag-list (if tags (save-match-data (split-string tags)))))
874 (goto-char (point-max))
875 (if (/= (match-beginning 1) line)
876 (insert (concat "Error: Unexpected output from notmuch search:\n" (substring string line (match-beginning 1)) "\n")))
877 ;; We currently just throw away excluded matches.
878 (unless (eq (aref count 1) ?0)
880 (notmuch-search-show-result date count authors
881 (notmuch-prettify-subject subject) tags)
882 (notmuch-search-color-line beg (point) tag-list)
883 (put-text-property beg (point) 'notmuch-search-thread-id thread-id)
884 (put-text-property beg (point) 'notmuch-search-authors authors)
885 (put-text-property beg (point) 'notmuch-search-subject subject)
886 (when (string= thread-id notmuch-search-target-thread)
887 (set 'found-target beg)
888 (set 'notmuch-search-target-thread "found"))))
889 (set 'line (match-end 0)))
891 (while (and (< line (length string)) (= (elt string line) ?\n))
892 (setq line (1+ line)))
893 (if (< line (length string))
894 (setq notmuch-search-process-filter-data (substring string line)))
897 (goto-char found-target)))
898 (delete-process proc))))
900 (defun notmuch-search-tag-all (&rest tag-changes)
901 "Add/remove tags from all matching messages.
903 This command adds or removes tags from all messages matching the
904 current search terms. When called interactively, this command
905 will prompt for tags to be added or removed. Tags prefixed with
906 '+' will be added and tags prefixed with '-' will be removed.
908 Each character of the tag name may consist of alphanumeric
909 characters as well as `_.+-'.
911 (interactive (notmuch-read-tag-changes))
912 (apply 'notmuch-tag notmuch-search-query-string tag-changes))
914 (defun notmuch-search-buffer-title (query)
915 "Returns the title for a buffer with notmuch search results."
919 (loop for tuple in notmuch-saved-searches
920 if (let ((quoted-query (regexp-quote (cdr tuple))))
921 (and (string-match (concat "^" quoted-query) query)
922 (> (length (match-string 0 query))
924 do (setq longest tuple))
926 (saved-search-name (car saved-search))
927 (saved-search-query (cdr saved-search)))
928 (cond ((and saved-search (equal saved-search-query query))
929 ;; Query is the same as saved search (ignoring case)
930 (concat "*notmuch-saved-search-" saved-search-name "*"))
932 (concat "*notmuch-search-"
933 (replace-regexp-in-string (concat "^" (regexp-quote saved-search-query))
934 (concat "[ " saved-search-name " ]")
938 (concat "*notmuch-search-" query "*"))
941 (defun notmuch-read-query (prompt)
942 "Read a notmuch-query from the minibuffer with completion.
944 PROMPT is the string to prompt with."
947 (append (list "folder:" "thread:" "id:" "date:" "from:" "to:"
948 "subject:" "attachment:")
949 (mapcar (lambda (tag)
951 (process-lines notmuch-command "search" "--output=tags" "*")))))
952 (let ((keymap (copy-keymap minibuffer-local-map))
953 (minibuffer-completion-table
954 (completion-table-dynamic
956 ;; generate a list of possible completions for the current input
958 ;; this ugly regexp is used to get the last word of the input
959 ;; possibly preceded by a '('
960 ((string-match "\\(^\\|.* (?\\)\\([^ ]*\\)$" string)
961 (mapcar (lambda (compl)
962 (concat (match-string-no-properties 1 string) compl))
963 (all-completions (match-string-no-properties 2 string)
965 (t (list string)))))))
966 ;; this was simpler than convincing completing-read to accept spaces:
967 (define-key keymap (kbd "TAB") 'minibuffer-complete)
968 (let ((history-delete-duplicates t))
969 (read-from-minibuffer prompt nil keymap nil
970 'notmuch-search-history nil nil)))))
973 (defun notmuch-search (&optional query oldest-first target-thread target-line continuation)
974 "Run \"notmuch search\" with the given `query' and display results.
976 If `query' is nil, it is read interactively from the minibuffer.
977 Other optional parameters are used as follows:
979 oldest-first: A Boolean controlling the sort order of returned threads
980 target-thread: A thread ID (with the thread: prefix) that will be made
981 current if it appears in the search results.
982 target-line: The line number to move to if the target thread does not
983 appear in the search results."
986 (setq query (notmuch-read-query "Notmuch search: ")))
987 (let ((buffer (get-buffer-create (notmuch-search-buffer-title query))))
988 (switch-to-buffer buffer)
989 (notmuch-search-mode)
990 ;; Don't track undo information for this buffer
991 (set 'buffer-undo-list t)
992 (set 'notmuch-search-query-string query)
993 (set 'notmuch-search-oldest-first oldest-first)
994 (set 'notmuch-search-target-thread target-thread)
995 (set 'notmuch-search-target-line target-line)
996 (set 'notmuch-search-continuation continuation)
997 (let ((proc (get-buffer-process (current-buffer)))
998 (inhibit-read-only t))
1000 (error "notmuch search process already running for query `%s'" query)
1003 (goto-char (point-min))
1005 (let ((proc (start-process
1006 "notmuch-search" buffer
1007 notmuch-command "search"
1009 "--sort=oldest-first"
1010 "--sort=newest-first")
1012 (set-process-sentinel proc 'notmuch-search-process-sentinel)
1013 (set-process-filter proc 'notmuch-search-process-filter)
1014 (set-process-query-on-exit-flag proc nil))))
1015 (run-hooks 'notmuch-search-hook)))
1017 (defun notmuch-search-refresh-view ()
1018 "Refresh the current view.
1020 Kills the current buffer and runs a new search with the same
1021 query string as the current search. If the current thread is in
1022 the new search results, then point will be placed on the same
1023 thread. Otherwise, point will be moved to attempt to be in the
1024 same relative position within the new buffer."
1026 (let ((target-line (line-number-at-pos))
1027 (oldest-first notmuch-search-oldest-first)
1028 (target-thread (notmuch-search-find-thread-id))
1029 (query notmuch-search-query-string)
1030 (continuation notmuch-search-continuation))
1031 (notmuch-kill-this-buffer)
1032 (notmuch-search query oldest-first target-thread target-line continuation)
1033 (goto-char (point-min))))
1035 (defcustom notmuch-poll-script nil
1036 "An external script to incorporate new mail into the notmuch database.
1038 This variable controls the action invoked by
1039 `notmuch-search-poll-and-refresh-view' and
1040 `notmuch-hello-poll-and-update' (each have a default keybinding
1041 of 'G') to incorporate new mail into the notmuch database.
1043 If set to nil (the default), new mail is processed by invoking
1044 \"notmuch new\". Otherwise, this should be set to a string that
1045 gives the name of an external script that processes new mail. If
1046 set to the empty string, no command will be run.
1048 The external script could do any of the following depending on
1051 1. Invoke a program to transfer mail to the local mail store
1052 2. Invoke \"notmuch new\" to incorporate the new mail
1053 3. Invoke one or more \"notmuch tag\" commands to classify the mail
1055 Note that the recommended way of achieving the same is using
1056 \"notmuch new\" hooks."
1057 :type '(choice (const :tag "notmuch new" nil)
1058 (const :tag "Disabled" "")
1059 (string :tag "Custom script"))
1060 :group 'notmuch-external)
1062 (defun notmuch-poll ()
1063 "Run \"notmuch new\" or an external script to import mail.
1065 Invokes `notmuch-poll-script', \"notmuch new\", or does nothing
1066 depending on the value of `notmuch-poll-script'."
1068 (if (stringp notmuch-poll-script)
1069 (unless (string= notmuch-poll-script "")
1070 (call-process notmuch-poll-script nil nil))
1071 (call-process notmuch-command nil nil nil "new")))
1073 (defun notmuch-search-poll-and-refresh-view ()
1074 "Invoke `notmuch-poll' to import mail, then refresh the current view."
1077 (notmuch-search-refresh-view))
1079 (defun notmuch-search-toggle-order ()
1080 "Toggle the current search order.
1082 By default, the \"inbox\" view created by `notmuch' is displayed
1083 in chronological order (oldest thread at the beginning of the
1084 buffer), while any global searches created by `notmuch-search'
1085 are displayed in reverse-chronological order (newest thread at
1086 the beginning of the buffer).
1088 This command toggles the sort order for the current search.
1090 Note that any filtered searches created by
1091 `notmuch-search-filter' retain the search order of the parent
1094 (set 'notmuch-search-oldest-first (not notmuch-search-oldest-first))
1095 (notmuch-search-refresh-view))
1097 (defun notmuch-search-filter (query)
1098 "Filter the current search results based on an additional query string.
1100 Runs a new search matching only messages that match both the
1101 current search results AND the additional query string provided."
1102 (interactive (list (notmuch-read-query "Filter search: ")))
1103 (let ((grouped-query (if (string-match-p notmuch-search-disjunctive-regexp query)
1104 (concat "( " query " )")
1106 (notmuch-search (if (string= notmuch-search-query-string "*")
1108 (concat notmuch-search-query-string " and " grouped-query)) notmuch-search-oldest-first)))
1110 (defun notmuch-search-filter-by-tag (tag)
1111 "Filter the current search results based on a single tag.
1113 Runs a new search matching only messages that match both the
1114 current search results AND that are tagged with the given tag."
1116 (list (notmuch-select-tag-with-completion "Filter by tag: ")))
1117 (notmuch-search (concat notmuch-search-query-string " and tag:" tag) notmuch-search-oldest-first))
1121 "Run notmuch and display saved searches, known tags, etc."
1125 (defun notmuch-interesting-buffer (b)
1126 "Is the current buffer of interest to a notmuch user?"
1127 (with-current-buffer b
1128 (memq major-mode '(notmuch-show-mode
1134 (defun notmuch-cycle-notmuch-buffers ()
1135 "Cycle through any existing notmuch buffers (search, show or hello).
1137 If the current buffer is the only notmuch buffer, bury it. If no
1138 notmuch buffers exist, run `notmuch'."
1142 ;; If the current buffer is a notmuch buffer, remember it and then
1144 (when (notmuch-interesting-buffer (current-buffer))
1145 (setq start (current-buffer))
1148 ;; Find the first notmuch buffer.
1149 (setq first (loop for buffer in (buffer-list)
1150 if (notmuch-interesting-buffer buffer)
1154 ;; If the first one we found is any other than the starting
1155 ;; buffer, switch to it.
1156 (unless (eq first start)
1157 (switch-to-buffer first))
1160 (setq mail-user-agent 'notmuch-user-agent)