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