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