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