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