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