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