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