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
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.
93 Supported fields are: date, count, authors, subject, tags.
95 (setq notmuch-search-result-format
96 \\='((\"authors\" . \"%-40s\")
97 (\"subject\" . \"%s\")))
99 Line breaks are permitted in format strings (though this is
100 currently experimental). Note that a line break at the end of an
101 \"authors\" field will get elided if the authors list is long;
102 place it instead at the beginning of the following field. To
103 enter a line break when setting this variable with setq, use \\n.
104 To enter a line break in customize, press \\[quoted-insert] C-j."
105 :type '(alist :key-type string :value-type string)
106 :group 'notmuch-search)
108 ;; The name of this variable `notmuch-init-file' is consistent with the
109 ;; convention used in e.g. emacs and gnus. The value, `notmuch-config[.el[c]]'
110 ;; is consistent with notmuch cli configuration file `~/.notmuch-config'.
111 (defcustom notmuch-init-file (locate-user-emacs-file "notmuch-config")
112 "Your Notmuch Emacs-Lisp configuration file name.
113 If a file with one of the suffixes defined by `get-load-suffixes' exists,
114 it will be read instead.
115 This file is read once when notmuch is loaded; the notmuch hooks added
116 there will be called at other points of notmuch execution."
120 (defcustom notmuch-search-hook '(notmuch-hl-line-mode)
121 "List of functions to call when notmuch displays the search results."
123 :options '(notmuch-hl-line-mode)
124 :group 'notmuch-search
125 :group 'notmuch-hooks)
129 (defun notmuch-foreach-mime-part (function mm-handle)
130 (cond ((stringp (car mm-handle))
131 (dolist (part (cdr mm-handle))
132 (notmuch-foreach-mime-part function part)))
133 ((bufferp (car mm-handle))
134 (funcall function mm-handle))
135 (t (dolist (part mm-handle)
136 (notmuch-foreach-mime-part function part)))))
138 (defun notmuch-count-attachments (mm-handle)
140 (notmuch-foreach-mime-part
142 (let ((disposition (mm-handle-disposition p)))
143 (and (listp disposition)
144 (or (equal (car disposition) "attachment")
145 (and (equal (car disposition) "inline")
146 (assq 'filename disposition)))
151 (defun notmuch-save-attachments (mm-handle &optional queryp)
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)))
161 (concat "Save '" (cdr (assq 'filename disposition)) "' ")))
167 (defvar notmuch-search-mode-map
168 (let ((map (make-sparse-keymap)))
169 (set-keymap-parent map notmuch-common-keymap)
170 (define-key map "x" 'notmuch-bury-or-kill-this-buffer)
171 (define-key map (kbd "DEL") 'notmuch-search-scroll-down)
172 (define-key map "b" 'notmuch-search-scroll-down)
173 (define-key map " " 'notmuch-search-scroll-up)
174 (define-key map "<" 'notmuch-search-first-thread)
175 (define-key map ">" 'notmuch-search-last-thread)
176 (define-key map "p" 'notmuch-search-previous-thread)
177 (define-key map "n" 'notmuch-search-next-thread)
178 (define-key map "r" 'notmuch-search-reply-to-thread-sender)
179 (define-key map "R" 'notmuch-search-reply-to-thread)
180 (define-key map "o" 'notmuch-search-toggle-order)
181 (define-key map "c" 'notmuch-search-stash-map)
182 (define-key map "t" 'notmuch-search-filter-by-tag)
183 (define-key map "l" 'notmuch-search-filter)
184 (define-key map [mouse-1] 'notmuch-search-show-thread)
185 (define-key map "k" 'notmuch-tag-jump)
186 (define-key map "*" 'notmuch-search-tag-all)
187 (define-key map "a" 'notmuch-search-archive-thread)
188 (define-key map "-" 'notmuch-search-remove-tag)
189 (define-key map "+" 'notmuch-search-add-tag)
190 (define-key map (kbd "RET") 'notmuch-search-show-thread)
191 (define-key map (kbd "M-RET") 'notmuch-tree-from-search-thread)
192 (define-key map "Z" 'notmuch-tree-from-search-current-query)
193 (define-key map "U" 'notmuch-unthreaded-from-search-current-query)
195 "Keymap for \"notmuch search\" buffers.")
197 ;;; Internal Variables
199 (defvar notmuch-query-history nil
200 "Variable to store minibuffer history for notmuch queries.")
202 (defvar-local notmuch-search-query-string nil)
203 (defvar-local notmuch-search-target-thread nil)
204 (defvar-local notmuch-search-target-line nil)
208 (defvar notmuch-search-stash-map
209 (let ((map (make-sparse-keymap)))
210 (define-key map "i" 'notmuch-search-stash-thread-id)
211 (define-key map "q" 'notmuch-stash-query)
212 (define-key map "?" 'notmuch-subkeymap-help)
214 "Submap for stash commands.")
215 (fset 'notmuch-search-stash-map notmuch-search-stash-map)
217 (defun notmuch-search-stash-thread-id ()
218 "Copy thread ID of current thread to kill-ring."
220 (notmuch-common-do-stash (notmuch-search-find-thread-id)))
222 (defun notmuch-stash-query ()
223 "Copy current query to kill-ring."
225 (notmuch-common-do-stash notmuch-search-query-string))
229 (defun notmuch-search-scroll-up ()
230 "Move forward through search results by one window's worth."
234 ((end-of-buffer) (notmuch-search-last-thread))))
236 (defun notmuch-search-scroll-down ()
237 "Move backward through the search results by one window's worth."
239 ;; I don't know why scroll-down doesn't signal beginning-of-buffer
240 ;; the way that scroll-up signals end-of-buffer, but c'est la vie.
242 ;; So instead of trapping a signal we instead check whether the
243 ;; window begins on the first line of the buffer and if so, move
244 ;; directly to that position. (We have to count lines since the
245 ;; window-start position is not the same as point-min due to the
246 ;; invisible thread-ID characters on the first line.
247 (if (equal (count-lines (point-min) (window-start)) 0)
248 (goto-char (point-min))
251 (defun notmuch-search-next-thread ()
252 "Select the next thread in the search results."
254 (when (notmuch-search-get-result)
255 (goto-char (notmuch-search-result-end))))
257 (defun notmuch-search-previous-thread ()
258 "Select the previous thread in the search results."
260 (if (notmuch-search-get-result)
262 (goto-char (notmuch-search-result-beginning (- (point) 1))))
263 ;; We must be past the end; jump to the last result
264 (notmuch-search-last-thread)))
266 (defun notmuch-search-last-thread ()
267 "Select the last thread in the search results."
269 (goto-char (point-max))
271 (let ((beg (notmuch-search-result-beginning)))
275 (defun notmuch-search-first-thread ()
276 "Select the first thread in the search results."
278 (goto-char (point-min)))
282 (defface notmuch-message-summary-face
283 `((((class color) (background light))
284 ,@(and (>= emacs-major-version 27) '(:extend t))
285 :background "#f0f0f0")
286 (((class color) (background dark))
287 ,@(and (>= emacs-major-version 27) '(:extend t))
288 :background "#303030"))
289 "Face for the single-line message summary in notmuch-show-mode."
291 :group 'notmuch-faces)
293 (defface notmuch-search-date
294 '((t :inherit default))
295 "Face used in search mode for dates."
296 :group 'notmuch-search
297 :group 'notmuch-faces)
299 (defface notmuch-search-count
300 '((t :inherit default))
301 "Face used in search mode for the count matching the query."
302 :group 'notmuch-search
303 :group 'notmuch-faces)
305 (defface notmuch-search-subject
306 '((t :inherit default))
307 "Face used in search mode for subjects."
308 :group 'notmuch-search
309 :group 'notmuch-faces)
311 (defface notmuch-search-matching-authors
312 '((t :inherit default))
313 "Face used in search mode for authors matching the query."
314 :group 'notmuch-search
315 :group 'notmuch-faces)
317 (defface notmuch-search-non-matching-authors
320 (:foreground "grey30"))
323 (:foreground "grey60"))
326 "Face used in search mode for authors not matching the query."
327 :group 'notmuch-search
328 :group 'notmuch-faces)
330 (defface notmuch-tag-face
333 (:foreground "OliveDrab1"))
336 (:foreground "navy blue" :bold t))
339 "Face used in search mode face for tags."
340 :group 'notmuch-search
341 :group 'notmuch-faces)
343 (defface notmuch-search-flagged-face
346 (:foreground "LightBlue1"))
349 (:foreground "blue")))
350 "Face used in search mode face for flagged threads.
352 This face is the default value for the \"flagged\" tag in
353 `notmuch-search-line-faces'."
354 :group 'notmuch-search
355 :group 'notmuch-faces)
357 (defface notmuch-search-unread-face
360 "Face used in search mode for unread threads.
362 This face is the default value for the \"unread\" tag in
363 `notmuch-search-line-faces'."
364 :group 'notmuch-search
365 :group 'notmuch-faces)
369 (define-derived-mode notmuch-search-mode fundamental-mode "notmuch-search"
370 "Major mode displaying results of a notmuch search.
372 This buffer contains the results of a \"notmuch search\" of your
373 email archives. Each line in the buffer represents a single
374 thread giving a summary of the thread (a relative date, the
375 number of matched messages and total messages in the thread,
376 participants in the thread, a representative subject line, and
379 Pressing \\[notmuch-search-show-thread] on any line displays that
380 thread. The '\\[notmuch-search-add-tag]' and
381 '\\[notmuch-search-remove-tag]' keys can be used to add or remove
382 tags from a thread. The '\\[notmuch-search-archive-thread]' key
383 is a convenience for archiving a thread (applying changes in
384 `notmuch-archive-tags'). The '\\[notmuch-search-tag-all]' key can
385 be used to add and/or remove tags from all messages (as opposed
386 to threads) that match the current query. Use with caution, as
387 this will also tag matching messages that arrived *after*
388 constructing the buffer.
390 Other useful commands are '\\[notmuch-search-filter]' for
391 filtering the current search based on an additional query string,
392 '\\[notmuch-search-filter-by-tag]' for filtering to include only
393 messages with a given tag, and '\\[notmuch-search]' to execute a
396 Complete list of currently available key bindings:
398 \\{notmuch-search-mode-map}"
399 (setq notmuch-buffer-refresh-function #'notmuch-search-refresh-view)
400 (setq-local scroll-preserve-screen-position t)
401 (add-to-invisibility-spec (cons 'ellipsis t))
402 (setq truncate-lines t)
403 (setq buffer-read-only t)
404 (setq imenu-prev-index-position-function
405 #'notmuch-search-imenu-prev-index-position-function)
406 (setq imenu-extract-index-name-function
407 #'notmuch-search-imenu-extract-index-name-function))
411 (defun notmuch-search-get-result (&optional pos)
412 "Return the result object for the thread at POS (or point).
414 If there is no thread at POS (or point), returns nil."
415 (get-text-property (or pos (point)) 'notmuch-search-result))
417 (defun notmuch-search-result-beginning (&optional pos)
418 "Return the point at the beginning of the thread at POS (or point).
420 If there is no thread at POS (or point), returns nil."
421 (and (notmuch-search-get-result pos)
422 ;; We pass 1+point because previous-single-property-change starts
423 ;; searching one before the position we give it.
424 (previous-single-property-change (1+ (or pos (point)))
425 'notmuch-search-result nil
428 (defun notmuch-search-result-end (&optional pos)
429 "Return the point at the end of the thread at POS (or point).
431 The returned point will be just after the newline character that
432 ends the result line. If there is no thread at POS (or point),
434 (and (notmuch-search-get-result pos)
435 (next-single-property-change (or pos (point))
436 'notmuch-search-result nil
439 (defun notmuch-search-foreach-result (beg end fn)
440 "Invoke FN for each result between BEG and END.
442 FN should take one argument. It will be applied to the character
443 position of the beginning of each result that overlaps the region
444 between points BEG and END. As a special case, if (= BEG END),
445 FN will be applied to the result containing point BEG."
446 (let ((pos (notmuch-search-result-beginning beg))
447 ;; End must be a marker in case fn changes the
449 (end (copy-marker end))
450 ;; Make sure we examine at least one result, even if
453 ;; We have to be careful if the region extends beyond the results.
454 ;; In this case, pos could be null or there could be no result at
456 (while (and pos (or (< pos end) first))
457 (when (notmuch-search-get-result pos)
459 (setq pos (notmuch-search-result-end pos))
461 ;; Unindent the function argument of notmuch-search-foreach-result so
462 ;; the indentation of callers doesn't get out of hand.
463 (put 'notmuch-search-foreach-result 'lisp-indent-function 2)
465 (defun notmuch-search-properties-in-region (property beg end)
467 (notmuch-search-foreach-result beg end
469 (push (plist-get (notmuch-search-get-result pos) property) output)))
472 (defun notmuch-search-find-thread-id (&optional bare)
473 "Return the thread for the current thread.
475 If BARE is set then do not prefix with \"thread:\"."
476 (let ((thread (plist-get (notmuch-search-get-result) :thread)))
478 (concat (and (not bare) "thread:") thread))))
480 (defun notmuch-search-find-stable-query ()
481 "Return the stable queries for the current thread.
483 Return a list (MATCHED-QUERY UNMATCHED-QUERY) for the
484 matched and unmatched messages in the current thread."
485 (plist-get (notmuch-search-get-result) :query))
487 (defun notmuch-search-find-stable-query-region (beg end &optional only-matched)
488 "Return the stable query for the current region.
490 If ONLY-MATCHED is non-nil, include only matched messages. If it
491 is nil, include both matched and unmatched messages. If there are
492 no messages in the region then return nil."
493 (let ((query-list nil) (all (not only-matched)))
494 (dolist (queries (notmuch-search-properties-in-region :query beg end))
496 (push (car queries) query-list))
497 (when (and all (cadr queries))
498 (push (cadr queries) query-list)))
500 (concat "(" (mapconcat 'identity query-list ") or (") ")"))))
502 (defun notmuch-search-find-authors ()
503 "Return the authors for the current thread."
504 (plist-get (notmuch-search-get-result) :authors))
506 (defun notmuch-search-find-authors-region (beg end)
507 "Return a list of authors for the current region."
508 (notmuch-search-properties-in-region :authors beg end))
510 (defun notmuch-search-find-subject ()
511 "Return the subject for the current thread."
512 (plist-get (notmuch-search-get-result) :subject))
514 (defun notmuch-search-find-subject-region (beg end)
515 "Return a list of authors for the current region."
516 (notmuch-search-properties-in-region :subject beg end))
518 (defun notmuch-search-show-thread (&optional elide-toggle)
519 "Display the currently selected thread.
521 With a prefix argument, invert the default value of
522 `notmuch-show-only-matching-messages' when displaying the
525 Return non-nil on success."
527 (let ((thread-id (notmuch-search-find-thread-id)))
529 (notmuch-show thread-id
532 notmuch-search-query-string
533 ;; Name the buffer based on the subject.
534 (format "*%s*" (truncate-string-to-width
535 (notmuch-search-find-subject)
537 (message "End of search results.")
540 (defun notmuch-tree-from-search-current-query ()
541 "Tree view of current query."
543 (notmuch-tree notmuch-search-query-string))
545 (defun notmuch-unthreaded-from-search-current-query ()
546 "Unthreaded view of current query."
548 (notmuch-unthreaded notmuch-search-query-string))
550 (defun notmuch-tree-from-search-thread ()
551 "Show the selected thread with notmuch-tree."
553 (notmuch-tree (notmuch-search-find-thread-id)
554 notmuch-search-query-string
556 (notmuch-prettify-subject (notmuch-search-find-subject))
557 t nil (current-buffer)))
559 (defun notmuch-search-reply-to-thread (&optional prompt-for-sender)
560 "Begin composing a reply-all to the entire current thread in a new buffer."
562 (notmuch-mua-new-reply (notmuch-search-find-thread-id)
563 prompt-for-sender t))
565 (defun notmuch-search-reply-to-thread-sender (&optional prompt-for-sender)
566 "Begin composing a reply to the entire current thread in a new buffer."
568 (notmuch-mua-new-reply (notmuch-search-find-thread-id)
569 prompt-for-sender nil))
573 (defun notmuch-search-set-tags (tags &optional pos)
574 (notmuch-search-update-result
575 (plist-put (notmuch-search-get-result pos) :tags tags)
578 (defun notmuch-search-get-tags (&optional pos)
579 (plist-get (notmuch-search-get-result pos) :tags))
581 (defun notmuch-search-get-tags-region (beg end)
583 (notmuch-search-foreach-result beg end
585 (setq output (append output (notmuch-search-get-tags pos)))))
586 (delete-dups output)))
588 (defun notmuch-search-interactive-tag-changes (&optional initial-input)
589 "Prompt for tag changes for the current thread or region.
591 Return (TAG-CHANGES REGION-BEGIN REGION-END)."
592 (pcase-let ((`(,beg ,end) (notmuch-interactive-region)))
593 (list (notmuch-read-tag-changes (notmuch-search-get-tags-region beg end)
594 (if (= beg end) "Tag thread" "Tag region")
598 (defun notmuch-search-tag (tag-changes &optional beg end only-matched)
599 "Change tags for the currently selected thread or region.
601 See `notmuch-tag' for information on the format of TAG-CHANGES.
602 When called interactively, this uses the region if the region is
603 active. When called directly, BEG and END provide the region.
604 If these are nil or not provided, then, if the region is active
605 this applied to all threads meeting the region, and if the region
606 is inactive this applies to the thread at point.
608 If ONLY-MATCHED is non-nil, only tag matched messages."
609 (interactive (notmuch-search-interactive-tag-changes))
610 (unless (and beg end)
611 (setq beg (car (notmuch-interactive-region)))
612 (setq end (cadr (notmuch-interactive-region))))
613 (let ((search-string (notmuch-search-find-stable-query-region
614 beg end only-matched)))
615 (notmuch-tag search-string tag-changes)
616 (notmuch-search-foreach-result beg end
618 (notmuch-search-set-tags
619 (notmuch-update-tags (notmuch-search-get-tags pos) tag-changes)
622 (defun notmuch-search-add-tag (tag-changes &optional beg end)
623 "Change tags for the current thread or region (defaulting to add).
625 Same as `notmuch-search-tag' but sets initial input to '+'."
626 (interactive (notmuch-search-interactive-tag-changes "+"))
627 (notmuch-search-tag tag-changes beg end))
629 (defun notmuch-search-remove-tag (tag-changes &optional beg end)
630 "Change tags for the current thread or region (defaulting to remove).
632 Same as `notmuch-search-tag' but sets initial input to '-'."
633 (interactive (notmuch-search-interactive-tag-changes "-"))
634 (notmuch-search-tag tag-changes beg end))
636 (put 'notmuch-search-archive-thread 'notmuch-prefix-doc
637 "Un-archive the currently selected thread.")
638 (defun notmuch-search-archive-thread (&optional unarchive beg end)
639 "Archive the currently selected thread or region.
641 Archive each message in the currently selected thread by applying
642 the tag changes in `notmuch-archive-tags' to each (remove the
643 \"inbox\" tag by default). If a prefix argument is given, the
644 messages will be \"unarchived\" (i.e. the tag changes in
645 `notmuch-archive-tags' will be reversed).
647 This function advances the next thread when finished."
648 (interactive (cons current-prefix-arg (notmuch-interactive-region)))
649 (when notmuch-archive-tags
651 (notmuch-tag-change-list notmuch-archive-tags unarchive) beg end))
653 (notmuch-search-next-thread)))
657 (defun notmuch-search-update-result (result &optional pos)
658 "Replace the result object of the thread at POS (or point) by
659 RESULT and redraw it.
661 This will keep point in a reasonable location. However, if there
662 are enclosing save-excursions and the saved point is in the
663 result being updated, the point will be restored to the beginning
665 (let ((start (notmuch-search-result-beginning pos))
666 (end (notmuch-search-result-end pos))
668 (inhibit-read-only t))
669 ;; Delete the current thread
670 (delete-region start end)
671 ;; Insert the updated thread
672 (notmuch-search-show-result result start)
673 ;; If point was inside the old result, make an educated guess
674 ;; about where to place it now. Unfortunately, this won't work
675 ;; with save-excursion (or any other markers that would be nice to
676 ;; preserve, such as the window start), but there's nothing we can
677 ;; do about that without a way to retrieve markers in a region.
678 (when (and (>= init-point start) (<= init-point end))
679 (let* ((new-end (notmuch-search-result-end start))
680 (new-point (if (= init-point end)
682 (min init-point (- new-end 1)))))
683 (goto-char new-point)))))
685 (defun notmuch-search-process-sentinel (proc _msg)
686 "Add a message to let user know when \"notmuch search\" exits."
687 (let ((buffer (process-buffer proc))
688 (status (process-status proc))
689 (exit-status (process-exit-status proc))
690 (never-found-target-thread nil))
691 (when (memq status '(exit signal))
693 (kill-buffer (process-get proc 'parse-buf))
694 (when (buffer-live-p buffer)
695 (with-current-buffer buffer
697 (let ((inhibit-read-only t)
699 (goto-char (point-max))
700 (when (eq status 'signal)
701 (insert "Incomplete search results (search process was killed).\n"))
702 (when (eq status 'exit)
703 (insert "End of search results.\n")
704 ;; For version mismatch, there's no point in
705 ;; showing the search buffer
706 (when (or (= exit-status 20) (= exit-status 21))
710 (not (string= notmuch-search-target-thread "found")))
711 (setq never-found-target-thread t)))))
712 (when (and never-found-target-thread
713 notmuch-search-target-line)
714 (goto-char (point-min))
715 (forward-line (1- notmuch-search-target-line)))))))))
717 (define-widget 'notmuch--custom-face-edit 'lazy
718 "Custom face edit with a tag Edit Face"
719 ;; I could not persuage custom-face-edit to respect the :tag
720 ;; property so create a widget specially
721 :tag "Manually specify face"
722 :type 'custom-face-edit)
724 (defcustom notmuch-search-line-faces
725 '(("unread" . notmuch-search-unread-face)
726 ("flagged" . notmuch-search-flagged-face))
727 "Alist of tags to faces for line highlighting in notmuch-search.
728 Each element looks like (TAG . FACE).
729 A thread with TAG will have FACE applied.
731 Here is an example of how to color search results based on tags.
732 (the following text would be placed in your ~/.emacs file):
734 (setq notmuch-search-line-faces \\='((\"unread\" . (:foreground \"green\"))
735 (\"deleted\" . (:foreground \"red\"
736 :background \"blue\"))))
738 The FACE must be a face name (a symbol or string), a property
739 list of face attributes, or a list of these. The faces for
740 matching tags are merged, with earlier attributes overriding
741 later. A message having both \"deleted\" and \"unread\" tags with
742 the above settings would have a green foreground and blue
744 :type '(alist :key-type (string)
745 :value-type (radio (face :tag "Face name")
746 (notmuch--custom-face-edit)))
747 :group 'notmuch-search
748 :group 'notmuch-faces)
750 (defun notmuch-search-color-line (start end line-tag-list)
751 "Colorize lines in `notmuch-show' based on tags."
752 ;; Reverse the list so earlier entries take precedence
753 (dolist (elem (reverse notmuch-search-line-faces))
754 (let ((tag (car elem))
756 (when (member tag line-tag-list)
757 (notmuch-apply-face nil face nil start end)))))
759 (defun notmuch-search-author-propertize (authors)
760 "Split `authors' into matching and non-matching authors and
761 propertize appropriately. If no boundary between authors and
762 non-authors is found, assume that all of the authors match."
763 (if (string-match "\\(.*\\)|\\(.*\\)" authors)
764 (concat (propertize (concat (match-string 1 authors) ",")
765 'face 'notmuch-search-matching-authors)
766 (propertize (match-string 2 authors)
767 'face 'notmuch-search-non-matching-authors))
768 (propertize authors 'face 'notmuch-search-matching-authors)))
770 (defun notmuch-search-insert-authors (format-string authors)
771 ;; Save the match data to avoid interfering with
772 ;; `notmuch-search-process-filter'.
774 (let* ((formatted-authors (format format-string authors))
775 (formatted-sample (format format-string ""))
776 (visible-string formatted-authors)
777 (invisible-string "")
779 ;; Truncate the author string to fit the specification.
780 (when (> (length formatted-authors)
781 (length formatted-sample))
782 (let ((visible-length (- (length formatted-sample)
784 ;; Truncate the visible string according to the width of
785 ;; the display string.
786 (setq visible-string (substring formatted-authors 0 visible-length))
787 (setq invisible-string (substring formatted-authors visible-length))
788 ;; If possible, truncate the visible string at a natural
789 ;; break (comma or pipe), as incremental search doesn't
790 ;; match across the visible/invisible border.
791 (when (string-match "\\(.*\\)\\([,|] \\)\\([^,|]*\\)" visible-string)
792 ;; Second clause is destructive on `visible-string', so
793 ;; order is important.
794 (setq invisible-string (concat (match-string 3 visible-string)
796 (setq visible-string (concat (match-string 1 visible-string)
797 (match-string 2 visible-string))))
798 ;; `visible-string' may be shorter than the space allowed
799 ;; by `format-string'. If so we must insert some padding
800 ;; after `invisible-string'.
801 (setq padding (make-string (- (length formatted-sample)
802 (length visible-string)
805 ;; Use different faces to show matching and non-matching authors.
806 (if (string-match "\\(.*\\)|\\(.*\\)" visible-string)
807 ;; The visible string contains both matching and
808 ;; non-matching authors.
810 (setq visible-string (notmuch-search-author-propertize visible-string))
811 ;; The invisible string must contain only non-matching
812 ;; authors, as the visible-string contains both.
813 (setq invisible-string (propertize invisible-string
814 'face 'notmuch-search-non-matching-authors)))
815 ;; The visible string contains only matching authors.
816 (setq visible-string (propertize visible-string
817 'face 'notmuch-search-matching-authors))
818 ;; The invisible string may contain both matching and
819 ;; non-matching authors.
820 (setq invisible-string (notmuch-search-author-propertize invisible-string)))
821 ;; If there is any invisible text, add it as a tooltip to the
823 (unless (string-empty-p invisible-string)
825 (propertize visible-string
826 'help-echo (concat "..." invisible-string))))
827 ;; Insert the visible and, if present, invisible author strings.
828 (insert visible-string)
829 (unless (string-empty-p invisible-string)
830 (let ((start (point))
832 (insert invisible-string)
833 (setq overlay (make-overlay start (point)))
834 (overlay-put overlay 'invisible 'ellipsis)
835 (overlay-put overlay 'isearch-open-invisible #'delete-overlay)))
838 (defun notmuch-search-insert-field (field format-string result)
841 (insert (funcall field format-string result)))
843 (insert (propertize (format format-string (plist-get result :date_relative))
844 'face 'notmuch-search-date)))
846 (insert (propertize (format format-string
847 (format "[%s/%s]" (plist-get result :matched)
848 (plist-get result :total)))
849 'face 'notmuch-search-count)))
851 (insert (propertize (format format-string
852 (notmuch-sanitize (plist-get result :subject)))
853 'face 'notmuch-search-subject)))
855 (notmuch-search-insert-authors format-string
856 (notmuch-sanitize (plist-get result :authors))))
858 (let ((tags (plist-get result :tags))
859 (orig-tags (plist-get result :orig-tags)))
860 (insert (format format-string (notmuch-tag-format-tags tags orig-tags)))))))
862 (defun notmuch-search-show-result (result pos)
863 "Insert RESULT at POS."
864 ;; Ignore excluded matches
865 (unless (= (plist-get result :matched) 0)
868 (dolist (spec notmuch-search-result-format)
869 (notmuch-search-insert-field (car spec) (cdr spec) result))
871 (notmuch-search-color-line pos (point) (plist-get result :tags))
872 (put-text-property pos (point) 'notmuch-search-result result))))
874 (defun notmuch-search-append-result (result)
875 "Insert RESULT at the end of the buffer.
877 This is only called when a result is first inserted so it also
878 sets the :orig-tag property."
879 (let ((new-result (plist-put result :orig-tags (plist-get result :tags)))
881 (notmuch-search-show-result new-result pos)
882 (when (string= (plist-get result :thread) notmuch-search-target-thread)
883 (setq notmuch-search-target-thread "found")
886 (defvar-local notmuch--search-hook-run nil
887 "Flag used to ensure the notmuch-search-hook is only run once per buffer")
889 (defun notmuch--search-hook-wrapper ()
890 (unless notmuch--search-hook-run
891 (setq notmuch--search-hook-run t)
892 (run-hooks 'notmuch-search-hook)))
894 (defun notmuch-search-process-filter (proc string)
895 "Process and filter the output of \"notmuch search\"."
896 (let ((results-buf (process-buffer proc))
897 (parse-buf (process-get proc 'parse-buf))
898 (inhibit-read-only t))
899 (when (buffer-live-p results-buf)
900 (with-current-buffer parse-buf
903 (goto-char (point-max))
905 (notmuch-sexp-parse-partial-list 'notmuch-search-append-result
907 (with-current-buffer results-buf
908 (notmuch--search-hook-wrapper)))))
910 ;;; Commands (and some helper functions used by them)
912 (defun notmuch-search-tag-all (tag-changes)
913 "Add/remove tags from all messages in current search buffer.
915 See `notmuch-tag' for information on the format of TAG-CHANGES."
917 (list (notmuch-read-tag-changes
918 (notmuch-search-get-tags-region (point-min) (point-max)) "Tag all")))
919 (notmuch-search-tag tag-changes (point-min) (point-max) t))
921 (defcustom notmuch-search-buffer-name-format "*notmuch-%t-%s*"
922 "Format for the name of search results buffers.
924 In this spec, %s will be replaced by a description of the search
925 query and %t by its type (search, tree or unthreaded). The
926 buffer name is formatted using `format-spec': see its docstring
927 for additional parameters for the s and t format specifiers.
929 See also `notmuch-saved-search-buffer-name-format'"
931 :group 'notmuch-search)
933 (defcustom notmuch-saved-search-buffer-name-format "*notmuch-saved-%t-%s*"
934 "Format for the name of search results buffers for saved searches.
936 In this spec, %s will be replaced by the saved search name and %t
937 by its type (search, tree or unthreaded). The buffer name is
938 formatted using `format-spec': see its docstring for additional
939 parameters for the s and t format specifiers.
941 See also `notmuch-search-buffer-name-format'"
943 :group 'notmuch-search)
945 (defun notmuch-search-format-buffer-name (query type saved)
946 "Compose a buffer name for the given QUERY, TYPE (search, tree,
947 unthreaded) and whether it's SAVED (t or nil)."
949 notmuch-saved-search-buffer-name-format
950 notmuch-search-buffer-name-format)))
951 (format-spec fmt `((?t . ,(or type "search")) (?s . ,query)))))
953 (defun notmuch-search-buffer-title (query &optional type)
954 "Returns the title for a buffer with notmuch search results."
958 (cl-loop for tuple in notmuch-saved-searches
959 if (let ((quoted-query
961 (notmuch-saved-search-get tuple :query))))
962 (and (string-match (concat "^" quoted-query) query)
963 (> (length (match-string 0 query))
965 do (setq longest tuple))
967 (saved-search-name (notmuch-saved-search-get saved-search :name))
968 (saved-search-type (notmuch-saved-search-get saved-search :search-type))
969 (saved-search-query (notmuch-saved-search-get saved-search :query)))
970 (cond ((and saved-search (equal saved-search-query query))
971 ;; Query is the same as saved search (ignoring case)
972 (notmuch-search-format-buffer-name saved-search-name
976 (let ((query (replace-regexp-in-string
977 (concat "^" (regexp-quote saved-search-query))
978 (concat "[ " saved-search-name " ]")
980 (notmuch-search-format-buffer-name query saved-search-type t)))
981 (t (notmuch-search-format-buffer-name query type nil)))))
983 (defun notmuch-read-query (prompt)
984 "Read a notmuch-query from the minibuffer with completion.
986 PROMPT is the string to prompt with."
988 (mapcar (lambda (tag) (notmuch-escape-boolean-term tag))
989 (notmuch--process-lines notmuch-command "search" "--output=tags" "*")))
991 (append (list "folder:" "path:" "thread:" "id:" "date:" "from:" "to:"
992 "subject:" "attachment:")
993 (mapcar (lambda (tag) (concat "tag:" tag)) all-tags)
994 (mapcar (lambda (tag) (concat "is:" tag)) all-tags)
995 (mapcar (lambda (mimetype) (concat "mimetype:" mimetype))
996 (mailcap-mime-types))))
997 (keymap (copy-keymap minibuffer-local-map))
998 (current-query (cl-case major-mode
999 (notmuch-search-mode (notmuch-search-get-query))
1000 (notmuch-show-mode (notmuch-show-get-query))
1001 (notmuch-tree-mode (notmuch-tree-get-query))))
1002 (minibuffer-completion-table
1003 (completion-table-dynamic
1005 ;; Generate a list of possible completions for the current input.
1007 ;; This ugly regexp is used to get the last word of the input
1008 ;; possibly preceded by a '('.
1009 ((string-match "\\(^\\|.* (?\\)\\([^ ]*\\)$" string)
1010 (mapcar (lambda (compl)
1011 (concat (match-string-no-properties 1 string) compl))
1012 (all-completions (match-string-no-properties 2 string)
1014 (t (list string)))))))
1015 ;; This was simpler than convincing completing-read to accept spaces:
1016 (define-key keymap (kbd "TAB") 'minibuffer-complete)
1017 (let ((history-delete-duplicates t))
1018 (read-from-minibuffer prompt nil keymap nil
1019 'notmuch-search-history current-query nil))))
1021 (defun notmuch-search-get-query ()
1022 "Return the current query in this search buffer."
1023 notmuch-search-query-string)
1025 (put 'notmuch-search 'notmuch-doc "Search for messages.")
1027 (defun notmuch-search (&optional query oldest-first target-thread target-line
1029 "Display threads matching QUERY in a notmuch-search buffer.
1031 If QUERY is nil, it is read interactively from the minibuffer.
1032 Other optional parameters are used as follows:
1034 OLDEST-FIRST: A Boolean controlling the sort order of returned threads
1035 TARGET-THREAD: A thread ID (without the thread: prefix) that will be made
1036 current if it appears in the search results.
1037 TARGET-LINE: The line number to move to if the target thread does not
1038 appear in the search results.
1039 NO-DISPLAY: Do not try to foreground the search results buffer. If it is
1040 already foregrounded i.e. displayed in a window, this has no
1041 effect, meaning the buffer will remain visible.
1043 When called interactively, this will prompt for a query and use
1044 the configured default sort order."
1047 ;; Prompt for a query
1049 ;; Use the default search order (if we're doing a search from a
1050 ;; search buffer, ignore any buffer-local overrides)
1051 (default-value 'notmuch-search-oldest-first)))
1053 (let* ((query (or query (notmuch-read-query "Notmuch search: ")))
1054 (buffer (get-buffer-create (notmuch-search-buffer-title query))))
1057 (pop-to-buffer-same-window buffer))
1058 (notmuch-search-mode)
1059 ;; Don't track undo information for this buffer
1060 (setq buffer-undo-list t)
1061 (setq notmuch-search-query-string query)
1062 (setq notmuch-search-oldest-first oldest-first)
1063 (setq notmuch-search-target-thread target-thread)
1064 (setq notmuch-search-target-line target-line)
1065 (notmuch-tag-clear-cache)
1066 (when (get-buffer-process buffer)
1067 (error "notmuch search process already running for query `%s'" query))
1068 (let ((inhibit-read-only t))
1070 (goto-char (point-min))
1072 (let ((proc (notmuch-start-notmuch
1073 "notmuch-search" buffer #'notmuch-search-process-sentinel
1074 "search" "--format=sexp" "--format-version=5"
1076 "--sort=oldest-first"
1077 "--sort=newest-first")
1079 ;; Use a scratch buffer to accumulate partial output.
1080 ;; This buffer will be killed by the sentinel, which
1081 ;; should be called no matter how the process dies.
1082 (process-put proc 'parse-buf
1083 (generate-new-buffer " *notmuch search parse*"))
1084 (set-process-filter proc 'notmuch-search-process-filter)
1085 (set-process-query-on-exit-flag proc nil))))))
1087 (defun notmuch-search-refresh-view ()
1088 "Refresh the current view.
1090 Erases the current buffer and runs a new search with the same
1091 query string as the current search. If the current thread is in
1092 the new search results, then point will be placed on the same
1093 thread. Otherwise, point will be moved to attempt to be in the
1094 same relative position within the new buffer."
1096 (notmuch-search notmuch-search-query-string
1097 notmuch-search-oldest-first
1098 (notmuch-search-find-thread-id 'bare)
1099 (line-number-at-pos)
1101 (goto-char (point-min)))
1103 (defun notmuch-search-toggle-order ()
1104 "Toggle the current search order.
1106 This command toggles the sort order for the current search. The
1107 default sort order is defined by `notmuch-search-oldest-first'."
1109 (setq notmuch-search-oldest-first (not notmuch-search-oldest-first))
1110 (notmuch-search-refresh-view))
1112 (defun notmuch-group-disjunctive-query-string (query-string)
1113 "Group query if it contains a complex expression.
1114 Enclose QUERY-STRING in parentheses if contains \"OR\" operators."
1115 (if (string-match-p "\\<[oO][rR]\\>" query-string)
1116 (concat "( " query-string " )")
1119 (defun notmuch-search-filter (query)
1120 "Filter or LIMIT the current search results based on an additional query string.
1122 Runs a new search matching only messages that match both the
1123 current search results AND the additional query string provided."
1124 (interactive (list (notmuch-read-query "Filter search: ")))
1125 (let ((grouped-query (notmuch-group-disjunctive-query-string query))
1126 (grouped-original-query (notmuch-group-disjunctive-query-string
1127 notmuch-search-query-string)))
1128 (notmuch-search (if (string= grouped-original-query "*")
1130 (concat grouped-original-query " and " grouped-query))
1131 notmuch-search-oldest-first)))
1133 (defun notmuch-search-filter-by-tag (tag)
1134 "Filter the current search results based on a single TAG.
1136 Run a new search matching only messages that match the current
1137 search results and that are also tagged with the given TAG."
1139 (list (notmuch-select-tag-with-completion "Filter by tag: "
1140 notmuch-search-query-string)))
1141 (notmuch-search (concat notmuch-search-query-string " and tag:" tag)
1142 notmuch-search-oldest-first))
1144 (defun notmuch-search-by-tag (tag)
1145 "Display threads matching TAG in a notmuch-search buffer."
1147 (list (notmuch-select-tag-with-completion "Notmuch search tag: ")))
1148 (notmuch-search (concat "tag:" tag)))
1152 "Run notmuch and display saved searches, known tags, etc."
1156 (defun notmuch-interesting-buffer (b)
1157 "Whether the current buffer's major-mode is a notmuch mode."
1158 (with-current-buffer b
1159 (memq major-mode '(notmuch-show-mode
1163 notmuch-message-mode))))
1166 (defun notmuch-cycle-notmuch-buffers ()
1167 "Cycle through any existing notmuch buffers (search, show or hello).
1169 If the current buffer is the only notmuch buffer, bury it.
1170 If no notmuch buffers exist, run `notmuch'."
1173 ;; If the current buffer is a notmuch buffer, remember it and then
1175 (when (notmuch-interesting-buffer (current-buffer))
1176 (setq start (current-buffer))
1179 ;; Find the first notmuch buffer.
1180 (setq first (cl-loop for buffer in (buffer-list)
1181 if (notmuch-interesting-buffer buffer)
1185 ;; If the first one we found is any other than the starting
1186 ;; buffer, switch to it.
1187 (unless (eq first start)
1188 (pop-to-buffer-same-window first))
1192 ;;;; Hl-line Support
1194 (defun notmuch-hl-line-mode ()
1195 (prog1 (hl-line-mode)
1196 (when hl-line-overlay
1197 (overlay-put hl-line-overlay 'priority 1))))
1201 (defun notmuch-search-imenu-prev-index-position-function ()
1202 "Move point to previous message in notmuch-search buffer.
1203 Used as`imenu-prev-index-position-function' in notmuch buffers."
1204 (notmuch-search-previous-thread))
1206 (defun notmuch-search-imenu-extract-index-name-function ()
1207 "Return imenu name for line at point.
1208 Used as `imenu-extract-index-name-function' in notmuch buffers.
1209 Point should be at the beginning of the line."
1211 (notmuch-search-find-subject)
1212 (notmuch-search-find-authors)))
1218 ;; After provide to avoid loops if notmuch was require'd via notmuch-init-file.
1219 (when init-file-user ; don't load init file if the -q option was used.
1220 (load notmuch-init-file t t nil t))
1222 ;;; notmuch.el ends here