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 <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))
72 (require 'notmuch-lib)
73 (require 'notmuch-tag)
74 (require 'notmuch-show)
75 (require 'notmuch-tree)
76 (require 'notmuch-mua)
77 (require 'notmuch-hello)
78 (require 'notmuch-maildir-fcc)
79 (require 'notmuch-message)
80 (require 'notmuch-parser)
82 (defcustom notmuch-search-result-format
85 ("authors" . "%-20s ")
88 "Search result formatting. Supported fields are:
89 date, count, authors, subject, tags
91 (setq notmuch-search-result-format \(\(\"authors\" . \"%-40s\"\)
92 \(\"subject\" . \"%s\"\)\)\)
93 Line breaks are permitted in format strings (though this is
94 currently experimental). Note that a line break at the end of an
95 \"authors\" field will get elided if the authors list is long;
96 place it instead at the beginning of the following field. To
97 enter a line break when setting this variable with setq, use \\n.
98 To enter a line break in customize, press \\[quoted-insert] C-j."
99 :type '(alist :key-type (string) :value-type (string))
100 :group 'notmuch-search)
102 ;; The name of this variable `notmuch-init-file' is consistent with the
103 ;; convention used in e.g. emacs and gnus. The value, `notmuch-config[.el[c]]'
104 ;; is consistent with notmuch cli configuration file `~/.notmuch-config'.
105 (defcustom notmuch-init-file (locate-user-emacs-file "notmuch-config")
106 "Your Notmuch Emacs-Lisp configuration file name.
107 If a file with one of the suffixes defined by `get-load-suffixes' exists,
108 it will be read instead.
109 This file is read once when notmuch is loaded; the notmuch hooks added
110 there will be called at other points of notmuch execution."
114 (defvar notmuch-query-history nil
115 "Variable to store minibuffer history for notmuch queries")
117 (defun notmuch-foreach-mime-part (function mm-handle)
118 (cond ((stringp (car mm-handle))
119 (dolist (part (cdr mm-handle))
120 (notmuch-foreach-mime-part function part)))
121 ((bufferp (car mm-handle))
122 (funcall function mm-handle))
123 (t (dolist (part mm-handle)
124 (notmuch-foreach-mime-part function part)))))
126 (defun notmuch-count-attachments (mm-handle)
128 (notmuch-foreach-mime-part
130 (let ((disposition (mm-handle-disposition p)))
131 (and (listp disposition)
132 (or (equal (car disposition) "attachment")
133 (and (equal (car disposition) "inline")
134 (assq 'filename disposition)))
139 (defun notmuch-save-attachments (mm-handle &optional queryp)
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)))
149 (concat "Save '" (cdr (assq 'filename disposition)) "' ")))
155 (defun notmuch-hl-line-mode ()
156 (prog1 (hl-line-mode)
157 (when hl-line-overlay
158 (overlay-put hl-line-overlay 'priority 1))))
160 (defcustom notmuch-search-hook '(notmuch-hl-line-mode)
161 "List of functions to call when notmuch displays the search results."
163 :options '(notmuch-hl-line-mode)
164 :group 'notmuch-search
165 :group 'notmuch-hooks)
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)
194 "Keymap for \"notmuch search\" buffers.")
195 (fset 'notmuch-search-mode-map notmuch-search-mode-map)
197 (defvar notmuch-search-stash-map
198 (let ((map (make-sparse-keymap)))
199 (define-key map "i" 'notmuch-search-stash-thread-id)
200 (define-key map "q" 'notmuch-stash-query)
201 (define-key map "?" 'notmuch-subkeymap-help)
203 "Submap for stash commands")
204 (fset 'notmuch-search-stash-map notmuch-search-stash-map)
206 (defun notmuch-search-stash-thread-id ()
207 "Copy thread ID of current thread to kill-ring."
209 (notmuch-common-do-stash (notmuch-search-find-thread-id)))
211 (defun notmuch-stash-query ()
212 "Copy current query to kill-ring."
214 (notmuch-common-do-stash (notmuch-search-get-query)))
216 (defvar notmuch-search-query-string)
217 (defvar notmuch-search-target-thread)
218 (defvar notmuch-search-target-line)
220 (defvar notmuch-search-disjunctive-regexp "\\<[oO][rR]\\>")
222 (defun notmuch-search-scroll-up ()
223 "Move forward through search results by one window's worth."
227 ((end-of-buffer) (notmuch-search-last-thread))))
229 (defun notmuch-search-scroll-down ()
230 "Move backward through the search results by one window's worth."
232 ;; I don't know why scroll-down doesn't signal beginning-of-buffer
233 ;; the way that scroll-up signals end-of-buffer, but c'est la vie.
235 ;; So instead of trapping a signal we instead check whether the
236 ;; window begins on the first line of the buffer and if so, move
237 ;; directly to that position. (We have to count lines since the
238 ;; window-start position is not the same as point-min due to the
239 ;; invisible thread-ID characters on the first line.
240 (if (equal (count-lines (point-min) (window-start)) 0)
241 (goto-char (point-min))
244 (defun notmuch-search-next-thread ()
245 "Select the next thread in the search results."
247 (when (notmuch-search-get-result)
248 (goto-char (notmuch-search-result-end))))
250 (defun notmuch-search-previous-thread ()
251 "Select the previous thread in the search results."
253 (if (notmuch-search-get-result)
255 (goto-char (notmuch-search-result-beginning (- (point) 1))))
256 ;; We must be past the end; jump to the last result
257 (notmuch-search-last-thread)))
259 (defun notmuch-search-last-thread ()
260 "Select the last thread in the search results."
262 (goto-char (point-max))
264 (let ((beg (notmuch-search-result-beginning)))
265 (when beg (goto-char beg))))
267 (defun notmuch-search-first-thread ()
268 "Select the first thread in the search results."
270 (goto-char (point-min)))
272 (defface notmuch-message-summary-face
273 '((((class color) (background light)) (:background "#f0f0f0"))
274 (((class color) (background dark)) (:background "#303030")))
275 "Face for the single-line message summary in notmuch-show-mode."
277 :group 'notmuch-faces)
279 (defface notmuch-search-date
280 '((t :inherit default))
281 "Face used in search mode for dates."
282 :group 'notmuch-search
283 :group 'notmuch-faces)
285 (defface notmuch-search-count
286 '((t :inherit default))
287 "Face used in search mode for the count matching the query."
288 :group 'notmuch-search
289 :group 'notmuch-faces)
291 (defface notmuch-search-subject
292 '((t :inherit default))
293 "Face used in search mode for subjects."
294 :group 'notmuch-search
295 :group 'notmuch-faces)
297 (defface notmuch-search-matching-authors
298 '((t :inherit default))
299 "Face used in search mode for authors matching the query."
300 :group 'notmuch-search
301 :group 'notmuch-faces)
303 (defface notmuch-search-non-matching-authors
306 (:foreground "grey30"))
309 (:foreground "grey60"))
312 "Face used in search mode for authors not matching the query."
313 :group 'notmuch-search
314 :group 'notmuch-faces)
316 (defface notmuch-tag-face
319 (:foreground "OliveDrab1"))
322 (:foreground "navy blue" :bold t))
325 "Face used in search mode face for tags."
326 :group 'notmuch-search
327 :group 'notmuch-faces)
329 (defface notmuch-search-flagged-face
332 (:foreground "LightBlue1"))
335 (:foreground "blue")))
336 "Face used in search mode face for flagged threads.
338 This face is the default value for the \"flagged\" tag in
339 `notmuch-search-line-faces`."
340 :group 'notmuch-search
341 :group 'notmuch-faces)
343 (defface notmuch-search-unread-face
346 "Face used in search mode for unread threads.
348 This face is the default value for the \"unread\" tag in
349 `notmuch-search-line-faces`."
350 :group 'notmuch-search
351 :group 'notmuch-faces)
353 (define-derived-mode notmuch-search-mode fundamental-mode "notmuch-search"
354 "Major mode displaying results of a notmuch search.
356 This buffer contains the results of a \"notmuch search\" of your
357 email archives. Each line in the buffer represents a single
358 thread giving a summary of the thread (a relative date, the
359 number of matched messages and total messages in the thread,
360 participants in the thread, a representative subject line, and
363 Pressing \\[notmuch-search-show-thread] on any line displays that
364 thread. The '\\[notmuch-search-add-tag]' and
365 '\\[notmuch-search-remove-tag]' keys can be used to add or remove
366 tags from a thread. The '\\[notmuch-search-archive-thread]' key
367 is a convenience for archiving a thread (applying changes in
368 `notmuch-archive-tags'). The '\\[notmuch-search-tag-all]' key can
369 be used to add and/or remove tags from all messages (as opposed
370 to threads) that match the current query. Use with caution, as
371 this will also tag matching messages that arrived *after*
372 constructing the buffer.
374 Other useful commands are '\\[notmuch-search-filter]' for
375 filtering the current search based on an additional query string,
376 '\\[notmuch-search-filter-by-tag]' for filtering to include only
377 messages with a given tag, and '\\[notmuch-search]' to execute a
380 Complete list of currently available key bindings:
382 \\{notmuch-search-mode-map}"
383 (make-local-variable 'notmuch-search-query-string)
384 (make-local-variable 'notmuch-search-oldest-first)
385 (make-local-variable 'notmuch-search-target-thread)
386 (make-local-variable 'notmuch-search-target-line)
387 (setq notmuch-buffer-refresh-function #'notmuch-search-refresh-view)
388 (set (make-local-variable 'scroll-preserve-screen-position) t)
389 (add-to-invisibility-spec (cons 'ellipsis t))
390 (setq truncate-lines t)
391 (setq buffer-read-only t)
392 (setq imenu-prev-index-position-function
393 #'notmuch-search-imenu-prev-index-position-function)
394 (setq imenu-extract-index-name-function
395 #'notmuch-search-imenu-extract-index-name-function))
397 (defun notmuch-search-get-result (&optional pos)
398 "Return the result object for the thread at POS (or point).
400 If there is no thread at POS (or point), returns nil."
401 (get-text-property (or pos (point)) 'notmuch-search-result))
403 (defun notmuch-search-result-beginning (&optional pos)
404 "Return the point at the beginning of the thread at POS (or point).
406 If there is no thread at POS (or point), returns nil."
407 (when (notmuch-search-get-result pos)
408 ;; We pass 1+point because previous-single-property-change starts
409 ;; searching one before the position we give it.
410 (previous-single-property-change (1+ (or pos (point)))
411 'notmuch-search-result nil (point-min))))
413 (defun notmuch-search-result-end (&optional pos)
414 "Return the point at the end of the thread at POS (or point).
416 The returned point will be just after the newline character that
417 ends the result line. If there is no thread at POS (or point),
419 (when (notmuch-search-get-result pos)
420 (next-single-property-change (or pos (point)) 'notmuch-search-result
423 (defun notmuch-search-foreach-result (beg end fn)
424 "Invoke FN for each result between BEG and END.
426 FN should take one argument. It will be applied to the
427 character position of the beginning of each result that overlaps
428 the region between points BEG and END. As a special case, if (=
429 BEG END), FN will be applied to the result containing point
432 (lexical-let ((pos (notmuch-search-result-beginning beg))
433 ;; End must be a marker in case fn changes the
435 (end (copy-marker end))
436 ;; Make sure we examine at least one result, even if
439 ;; We have to be careful if the region extends beyond the results.
440 ;; In this case, pos could be null or there could be no result at
442 (while (and pos (or (< pos end) first))
443 (when (notmuch-search-get-result pos)
445 (setq pos (notmuch-search-result-end pos)
447 ;; Unindent the function argument of notmuch-search-foreach-result so
448 ;; the indentation of callers doesn't get out of hand.
449 (put 'notmuch-search-foreach-result 'lisp-indent-function 2)
451 (defun notmuch-search-properties-in-region (property beg end)
453 (notmuch-search-foreach-result beg end
455 (push (plist-get (notmuch-search-get-result pos) property) output)))
458 (defun notmuch-search-find-thread-id (&optional bare)
459 "Return the thread for the current thread
461 If BARE is set then do not prefix with \"thread:\""
462 (let ((thread (plist-get (notmuch-search-get-result) :thread)))
463 (when thread (concat (unless bare "thread:") thread))))
465 (defun notmuch-search-find-stable-query ()
466 "Return the stable queries for the current thread.
468 This returns a list (MATCHED-QUERY UNMATCHED-QUERY) for the
469 matched and unmatched messages in the current thread."
470 (plist-get (notmuch-search-get-result) :query))
472 (defun notmuch-search-find-stable-query-region (beg end &optional only-matched)
473 "Return the stable query for the current region.
475 If ONLY-MATCHED is non-nil, include only matched messages. If it
476 is nil, include both matched and unmatched messages. If there are
477 no messages in the region then return nil."
478 (let ((query-list nil) (all (not only-matched)))
479 (dolist (queries (notmuch-search-properties-in-region :query beg end))
480 (when (first queries)
481 (push (first queries) query-list))
482 (when (and all (second queries))
483 (push (second queries) query-list)))
485 (concat "(" (mapconcat 'identity query-list ") or (") ")"))))
487 (defun notmuch-search-find-authors ()
488 "Return the authors for the current thread"
489 (plist-get (notmuch-search-get-result) :authors))
491 (defun notmuch-search-find-authors-region (beg end)
492 "Return a list of authors for the current region"
493 (notmuch-search-properties-in-region :authors beg end))
495 (defun notmuch-search-find-subject ()
496 "Return the subject for the current thread"
497 (plist-get (notmuch-search-get-result) :subject))
499 (defun notmuch-search-find-subject-region (beg end)
500 "Return a list of authors for the current region"
501 (notmuch-search-properties-in-region :subject beg end))
503 (defun notmuch-search-show-thread (&optional elide-toggle)
504 "Display the currently selected thread.
506 With a prefix argument, invert the default value of
507 `notmuch-show-only-matching-messages' when displaying the
510 (let ((thread-id (notmuch-search-find-thread-id))
511 (subject (notmuch-search-find-subject)))
512 (if (> (length thread-id) 0)
513 (notmuch-show thread-id
516 notmuch-search-query-string
517 ;; Name the buffer based on the subject.
518 (concat "*" (truncate-string-to-width subject 30 nil nil t) "*"))
519 (message "End of search results."))))
521 (defun notmuch-tree-from-search-current-query ()
522 "Call notmuch tree with the current query"
524 (notmuch-tree notmuch-search-query-string))
526 (defun notmuch-tree-from-search-thread ()
527 "Show the selected thread with notmuch-tree"
529 (notmuch-tree (notmuch-search-find-thread-id)
530 notmuch-search-query-string
532 (notmuch-prettify-subject (notmuch-search-find-subject))
535 (defun notmuch-search-reply-to-thread (&optional prompt-for-sender)
536 "Begin composing a reply-all to the entire current thread in a new buffer."
538 (let ((message-id (notmuch-search-find-thread-id)))
539 (notmuch-mua-new-reply message-id prompt-for-sender t)))
541 (defun notmuch-search-reply-to-thread-sender (&optional prompt-for-sender)
542 "Begin composing a reply to the entire current thread in a new buffer."
544 (let ((message-id (notmuch-search-find-thread-id)))
545 (notmuch-mua-new-reply message-id prompt-for-sender nil)))
547 (defun notmuch-search-set-tags (tags &optional pos)
548 (let ((new-result (plist-put (notmuch-search-get-result pos) :tags tags)))
549 (notmuch-search-update-result new-result pos)))
551 (defun notmuch-search-get-tags (&optional pos)
552 (plist-get (notmuch-search-get-result pos) :tags))
554 (defun notmuch-search-get-tags-region (beg end)
556 (notmuch-search-foreach-result beg end
558 (setq output (append output (notmuch-search-get-tags pos)))))
561 (defun notmuch-search-interactive-tag-changes (&optional initial-input)
562 "Prompt for tag changes for the current thread or region.
564 Returns (TAG-CHANGES REGION-BEGIN REGION-END)."
565 (let* ((region (notmuch-interactive-region))
566 (beg (first region)) (end (second region))
567 (prompt (if (= beg end) "Tag thread" "Tag region")))
568 (cons (notmuch-read-tag-changes
569 (notmuch-search-get-tags-region beg end) prompt initial-input)
572 (defun notmuch-search-tag (tag-changes &optional beg end only-matched)
573 "Change tags for the currently selected thread or region.
575 See `notmuch-tag' for information on the format of TAG-CHANGES.
576 When called interactively, this uses the region if the region is
577 active. When called directly, BEG and END provide the region.
578 If these are nil or not provided, then, if the region is active
579 this applied to all threads meeting the region, and if the region
580 is inactive this applies to the thread at point.
582 If ONLY-MATCHED is non-nil, only tag matched messages."
583 (interactive (notmuch-search-interactive-tag-changes))
584 (unless (and beg end)
585 (setq beg (car (notmuch-interactive-region))
586 end (cadr (notmuch-interactive-region))))
587 (let ((search-string (notmuch-search-find-stable-query-region
588 beg end only-matched)))
589 (notmuch-tag search-string tag-changes)
590 (notmuch-search-foreach-result beg end
592 (notmuch-search-set-tags
593 (notmuch-update-tags (notmuch-search-get-tags pos) tag-changes)
596 (defun notmuch-search-add-tag (tag-changes &optional beg end)
597 "Change tags for the current thread or region (defaulting to add).
599 Same as `notmuch-search-tag' but sets initial input to '+'."
600 (interactive (notmuch-search-interactive-tag-changes "+"))
601 (notmuch-search-tag tag-changes beg end))
603 (defun notmuch-search-remove-tag (tag-changes &optional beg end)
604 "Change tags for the current thread or region (defaulting to remove).
606 Same as `notmuch-search-tag' but sets initial input to '-'."
607 (interactive (notmuch-search-interactive-tag-changes "-"))
608 (notmuch-search-tag tag-changes beg end))
610 (put 'notmuch-search-archive-thread 'notmuch-prefix-doc
611 "Un-archive the currently selected thread.")
612 (defun notmuch-search-archive-thread (&optional unarchive beg end)
613 "Archive the currently selected thread or region.
615 Archive each message in the currently selected thread by applying
616 the tag changes in `notmuch-archive-tags' to each (remove the
617 \"inbox\" tag by default). If a prefix argument is given, the
618 messages will be \"unarchived\" (i.e. the tag changes in
619 `notmuch-archive-tags' will be reversed).
621 This function advances the next thread when finished."
622 (interactive (cons current-prefix-arg (notmuch-interactive-region)))
623 (when notmuch-archive-tags
625 (notmuch-tag-change-list notmuch-archive-tags unarchive) beg end))
627 (notmuch-search-next-thread)))
629 (defun notmuch-search-update-result (result &optional pos)
630 "Replace the result object of the thread at POS (or point) by
631 RESULT and redraw it.
633 This will keep point in a reasonable location. However, if there
634 are enclosing save-excursions and the saved point is in the
635 result being updated, the point will be restored to the beginning
637 (let ((start (notmuch-search-result-beginning pos))
638 (end (notmuch-search-result-end pos))
640 (inhibit-read-only t))
641 ;; Delete the current thread
642 (delete-region start end)
643 ;; Insert the updated thread
644 (notmuch-search-show-result result start)
645 ;; If point was inside the old result, make an educated guess
646 ;; about where to place it now. Unfortunately, this won't work
647 ;; with save-excursion (or any other markers that would be nice to
648 ;; preserve, such as the window start), but there's nothing we can
649 ;; do about that without a way to retrieve markers in a region.
650 (when (and (>= init-point start) (<= init-point end))
651 (let* ((new-end (notmuch-search-result-end start))
652 (new-point (if (= init-point end)
654 (min init-point (- new-end 1)))))
655 (goto-char new-point)))))
657 (defun notmuch-search-process-sentinel (proc msg)
658 "Add a message to let user know when \"notmuch search\" exits"
659 (let ((buffer (process-buffer proc))
660 (status (process-status proc))
661 (exit-status (process-exit-status proc))
662 (never-found-target-thread nil))
663 (when (memq status '(exit signal))
665 (kill-buffer (process-get proc 'parse-buf))
666 (if (buffer-live-p buffer)
667 (with-current-buffer buffer
669 (let ((inhibit-read-only t)
671 (goto-char (point-max))
672 (if (eq status 'signal)
673 (insert "Incomplete search results (search process was killed).\n"))
674 (when (eq status 'exit)
675 (insert "End of search results.\n")
676 ;; For version mismatch, there's no point in
677 ;; showing the search buffer
678 (when (or (= exit-status 20) (= exit-status 21))
682 (not (string= notmuch-search-target-thread "found")))
683 (set 'never-found-target-thread t)))))
684 (when (and never-found-target-thread
685 notmuch-search-target-line)
686 (goto-char (point-min))
687 (forward-line (1- notmuch-search-target-line)))))))))
689 (define-widget 'notmuch--custom-face-edit 'lazy
690 "Custom face edit with a tag Edit Face"
691 ;; I could not persuage custom-face-edit to respect the :tag
692 ;; property so create a widget specially
693 :tag "Manually specify face"
694 :type 'custom-face-edit)
696 (defcustom notmuch-search-line-faces
697 '(("unread" . notmuch-search-unread-face)
698 ("flagged" . notmuch-search-flagged-face))
699 "Alist of tags to faces for line highlighting in notmuch-search.
700 Each element looks like (TAG . FACE).
701 A thread with TAG will have FACE applied.
703 Here is an example of how to color search results based on tags.
704 (the following text would be placed in your ~/.emacs file):
706 (setq notmuch-search-line-faces \\='((\"unread\" . (:foreground \"green\"))
707 (\"deleted\" . (:foreground \"red\"
708 :background \"blue\"))))
710 The FACE must be a face name (a symbol or string), a property
711 list of face attributes, or a list of these. The faces for
712 matching tags are merged, with earlier attributes overriding
713 later. A message having both \"deleted\" and \"unread\" tags with
714 the above settings would have a green foreground and blue
716 :type '(alist :key-type (string)
717 :value-type (radio (face :tag "Face name")
718 (notmuch--custom-face-edit)))
719 :group 'notmuch-search
720 :group 'notmuch-faces)
722 (defun notmuch-search-color-line (start end line-tag-list)
723 "Colorize lines in `notmuch-show' based on tags."
724 ;; Reverse the list so earlier entries take precedence
725 (dolist (elem (reverse notmuch-search-line-faces))
726 (let ((tag (car elem))
728 (when (member tag line-tag-list)
729 (notmuch-apply-face nil face nil start end)))))
731 (defun notmuch-search-author-propertize (authors)
732 "Split `authors' into matching and non-matching authors and
733 propertize appropriately. If no boundary between authors and
734 non-authors is found, assume that all of the authors match."
735 (if (string-match "\\(.*\\)|\\(.*\\)" authors)
736 (concat (propertize (concat (match-string 1 authors) ",")
737 'face 'notmuch-search-matching-authors)
738 (propertize (match-string 2 authors)
739 'face 'notmuch-search-non-matching-authors))
740 (propertize authors 'face 'notmuch-search-matching-authors)))
742 (defun notmuch-search-insert-authors (format-string authors)
743 ;; Save the match data to avoid interfering with
744 ;; `notmuch-search-process-filter'.
746 (let* ((formatted-authors (format format-string authors))
747 (formatted-sample (format format-string ""))
748 (visible-string formatted-authors)
749 (invisible-string "")
752 ;; Truncate the author string to fit the specification.
753 (if (> (length formatted-authors)
754 (length formatted-sample))
755 (let ((visible-length (- (length formatted-sample)
757 ;; Truncate the visible string according to the width of
758 ;; the display string.
759 (setq visible-string (substring formatted-authors 0 visible-length)
760 invisible-string (substring formatted-authors visible-length))
761 ;; If possible, truncate the visible string at a natural
762 ;; break (comma or pipe), as incremental search doesn't
763 ;; match across the visible/invisible border.
764 (when (string-match "\\(.*\\)\\([,|] \\)\\([^,|]*\\)" visible-string)
765 ;; Second clause is destructive on `visible-string', so
766 ;; order is important.
767 (setq invisible-string (concat (match-string 3 visible-string)
769 visible-string (concat (match-string 1 visible-string)
770 (match-string 2 visible-string))))
771 ;; `visible-string' may be shorter than the space allowed
772 ;; by `format-string'. If so we must insert some padding
773 ;; after `invisible-string'.
774 (setq padding (make-string (- (length formatted-sample)
775 (length visible-string)
779 ;; Use different faces to show matching and non-matching authors.
780 (if (string-match "\\(.*\\)|\\(.*\\)" visible-string)
781 ;; The visible string contains both matching and
782 ;; non-matching authors.
783 (setq visible-string (notmuch-search-author-propertize visible-string)
784 ;; The invisible string must contain only non-matching
785 ;; authors, as the visible-string contains both.
786 invisible-string (propertize invisible-string
787 'face 'notmuch-search-non-matching-authors))
788 ;; The visible string contains only matching authors.
789 (setq visible-string (propertize visible-string
790 'face 'notmuch-search-matching-authors)
791 ;; The invisible string may contain both matching and
792 ;; non-matching authors.
793 invisible-string (notmuch-search-author-propertize invisible-string)))
795 ;; If there is any invisible text, add it as a tooltip to the
797 (when (not (string= invisible-string ""))
798 (setq visible-string (propertize visible-string 'help-echo (concat "..." invisible-string))))
800 ;; Insert the visible and, if present, invisible author strings.
801 (insert visible-string)
802 (when (not (string= invisible-string ""))
803 (let ((start (point))
805 (insert invisible-string)
806 (setq overlay (make-overlay start (point)))
807 (overlay-put overlay 'invisible 'ellipsis)
808 (overlay-put overlay 'isearch-open-invisible #'delete-overlay)))
811 (defun notmuch-search-insert-field (field format-string result)
813 ((string-equal field "date")
814 (insert (propertize (format format-string (plist-get result :date_relative))
815 'face 'notmuch-search-date)))
816 ((string-equal field "count")
817 (insert (propertize (format format-string
818 (format "[%s/%s]" (plist-get result :matched)
819 (plist-get result :total)))
820 'face 'notmuch-search-count)))
821 ((string-equal field "subject")
822 (insert (propertize (format format-string
823 (notmuch-sanitize (plist-get result :subject)))
824 'face 'notmuch-search-subject)))
826 ((string-equal field "authors")
827 (notmuch-search-insert-authors
828 format-string (notmuch-sanitize (plist-get result :authors))))
830 ((string-equal field "tags")
831 (let ((tags (plist-get result :tags))
832 (orig-tags (plist-get result :orig-tags)))
833 (insert (format format-string (notmuch-tag-format-tags tags orig-tags)))))))
835 (defun notmuch-search-show-result (result pos)
836 "Insert RESULT at POS."
837 ;; Ignore excluded matches
838 (unless (= (plist-get result :matched) 0)
841 (dolist (spec notmuch-search-result-format)
842 (notmuch-search-insert-field (car spec) (cdr spec) result))
844 (notmuch-search-color-line pos (point) (plist-get result :tags))
845 (put-text-property pos (point) 'notmuch-search-result result))))
847 (defun notmuch-search-append-result (result)
848 "Insert RESULT at the end of the buffer.
850 This is only called when a result is first inserted so it also
851 sets the :orig-tag property."
852 (let ((new-result (plist-put result :orig-tags (plist-get result :tags)))
854 (notmuch-search-show-result new-result pos)
855 (when (string= (plist-get result :thread) notmuch-search-target-thread)
856 (setq notmuch-search-target-thread "found")
859 (defun notmuch-search-process-filter (proc string)
860 "Process and filter the output of \"notmuch search\""
861 (let ((results-buf (process-buffer proc))
862 (parse-buf (process-get proc 'parse-buf))
863 (inhibit-read-only t)
865 (when (buffer-live-p results-buf)
866 (with-current-buffer parse-buf
869 (goto-char (point-max))
871 (notmuch-sexp-parse-partial-list 'notmuch-search-append-result
874 (defun notmuch-search-tag-all (tag-changes)
875 "Add/remove tags from all messages in current search buffer.
877 See `notmuch-tag' for information on the format of TAG-CHANGES."
879 (list (notmuch-read-tag-changes
880 (notmuch-search-get-tags-region (point-min) (point-max)) "Tag all")))
881 (notmuch-search-tag tag-changes (point-min) (point-max) t))
883 (defun notmuch-search-buffer-title (query)
884 "Returns the title for a buffer with notmuch search results."
888 (loop for tuple in notmuch-saved-searches
889 if (let ((quoted-query (regexp-quote (notmuch-saved-search-get tuple :query))))
890 (and (string-match (concat "^" quoted-query) query)
891 (> (length (match-string 0 query))
893 do (setq longest tuple))
895 (saved-search-name (notmuch-saved-search-get saved-search :name))
896 (saved-search-query (notmuch-saved-search-get saved-search :query)))
897 (cond ((and saved-search (equal saved-search-query query))
898 ;; Query is the same as saved search (ignoring case)
899 (concat "*notmuch-saved-search-" saved-search-name "*"))
901 (concat "*notmuch-search-"
902 (replace-regexp-in-string (concat "^" (regexp-quote saved-search-query))
903 (concat "[ " saved-search-name " ]")
907 (concat "*notmuch-search-" query "*"))
910 (defun notmuch-read-query (prompt)
911 "Read a notmuch-query from the minibuffer with completion.
913 PROMPT is the string to prompt with."
916 (mapcar (lambda (tag) (notmuch-escape-boolean-term tag))
917 (process-lines notmuch-command "search" "--output=tags" "*")))
919 (append (list "folder:" "path:" "thread:" "id:" "date:" "from:" "to:"
920 "subject:" "attachment:")
921 (mapcar (lambda (tag) (concat "tag:" tag)) all-tags)
922 (mapcar (lambda (tag) (concat "is:" tag)) all-tags)
923 (mapcar (lambda (mimetype) (concat "mimetype:" mimetype)) (mailcap-mime-types)))))
924 (let ((keymap (copy-keymap minibuffer-local-map))
925 (current-query (case major-mode
926 (notmuch-search-mode (notmuch-search-get-query))
927 (notmuch-show-mode (notmuch-show-get-query))
928 (notmuch-tree-mode (notmuch-tree-get-query))))
929 (minibuffer-completion-table
930 (completion-table-dynamic
932 ;; generate a list of possible completions for the current input
934 ;; this ugly regexp is used to get the last word of the input
935 ;; possibly preceded by a '('
936 ((string-match "\\(^\\|.* (?\\)\\([^ ]*\\)$" string)
937 (mapcar (lambda (compl)
938 (concat (match-string-no-properties 1 string) compl))
939 (all-completions (match-string-no-properties 2 string)
941 (t (list string)))))))
942 ;; this was simpler than convincing completing-read to accept spaces:
943 (define-key keymap (kbd "TAB") 'minibuffer-complete)
944 (let ((history-delete-duplicates t))
945 (read-from-minibuffer prompt nil keymap nil
946 'notmuch-search-history current-query nil)))))
948 (defun notmuch-search-get-query ()
949 "Return the current query in this search buffer"
950 notmuch-search-query-string)
952 (put 'notmuch-search 'notmuch-doc "Search for messages.")
954 (defun notmuch-search (&optional query oldest-first target-thread target-line no-display)
955 "Display threads matching QUERY in a notmuch-search buffer.
957 If QUERY is nil, it is read interactively from the minibuffer.
958 Other optional parameters are used as follows:
960 OLDEST-FIRST: A Boolean controlling the sort order of returned threads
961 TARGET-THREAD: A thread ID (without the thread: prefix) that will be made
962 current if it appears in the search results.
963 TARGET-LINE: The line number to move to if the target thread does not
964 appear in the search results.
965 NO-DISPLAY: Do not try to foreground the search results buffer. If it is
966 already foregrounded i.e. displayed in a window, this has no
967 effect, meaning the buffer will remain visible.
969 When called interactively, this will prompt for a query and use
970 the configured default sort order."
973 ;; Prompt for a query
975 ;; Use the default search order (if we're doing a search from a
976 ;; search buffer, ignore any buffer-local overrides)
977 (default-value 'notmuch-search-oldest-first)))
979 (let* ((query (or query (notmuch-read-query "Notmuch search: ")))
980 (buffer (get-buffer-create (notmuch-search-buffer-title query))))
983 (switch-to-buffer buffer))
984 (notmuch-search-mode)
985 ;; Don't track undo information for this buffer
986 (set 'buffer-undo-list t)
987 (set 'notmuch-search-query-string query)
988 (set 'notmuch-search-oldest-first oldest-first)
989 (set 'notmuch-search-target-thread target-thread)
990 (set 'notmuch-search-target-line target-line)
991 (notmuch-tag-clear-cache)
992 (let ((proc (get-buffer-process (current-buffer)))
993 (inhibit-read-only t))
995 (error "notmuch search process already running for query `%s'" query)
998 (goto-char (point-min))
1000 (let ((proc (notmuch-start-notmuch
1001 "notmuch-search" buffer #'notmuch-search-process-sentinel
1002 "search" "--format=sexp" "--format-version=4"
1004 "--sort=oldest-first"
1005 "--sort=newest-first")
1007 ;; Use a scratch buffer to accumulate partial output.
1008 ;; This buffer will be killed by the sentinel, which
1009 ;; should be called no matter how the process dies.
1010 (parse-buf (generate-new-buffer " *notmuch search parse*")))
1011 (process-put proc 'parse-buf parse-buf)
1012 (set-process-filter proc 'notmuch-search-process-filter)
1013 (set-process-query-on-exit-flag proc nil))))
1014 (run-hooks 'notmuch-search-hook)))
1016 (defun notmuch-search-refresh-view ()
1017 "Refresh the current view.
1019 Erases the current buffer and runs a new search with the same
1020 query string as the current search. If the current thread is in
1021 the new search results, then point will be placed on the same
1022 thread. Otherwise, point will be moved to attempt to be in the
1023 same relative position within the new buffer."
1025 (let ((target-line (line-number-at-pos))
1026 (oldest-first notmuch-search-oldest-first)
1027 (target-thread (notmuch-search-find-thread-id 'bare))
1028 (query notmuch-search-query-string))
1029 ;; notmuch-search erases the current buffer.
1030 (notmuch-search query oldest-first target-thread target-line t)
1031 (goto-char (point-min))))
1033 (defun notmuch-search-toggle-order ()
1034 "Toggle the current search order.
1036 This command toggles the sort order for the current search. The
1037 default sort order is defined by `notmuch-search-oldest-first'."
1039 (set 'notmuch-search-oldest-first (not notmuch-search-oldest-first))
1040 (notmuch-search-refresh-view))
1042 (defun notmuch-group-disjunctive-query-string (query-string)
1043 "Group query if it contains a complex expression.
1045 Enclose QUERY-STRING in parentheses if it matches
1046 `notmuch-search-disjunctive-regexp'."
1047 (if (string-match-p notmuch-search-disjunctive-regexp query-string)
1048 (concat "( " query-string " )")
1051 (defun notmuch-search-filter (query)
1052 "Filter or LIMIT the current search results based on an additional query string.
1054 Runs a new search matching only messages that match both the
1055 current search results AND the additional query string provided."
1056 (interactive (list (notmuch-read-query "Filter search: ")))
1057 (let ((grouped-query (notmuch-group-disjunctive-query-string query))
1058 (grouped-original-query (notmuch-group-disjunctive-query-string
1059 notmuch-search-query-string)))
1060 (notmuch-search (if (string= grouped-original-query "*")
1062 (concat grouped-original-query " and " grouped-query))
1063 notmuch-search-oldest-first)))
1065 (defun notmuch-search-filter-by-tag (tag)
1066 "Filter the current search results based on a single tag.
1068 Runs a new search matching only messages that match both the
1069 current search results AND that are tagged with the given tag."
1071 (list (notmuch-select-tag-with-completion "Filter by tag: " notmuch-search-query-string)))
1072 (notmuch-search (concat notmuch-search-query-string " and tag:" tag) notmuch-search-oldest-first))
1076 "Run notmuch and display saved searches, known tags, etc."
1080 (defun notmuch-interesting-buffer (b)
1081 "Is the current buffer of interest to a notmuch user?"
1082 (with-current-buffer b
1083 (memq major-mode '(notmuch-show-mode
1087 notmuch-message-mode))))
1090 (defun notmuch-cycle-notmuch-buffers ()
1091 "Cycle through any existing notmuch buffers (search, show or hello).
1093 If the current buffer is the only notmuch buffer, bury it. If no
1094 notmuch buffers exist, run `notmuch'."
1098 ;; If the current buffer is a notmuch buffer, remember it and then
1100 (when (notmuch-interesting-buffer (current-buffer))
1101 (setq start (current-buffer))
1104 ;; Find the first notmuch buffer.
1105 (setq first (loop for buffer in (buffer-list)
1106 if (notmuch-interesting-buffer buffer)
1110 ;; If the first one we found is any other than the starting
1111 ;; buffer, switch to it.
1112 (unless (eq first start)
1113 (switch-to-buffer first))
1118 (defun notmuch-search-imenu-prev-index-position-function ()
1119 "Move point to previous message in notmuch-search buffer.
1120 This function is used as a value for
1121 `imenu-prev-index-position-function'."
1122 (notmuch-search-previous-thread))
1124 (defun notmuch-search-imenu-extract-index-name-function ()
1125 "Return imenu name for line at point.
1126 This function is used as a value for
1127 `imenu-extract-index-name-function'. Point should be at the
1128 beginning of the line."
1129 (let ((subject (notmuch-search-find-subject))
1130 (author (notmuch-search-find-authors)))
1131 (format "%s (%s)" subject author)))
1133 (setq mail-user-agent 'notmuch-user-agent)
1137 ;; After provide to avoid loops if notmuch was require'd via notmuch-init-file.
1138 (if init-file-user ; don't load init file if the -q option was used.
1139 (let ((init-file (locate-file notmuch-init-file '("/")
1140 (get-load-suffixes))))
1141 (if init-file (load init-file nil t t))))
1143 ;;; notmuch.el ends here