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