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