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