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