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