]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch.el
emacs: Add new option notmuch-search-hide-excluded
[notmuch] / emacs / notmuch.el
1 ;;; notmuch.el --- run notmuch within emacs
2 ;;
3 ;; Copyright © Carl Worth
4 ;;
5 ;; This file is part of Notmuch.
6 ;;
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.
11 ;;
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.
16 ;;
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/>.
19 ;;
20 ;; Authors: Carl Worth <cworth@cworth.org>
21 ;; Homepage: https://notmuchmail.org/
22
23 ;;; Commentary:
24
25 ;; This is an emacs-based interface to the notmuch mail system.
26 ;;
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.
30 ;;
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:
35 ;;
36 ;;      sudo make install-emacs
37 ;;
38 ;; to install it.
39 ;;
40 ;; Then, to actually run it, add:
41 ;;
42 ;;      (autoload 'notmuch "notmuch" "Notmuch mail" t)
43 ;;
44 ;; to your ~/.emacs file, and then run "M-x notmuch" from within emacs,
45 ;; or run:
46 ;;
47 ;;      emacs -f notmuch
48 ;;
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).
52 ;;
53 ;; Note for MELPA users (and others tracking the development version
54 ;; of notmuch-emacs):
55 ;;
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.
62 ;;
63 ;; TL;DR: notmuch-emacs from MELPA and notmuch from distro packages is
64 ;; NOT SUPPORTED.
65 ;;
66 ;;; Code:
67
68 (eval-when-compile (require 'cl))
69 (require 'mm-view)
70 (require 'message)
71
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)
81
82 (defcustom notmuch-search-result-format
83   `(("date" . "%12s ")
84     ("count" . "%-7s ")
85     ("authors" . "%-20s ")
86     ("subject" . "%s ")
87     ("tags" . "(%s)"))
88   "Search result formatting. Supported fields are:
89         date, count, authors, subject, tags
90 For example:
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)
101
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."
111   :type 'file
112   :group 'notmuch)
113
114 (defvar notmuch-query-history nil
115   "Variable to store minibuffer history for notmuch queries")
116
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)))))
125
126 (defun notmuch-count-attachments (mm-handle)
127   (let ((count 0))
128     (notmuch-foreach-mime-part
129      (lambda (p)
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)))
135               (incf count))))
136      mm-handle)
137     count))
138
139 (defun notmuch-save-attachments (mm-handle &optional queryp)
140   (notmuch-foreach-mime-part
141    (lambda (p)
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)))
147             (or (not queryp)
148                 (y-or-n-p
149                  (concat "Save '" (cdr (assq 'filename disposition)) "' ")))
150             (mm-save-part p))))
151    mm-handle))
152
153 (require 'hl-line)
154
155 (defun notmuch-hl-line-mode ()
156   (prog1 (hl-line-mode)
157     (when hl-line-overlay
158       (overlay-put hl-line-overlay 'priority 1))))
159
160 (defcustom notmuch-search-hook '(notmuch-hl-line-mode)
161   "List of functions to call when notmuch displays the search results."
162   :type 'hook
163   :options '(notmuch-hl-line-mode)
164   :group 'notmuch-search
165   :group 'notmuch-hooks)
166
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 "Z" 'notmuch-tree-from-search-current-query)
192     map)
193   "Keymap for \"notmuch search\" buffers.")
194 (fset 'notmuch-search-mode-map notmuch-search-mode-map)
195
196 (defvar notmuch-search-stash-map
197   (let ((map (make-sparse-keymap)))
198     (define-key map "i" 'notmuch-search-stash-thread-id)
199     (define-key map "q" 'notmuch-stash-query)
200     (define-key map "?" 'notmuch-subkeymap-help)
201     map)
202   "Submap for stash commands")
203 (fset 'notmuch-search-stash-map notmuch-search-stash-map)
204
205 (defun notmuch-search-stash-thread-id ()
206   "Copy thread ID of current thread to kill-ring."
207   (interactive)
208   (notmuch-common-do-stash (notmuch-search-find-thread-id)))
209
210 (defun notmuch-stash-query ()
211   "Copy current query to kill-ring."
212   (interactive)
213   (notmuch-common-do-stash (notmuch-search-get-query)))
214
215 (defvar notmuch-search-query-string)
216 (defvar notmuch-search-target-thread)
217 (defvar notmuch-search-target-line)
218
219 (defvar notmuch-search-disjunctive-regexp      "\\<[oO][rR]\\>")
220
221 (defun notmuch-search-scroll-up ()
222   "Move forward through search results by one window's worth."
223   (interactive)
224   (condition-case nil
225       (scroll-up nil)
226     ((end-of-buffer) (notmuch-search-last-thread))))
227
228 (defun notmuch-search-scroll-down ()
229   "Move backward through the search results by one window's worth."
230   (interactive)
231   ;; I don't know why scroll-down doesn't signal beginning-of-buffer
232   ;; the way that scroll-up signals end-of-buffer, but c'est la vie.
233   ;;
234   ;; So instead of trapping a signal we instead check whether the
235   ;; window begins on the first line of the buffer and if so, move
236   ;; directly to that position. (We have to count lines since the
237   ;; window-start position is not the same as point-min due to the
238   ;; invisible thread-ID characters on the first line.
239   (if (equal (count-lines (point-min) (window-start)) 0)
240       (goto-char (point-min))
241     (scroll-down nil)))
242
243 (defun notmuch-search-next-thread ()
244   "Select the next thread in the search results."
245   (interactive)
246   (when (notmuch-search-get-result)
247     (goto-char (notmuch-search-result-end))))
248
249 (defun notmuch-search-previous-thread ()
250   "Select the previous thread in the search results."
251   (interactive)
252   (if (notmuch-search-get-result)
253       (unless (bobp)
254         (goto-char (notmuch-search-result-beginning (- (point) 1))))
255     ;; We must be past the end; jump to the last result
256     (notmuch-search-last-thread)))
257
258 (defun notmuch-search-last-thread ()
259   "Select the last thread in the search results."
260   (interactive)
261   (goto-char (point-max))
262   (forward-line -2)
263   (let ((beg (notmuch-search-result-beginning)))
264     (when beg (goto-char beg))))
265
266 (defun notmuch-search-first-thread ()
267   "Select the first thread in the search results."
268   (interactive)
269   (goto-char (point-min)))
270
271 (defface notmuch-message-summary-face
272  '((((class color) (background light)) (:background "#f0f0f0"))
273    (((class color) (background dark)) (:background "#303030")))
274  "Face for the single-line message summary in notmuch-show-mode."
275  :group 'notmuch-show
276  :group 'notmuch-faces)
277
278 (defface notmuch-search-date
279   '((t :inherit default))
280   "Face used in search mode for dates."
281   :group 'notmuch-search
282   :group 'notmuch-faces)
283
284 (defface notmuch-search-count
285   '((t :inherit default))
286   "Face used in search mode for the count matching the query."
287   :group 'notmuch-search
288   :group 'notmuch-faces)
289
290 (defface notmuch-search-subject
291   '((t :inherit default))
292   "Face used in search mode for subjects."
293   :group 'notmuch-search
294   :group 'notmuch-faces)
295
296 (defface notmuch-search-matching-authors
297   '((t :inherit default))
298   "Face used in search mode for authors matching the query."
299   :group 'notmuch-search
300   :group 'notmuch-faces)
301
302 (defface notmuch-search-non-matching-authors
303   '((((class color)
304       (background dark))
305      (:foreground "grey30"))
306     (((class color)
307       (background light))
308      (:foreground "grey60"))
309     (t
310      (:italic t)))
311   "Face used in search mode for authors not matching the query."
312   :group 'notmuch-search
313   :group 'notmuch-faces)
314
315 (defface notmuch-tag-face
316   '((((class color)
317       (background dark))
318      (:foreground "OliveDrab1"))
319     (((class color)
320       (background light))
321      (:foreground "navy blue" :bold t))
322     (t
323      (:bold t)))
324   "Face used in search mode face for tags."
325   :group 'notmuch-search
326   :group 'notmuch-faces)
327
328 (defface notmuch-search-flagged-face
329   '((((class color)
330       (background dark))
331      (:foreground "LightBlue1"))
332     (((class color)
333       (background light))
334      (:foreground "blue")))
335   "Face used in search mode face for flagged threads.
336
337 This face is the default value for the \"flagged\" tag in
338 `notmuch-search-line-faces`."
339   :group 'notmuch-search
340   :group 'notmuch-faces)
341
342 (defface notmuch-search-unread-face
343   '((t
344      (:weight bold)))
345   "Face used in search mode for unread threads.
346
347 This face is the default value for the \"unread\" tag in
348 `notmuch-search-line-faces`."
349   :group 'notmuch-search
350   :group 'notmuch-faces)
351
352 (define-derived-mode notmuch-search-mode fundamental-mode "notmuch-search"
353   "Major mode displaying results of a notmuch search.
354
355 This buffer contains the results of a \"notmuch search\" of your
356 email archives. Each line in the buffer represents a single
357 thread giving a summary of the thread (a relative date, the
358 number of matched messages and total messages in the thread,
359 participants in the thread, a representative subject line, and
360 any tags).
361
362 Pressing \\[notmuch-search-show-thread] on any line displays that
363 thread. The '\\[notmuch-search-add-tag]' and
364 '\\[notmuch-search-remove-tag]' keys can be used to add or remove
365 tags from a thread. The '\\[notmuch-search-archive-thread]' key
366 is a convenience for archiving a thread (applying changes in
367 `notmuch-archive-tags'). The '\\[notmuch-search-tag-all]' key can
368 be used to add and/or remove tags from all messages (as opposed
369 to threads) that match the current query.  Use with caution, as
370 this will also tag matching messages that arrived *after*
371 constructing the buffer.
372
373 Other useful commands are '\\[notmuch-search-filter]' for
374 filtering the current search based on an additional query string,
375 '\\[notmuch-search-filter-by-tag]' for filtering to include only
376 messages with a given tag, and '\\[notmuch-search]' to execute a
377 new, global search.
378
379 Complete list of currently available key bindings:
380
381 \\{notmuch-search-mode-map}"
382   (make-local-variable 'notmuch-search-query-string)
383   (make-local-variable 'notmuch-search-oldest-first)
384   (make-local-variable 'notmuch-search-target-thread)
385   (make-local-variable 'notmuch-search-target-line)
386   (setq notmuch-buffer-refresh-function #'notmuch-search-refresh-view)
387   (set (make-local-variable 'scroll-preserve-screen-position) t)
388   (add-to-invisibility-spec (cons 'ellipsis t))
389   (setq truncate-lines t)
390   (setq buffer-read-only t)
391   (setq imenu-prev-index-position-function
392         #'notmuch-search-imenu-prev-index-position-function)
393   (setq imenu-extract-index-name-function
394         #'notmuch-search-imenu-extract-index-name-function))
395
396 (defun notmuch-search-get-result (&optional pos)
397   "Return the result object for the thread at POS (or point).
398
399 If there is no thread at POS (or point), returns nil."
400   (get-text-property (or pos (point)) 'notmuch-search-result))
401
402 (defun notmuch-search-result-beginning (&optional pos)
403   "Return the point at the beginning of the thread at POS (or point).
404
405 If there is no thread at POS (or point), returns nil."
406   (when (notmuch-search-get-result pos)
407     ;; We pass 1+point because previous-single-property-change starts
408     ;; searching one before the position we give it.
409     (previous-single-property-change (1+ (or pos (point)))
410                                      'notmuch-search-result nil (point-min))))
411
412 (defun notmuch-search-result-end (&optional pos)
413   "Return the point at the end of the thread at POS (or point).
414
415 The returned point will be just after the newline character that
416 ends the result line.  If there is no thread at POS (or point),
417 returns nil"
418   (when (notmuch-search-get-result pos)
419     (next-single-property-change (or pos (point)) 'notmuch-search-result
420                                  nil (point-max))))
421
422 (defun notmuch-search-foreach-result (beg end fn)
423   "Invoke FN for each result between BEG and END.
424
425 FN should take one argument.  It will be applied to the
426 character position of the beginning of each result that overlaps
427 the region between points BEG and END.  As a special case, if (=
428 BEG END), FN will be applied to the result containing point
429 BEG."
430
431   (lexical-let ((pos (notmuch-search-result-beginning beg))
432                 ;; End must be a marker in case fn changes the
433                 ;; text.
434                 (end (copy-marker end))
435                 ;; Make sure we examine at least one result, even if
436                 ;; (= beg end).
437                 (first t))
438     ;; We have to be careful if the region extends beyond the results.
439     ;; In this case, pos could be null or there could be no result at
440     ;; pos.
441     (while (and pos (or (< pos end) first))
442       (when (notmuch-search-get-result pos)
443         (funcall fn pos))
444       (setq pos (notmuch-search-result-end pos)
445             first nil))))
446 ;; Unindent the function argument of notmuch-search-foreach-result so
447 ;; the indentation of callers doesn't get out of hand.
448 (put 'notmuch-search-foreach-result 'lisp-indent-function 2)
449
450 (defun notmuch-search-properties-in-region (property beg end)
451   (let (output)
452     (notmuch-search-foreach-result beg end
453       (lambda (pos)
454         (push (plist-get (notmuch-search-get-result pos) property) output)))
455     output))
456
457 (defun notmuch-search-find-thread-id (&optional bare)
458   "Return the thread for the current thread
459
460 If BARE is set then do not prefix with \"thread:\""
461   (let ((thread (plist-get (notmuch-search-get-result) :thread)))
462     (when thread (concat (unless bare "thread:") thread))))
463
464 (defun notmuch-search-find-stable-query ()
465   "Return the stable queries for the current thread.
466
467 This returns a list (MATCHED-QUERY UNMATCHED-QUERY) for the
468 matched and unmatched messages in the current thread."
469   (plist-get (notmuch-search-get-result) :query))
470
471 (defun notmuch-search-find-stable-query-region (beg end &optional only-matched)
472   "Return the stable query for the current region.
473
474 If ONLY-MATCHED is non-nil, include only matched messages.  If it
475 is nil, include both matched and unmatched messages. If there are
476 no messages in the region then return nil."
477   (let ((query-list nil) (all (not only-matched)))
478     (dolist (queries (notmuch-search-properties-in-region :query beg end))
479       (when (first queries)
480         (push (first queries) query-list))
481       (when (and all (second queries))
482         (push (second queries) query-list)))
483     (when query-list
484       (concat "(" (mapconcat 'identity query-list ") or (") ")"))))
485
486 (defun notmuch-search-find-authors ()
487   "Return the authors for the current thread"
488   (plist-get (notmuch-search-get-result) :authors))
489
490 (defun notmuch-search-find-authors-region (beg end)
491   "Return a list of authors for the current region"
492   (notmuch-search-properties-in-region :authors beg end))
493
494 (defun notmuch-search-find-subject ()
495   "Return the subject for the current thread"
496   (plist-get (notmuch-search-get-result) :subject))
497
498 (defun notmuch-search-find-subject-region (beg end)
499   "Return a list of authors for the current region"
500   (notmuch-search-properties-in-region :subject beg end))
501
502 (defun notmuch-search-show-thread (&optional elide-toggle)
503   "Display the currently selected thread.
504
505 With a prefix argument, invert the default value of
506 `notmuch-show-only-matching-messages' when displaying the
507 thread."
508   (interactive "P")
509   (let ((thread-id (notmuch-search-find-thread-id))
510         (subject (notmuch-search-find-subject)))
511     (if (> (length thread-id) 0)
512         (notmuch-show thread-id
513                       elide-toggle
514                       (current-buffer)
515                       notmuch-search-query-string
516                       ;; Name the buffer based on the subject.
517                       (concat "*" (truncate-string-to-width subject 30 nil nil t) "*"))
518       (message "End of search results."))))
519
520 (defun notmuch-tree-from-search-current-query ()
521   "Call notmuch tree with the current query"
522   (interactive)
523   (notmuch-tree notmuch-search-query-string))
524
525 (defun notmuch-tree-from-search-thread ()
526   "Show the selected thread with notmuch-tree"
527   (interactive)
528   (notmuch-tree (notmuch-search-find-thread-id)
529                 notmuch-search-query-string
530                 nil
531                 (notmuch-prettify-subject (notmuch-search-find-subject))
532                 t))
533
534 (defun notmuch-search-reply-to-thread (&optional prompt-for-sender)
535   "Begin composing a reply-all to the entire current thread in a new buffer."
536   (interactive "P")
537   (let ((message-id (notmuch-search-find-thread-id)))
538     (notmuch-mua-new-reply message-id prompt-for-sender t)))
539
540 (defun notmuch-search-reply-to-thread-sender (&optional prompt-for-sender)
541   "Begin composing a reply to the entire current thread in a new buffer."
542   (interactive "P")
543   (let ((message-id (notmuch-search-find-thread-id)))
544     (notmuch-mua-new-reply message-id prompt-for-sender nil)))
545
546 (defun notmuch-search-set-tags (tags &optional pos)
547   (let ((new-result (plist-put (notmuch-search-get-result pos) :tags tags)))
548     (notmuch-search-update-result new-result pos)))
549
550 (defun notmuch-search-get-tags (&optional pos)
551   (plist-get (notmuch-search-get-result pos) :tags))
552
553 (defun notmuch-search-get-tags-region (beg end)
554   (let (output)
555     (notmuch-search-foreach-result beg end
556       (lambda (pos)
557         (setq output (append output (notmuch-search-get-tags pos)))))
558     output))
559
560 (defun notmuch-search-interactive-region ()
561   "Return the bounds of the current interactive region.
562
563 This returns (BEG END), where BEG and END are the bounds of the
564 region if the region is active, or both `point' otherwise."
565   (if (region-active-p)
566       (list (region-beginning) (region-end))
567     (list (point) (point))))
568
569 (defun notmuch-search-interactive-tag-changes (&optional initial-input)
570   "Prompt for tag changes for the current thread or region.
571
572 Returns (TAG-CHANGES REGION-BEGIN REGION-END)."
573   (let* ((region (notmuch-search-interactive-region))
574          (beg (first region)) (end (second region))
575          (prompt (if (= beg end) "Tag thread" "Tag region")))
576     (cons (notmuch-read-tag-changes
577            (notmuch-search-get-tags-region beg end) prompt initial-input)
578           region)))
579
580 (defun notmuch-search-tag (tag-changes &optional beg end only-matched)
581   "Change tags for the currently selected thread or region.
582
583 See `notmuch-tag' for information on the format of TAG-CHANGES.
584 When called interactively, this uses the region if the region is
585 active.  When called directly, BEG and END provide the region.
586 If these are nil or not provided, then, if the region is active
587 this applied to all threads meeting the region, and if the region
588 is inactive this applies to the thread at point.
589
590 If ONLY-MATCHED is non-nil, only tag matched messages."
591   (interactive (notmuch-search-interactive-tag-changes))
592   (unless (and beg end)
593     (setq beg (car (notmuch-search-interactive-region))
594           end (cadr (notmuch-search-interactive-region))))
595   (let ((search-string (notmuch-search-find-stable-query-region
596                         beg end only-matched)))
597     (notmuch-tag search-string tag-changes)
598     (notmuch-search-foreach-result beg end
599       (lambda (pos)
600         (notmuch-search-set-tags
601          (notmuch-update-tags (notmuch-search-get-tags pos) tag-changes)
602          pos)))))
603
604 (defun notmuch-search-add-tag (tag-changes &optional beg end)
605   "Change tags for the current thread or region (defaulting to add).
606
607 Same as `notmuch-search-tag' but sets initial input to '+'."
608   (interactive (notmuch-search-interactive-tag-changes "+"))
609   (notmuch-search-tag tag-changes beg end))
610
611 (defun notmuch-search-remove-tag (tag-changes &optional beg end)
612   "Change tags for the current thread or region (defaulting to remove).
613
614 Same as `notmuch-search-tag' but sets initial input to '-'."
615   (interactive (notmuch-search-interactive-tag-changes "-"))
616   (notmuch-search-tag tag-changes beg end))
617
618 (put 'notmuch-search-archive-thread 'notmuch-prefix-doc
619      "Un-archive the currently selected thread.")
620 (defun notmuch-search-archive-thread (&optional unarchive beg end)
621   "Archive the currently selected thread or region.
622
623 Archive each message in the currently selected thread by applying
624 the tag changes in `notmuch-archive-tags' to each (remove the
625 \"inbox\" tag by default). If a prefix argument is given, the
626 messages will be \"unarchived\" (i.e. the tag changes in
627 `notmuch-archive-tags' will be reversed).
628
629 This function advances the next thread when finished."
630   (interactive (cons current-prefix-arg (notmuch-search-interactive-region)))
631   (when notmuch-archive-tags
632     (notmuch-search-tag
633      (notmuch-tag-change-list notmuch-archive-tags unarchive) beg end))
634   (when (eq beg end)
635     (notmuch-search-next-thread)))
636
637 (defun notmuch-search-update-result (result &optional pos)
638   "Replace the result object of the thread at POS (or point) by
639 RESULT and redraw it.
640
641 This will keep point in a reasonable location.  However, if there
642 are enclosing save-excursions and the saved point is in the
643 result being updated, the point will be restored to the beginning
644 of the result."
645   (let ((start (notmuch-search-result-beginning pos))
646         (end (notmuch-search-result-end pos))
647         (init-point (point))
648         (inhibit-read-only t))
649     ;; Delete the current thread
650     (delete-region start end)
651     ;; Insert the updated thread
652     (notmuch-search-show-result result start)
653     ;; If point was inside the old result, make an educated guess
654     ;; about where to place it now.  Unfortunately, this won't work
655     ;; with save-excursion (or any other markers that would be nice to
656     ;; preserve, such as the window start), but there's nothing we can
657     ;; do about that without a way to retrieve markers in a region.
658     (when (and (>= init-point start) (<= init-point end))
659       (let* ((new-end (notmuch-search-result-end start))
660              (new-point (if (= init-point end)
661                             new-end
662                           (min init-point (- new-end 1)))))
663         (goto-char new-point)))))
664
665 (defun notmuch-search-process-sentinel (proc msg)
666   "Add a message to let user know when \"notmuch search\" exits"
667   (let ((buffer (process-buffer proc))
668         (status (process-status proc))
669         (exit-status (process-exit-status proc))
670         (never-found-target-thread nil))
671     (when (memq status '(exit signal))
672       (catch 'return
673         (kill-buffer (process-get proc 'parse-buf))
674         (if (buffer-live-p buffer)
675             (with-current-buffer buffer
676               (save-excursion
677                 (let ((inhibit-read-only t)
678                       (atbob (bobp)))
679                   (goto-char (point-max))
680                   (if (eq status 'signal)
681                       (insert "Incomplete search results (search process was killed).\n"))
682                   (when (eq status 'exit)
683                     (insert "End of search results.\n")
684                     ;; For version mismatch, there's no point in
685                     ;; showing the search buffer
686                     (when (or (= exit-status 20) (= exit-status 21))
687                       (kill-buffer)
688                       (throw 'return nil))
689                     (if (and atbob
690                              (not (string= notmuch-search-target-thread "found")))
691                         (set 'never-found-target-thread t)))))
692               (when (and never-found-target-thread
693                        notmuch-search-target-line)
694                   (goto-char (point-min))
695                   (forward-line (1- notmuch-search-target-line)))))))))
696
697 (define-widget 'notmuch--custom-face-edit 'lazy
698   "Custom face edit with a tag Edit Face"
699   ;; I could not persuage custom-face-edit to respect the :tag
700   ;; property so create a widget specially
701   :tag "Manually specify face"
702   :type 'custom-face-edit)
703
704 (defcustom notmuch-search-line-faces
705   '(("unread" . notmuch-search-unread-face)
706     ("flagged" . notmuch-search-flagged-face))
707   "Alist of tags to faces for line highlighting in notmuch-search.
708 Each element looks like (TAG . FACE).
709 A thread with TAG will have FACE applied.
710
711 Here is an example of how to color search results based on tags.
712  (the following text would be placed in your ~/.emacs file):
713
714  (setq notmuch-search-line-faces \\='((\"unread\" . (:foreground \"green\"))
715                                    (\"deleted\" . (:foreground \"red\"
716                                                   :background \"blue\"))))
717
718 The FACE must be a face name (a symbol or string), a property
719 list of face attributes, or a list of these.  The faces for
720 matching tags are merged, with earlier attributes overriding
721 later. A message having both \"deleted\" and \"unread\" tags with
722 the above settings would have a green foreground and blue
723 background."
724   :type '(alist :key-type (string)
725                 :value-type (radio (face :tag "Face name")
726                                     (notmuch--custom-face-edit)))
727   :group 'notmuch-search
728   :group 'notmuch-faces)
729
730 (defun notmuch-search-color-line (start end line-tag-list)
731   "Colorize lines in `notmuch-show' based on tags."
732   ;; Reverse the list so earlier entries take precedence
733   (dolist (elem (reverse notmuch-search-line-faces))
734     (let ((tag (car elem))
735           (face (cdr elem)))
736       (when (member tag line-tag-list)
737         (notmuch-apply-face nil face nil start end)))))
738
739 (defun notmuch-search-author-propertize (authors)
740   "Split `authors' into matching and non-matching authors and
741 propertize appropriately. If no boundary between authors and
742 non-authors is found, assume that all of the authors match."
743   (if (string-match "\\(.*\\)|\\(.*\\)" authors)
744       (concat (propertize (concat (match-string 1 authors) ",")
745                           'face 'notmuch-search-matching-authors)
746               (propertize (match-string 2 authors)
747                           'face 'notmuch-search-non-matching-authors))
748     (propertize authors 'face 'notmuch-search-matching-authors)))
749
750 (defun notmuch-search-insert-authors (format-string authors)
751   ;; Save the match data to avoid interfering with
752   ;; `notmuch-search-process-filter'.
753   (save-match-data
754     (let* ((formatted-authors (format format-string authors))
755            (formatted-sample (format format-string ""))
756            (visible-string formatted-authors)
757            (invisible-string "")
758            (padding ""))
759
760       ;; Truncate the author string to fit the specification.
761       (if (> (length formatted-authors)
762              (length formatted-sample))
763           (let ((visible-length (- (length formatted-sample)
764                                    (length "... "))))
765             ;; Truncate the visible string according to the width of
766             ;; the display string.
767             (setq visible-string (substring formatted-authors 0 visible-length)
768                   invisible-string (substring formatted-authors visible-length))
769             ;; If possible, truncate the visible string at a natural
770             ;; break (comma or pipe), as incremental search doesn't
771             ;; match across the visible/invisible border.
772             (when (string-match "\\(.*\\)\\([,|] \\)\\([^,|]*\\)" visible-string)
773               ;; Second clause is destructive on `visible-string', so
774               ;; order is important.
775               (setq invisible-string (concat (match-string 3 visible-string)
776                                              invisible-string)
777                     visible-string (concat (match-string 1 visible-string)
778                                            (match-string 2 visible-string))))
779             ;; `visible-string' may be shorter than the space allowed
780             ;; by `format-string'. If so we must insert some padding
781             ;; after `invisible-string'.
782             (setq padding (make-string (- (length formatted-sample)
783                                           (length visible-string)
784                                           (length "..."))
785                                        ? ))))
786
787       ;; Use different faces to show matching and non-matching authors.
788       (if (string-match "\\(.*\\)|\\(.*\\)" visible-string)
789           ;; The visible string contains both matching and
790           ;; non-matching authors.
791           (setq visible-string (notmuch-search-author-propertize visible-string)
792                 ;; The invisible string must contain only non-matching
793                 ;; authors, as the visible-string contains both.
794                 invisible-string (propertize invisible-string
795                                              'face 'notmuch-search-non-matching-authors))
796         ;; The visible string contains only matching authors.
797         (setq visible-string (propertize visible-string
798                                          'face 'notmuch-search-matching-authors)
799               ;; The invisible string may contain both matching and
800               ;; non-matching authors.
801               invisible-string (notmuch-search-author-propertize invisible-string)))
802
803       ;; If there is any invisible text, add it as a tooltip to the
804       ;; visible text.
805       (when (not (string= invisible-string ""))
806         (setq visible-string (propertize visible-string 'help-echo (concat "..." invisible-string))))
807
808       ;; Insert the visible and, if present, invisible author strings.
809       (insert visible-string)
810       (when (not (string= invisible-string ""))
811         (let ((start (point))
812               overlay)
813           (insert invisible-string)
814           (setq overlay (make-overlay start (point)))
815           (overlay-put overlay 'invisible 'ellipsis)
816           (overlay-put overlay 'isearch-open-invisible #'delete-overlay)))
817       (insert padding))))
818
819 (defun notmuch-search-insert-field (field format-string result)
820   (cond
821    ((string-equal field "date")
822     (insert (propertize (format format-string (plist-get result :date_relative))
823                         'face 'notmuch-search-date)))
824    ((string-equal field "count")
825     (insert (propertize (format format-string
826                                 (format "[%s/%s]" (plist-get result :matched)
827                                         (plist-get result :total)))
828                         'face 'notmuch-search-count)))
829    ((string-equal field "subject")
830     (insert (propertize (format format-string
831                                 (notmuch-sanitize (plist-get result :subject)))
832                         'face 'notmuch-search-subject)))
833
834    ((string-equal field "authors")
835     (notmuch-search-insert-authors
836      format-string (notmuch-sanitize (plist-get result :authors))))
837
838    ((string-equal field "tags")
839     (let ((tags (plist-get result :tags))
840           (orig-tags (plist-get result :orig-tags)))
841       (insert (format format-string (notmuch-tag-format-tags tags orig-tags)))))))
842
843 (defun notmuch-search-show-result (result pos)
844   "Insert RESULT at POS."
845   ;; Ignore excluded matches
846   (unless (= (plist-get result :matched) 0)
847     (save-excursion
848       (goto-char pos)
849       (dolist (spec notmuch-search-result-format)
850         (notmuch-search-insert-field (car spec) (cdr spec) result))
851       (insert "\n")
852       (notmuch-search-color-line pos (point) (plist-get result :tags))
853       (put-text-property pos (point) 'notmuch-search-result result))))
854
855 (defun notmuch-search-append-result (result)
856   "Insert RESULT at the end of the buffer.
857
858 This is only called when a result is first inserted so it also
859 sets the :orig-tag property."
860   (let ((new-result (plist-put result :orig-tags (plist-get result :tags)))
861         (pos (point-max)))
862     (notmuch-search-show-result new-result pos)
863     (when (string= (plist-get result :thread) notmuch-search-target-thread)
864       (setq notmuch-search-target-thread "found")
865       (goto-char pos))))
866
867 (defun notmuch-search-process-filter (proc string)
868   "Process and filter the output of \"notmuch search\""
869   (let ((results-buf (process-buffer proc))
870         (parse-buf (process-get proc 'parse-buf))
871         (inhibit-read-only t)
872         done)
873     (when (buffer-live-p results-buf)
874       (with-current-buffer parse-buf
875         ;; Insert new data
876         (save-excursion
877           (goto-char (point-max))
878           (insert string))
879         (notmuch-sexp-parse-partial-list 'notmuch-search-append-result
880                                          results-buf)))))
881
882 (defun notmuch-search-tag-all (tag-changes)
883   "Add/remove tags from all messages in current search buffer.
884
885 See `notmuch-tag' for information on the format of TAG-CHANGES."
886   (interactive
887    (list (notmuch-read-tag-changes
888           (notmuch-search-get-tags-region (point-min) (point-max)) "Tag all")))
889   (notmuch-search-tag tag-changes (point-min) (point-max) t))
890
891 (defun notmuch-search-buffer-title (query)
892   "Returns the title for a buffer with notmuch search results."
893   (let* ((saved-search
894           (let (longest
895                 (longest-length 0))
896             (loop for tuple in notmuch-saved-searches
897                   if (let ((quoted-query (regexp-quote (notmuch-saved-search-get tuple :query))))
898                        (and (string-match (concat "^" quoted-query) query)
899                             (> (length (match-string 0 query))
900                                longest-length)))
901                   do (setq longest tuple))
902             longest))
903          (saved-search-name (notmuch-saved-search-get saved-search :name))
904          (saved-search-query (notmuch-saved-search-get saved-search :query)))
905     (cond ((and saved-search (equal saved-search-query query))
906            ;; Query is the same as saved search (ignoring case)
907            (concat "*notmuch-saved-search-" saved-search-name "*"))
908           (saved-search
909            (concat "*notmuch-search-"
910                    (replace-regexp-in-string (concat "^" (regexp-quote saved-search-query))
911                                              (concat "[ " saved-search-name " ]")
912                                              query)
913                    "*"))
914           (t
915            (concat "*notmuch-search-" query "*"))
916           )))
917
918 (defun notmuch-read-query (prompt)
919   "Read a notmuch-query from the minibuffer with completion.
920
921 PROMPT is the string to prompt with."
922   (lexical-let*
923       ((all-tags
924         (mapcar (lambda (tag) (notmuch-escape-boolean-term tag))
925                 (process-lines notmuch-command "search" "--output=tags" "*")))
926        (completions
927          (append (list "folder:" "path:" "thread:" "id:" "date:" "from:" "to:"
928                        "subject:" "attachment:")
929                  (mapcar (lambda (tag) (concat "tag:" tag)) all-tags)
930                  (mapcar (lambda (tag) (concat "is:" tag)) all-tags)
931                  (mapcar (lambda (mimetype) (concat "mimetype:" mimetype)) (mailcap-mime-types)))))
932     (let ((keymap (copy-keymap minibuffer-local-map))
933           (current-query (case major-mode
934                            (notmuch-search-mode (notmuch-search-get-query))
935                            (notmuch-show-mode (notmuch-show-get-query))
936                            (notmuch-tree-mode (notmuch-tree-get-query))))
937           (minibuffer-completion-table
938            (completion-table-dynamic
939             (lambda (string)
940               ;; generate a list of possible completions for the current input
941               (cond
942                ;; this ugly regexp is used to get the last word of the input
943                ;; possibly preceded by a '('
944                ((string-match "\\(^\\|.* (?\\)\\([^ ]*\\)$" string)
945                 (mapcar (lambda (compl)
946                           (concat (match-string-no-properties 1 string) compl))
947                         (all-completions (match-string-no-properties 2 string)
948                                          completions)))
949                (t (list string)))))))
950       ;; this was simpler than convincing completing-read to accept spaces:
951       (define-key keymap (kbd "TAB") 'minibuffer-complete)
952       (let ((history-delete-duplicates t))
953         (read-from-minibuffer prompt nil keymap nil
954                               'notmuch-search-history current-query nil)))))
955
956 (defun notmuch-search-get-query ()
957   "Return the current query in this search buffer"
958   notmuch-search-query-string)
959
960 (put 'notmuch-search 'notmuch-doc "Search for messages.")
961 ;;;###autoload
962 (defun notmuch-search (&optional query oldest-first target-thread target-line no-display)
963   "Display threads matching QUERY in a notmuch-search buffer.
964
965 If QUERY is nil, it is read interactively from the minibuffer.
966 Other optional parameters are used as follows:
967
968   OLDEST-FIRST: A Boolean controlling the sort order of returned threads
969   TARGET-THREAD: A thread ID (without the thread: prefix) that will be made
970                  current if it appears in the search results.
971   TARGET-LINE: The line number to move to if the target thread does not
972                appear in the search results.
973   NO-DISPLAY: Do not try to foreground the search results buffer. If it is
974               already foregrounded i.e. displayed in a window, this has no
975               effect, meaning the buffer will remain visible.
976
977 When called interactively, this will prompt for a query and use
978 the configured default sort order."
979   (interactive
980    (list
981     ;; Prompt for a query
982     nil
983     ;; Use the default search order (if we're doing a search from a
984     ;; search buffer, ignore any buffer-local overrides)
985     (default-value 'notmuch-search-oldest-first)))
986
987   (let* ((query (or query (notmuch-read-query "Notmuch search: ")))
988          (buffer (get-buffer-create (notmuch-search-buffer-title query))))
989     (if no-display
990         (set-buffer buffer)
991       (switch-to-buffer buffer))
992     (notmuch-search-mode)
993     ;; Don't track undo information for this buffer
994     (set 'buffer-undo-list t)
995     (set 'notmuch-search-query-string query)
996     (set 'notmuch-search-oldest-first oldest-first)
997     (set 'notmuch-search-target-thread target-thread)
998     (set 'notmuch-search-target-line target-line)
999     (notmuch-tag-clear-cache)
1000     (let ((proc (get-buffer-process (current-buffer)))
1001           (inhibit-read-only t))
1002       (if proc
1003           (error "notmuch search process already running for query `%s'" query)
1004         )
1005       (erase-buffer)
1006       (goto-char (point-min))
1007       (save-excursion
1008         (let ((proc (notmuch-start-notmuch
1009                      "notmuch-search" buffer #'notmuch-search-process-sentinel
1010                      "search" "--format=sexp" "--format-version=4"
1011                      (if oldest-first
1012                          "--sort=oldest-first"
1013                        "--sort=newest-first")
1014                      query))
1015               ;; Use a scratch buffer to accumulate partial output.
1016               ;; This buffer will be killed by the sentinel, which
1017               ;; should be called no matter how the process dies.
1018               (parse-buf (generate-new-buffer " *notmuch search parse*")))
1019           (process-put proc 'parse-buf parse-buf)
1020           (set-process-filter proc 'notmuch-search-process-filter)
1021           (set-process-query-on-exit-flag proc nil))))
1022     (run-hooks 'notmuch-search-hook)))
1023
1024 (defun notmuch-search-refresh-view ()
1025   "Refresh the current view.
1026
1027 Erases the current buffer and runs a new search with the same
1028 query string as the current search. If the current thread is in
1029 the new search results, then point will be placed on the same
1030 thread. Otherwise, point will be moved to attempt to be in the
1031 same relative position within the new buffer."
1032   (interactive)
1033   (let ((target-line (line-number-at-pos))
1034         (oldest-first notmuch-search-oldest-first)
1035         (target-thread (notmuch-search-find-thread-id 'bare))
1036         (query notmuch-search-query-string))
1037     ;; notmuch-search erases the current buffer.
1038     (notmuch-search query oldest-first target-thread target-line t)
1039     (goto-char (point-min))))
1040
1041 (defun notmuch-search-toggle-order ()
1042   "Toggle the current search order.
1043
1044 This command toggles the sort order for the current search. The
1045 default sort order is defined by `notmuch-search-oldest-first'."
1046   (interactive)
1047   (set 'notmuch-search-oldest-first (not notmuch-search-oldest-first))
1048   (notmuch-search-refresh-view))
1049
1050 (defun notmuch-group-disjunctive-query-string (query-string)
1051   "Group query if it contains a complex expression.
1052
1053 Enclose QUERY-STRING in parentheses if it matches
1054 `notmuch-search-disjunctive-regexp'."
1055   (if (string-match-p notmuch-search-disjunctive-regexp query-string)
1056       (concat "( " query-string " )")
1057     query-string))
1058
1059 (defun notmuch-search-filter (query)
1060   "Filter or LIMIT the current search results based on an additional query string.
1061
1062 Runs a new search matching only messages that match both the
1063 current search results AND the additional query string provided."
1064   (interactive (list (notmuch-read-query "Filter search: ")))
1065   (let ((grouped-query (notmuch-group-disjunctive-query-string query))
1066         (grouped-original-query (notmuch-group-disjunctive-query-string
1067                                  notmuch-search-query-string)))
1068     (notmuch-search (if (string= grouped-original-query "*")
1069                         grouped-query
1070                       (concat grouped-original-query " and " grouped-query))
1071                     notmuch-search-oldest-first)))
1072
1073 (defun notmuch-search-filter-by-tag (tag)
1074   "Filter the current search results based on a single tag.
1075
1076 Runs a new search matching only messages that match both the
1077 current search results AND that are tagged with the given tag."
1078   (interactive
1079    (list (notmuch-select-tag-with-completion "Filter by tag: " notmuch-search-query-string)))
1080   (notmuch-search (concat notmuch-search-query-string " and tag:" tag) notmuch-search-oldest-first))
1081
1082 ;;;###autoload
1083 (defun notmuch ()
1084   "Run notmuch and display saved searches, known tags, etc."
1085   (interactive)
1086   (notmuch-hello))
1087
1088 (defun notmuch-interesting-buffer (b)
1089   "Is the current buffer of interest to a notmuch user?"
1090   (with-current-buffer b
1091     (memq major-mode '(notmuch-show-mode
1092                        notmuch-search-mode
1093                        notmuch-tree-mode
1094                        notmuch-hello-mode
1095                        notmuch-message-mode))))
1096
1097 ;;;###autoload
1098 (defun notmuch-cycle-notmuch-buffers ()
1099   "Cycle through any existing notmuch buffers (search, show or hello).
1100
1101 If the current buffer is the only notmuch buffer, bury it. If no
1102 notmuch buffers exist, run `notmuch'."
1103   (interactive)
1104
1105   (let (start first)
1106     ;; If the current buffer is a notmuch buffer, remember it and then
1107     ;; bury it.
1108     (when (notmuch-interesting-buffer (current-buffer))
1109       (setq start (current-buffer))
1110       (bury-buffer))
1111
1112     ;; Find the first notmuch buffer.
1113     (setq first (loop for buffer in (buffer-list)
1114                       if (notmuch-interesting-buffer buffer)
1115                       return buffer))
1116
1117     (if first
1118         ;; If the first one we found is any other than the starting
1119         ;; buffer, switch to it.
1120         (unless (eq first start)
1121           (switch-to-buffer first))
1122       (notmuch))))
1123
1124 ;;;; Imenu Support
1125
1126 (defun notmuch-search-imenu-prev-index-position-function ()
1127   "Move point to previous message in notmuch-search buffer.
1128 This function is used as a value for
1129 `imenu-prev-index-position-function'."
1130   (notmuch-search-previous-thread))
1131
1132 (defun notmuch-search-imenu-extract-index-name-function ()
1133   "Return imenu name for line at point.
1134 This function is used as a value for
1135 `imenu-extract-index-name-function'.  Point should be at the
1136 beginning of the line."
1137   (let ((subject (notmuch-search-find-subject))
1138         (author (notmuch-search-find-authors)))
1139     (format "%s (%s)" subject author)))
1140
1141 (setq mail-user-agent 'notmuch-user-agent)
1142
1143 (provide 'notmuch)
1144
1145 ;; After provide to avoid loops if notmuch was require'd via notmuch-init-file.
1146 (if init-file-user ; don't load init file if the -q option was used.
1147     (let ((init-file (locate-file notmuch-init-file '("/")
1148                                   (get-load-suffixes))))
1149       (if init-file (load init-file nil t t))))
1150
1151 ;;; notmuch.el ends here