1 ;;; notmuch.el --- run notmuch within emacs -*- lexical-binding: t -*-
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 <https://www.gnu.org/licenses/>.
20 ;; Authors: Carl Worth <cworth@cworth.org>
21 ;; Homepage: https://notmuchmail.org
25 ;; This is an emacs-based interface to the notmuch mail system.
27 ;; You will first need to have the notmuch program installed and have a
28 ;; notmuch database built in order to use this. See
29 ;; https://notmuchmail.org for details.
31 ;; To install this software, copy it to a directory that is on the
32 ;; `load-path' variable within emacs (a good candidate is
33 ;; /usr/local/share/emacs/site-lisp). If you are viewing this from the
34 ;; notmuch source distribution then you can simply run:
36 ;; sudo make install-emacs
40 ;; Then, to actually run it, add:
42 ;; (autoload 'notmuch "notmuch" "Notmuch mail" t)
44 ;; to your ~/.emacs file, and then run "M-x notmuch" from within emacs,
49 ;; Have fun, and let us know if you have any comment, questions, or
50 ;; kudos: Notmuch list <notmuch@notmuchmail.org> (subscription is not
51 ;; required, but is available from https://notmuchmail.org).
53 ;; Note for MELPA users (and others tracking the development version
56 ;; This emacs package needs a fairly closely matched version of the
57 ;; notmuch program. If you use the MELPA version of notmuch.el (as
58 ;; opposed to MELPA stable), you should be prepared to track the
59 ;; master development branch (i.e. build from git) for the notmuch
60 ;; program as well. Upgrading notmuch-emacs too far beyond the notmuch
61 ;; program can CAUSE YOUR EMAIL TO STOP WORKING.
63 ;; TL;DR: notmuch-emacs from MELPA and notmuch from distro packages is
68 (eval-when-compile (require 'cl-lib))
73 (require 'notmuch-lib)
74 (require 'notmuch-tag)
75 (require 'notmuch-show)
76 (require 'notmuch-tree)
77 (require 'notmuch-mua)
78 (require 'notmuch-hello)
79 (require 'notmuch-maildir-fcc)
80 (require 'notmuch-message)
81 (require 'notmuch-parser)
85 (defcustom notmuch-search-result-format
88 ("authors" . "%-20s ")
91 "Search result formatting. Supported fields are:
92 date, count, authors, subject, tags
94 (setq notmuch-search-result-format \(\(\"authors\" . \"%-40s\"\)
95 \(\"subject\" . \"%s\"\)\)\)
96 Line breaks are permitted in format strings (though this is
97 currently experimental). Note that a line break at the end of an
98 \"authors\" field will get elided if the authors list is long;
99 place it instead at the beginning of the following field. To
100 enter a line break when setting this variable with setq, use \\n.
101 To enter a line break in customize, press \\[quoted-insert] C-j."
102 :type '(alist :key-type (string) :value-type (string))
103 :group 'notmuch-search)
105 ;; The name of this variable `notmuch-init-file' is consistent with the
106 ;; convention used in e.g. emacs and gnus. The value, `notmuch-config[.el[c]]'
107 ;; is consistent with notmuch cli configuration file `~/.notmuch-config'.
108 (defcustom notmuch-init-file (locate-user-emacs-file "notmuch-config")
109 "Your Notmuch Emacs-Lisp configuration file name.
110 If a file with one of the suffixes defined by `get-load-suffixes' exists,
111 it will be read instead.
112 This file is read once when notmuch is loaded; the notmuch hooks added
113 there will be called at other points of notmuch execution."
117 (defvar notmuch-query-history nil
118 "Variable to store minibuffer history for notmuch queries.")
122 (defun notmuch-foreach-mime-part (function mm-handle)
123 (cond ((stringp (car mm-handle))
124 (dolist (part (cdr mm-handle))
125 (notmuch-foreach-mime-part function part)))
126 ((bufferp (car mm-handle))
127 (funcall function mm-handle))
128 (t (dolist (part mm-handle)
129 (notmuch-foreach-mime-part function part)))))
131 (defun notmuch-count-attachments (mm-handle)
133 (notmuch-foreach-mime-part
135 (let ((disposition (mm-handle-disposition p)))
136 (and (listp disposition)
137 (or (equal (car disposition) "attachment")
138 (and (equal (car disposition) "inline")
139 (assq 'filename disposition)))
144 (defun notmuch-save-attachments (mm-handle &optional queryp)
145 (notmuch-foreach-mime-part
147 (let ((disposition (mm-handle-disposition p)))
148 (and (listp disposition)
149 (or (equal (car disposition) "attachment")
150 (and (equal (car disposition) "inline")
151 (assq 'filename disposition)))
154 (concat "Save '" (cdr (assq 'filename disposition)) "' ")))
162 (defun notmuch-hl-line-mode ()
163 (prog1 (hl-line-mode)
164 (when hl-line-overlay
165 (overlay-put hl-line-overlay 'priority 1))))
169 (defcustom notmuch-search-hook '(notmuch-hl-line-mode)
170 "List of functions to call when notmuch displays the search results."
172 :options '(notmuch-hl-line-mode)
173 :group 'notmuch-search
174 :group 'notmuch-hooks)
178 (defvar notmuch-search-mode-map
179 (let ((map (make-sparse-keymap)))
180 (set-keymap-parent map notmuch-common-keymap)
181 (define-key map "x" 'notmuch-bury-or-kill-this-buffer)
182 (define-key map (kbd "DEL") 'notmuch-search-scroll-down)
183 (define-key map "b" 'notmuch-search-scroll-down)
184 (define-key map " " 'notmuch-search-scroll-up)
185 (define-key map "<" 'notmuch-search-first-thread)
186 (define-key map ">" 'notmuch-search-last-thread)
187 (define-key map "p" 'notmuch-search-previous-thread)
188 (define-key map "n" 'notmuch-search-next-thread)
189 (define-key map "r" 'notmuch-search-reply-to-thread-sender)
190 (define-key map "R" 'notmuch-search-reply-to-thread)
191 (define-key map "o" 'notmuch-search-toggle-order)
192 (define-key map "c" 'notmuch-search-stash-map)
193 (define-key map "t" 'notmuch-search-filter-by-tag)
194 (define-key map "l" 'notmuch-search-filter)
195 (define-key map [mouse-1] 'notmuch-search-show-thread)
196 (define-key map "k" 'notmuch-tag-jump)
197 (define-key map "*" 'notmuch-search-tag-all)
198 (define-key map "a" 'notmuch-search-archive-thread)
199 (define-key map "-" 'notmuch-search-remove-tag)
200 (define-key map "+" 'notmuch-search-add-tag)
201 (define-key map (kbd "RET") 'notmuch-search-show-thread)
202 (define-key map (kbd "M-RET") 'notmuch-tree-from-search-thread)
203 (define-key map "Z" 'notmuch-tree-from-search-current-query)
204 (define-key map "U" 'notmuch-unthreaded-from-search-current-query)
206 "Keymap for \"notmuch search\" buffers.")
208 ;;; Internal Variables
210 (defvar-local notmuch-search-query-string nil)
211 (defvar-local notmuch-search-target-thread nil)
212 (defvar-local notmuch-search-target-line nil)
216 (defvar notmuch-search-stash-map
217 (let ((map (make-sparse-keymap)))
218 (define-key map "i" 'notmuch-search-stash-thread-id)
219 (define-key map "q" 'notmuch-stash-query)
220 (define-key map "?" 'notmuch-subkeymap-help)
222 "Submap for stash commands.")
223 (fset 'notmuch-search-stash-map notmuch-search-stash-map)
225 (defun notmuch-search-stash-thread-id ()
226 "Copy thread ID of current thread to kill-ring."
228 (notmuch-common-do-stash (notmuch-search-find-thread-id)))
230 (defun notmuch-stash-query ()
231 "Copy current query to kill-ring."
233 (notmuch-common-do-stash (notmuch-search-get-query)))
237 (defun notmuch-search-scroll-up ()
238 "Move forward through search results by one window's worth."
242 ((end-of-buffer) (notmuch-search-last-thread))))
244 (defun notmuch-search-scroll-down ()
245 "Move backward through the search results by one window's worth."
247 ;; I don't know why scroll-down doesn't signal beginning-of-buffer
248 ;; the way that scroll-up signals end-of-buffer, but c'est la vie.
250 ;; So instead of trapping a signal we instead check whether the
251 ;; window begins on the first line of the buffer and if so, move
252 ;; directly to that position. (We have to count lines since the
253 ;; window-start position is not the same as point-min due to the
254 ;; invisible thread-ID characters on the first line.
255 (if (equal (count-lines (point-min) (window-start)) 0)
256 (goto-char (point-min))
259 (defun notmuch-search-next-thread ()
260 "Select the next thread in the search results."
262 (when (notmuch-search-get-result)
263 (goto-char (notmuch-search-result-end))))
265 (defun notmuch-search-previous-thread ()
266 "Select the previous thread in the search results."
268 (if (notmuch-search-get-result)
270 (goto-char (notmuch-search-result-beginning (- (point) 1))))
271 ;; We must be past the end; jump to the last result
272 (notmuch-search-last-thread)))
274 (defun notmuch-search-last-thread ()
275 "Select the last thread in the search results."
277 (goto-char (point-max))
279 (let ((beg (notmuch-search-result-beginning)))
283 (defun notmuch-search-first-thread ()
284 "Select the first thread in the search results."
286 (goto-char (point-min)))
290 (defface notmuch-message-summary-face
291 `((((class color) (background light))
292 ,@(and (>= emacs-major-version 27) '(:extend t))
293 :background "#f0f0f0")
294 (((class color) (background dark))
295 ,@(and (>= emacs-major-version 27) '(:extend t))
296 :background "#303030"))
297 "Face for the single-line message summary in notmuch-show-mode."
299 :group 'notmuch-faces)
301 (defface notmuch-search-date
302 '((t :inherit default))
303 "Face used in search mode for dates."
304 :group 'notmuch-search
305 :group 'notmuch-faces)
307 (defface notmuch-search-count
308 '((t :inherit default))
309 "Face used in search mode for the count matching the query."
310 :group 'notmuch-search
311 :group 'notmuch-faces)
313 (defface notmuch-search-subject
314 '((t :inherit default))
315 "Face used in search mode for subjects."
316 :group 'notmuch-search
317 :group 'notmuch-faces)
319 (defface notmuch-search-matching-authors
320 '((t :inherit default))
321 "Face used in search mode for authors matching the query."
322 :group 'notmuch-search
323 :group 'notmuch-faces)
325 (defface notmuch-search-non-matching-authors
328 (:foreground "grey30"))
331 (:foreground "grey60"))
334 "Face used in search mode for authors not matching the query."
335 :group 'notmuch-search
336 :group 'notmuch-faces)
338 (defface notmuch-tag-face
341 (:foreground "OliveDrab1"))
344 (:foreground "navy blue" :bold t))
347 "Face used in search mode face for tags."
348 :group 'notmuch-search
349 :group 'notmuch-faces)
351 (defface notmuch-search-flagged-face
354 (:foreground "LightBlue1"))
357 (:foreground "blue")))
358 "Face used in search mode face for flagged threads.
360 This face is the default value for the \"flagged\" tag in
361 `notmuch-search-line-faces'."
362 :group 'notmuch-search
363 :group 'notmuch-faces)
365 (defface notmuch-search-unread-face
368 "Face used in search mode for unread threads.
370 This face is the default value for the \"unread\" tag in
371 `notmuch-search-line-faces'."
372 :group 'notmuch-search
373 :group 'notmuch-faces)
377 (define-derived-mode notmuch-search-mode fundamental-mode "notmuch-search"
378 "Major mode displaying results of a notmuch search.
380 This buffer contains the results of a \"notmuch search\" of your
381 email archives. Each line in the buffer represents a single
382 thread giving a summary of the thread (a relative date, the
383 number of matched messages and total messages in the thread,
384 participants in the thread, a representative subject line, and
387 Pressing \\[notmuch-search-show-thread] on any line displays that
388 thread. The '\\[notmuch-search-add-tag]' and
389 '\\[notmuch-search-remove-tag]' keys can be used to add or remove
390 tags from a thread. The '\\[notmuch-search-archive-thread]' key
391 is a convenience for archiving a thread (applying changes in
392 `notmuch-archive-tags'). The '\\[notmuch-search-tag-all]' key can
393 be used to add and/or remove tags from all messages (as opposed
394 to threads) that match the current query. Use with caution, as
395 this will also tag matching messages that arrived *after*
396 constructing the buffer.
398 Other useful commands are '\\[notmuch-search-filter]' for
399 filtering the current search based on an additional query string,
400 '\\[notmuch-search-filter-by-tag]' for filtering to include only
401 messages with a given tag, and '\\[notmuch-search]' to execute a
404 Complete list of currently available key bindings:
406 \\{notmuch-search-mode-map}"
407 (setq notmuch-buffer-refresh-function #'notmuch-search-refresh-view)
408 (setq-local scroll-preserve-screen-position t)
409 (add-to-invisibility-spec (cons 'ellipsis t))
410 (setq truncate-lines t)
411 (setq buffer-read-only t)
412 (setq imenu-prev-index-position-function
413 #'notmuch-search-imenu-prev-index-position-function)
414 (setq imenu-extract-index-name-function
415 #'notmuch-search-imenu-extract-index-name-function))
419 (defun notmuch-search-get-result (&optional pos)
420 "Return the result object for the thread at POS (or point).
422 If there is no thread at POS (or point), returns nil."
423 (get-text-property (or pos (point)) 'notmuch-search-result))
425 (defun notmuch-search-result-beginning (&optional pos)
426 "Return the point at the beginning of the thread at POS (or point).
428 If there is no thread at POS (or point), returns nil."
429 (and (notmuch-search-get-result pos)
430 ;; We pass 1+point because previous-single-property-change starts
431 ;; searching one before the position we give it.
432 (previous-single-property-change (1+ (or pos (point)))
433 'notmuch-search-result nil
436 (defun notmuch-search-result-end (&optional pos)
437 "Return the point at the end of the thread at POS (or point).
439 The returned point will be just after the newline character that
440 ends the result line. If there is no thread at POS (or point),
442 (and (notmuch-search-get-result pos)
443 (next-single-property-change (or pos (point))
444 'notmuch-search-result nil
447 (defun notmuch-search-foreach-result (beg end fn)
448 "Invoke FN for each result between BEG and END.
450 FN should take one argument. It will be applied to the character
451 position of the beginning of each result that overlaps the region
452 between points BEG and END. As a special case, if (= BEG END),
453 FN will be applied to the result containing point BEG."
454 (let ((pos (notmuch-search-result-beginning beg))
455 ;; End must be a marker in case fn changes the
457 (end (copy-marker end))
458 ;; Make sure we examine at least one result, even if
461 ;; We have to be careful if the region extends beyond the results.
462 ;; In this case, pos could be null or there could be no result at
464 (while (and pos (or (< pos end) first))
465 (when (notmuch-search-get-result pos)
467 (setq pos (notmuch-search-result-end pos))
469 ;; Unindent the function argument of notmuch-search-foreach-result so
470 ;; the indentation of callers doesn't get out of hand.
471 (put 'notmuch-search-foreach-result 'lisp-indent-function 2)
473 (defun notmuch-search-properties-in-region (property beg end)
475 (notmuch-search-foreach-result beg end
477 (push (plist-get (notmuch-search-get-result pos) property) output)))
480 (defun notmuch-search-find-thread-id (&optional bare)
481 "Return the thread for the current thread.
483 If BARE is set then do not prefix with \"thread:\"."
484 (let ((thread (plist-get (notmuch-search-get-result) :thread)))
486 (concat (and (not bare) "thread:") thread))))
488 (defun notmuch-search-find-stable-query ()
489 "Return the stable queries for the current thread.
491 Return a list (MATCHED-QUERY UNMATCHED-QUERY) for the
492 matched and unmatched messages in the current thread."
493 (plist-get (notmuch-search-get-result) :query))
495 (defun notmuch-search-find-stable-query-region (beg end &optional only-matched)
496 "Return the stable query for the current region.
498 If ONLY-MATCHED is non-nil, include only matched messages. If it
499 is nil, include both matched and unmatched messages. If there are
500 no messages in the region then return nil."
501 (let ((query-list nil) (all (not only-matched)))
502 (dolist (queries (notmuch-search-properties-in-region :query beg end))
504 (push (car queries) query-list))
505 (when (and all (cadr queries))
506 (push (cadr queries) query-list)))
508 (concat "(" (mapconcat 'identity query-list ") or (") ")"))))
510 (defun notmuch-search-find-authors ()
511 "Return the authors for the current thread."
512 (plist-get (notmuch-search-get-result) :authors))
514 (defun notmuch-search-find-authors-region (beg end)
515 "Return a list of authors for the current region."
516 (notmuch-search-properties-in-region :authors beg end))
518 (defun notmuch-search-find-subject ()
519 "Return the subject for the current thread."
520 (plist-get (notmuch-search-get-result) :subject))
522 (defun notmuch-search-find-subject-region (beg end)
523 "Return a list of authors for the current region."
524 (notmuch-search-properties-in-region :subject beg end))
526 (defun notmuch-search-show-thread (&optional elide-toggle)
527 "Display the currently selected thread.
529 With a prefix argument, invert the default value of
530 `notmuch-show-only-matching-messages' when displaying the
533 (let ((thread-id (notmuch-search-find-thread-id))
534 (subject (notmuch-search-find-subject)))
535 (if (> (length thread-id) 0)
536 (notmuch-show thread-id
539 notmuch-search-query-string
540 ;; Name the buffer based on the subject.
542 (truncate-string-to-width subject 30 nil nil t)
544 (message "End of search results."))))
546 (defun notmuch-tree-from-search-current-query ()
547 "Call notmuch tree with the current query."
549 (notmuch-tree notmuch-search-query-string))
551 (defun notmuch-unthreaded-from-search-current-query ()
552 "Call notmuch tree with the current query."
554 (notmuch-unthreaded notmuch-search-query-string))
556 (defun notmuch-tree-from-search-thread ()
557 "Show the selected thread with notmuch-tree."
559 (notmuch-tree (notmuch-search-find-thread-id)
560 notmuch-search-query-string
562 (notmuch-prettify-subject (notmuch-search-find-subject))
563 t nil (current-buffer)))
565 (defun notmuch-search-reply-to-thread (&optional prompt-for-sender)
566 "Begin composing a reply-all to the entire current thread in a new buffer."
568 (let ((message-id (notmuch-search-find-thread-id)))
569 (notmuch-mua-new-reply message-id prompt-for-sender t)))
571 (defun notmuch-search-reply-to-thread-sender (&optional prompt-for-sender)
572 "Begin composing a reply to the entire current thread in a new buffer."
574 (let ((message-id (notmuch-search-find-thread-id)))
575 (notmuch-mua-new-reply message-id prompt-for-sender nil)))
579 (defun notmuch-search-set-tags (tags &optional pos)
580 (let ((new-result (plist-put (notmuch-search-get-result pos) :tags tags)))
581 (notmuch-search-update-result new-result pos)))
583 (defun notmuch-search-get-tags (&optional pos)
584 (plist-get (notmuch-search-get-result pos) :tags))
586 (defun notmuch-search-get-tags-region (beg end)
588 (notmuch-search-foreach-result beg end
590 (setq output (append output (notmuch-search-get-tags pos)))))
593 (defun notmuch-search-interactive-tag-changes (&optional initial-input)
594 "Prompt for tag changes for the current thread or region.
596 Return (TAG-CHANGES REGION-BEGIN REGION-END)."
597 (pcase-let ((`(,beg ,end) (notmuch-interactive-region)))
598 (list (notmuch-read-tag-changes (notmuch-search-get-tags-region beg end)
599 (if (= beg end) "Tag thread" "Tag region")
603 (defun notmuch-search-tag (tag-changes &optional beg end only-matched)
604 "Change tags for the currently selected thread or region.
606 See `notmuch-tag' for information on the format of TAG-CHANGES.
607 When called interactively, this uses the region if the region is
608 active. When called directly, BEG and END provide the region.
609 If these are nil or not provided, then, if the region is active
610 this applied to all threads meeting the region, and if the region
611 is inactive this applies to the thread at point.
613 If ONLY-MATCHED is non-nil, only tag matched messages."
614 (interactive (notmuch-search-interactive-tag-changes))
615 (unless (and beg end)
616 (setq beg (car (notmuch-interactive-region)))
617 (setq end (cadr (notmuch-interactive-region))))
618 (let ((search-string (notmuch-search-find-stable-query-region
619 beg end only-matched)))
620 (notmuch-tag search-string tag-changes)
621 (notmuch-search-foreach-result beg end
623 (notmuch-search-set-tags
624 (notmuch-update-tags (notmuch-search-get-tags pos) tag-changes)
627 (defun notmuch-search-add-tag (tag-changes &optional beg end)
628 "Change tags for the current thread or region (defaulting to add).
630 Same as `notmuch-search-tag' but sets initial input to '+'."
631 (interactive (notmuch-search-interactive-tag-changes "+"))
632 (notmuch-search-tag tag-changes beg end))
634 (defun notmuch-search-remove-tag (tag-changes &optional beg end)
635 "Change tags for the current thread or region (defaulting to remove).
637 Same as `notmuch-search-tag' but sets initial input to '-'."
638 (interactive (notmuch-search-interactive-tag-changes "-"))
639 (notmuch-search-tag tag-changes beg end))
641 (put 'notmuch-search-archive-thread 'notmuch-prefix-doc
642 "Un-archive the currently selected thread.")
643 (defun notmuch-search-archive-thread (&optional unarchive beg end)
644 "Archive the currently selected thread or region.
646 Archive each message in the currently selected thread by applying
647 the tag changes in `notmuch-archive-tags' to each (remove the
648 \"inbox\" tag by default). If a prefix argument is given, the
649 messages will be \"unarchived\" (i.e. the tag changes in
650 `notmuch-archive-tags' will be reversed).
652 This function advances the next thread when finished."
653 (interactive (cons current-prefix-arg (notmuch-interactive-region)))
654 (when notmuch-archive-tags
656 (notmuch-tag-change-list notmuch-archive-tags unarchive) beg end))
658 (notmuch-search-next-thread)))
662 (defun notmuch-search-update-result (result &optional pos)
663 "Replace the result object of the thread at POS (or point) by
664 RESULT and redraw it.
666 This will keep point in a reasonable location. However, if there
667 are enclosing save-excursions and the saved point is in the
668 result being updated, the point will be restored to the beginning
670 (let ((start (notmuch-search-result-beginning pos))
671 (end (notmuch-search-result-end pos))
673 (inhibit-read-only t))
674 ;; Delete the current thread
675 (delete-region start end)
676 ;; Insert the updated thread
677 (notmuch-search-show-result result start)
678 ;; If point was inside the old result, make an educated guess
679 ;; about where to place it now. Unfortunately, this won't work
680 ;; with save-excursion (or any other markers that would be nice to
681 ;; preserve, such as the window start), but there's nothing we can
682 ;; do about that without a way to retrieve markers in a region.
683 (when (and (>= init-point start) (<= init-point end))
684 (let* ((new-end (notmuch-search-result-end start))
685 (new-point (if (= init-point end)
687 (min init-point (- new-end 1)))))
688 (goto-char new-point)))))
690 (defun notmuch-search-process-sentinel (proc _msg)
691 "Add a message to let user know when \"notmuch search\" exits."
692 (let ((buffer (process-buffer proc))
693 (status (process-status proc))
694 (exit-status (process-exit-status proc))
695 (never-found-target-thread nil))
696 (when (memq status '(exit signal))
698 (kill-buffer (process-get proc 'parse-buf))
699 (when (buffer-live-p buffer)
700 (with-current-buffer buffer
702 (let ((inhibit-read-only t)
704 (goto-char (point-max))
705 (when (eq status 'signal)
706 (insert "Incomplete search results (search process was killed).\n"))
707 (when (eq status 'exit)
708 (insert "End of search results.\n")
709 ;; For version mismatch, there's no point in
710 ;; showing the search buffer
711 (when (or (= exit-status 20) (= exit-status 21))
715 (not (string= notmuch-search-target-thread "found")))
716 (setq never-found-target-thread t)))))
717 (when (and never-found-target-thread
718 notmuch-search-target-line)
719 (goto-char (point-min))
720 (forward-line (1- notmuch-search-target-line)))))))))
722 (define-widget 'notmuch--custom-face-edit 'lazy
723 "Custom face edit with a tag Edit Face"
724 ;; I could not persuage custom-face-edit to respect the :tag
725 ;; property so create a widget specially
726 :tag "Manually specify face"
727 :type 'custom-face-edit)
729 (defcustom notmuch-search-line-faces
730 '(("unread" . notmuch-search-unread-face)
731 ("flagged" . notmuch-search-flagged-face))
732 "Alist of tags to faces for line highlighting in notmuch-search.
733 Each element looks like (TAG . FACE).
734 A thread with TAG will have FACE applied.
736 Here is an example of how to color search results based on tags.
737 (the following text would be placed in your ~/.emacs file):
739 (setq notmuch-search-line-faces \\='((\"unread\" . (:foreground \"green\"))
740 (\"deleted\" . (:foreground \"red\"
741 :background \"blue\"))))
743 The FACE must be a face name (a symbol or string), a property
744 list of face attributes, or a list of these. The faces for
745 matching tags are merged, with earlier attributes overriding
746 later. A message having both \"deleted\" and \"unread\" tags with
747 the above settings would have a green foreground and blue
749 :type '(alist :key-type (string)
750 :value-type (radio (face :tag "Face name")
751 (notmuch--custom-face-edit)))
752 :group 'notmuch-search
753 :group 'notmuch-faces)
755 (defun notmuch-search-color-line (start end line-tag-list)
756 "Colorize lines in `notmuch-show' based on tags."
757 ;; Reverse the list so earlier entries take precedence
758 (dolist (elem (reverse notmuch-search-line-faces))
759 (let ((tag (car elem))
761 (when (member tag line-tag-list)
762 (notmuch-apply-face nil face nil start end)))))
764 (defun notmuch-search-author-propertize (authors)
765 "Split `authors' into matching and non-matching authors and
766 propertize appropriately. If no boundary between authors and
767 non-authors is found, assume that all of the authors match."
768 (if (string-match "\\(.*\\)|\\(.*\\)" authors)
769 (concat (propertize (concat (match-string 1 authors) ",")
770 'face 'notmuch-search-matching-authors)
771 (propertize (match-string 2 authors)
772 'face 'notmuch-search-non-matching-authors))
773 (propertize authors 'face 'notmuch-search-matching-authors)))
775 (defun notmuch-search-insert-authors (format-string authors)
776 ;; Save the match data to avoid interfering with
777 ;; `notmuch-search-process-filter'.
779 (let* ((formatted-authors (format format-string authors))
780 (formatted-sample (format format-string ""))
781 (visible-string formatted-authors)
782 (invisible-string "")
784 ;; Truncate the author string to fit the specification.
785 (when (> (length formatted-authors)
786 (length formatted-sample))
787 (let ((visible-length (- (length formatted-sample)
789 ;; Truncate the visible string according to the width of
790 ;; the display string.
791 (setq visible-string (substring formatted-authors 0 visible-length))
792 (setq invisible-string (substring formatted-authors visible-length))
793 ;; If possible, truncate the visible string at a natural
794 ;; break (comma or pipe), as incremental search doesn't
795 ;; match across the visible/invisible border.
796 (when (string-match "\\(.*\\)\\([,|] \\)\\([^,|]*\\)" visible-string)
797 ;; Second clause is destructive on `visible-string', so
798 ;; order is important.
799 (setq invisible-string (concat (match-string 3 visible-string)
801 (setq visible-string (concat (match-string 1 visible-string)
802 (match-string 2 visible-string))))
803 ;; `visible-string' may be shorter than the space allowed
804 ;; by `format-string'. If so we must insert some padding
805 ;; after `invisible-string'.
806 (setq padding (make-string (- (length formatted-sample)
807 (length visible-string)
810 ;; Use different faces to show matching and non-matching authors.
811 (if (string-match "\\(.*\\)|\\(.*\\)" visible-string)
812 ;; The visible string contains both matching and
813 ;; non-matching authors.
815 (setq visible-string (notmuch-search-author-propertize visible-string))
816 ;; The invisible string must contain only non-matching
817 ;; authors, as the visible-string contains both.
818 (setq invisible-string (propertize invisible-string
819 'face 'notmuch-search-non-matching-authors)))
820 ;; The visible string contains only matching authors.
821 (setq visible-string (propertize visible-string
822 'face 'notmuch-search-matching-authors))
823 ;; The invisible string may contain both matching and
824 ;; non-matching authors.
825 (setq invisible-string (notmuch-search-author-propertize invisible-string)))
826 ;; If there is any invisible text, add it as a tooltip to the
828 (unless (string= invisible-string "")
830 (propertize visible-string
831 'help-echo (concat "..." invisible-string))))
832 ;; Insert the visible and, if present, invisible author strings.
833 (insert visible-string)
834 (unless (string= invisible-string "")
835 (let ((start (point))
837 (insert invisible-string)
838 (setq overlay (make-overlay start (point)))
839 (overlay-put overlay 'invisible 'ellipsis)
840 (overlay-put overlay 'isearch-open-invisible #'delete-overlay)))
843 (defun notmuch-search-insert-field (field format-string result)
845 ((string-equal field "date")
846 (insert (propertize (format format-string (plist-get result :date_relative))
847 'face 'notmuch-search-date)))
848 ((string-equal field "count")
849 (insert (propertize (format format-string
850 (format "[%s/%s]" (plist-get result :matched)
851 (plist-get result :total)))
852 'face 'notmuch-search-count)))
853 ((string-equal field "subject")
854 (insert (propertize (format format-string
855 (notmuch-sanitize (plist-get result :subject)))
856 'face 'notmuch-search-subject)))
857 ((string-equal field "authors")
858 (notmuch-search-insert-authors
859 format-string (notmuch-sanitize (plist-get result :authors))))
860 ((string-equal field "tags")
861 (let ((tags (plist-get result :tags))
862 (orig-tags (plist-get result :orig-tags)))
863 (insert (format format-string (notmuch-tag-format-tags tags orig-tags)))))))
865 (defun notmuch-search-show-result (result pos)
866 "Insert RESULT at POS."
867 ;; Ignore excluded matches
868 (unless (= (plist-get result :matched) 0)
871 (dolist (spec notmuch-search-result-format)
872 (notmuch-search-insert-field (car spec) (cdr spec) result))
874 (notmuch-search-color-line pos (point) (plist-get result :tags))
875 (put-text-property pos (point) 'notmuch-search-result result))))
877 (defun notmuch-search-append-result (result)
878 "Insert RESULT at the end of the buffer.
880 This is only called when a result is first inserted so it also
881 sets the :orig-tag property."
882 (let ((new-result (plist-put result :orig-tags (plist-get result :tags)))
884 (notmuch-search-show-result new-result pos)
885 (when (string= (plist-get result :thread) notmuch-search-target-thread)
886 (setq notmuch-search-target-thread "found")
889 (defun notmuch-search-process-filter (proc string)
890 "Process and filter the output of \"notmuch search\"."
891 (let ((results-buf (process-buffer proc))
892 (parse-buf (process-get proc 'parse-buf))
893 (inhibit-read-only t))
894 (when (buffer-live-p results-buf)
895 (with-current-buffer parse-buf
898 (goto-char (point-max))
900 (notmuch-sexp-parse-partial-list 'notmuch-search-append-result
903 ;;; Commands (and some helper functions used by them)
905 (defun notmuch-search-tag-all (tag-changes)
906 "Add/remove tags from all messages in current search buffer.
908 See `notmuch-tag' for information on the format of TAG-CHANGES."
910 (list (notmuch-read-tag-changes
911 (notmuch-search-get-tags-region (point-min) (point-max)) "Tag all")))
912 (notmuch-search-tag tag-changes (point-min) (point-max) t))
914 (defun notmuch-search-buffer-title (query)
915 "Returns the title for a buffer with notmuch search results."
919 (cl-loop for tuple in notmuch-saved-searches
920 if (let ((quoted-query
922 (notmuch-saved-search-get tuple :query))))
923 (and (string-match (concat "^" quoted-query) query)
924 (> (length (match-string 0 query))
926 do (setq longest tuple))
928 (saved-search-name (notmuch-saved-search-get saved-search :name))
929 (saved-search-query (notmuch-saved-search-get saved-search :query)))
930 (cond ((and saved-search (equal saved-search-query query))
931 ;; Query is the same as saved search (ignoring case)
932 (concat "*notmuch-saved-search-" saved-search-name "*"))
934 (concat "*notmuch-search-"
935 (replace-regexp-in-string
936 (concat "^" (regexp-quote saved-search-query))
937 (concat "[ " saved-search-name " ]")
941 (concat "*notmuch-search-" query "*")))))
943 (defun notmuch-read-query (prompt)
944 "Read a notmuch-query from the minibuffer with completion.
946 PROMPT is the string to prompt with."
948 (mapcar (lambda (tag) (notmuch-escape-boolean-term tag))
949 (process-lines notmuch-command "search" "--output=tags" "*")))
951 (append (list "folder:" "path:" "thread:" "id:" "date:" "from:" "to:"
952 "subject:" "attachment:")
953 (mapcar (lambda (tag) (concat "tag:" tag)) all-tags)
954 (mapcar (lambda (tag) (concat "is:" tag)) all-tags)
955 (mapcar (lambda (mimetype) (concat "mimetype:" mimetype))
956 (mailcap-mime-types))))
957 (keymap (copy-keymap minibuffer-local-map))
958 (current-query (cl-case major-mode
959 (notmuch-search-mode (notmuch-search-get-query))
960 (notmuch-show-mode (notmuch-show-get-query))
961 (notmuch-tree-mode (notmuch-tree-get-query))))
962 (minibuffer-completion-table
963 (completion-table-dynamic
965 ;; Generate a list of possible completions for the current input.
967 ;; This ugly regexp is used to get the last word of the input
968 ;; possibly preceded by a '('.
969 ((string-match "\\(^\\|.* (?\\)\\([^ ]*\\)$" string)
970 (mapcar (lambda (compl)
971 (concat (match-string-no-properties 1 string) compl))
972 (all-completions (match-string-no-properties 2 string)
974 (t (list string)))))))
975 ;; This was simpler than convincing completing-read to accept spaces:
976 (define-key keymap (kbd "TAB") 'minibuffer-complete)
977 (let ((history-delete-duplicates t))
978 (read-from-minibuffer prompt nil keymap nil
979 'notmuch-search-history current-query nil))))
981 (defun notmuch-search-get-query ()
982 "Return the current query in this search buffer."
983 notmuch-search-query-string)
985 (put 'notmuch-search 'notmuch-doc "Search for messages.")
987 (defun notmuch-search (&optional query oldest-first target-thread target-line no-display)
988 "Display threads matching QUERY in a notmuch-search buffer.
990 If QUERY is nil, it is read interactively from the minibuffer.
991 Other optional parameters are used as follows:
993 OLDEST-FIRST: A Boolean controlling the sort order of returned threads
994 TARGET-THREAD: A thread ID (without the thread: prefix) that will be made
995 current if it appears in the search results.
996 TARGET-LINE: The line number to move to if the target thread does not
997 appear in the search results.
998 NO-DISPLAY: Do not try to foreground the search results buffer. If it is
999 already foregrounded i.e. displayed in a window, this has no
1000 effect, meaning the buffer will remain visible.
1002 When called interactively, this will prompt for a query and use
1003 the configured default sort order."
1006 ;; Prompt for a query
1008 ;; Use the default search order (if we're doing a search from a
1009 ;; search buffer, ignore any buffer-local overrides)
1010 (default-value 'notmuch-search-oldest-first)))
1012 (let* ((query (or query (notmuch-read-query "Notmuch search: ")))
1013 (buffer (get-buffer-create (notmuch-search-buffer-title query))))
1016 (pop-to-buffer-same-window buffer))
1017 (notmuch-search-mode)
1018 ;; Don't track undo information for this buffer
1019 (setq buffer-undo-list t)
1020 (setq notmuch-search-query-string query)
1021 (setq notmuch-search-oldest-first oldest-first)
1022 (setq notmuch-search-target-thread target-thread)
1023 (setq notmuch-search-target-line target-line)
1024 (notmuch-tag-clear-cache)
1025 (let ((proc (get-buffer-process (current-buffer)))
1026 (inhibit-read-only t))
1028 (error "notmuch search process already running for query `%s'" query))
1030 (goto-char (point-min))
1032 (let ((proc (notmuch-start-notmuch
1033 "notmuch-search" buffer #'notmuch-search-process-sentinel
1034 "search" "--format=sexp" "--format-version=4"
1036 "--sort=oldest-first"
1037 "--sort=newest-first")
1039 ;; Use a scratch buffer to accumulate partial output.
1040 ;; This buffer will be killed by the sentinel, which
1041 ;; should be called no matter how the process dies.
1042 (process-put proc 'parse-buf
1043 (generate-new-buffer " *notmuch search parse*"))
1044 (set-process-filter proc 'notmuch-search-process-filter)
1045 (set-process-query-on-exit-flag proc nil))))
1046 (run-hooks 'notmuch-search-hook)))
1048 (defun notmuch-search-refresh-view ()
1049 "Refresh the current view.
1051 Erases the current buffer and runs a new search with the same
1052 query string as the current search. If the current thread is in
1053 the new search results, then point will be placed on the same
1054 thread. Otherwise, point will be moved to attempt to be in the
1055 same relative position within the new buffer."
1057 (let ((target-line (line-number-at-pos))
1058 (oldest-first notmuch-search-oldest-first)
1059 (target-thread (notmuch-search-find-thread-id 'bare))
1060 (query notmuch-search-query-string))
1061 ;; notmuch-search erases the current buffer.
1062 (notmuch-search query oldest-first target-thread target-line t)
1063 (goto-char (point-min))))
1065 (defun notmuch-search-toggle-order ()
1066 "Toggle the current search order.
1068 This command toggles the sort order for the current search. The
1069 default sort order is defined by `notmuch-search-oldest-first'."
1071 (setq notmuch-search-oldest-first (not notmuch-search-oldest-first))
1072 (notmuch-search-refresh-view))
1074 (defun notmuch-group-disjunctive-query-string (query-string)
1075 "Group query if it contains a complex expression.
1076 Enclose QUERY-STRING in parentheses if contains \"OR\" operators."
1077 (if (string-match-p "\\<[oO][rR]\\>" query-string)
1078 (concat "( " query-string " )")
1081 (defun notmuch-search-filter (query)
1082 "Filter or LIMIT the current search results based on an additional query string.
1084 Runs a new search matching only messages that match both the
1085 current search results AND the additional query string provided."
1086 (interactive (list (notmuch-read-query "Filter search: ")))
1087 (let ((grouped-query (notmuch-group-disjunctive-query-string query))
1088 (grouped-original-query (notmuch-group-disjunctive-query-string
1089 notmuch-search-query-string)))
1090 (notmuch-search (if (string= grouped-original-query "*")
1092 (concat grouped-original-query " and " grouped-query))
1093 notmuch-search-oldest-first)))
1095 (defun notmuch-search-filter-by-tag (tag)
1096 "Filter the current search results based on a single TAG.
1098 Run a new search matching only messages that match the current
1099 search results and that are also tagged with the given TAG."
1101 (list (notmuch-select-tag-with-completion "Filter by tag: "
1102 notmuch-search-query-string)))
1103 (notmuch-search (concat notmuch-search-query-string " and tag:" tag)
1104 notmuch-search-oldest-first))
1106 (defun notmuch-search-by-tag (tag)
1107 "Display threads matching TAG in a notmuch-search buffer."
1109 (list (notmuch-select-tag-with-completion "Notmuch search tag: ")))
1110 (notmuch-search (concat "tag:" tag)))
1114 "Run notmuch and display saved searches, known tags, etc."
1118 (defun notmuch-interesting-buffer (b)
1119 "Whether the current buffer's major-mode is a notmuch mode."
1120 (with-current-buffer b
1121 (memq major-mode '(notmuch-show-mode
1125 notmuch-message-mode))))
1128 (defun notmuch-cycle-notmuch-buffers ()
1129 "Cycle through any existing notmuch buffers (search, show or hello).
1131 If the current buffer is the only notmuch buffer, bury it.
1132 If no notmuch buffers exist, run `notmuch'."
1135 ;; If the current buffer is a notmuch buffer, remember it and then
1137 (when (notmuch-interesting-buffer (current-buffer))
1138 (setq start (current-buffer))
1141 ;; Find the first notmuch buffer.
1142 (setq first (cl-loop for buffer in (buffer-list)
1143 if (notmuch-interesting-buffer buffer)
1147 ;; If the first one we found is any other than the starting
1148 ;; buffer, switch to it.
1149 (unless (eq first start)
1150 (pop-to-buffer-same-window first))
1155 (defun notmuch-search-imenu-prev-index-position-function ()
1156 "Move point to previous message in notmuch-search buffer.
1157 Used as`imenu-prev-index-position-function' in notmuch buffers."
1158 (notmuch-search-previous-thread))
1160 (defun notmuch-search-imenu-extract-index-name-function ()
1161 "Return imenu name for line at point.
1162 Used as `imenu-extract-index-name-function' in notmuch buffers.
1163 Point should be at the beginning of the line."
1164 (let ((subject (notmuch-search-find-subject))
1165 (author (notmuch-search-find-authors)))
1166 (format "%s (%s)" subject author)))
1170 (setq mail-user-agent 'notmuch-user-agent)
1174 ;; After provide to avoid loops if notmuch was require'd via notmuch-init-file.
1175 (when init-file-user ; don't load init file if the -q option was used.
1176 (load notmuch-init-file t t nil t))
1178 ;;; notmuch.el ends here