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