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