]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch.el
notmuch.el: colorize lines in notmuch-search based on thread tags.
[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 (require 'cl)
51 (require 'mm-view)
52 (require 'message)
53
54 (require 'notmuch-lib)
55 (require 'notmuch-show)
56
57 (defun notmuch-select-tag-with-completion (prompt &rest search-terms)
58   (let ((tag-list
59          (with-output-to-string
60            (with-current-buffer standard-output
61              (apply 'call-process notmuch-command nil t nil "search-tags" search-terms)))))
62     (completing-read prompt (split-string tag-list "\n+" t) nil nil nil)))
63
64 (defun notmuch-foreach-mime-part (function mm-handle)
65   (cond ((stringp (car mm-handle))
66          (dolist (part (cdr mm-handle))
67            (notmuch-foreach-mime-part function part)))
68         ((bufferp (car mm-handle))
69          (funcall function mm-handle))
70         (t (dolist (part mm-handle)
71              (notmuch-foreach-mime-part function part)))))
72
73 (defun notmuch-count-attachments (mm-handle)
74   (let ((count 0))
75     (notmuch-foreach-mime-part
76      (lambda (p)
77        (let ((disposition (mm-handle-disposition p)))
78          (and (listp disposition)
79               (or (equal (car disposition) "attachment")
80                   (and (equal (car disposition) "inline")
81                        (assq 'filename disposition)))
82               (incf count))))
83      mm-handle)
84     count))
85
86 (defun notmuch-save-attachments (mm-handle &optional queryp)
87   (notmuch-foreach-mime-part
88    (lambda (p)
89      (let ((disposition (mm-handle-disposition p)))
90        (and (listp disposition)
91             (or (equal (car disposition) "attachment")
92                 (and (equal (car disposition) "inline")
93                      (assq 'filename disposition)))
94             (or (not queryp)
95                 (y-or-n-p
96                  (concat "Save '" (cdr (assq 'filename disposition)) "' ")))
97             (mm-save-part p))))
98    mm-handle))
99
100 (defun notmuch-reply (query-string)
101   (switch-to-buffer (generate-new-buffer "notmuch-draft"))
102   (call-process notmuch-command nil t nil "reply" query-string)
103   (message-insert-signature)
104   (goto-char (point-min))
105   (if (re-search-forward "^$" nil t)
106       (progn
107         (insert "--text follows this line--")
108         (forward-line)))
109   (message-mode))
110
111 (defun notmuch-toggle-invisible-action (cite-button)
112   (let ((invis-spec (button-get cite-button 'invisibility-spec)))
113         (if (invisible-p invis-spec)
114             (remove-from-invisibility-spec invis-spec)
115           (add-to-invisibility-spec invis-spec)
116           ))
117   (force-window-update)
118   (redisplay t))
119
120 (define-button-type 'notmuch-button-citation-toggle-type 'help-echo "mouse-1, RET: Show citation"
121   :supertype 'notmuch-button-invisibility-toggle-type)
122 (define-button-type 'notmuch-button-signature-toggle-type 'help-echo "mouse-1, RET: Show signature"
123   :supertype 'notmuch-button-invisibility-toggle-type)
124 (define-button-type 'notmuch-button-body-toggle-type
125   'help-echo "mouse-1, RET: Show message"
126   'face 'notmuch-message-summary-face
127   :supertype 'notmuch-button-invisibility-toggle-type)
128
129 (defun notmuch-fontify-headers ()
130   (while (looking-at "[[:space:]]")
131     (forward-char))
132   (if (looking-at "[Tt]o:")
133       (progn
134         (overlay-put (make-overlay (point) (re-search-forward ":"))
135                      'face 'message-header-name)
136         (overlay-put (make-overlay (point) (re-search-forward ".*$"))
137                      'face 'message-header-to))
138     (if (looking-at "[B]?[Cc][Cc]:")
139         (progn
140           (overlay-put (make-overlay (point) (re-search-forward ":"))
141                        'face 'message-header-name)
142           (overlay-put (make-overlay (point) (re-search-forward ".*$"))
143                        'face 'message-header-cc))
144       (if (looking-at "[Ss]ubject:")
145           (progn
146             (overlay-put (make-overlay (point) (re-search-forward ":"))
147                          'face 'message-header-name)
148             (overlay-put (make-overlay (point) (re-search-forward ".*$"))
149                          'face 'message-header-subject))
150         (if (looking-at "[Ff]rom:")
151             (progn
152               (overlay-put (make-overlay (point) (re-search-forward ":"))
153                            'face 'message-header-name)
154               (overlay-put (make-overlay (point) (re-search-forward ".*$"))
155                            'face 'message-header-other))
156           (if (looking-at "[Dd]ate:")
157              (progn
158                (overlay-put (make-overlay (point) (re-search-forward ":"))
159                             'face 'message-header-name)
160                (overlay-put (make-overlay (point) (re-search-forward ".*$"))
161                             'face 'message-header-other))))))))
162
163 (defun notmuch-documentation-first-line (symbol)
164   "Return the first line of the documentation string for SYMBOL."
165   (let ((doc (documentation symbol)))
166     (if doc
167         (with-temp-buffer
168           (insert (documentation symbol t))
169           (goto-char (point-min))
170           (let ((beg (point)))
171             (end-of-line)
172             (buffer-substring beg (point))))
173       "")))
174
175 (defun notmuch-prefix-key-description (key)
176   "Given a prefix key code, return a human-readable string representation.
177
178 This is basically just `format-kbd-macro' but we also convert ESC to M-."
179   (let ((desc (format-kbd-macro (vector key))))
180     (if (string= desc "ESC")
181         "M-"
182       (concat desc " "))))
183
184 ; I would think that emacs would have code handy for walking a keymap
185 ; and generating strings for each key, and I would prefer to just call
186 ; that. But I couldn't find any (could be all implemented in C I
187 ; suppose), so I wrote my own here.
188 (defun notmuch-substitute-one-command-key-with-prefix (prefix binding)
189   "For a key binding, return a string showing a human-readable
190 representation of the prefixed key as well as the first line of
191 documentation from the bound function.
192
193 For a mouse binding, return nil."
194   (let ((key (car binding))
195         (action (cdr binding)))
196     (if (mouse-event-p key)
197         nil
198       (if (keymapp action)
199           (let ((substitute (apply-partially 'notmuch-substitute-one-command-key-with-prefix (notmuch-prefix-key-description key)))
200                 (as-list))
201             (map-keymap (lambda (a b)
202                           (push (cons a b) as-list))
203                         action)
204             (mapconcat substitute as-list "\n"))
205         (concat prefix (format-kbd-macro (vector key))
206                 "\t"
207                 (notmuch-documentation-first-line action))))))
208
209 (defalias 'notmuch-substitute-one-command-key
210   (apply-partially 'notmuch-substitute-one-command-key-with-prefix nil))
211
212 (defun notmuch-substitute-command-keys (doc)
213   "Like `substitute-command-keys' but with documentation, not function names."
214   (let ((beg 0))
215     (while (string-match "\\\\{\\([^}[:space:]]*\\)}" doc beg)
216       (let ((map (substring doc (match-beginning 1) (match-end 1))))
217         (setq doc (replace-match (mapconcat 'notmuch-substitute-one-command-key
218                                             (cdr (symbol-value (intern map))) "\n") 1 1 doc)))
219       (setq beg (match-end 0)))
220     doc))
221
222 (defun notmuch-help ()
223   "Display help for the current notmuch mode."
224   (interactive)
225   (let* ((mode major-mode)
226          (doc (substitute-command-keys (notmuch-substitute-command-keys (documentation mode t)))))
227     (with-current-buffer (generate-new-buffer "*notmuch-help*")
228       (insert doc)
229       (goto-char (point-min))
230       (set-buffer-modified-p nil)
231       (view-buffer (current-buffer) 'kill-buffer-if-not-modified))))
232
233 (defgroup notmuch nil
234   "Notmuch mail reader for Emacs."
235   :group 'mail)
236
237 (defcustom notmuch-search-hook nil
238   "List of functions to call when notmuch displays the search results."
239   :type 'hook
240   :options '(hl-line-mode)
241   :group 'notmuch)
242
243 (defvar notmuch-search-authors-width 20
244   "Number of columns to use to display authors in a notmuch-search buffer.")
245
246 (defvar notmuch-search-mode-map
247   (let ((map (make-sparse-keymap)))
248     (define-key map "?" 'notmuch-help)
249     (define-key map "q" 'kill-this-buffer)
250     (define-key map "x" 'kill-this-buffer)
251     (define-key map (kbd "<DEL>") 'notmuch-search-scroll-down)
252     (define-key map "b" 'notmuch-search-scroll-down)
253     (define-key map " " 'notmuch-search-scroll-up)
254     (define-key map "<" 'notmuch-search-first-thread)
255     (define-key map ">" 'notmuch-search-last-thread)
256     (define-key map "p" 'notmuch-search-previous-thread)
257     (define-key map "n" 'notmuch-search-next-thread)
258     (define-key map "r" 'notmuch-search-reply-to-thread)
259     (define-key map "m" 'message-mail)
260     (define-key map "s" 'notmuch-search)
261     (define-key map "o" 'notmuch-search-toggle-order)
262     (define-key map "=" 'notmuch-search-refresh-view)
263     (define-key map "t" 'notmuch-search-filter-by-tag)
264     (define-key map "f" 'notmuch-search-filter)
265     (define-key map [mouse-1] 'notmuch-search-show-thread)
266     (define-key map "*" 'notmuch-search-operate-all)
267     (define-key map "a" 'notmuch-search-archive-thread)
268     (define-key map "-" 'notmuch-search-remove-tag)
269     (define-key map "+" 'notmuch-search-add-tag)
270     (define-key map (kbd "RET") 'notmuch-search-show-thread)
271     (define-key map "F" 'notmuch-folder)
272     map)
273   "Keymap for \"notmuch search\" buffers.")
274 (fset 'notmuch-search-mode-map notmuch-search-mode-map)
275
276 (defvar notmuch-search-query-string)
277 (defvar notmuch-search-target-thread)
278 (defvar notmuch-search-target-line)
279 (defvar notmuch-search-oldest-first t
280   "Show the oldest mail first in the search-mode")
281
282 (defvar notmuch-search-disjunctive-regexp      "\\<[oO][rR]\\>")
283
284 (defun notmuch-search-scroll-up ()
285   "Move forward through search results by one window's worth."
286   (interactive)
287   (condition-case nil
288       (scroll-up nil)
289     ((end-of-buffer) (notmuch-search-last-thread))))
290
291 (defun notmuch-search-scroll-down ()
292   "Move backward through the search results by one window's worth."
293   (interactive)
294   ; I don't know why scroll-down doesn't signal beginning-of-buffer
295   ; the way that scroll-up signals end-of-buffer, but c'est la vie.
296   ;
297   ; So instead of trapping a signal we instead check whether the
298   ; window begins on the first line of the buffer and if so, move
299   ; directly to that position. (We have to count lines since the
300   ; window-start position is not the same as point-min due to the
301   ; invisible thread-ID characters on the first line.
302   (if (equal (count-lines (point-min) (window-start)) 0)
303       (goto-char (point-min))
304     (scroll-down nil)))
305
306 (defun notmuch-search-next-thread ()
307   "Select the next thread in the search results."
308   (interactive)
309   (forward-line 1))
310
311 (defun notmuch-search-previous-thread ()
312   "Select the previous thread in the search results."
313   (interactive)
314   (forward-line -1))
315
316 (defun notmuch-search-last-thread ()
317   "Select the last thread in the search results."
318   (interactive)
319   (goto-char (point-max))
320   (forward-line -2))
321
322 (defun notmuch-search-first-thread ()
323   "Select the first thread in the search results."
324   (interactive)
325   (goto-char (point-min)))
326
327 (defface notmuch-message-summary-face
328  '((((class color) (background light)) (:background "#f0f0f0"))
329    (((class color) (background dark)) (:background "#303030")))
330  "Face for the single-line message summary in notmuch-show-mode."
331  :group 'notmuch)
332
333 (defface notmuch-tag-face
334   '((((class color)
335       (background dark))
336      (:foreground "OliveDrab1"))
337     (((class color)
338       (background light))
339      (:foreground "navy blue" :bold t))
340     (t
341      (:bold t)))
342   "Notmuch search mode face used to highligh tags."
343   :group 'notmuch)
344
345 (defvar notmuch-tag-face-alist nil
346   "List containing the tag list that need to be highlighed")
347
348 (defvar notmuch-search-font-lock-keywords  nil)
349
350 ;;;###autoload
351 (defun notmuch-search-mode ()
352   "Major mode displaying results of a notmuch search.
353
354 This buffer contains the results of a \"notmuch search\" of your
355 email archives. Each line in the buffer represents a single
356 thread giving a summary of the thread (a relative date, the
357 number of matched messages and total messages in the thread,
358 participants in the thread, a representative subject line, and
359 any tags).
360
361 Pressing \\[notmuch-search-show-thread] on any line displays that thread. The '\\[notmuch-search-add-tag]' and '\\[notmuch-search-remove-tag]'
362 keys can be used to add or remove tags from a thread. The '\\[notmuch-search-archive-thread]' key
363 is a convenience for archiving a thread (removing the \"inbox\"
364 tag). The '\\[notmuch-search-operate-all]' key can be used to add or remove a tag from all
365 threads in the current buffer.
366
367 Other useful commands are '\\[notmuch-search-filter]' for filtering the current search
368 based on an additional query string, '\\[notmuch-search-filter-by-tag]' for filtering to include
369 only messages with a given tag, and '\\[notmuch-search]' to execute a new, global
370 search.
371
372 Complete list of currently available key bindings:
373
374 \\{notmuch-search-mode-map}"
375   (interactive)
376   (kill-all-local-variables)
377   (make-local-variable 'notmuch-search-query-string)
378   (make-local-variable 'notmuch-search-oldest-first)
379   (make-local-variable 'notmuch-search-target-thread)
380   (make-local-variable 'notmuch-search-target-line)
381   (set (make-local-variable 'scroll-preserve-screen-position) t)
382   (add-to-invisibility-spec 'notmuch-search)
383   (use-local-map notmuch-search-mode-map)
384   (setq truncate-lines t)
385   (setq major-mode 'notmuch-search-mode
386         mode-name "notmuch-search")
387   (setq buffer-read-only t)
388   (if (not notmuch-tag-face-alist)
389       (add-to-list 'notmuch-search-font-lock-keywords (list
390                 "(\\([^()]*\\))$" '(1  'notmuch-tag-face)))
391     (let ((notmuch-search-tags (mapcar 'car notmuch-tag-face-alist)))
392       (loop for notmuch-search-tag  in notmuch-search-tags
393             do (add-to-list 'notmuch-search-font-lock-keywords (list
394                         (concat "([^)]*\\(" notmuch-search-tag "\\)[^)]*)$")
395                         `(1  ,(cdr (assoc notmuch-search-tag notmuch-tag-face-alist))))))))
396   (set (make-local-variable 'font-lock-defaults)
397          '(notmuch-search-font-lock-keywords t)))
398
399 (defun notmuch-search-find-thread-id ()
400   "Return the thread for the current thread"
401   (get-text-property (point) 'notmuch-search-thread-id))
402
403 (defun notmuch-search-find-authors ()
404   "Return the authors for the current thread"
405   (get-text-property (point) 'notmuch-search-authors))
406
407 (defun notmuch-search-find-subject ()
408   "Return the subject for the current thread"
409   (get-text-property (point) 'notmuch-search-subject))
410
411 (defun notmuch-search-show-thread ()
412   "Display the currently selected thread."
413   (interactive)
414   (let ((thread-id (notmuch-search-find-thread-id))
415         (subject (notmuch-search-find-subject))
416         buffer-name)
417     (when (string-match "^[ \t]*$" subject)
418       (setq subject "[No Subject]"))
419     (setq buffer-name (concat "*"
420                               (truncate-string-to-width subject 32 nil nil t)
421                               "*"))
422     (if (> (length thread-id) 0)
423         (notmuch-show thread-id
424                       (current-buffer)
425                       notmuch-search-query-string
426                       buffer-name)
427       (error "End of search results"))))
428
429 (defun notmuch-search-reply-to-thread ()
430   "Begin composing a reply to the entire current thread in a new buffer."
431   (interactive)
432   (let ((message-id (notmuch-search-find-thread-id)))
433     (notmuch-reply message-id)))
434
435 (defun notmuch-call-notmuch-process (&rest args)
436   "Synchronously invoke \"notmuch\" with the given list of arguments.
437
438 Output from the process will be presented to the user as an error
439 and will also appear in a buffer named \"*Notmuch errors*\"."
440   (let ((error-buffer (get-buffer-create "*Notmuch errors*")))
441     (with-current-buffer error-buffer
442         (erase-buffer))
443     (if (eq (apply 'call-process notmuch-command nil error-buffer nil args) 0)
444         (point)
445       (progn
446         (with-current-buffer error-buffer
447           (let ((beg (point-min))
448                 (end (- (point-max) 1)))
449             (error (buffer-substring beg end))
450             ))))))
451
452 (defun notmuch-search-set-tags (tags)
453   (save-excursion
454     (end-of-line)
455     (re-search-backward "(")
456     (forward-char)
457     (let ((beg (point))
458           (inhibit-read-only t))
459       (re-search-forward ")")
460       (backward-char)
461       (let ((end (point)))
462         (delete-region beg end)
463         (insert (mapconcat  'identity tags " "))))))
464
465 (defun notmuch-search-get-tags ()
466   (save-excursion
467     (end-of-line)
468     (re-search-backward "(")
469     (let ((beg (+ (point) 1)))
470       (re-search-forward ")")
471       (let ((end (- (point) 1)))
472         (split-string (buffer-substring beg end))))))
473
474 (defun notmuch-search-add-tag (tag)
475   "Add a tag to the currently selected thread.
476
477 The tag is added to messages in the currently selected thread
478 which match the current search terms."
479   (interactive
480    (list (notmuch-select-tag-with-completion "Tag to add: ")))
481   (notmuch-call-notmuch-process "tag" (concat "+" tag) (notmuch-search-find-thread-id))
482   (notmuch-search-set-tags (delete-dups (sort (cons tag (notmuch-search-get-tags)) 'string<))))
483
484 (defun notmuch-search-remove-tag (tag)
485   "Remove a tag from the currently selected thread.
486
487 The tag is removed from all messages in the currently selected thread."
488   (interactive
489    (list (notmuch-select-tag-with-completion "Tag to remove: " (notmuch-search-find-thread-id))))
490   (notmuch-call-notmuch-process "tag" (concat "-" tag) (notmuch-search-find-thread-id))
491   (notmuch-search-set-tags (delete tag (notmuch-search-get-tags))))
492
493 (defun notmuch-search-archive-thread ()
494   "Archive the currently selected thread (remove its \"inbox\" tag).
495
496 This function advances the next thread when finished."
497   (interactive)
498   (notmuch-search-remove-tag "inbox")
499   (forward-line))
500
501 (defun notmuch-search-process-sentinel (proc msg)
502   "Add a message to let user know when \"notmuch search\" exits"
503   (let ((buffer (process-buffer proc))
504         (status (process-status proc))
505         (exit-status (process-exit-status proc))
506         (never-found-target-thread nil))
507     (if (memq status '(exit signal))
508         (if (buffer-live-p buffer)
509             (with-current-buffer buffer
510               (save-excursion
511                 (let ((inhibit-read-only t)
512                       (atbob (bobp)))
513                   (goto-char (point-max))
514                   (if (eq status 'signal)
515                       (insert "Incomplete search results (search process was killed).\n"))
516                   (if (eq status 'exit)
517                       (progn
518                         (insert "End of search results.")
519                         (if (not (= exit-status 0))
520                             (insert (format " (process returned %d)" exit-status)))
521                         (insert "\n")
522                         (if (and atbob
523                                  (not (string= notmuch-search-target-thread "found")))
524                             (set 'never-found-target-thread t))))))
525               (if (and never-found-target-thread
526                        notmuch-search-target-line)
527                   (goto-line notmuch-search-target-line)))))))
528
529 (defcustom notmuch-search-line-faces nil
530   "Tag/face mapping for line highlighting in notmuch-search.
531
532 Here is an example of how to color search results based on tags.
533 (the following text would be placed in your ~/.emacs file):
534
535 (setq notmuch-search-line-faces '((\"delete\" . '(:foreground \"red\"))
536                                  (\"unread\" . '(:foreground \"green\"))))
537
538 Order matters: for lines with multiple tags, the the first
539 matching will be applied."
540   :type '(alist :key-type (string) :value-type (list))
541   :group 'notmuch)
542
543 (defun notmuch-search-color-line (start end line-tag-list)
544   "Colorize lines in notmuch-show based on tags"
545   (if notmuch-search-line-faces
546       (let ((overlay (make-overlay start end))
547             (tags-faces (copy-alist notmuch-search-line-faces)))
548         (while tags-faces
549           (let* ((tag-face (car tags-faces))
550                  (tag (car tag-face))
551                  (face (cdr tag-face)))
552             (cond ((member tag line-tag-list)
553                    (overlay-put overlay 'face face)
554                    (setq tags-faces nil))
555                   (t
556                    (setq tags-faces (cdr tags-faces)))))))))
557
558 (defun notmuch-search-process-filter (proc string)
559   "Process and filter the output of \"notmuch search\""
560   (let ((buffer (process-buffer proc))
561         (found-target nil))
562     (if (buffer-live-p buffer)
563         (with-current-buffer buffer
564           (save-excursion
565             (let ((line 0)
566                   (more t)
567                   (inhibit-read-only t))
568               (while more
569                 (if (string-match "^\\(thread:[0-9A-Fa-f]*\\) \\(.*\\) \\(\\[[0-9/]*\\]\\) \\([^;]*\\); \\(.*\\) (\\([^()]*\\))$" string line)
570                     (let* ((thread-id (match-string 1 string))
571                            (date (match-string 2 string))
572                            (count (match-string 3 string))
573                            (authors (match-string 4 string))
574                            (authors-length (length authors))
575                            (subject (match-string 5 string))
576                            (tags (match-string 6 string))
577                            (tag-list (if tags (save-match-data (split-string tags)))))
578                       (if (> authors-length notmuch-search-authors-width)
579                           (set 'authors (concat (substring authors 0 (- notmuch-search-authors-width 3)) "...")))
580                       (goto-char (point-max))
581                       (let ((beg (point-marker))
582                             (format-string (format "%%s %%-7s %%-%ds %%s (%%s)\n" notmuch-search-authors-width)))
583                         (insert (format format-string date count authors subject tags))
584                         (notmuch-search-color-line beg (point-marker) tag-list)
585                         (put-text-property beg (point-marker) 'notmuch-search-thread-id thread-id)
586                         (put-text-property beg (point-marker) 'notmuch-search-authors authors)
587                         (put-text-property beg (point-marker) 'notmuch-search-subject subject)
588                         (if (string= thread-id notmuch-search-target-thread)
589                             (progn
590                               (set 'found-target beg)
591                               (set 'notmuch-search-target-thread "found"))))
592                       (set 'line (match-end 0)))
593                   (set 'more nil)))))
594           (if found-target
595               (goto-char found-target)))
596       (delete-process proc))))
597
598 (defun notmuch-search-operate-all (action)
599   "Add/remove tags from all matching messages.
600
601 Tis command adds or removes tags from all messages matching the
602 current search terms. When called interactively, this command
603 will prompt for tags to be added or removed. Tags prefixed with
604 '+' will be added and tags prefixed with '-' will be removed.
605
606 Each character of the tag name may consist of alphanumeric
607 characters as well as `_.+-'.
608 "
609   (interactive "sOperation (+add -drop): notmuch tag ")
610   (let ((action-split (split-string action " +")))
611     ;; Perform some validation
612     (let ((words action-split))
613       (when (null words) (error "No operation given"))
614       (while words
615         (unless (string-match-p "^[-+][-+_.[:word:]]+$" (car words))
616           (error "Action must be of the form `+thistag -that_tag'"))
617         (setq words (cdr words))))
618     (apply 'notmuch-call-notmuch-process "tag"
619            (append action-split (list notmuch-search-query-string) nil))))
620
621 ;;;###autoload
622 (defun notmuch-search (query &optional oldest-first target-thread target-line)
623   "Run \"notmuch search\" with the given query string and display results.
624
625 The optional parameters are used as follows:
626
627   oldest-first: A Boolean controlling the sort order of returned threads
628   target-thread: A thread ID (with the thread: prefix) that will be made
629                  current if it appears in the search results.
630   target-line: The line number to move to if the target thread does not
631                appear in the search results."
632   (interactive "sNotmuch search: ")
633   (let ((buffer (get-buffer-create (concat "*notmuch-search-" query "*"))))
634     (switch-to-buffer buffer)
635     (notmuch-search-mode)
636     (set 'notmuch-search-query-string query)
637     (set 'notmuch-search-oldest-first oldest-first)
638     (set 'notmuch-search-target-thread target-thread)
639     (set 'notmuch-search-target-line target-line)
640     (let ((proc (get-buffer-process (current-buffer)))
641           (inhibit-read-only t))
642       (if proc
643           (error "notmuch search process already running for query `%s'" query)
644         )
645       (erase-buffer)
646       (goto-char (point-min))
647       (save-excursion
648         (let ((proc (start-process-shell-command
649                      "notmuch-search" buffer notmuch-command "search"
650                      (if oldest-first "--sort=oldest-first" "--sort=newest-first")
651                      (shell-quote-argument query))))
652           (set-process-sentinel proc 'notmuch-search-process-sentinel)
653           (set-process-filter proc 'notmuch-search-process-filter))))
654     (run-hooks 'notmuch-search-hook)))
655
656 (defun notmuch-search-refresh-view ()
657   "Refresh the current view.
658
659 Kills the current buffer and runs a new search with the same
660 query string as the current search. If the current thread is in
661 the new search results, then point will be placed on the same
662 thread. Otherwise, point will be moved to attempt to be in the
663 same relative position within the new buffer."
664   (interactive)
665   (let ((target-line (line-number-at-pos))
666         (oldest-first notmuch-search-oldest-first)
667         (target-thread (notmuch-search-find-thread-id))
668         (query notmuch-search-query-string))
669     (kill-this-buffer)
670     (notmuch-search query oldest-first target-thread target-line)
671     (goto-char (point-min))
672     ))
673
674 (defun notmuch-search-toggle-order ()
675   "Toggle the current search order.
676
677 By default, the \"inbox\" view created by `notmuch' is displayed
678 in chronological order (oldest thread at the beginning of the
679 buffer), while any global searches created by `notmuch-search'
680 are displayed in reverse-chronological order (newest thread at
681 the beginning of the buffer).
682
683 This command toggles the sort order for the current search.
684
685 Note that any filtered searches created by
686 `notmuch-search-filter' retain the search order of the parent
687 search."
688   (interactive)
689   (set 'notmuch-search-oldest-first (not notmuch-search-oldest-first))
690   (notmuch-search-refresh-view))
691
692 (defun notmuch-search-filter (query)
693   "Filter the current search results based on an additional query string.
694
695 Runs a new search matching only messages that match both the
696 current search results AND the additional query string provided."
697   (interactive "sFilter search: ")
698   (let ((grouped-query (if (string-match-p notmuch-search-disjunctive-regexp query) (concat "( " query " )") query)))
699     (notmuch-search (concat notmuch-search-query-string " and " grouped-query) notmuch-search-oldest-first)))
700
701 (defun notmuch-search-filter-by-tag (tag)
702   "Filter the current search results based on a single tag.
703
704 Runs a new search matching only messages that match both the
705 current search results AND that are tagged with the given tag."
706   (interactive
707    (list (notmuch-select-tag-with-completion "Filter by tag: ")))
708   (notmuch-search (concat notmuch-search-query-string " and tag:" tag) notmuch-search-oldest-first))
709
710 ;;;###autoload
711 (defun notmuch ()
712   "Run notmuch to display all mail with tag of 'inbox'"
713   (interactive)
714   (notmuch-search "tag:inbox" notmuch-search-oldest-first))
715
716 (setq mail-user-agent 'message-user-agent)
717
718 (defvar notmuch-folder-mode-map
719   (let ((map (make-sparse-keymap)))
720     (define-key map "?" 'notmuch-help)
721     (define-key map "x" 'kill-this-buffer)
722     (define-key map "q" 'kill-this-buffer)
723     (define-key map "m" 'message-mail)
724     (define-key map "e" 'notmuch-folder-show-empty-toggle)
725     (define-key map ">" 'notmuch-folder-last)
726     (define-key map "<" 'notmuch-folder-first)
727     (define-key map "=" 'notmuch-folder)
728     (define-key map "s" 'notmuch-search)
729     (define-key map [mouse-1] 'notmuch-folder-show-search)
730     (define-key map (kbd "RET") 'notmuch-folder-show-search)
731     (define-key map " " 'notmuch-folder-show-search)
732     (define-key map "p" 'notmuch-folder-previous)
733     (define-key map "n" 'notmuch-folder-next)
734     map)
735   "Keymap for \"notmuch folder\" buffers.")
736
737 (fset 'notmuch-folder-mode-map notmuch-folder-mode-map)
738
739 (defcustom notmuch-folders (quote (("inbox" . "tag:inbox") ("unread" . "tag:unread")))
740   "List of searches for the notmuch folder view"
741   :type '(alist :key-type (string) :value-type (string))
742   :group 'notmuch)
743
744 (defun notmuch-folder-mode ()
745   "Major mode for showing notmuch 'folders'.
746
747 This buffer contains a list of message counts returned by a
748 customizable set of searches of your email archives. Each line in
749 the buffer shows the name of a saved search and the resulting
750 message count.
751
752 Pressing RET on any line opens a search window containing the
753 results for the saved search on that line.
754
755 Here is an example of how the search list could be
756 customized, (the following text would be placed in your ~/.emacs
757 file):
758
759 (setq notmuch-folders '((\"inbox\" . \"tag:inbox\")
760                         (\"unread\" . \"tag:inbox AND tag:unread\")
761                         (\"notmuch\" . \"tag:inbox AND to:notmuchmail.org\")))
762
763 Of course, you can have any number of folders, each configured
764 with any supported search terms (see \"notmuch help search-terms\").
765
766 Currently available key bindings:
767
768 \\{notmuch-folder-mode-map}"
769   (interactive)
770   (kill-all-local-variables)
771   (use-local-map 'notmuch-folder-mode-map)
772   (setq truncate-lines t)
773   (hl-line-mode 1)
774   (setq major-mode 'notmuch-folder-mode
775         mode-name "notmuch-folder")
776   (setq buffer-read-only t))
777
778 (defun notmuch-folder-next ()
779   "Select the next folder in the list."
780   (interactive)
781   (forward-line 1)
782   (if (eobp)
783       (forward-line -1)))
784
785 (defun notmuch-folder-previous ()
786   "Select the previous folder in the list."
787   (interactive)
788   (forward-line -1))
789
790 (defun notmuch-folder-first ()
791   "Select the first folder in the list."
792   (interactive)
793   (goto-char (point-min)))
794
795 (defun notmuch-folder-last ()
796   "Select the last folder in the list."
797   (interactive)
798   (goto-char (point-max))
799   (forward-line -1))
800
801 (defun notmuch-folder-count (search)
802   (car (process-lines notmuch-command "count" search)))
803
804 (defvar notmuch-folder-show-empty t
805   "Whether `notmuch-folder-mode' should display empty folders.")
806
807 (defun notmuch-folder-show-empty-toggle ()
808   "Toggle the listing of empty folders"
809   (interactive)
810   (setq notmuch-folder-show-empty (not notmuch-folder-show-empty))
811   (notmuch-folder))
812
813 (defun notmuch-folder-add (folders)
814   (if folders
815       (let* ((name (car (car folders)))
816             (inhibit-read-only t)
817             (search (cdr (car folders)))
818             (count (notmuch-folder-count search)))
819         (if (or notmuch-folder-show-empty
820                 (not (equal count "0")))
821             (progn
822               (insert name)
823               (indent-to 16 1)
824               (insert count)
825               (insert "\n")
826               )
827           )
828         (notmuch-folder-add (cdr folders)))))
829
830 (defun notmuch-folder-find-name ()
831   (save-excursion
832     (beginning-of-line)
833     (let ((beg (point)))
834       (re-search-forward "\\([ \t]*[^ \t]+\\)")
835       (filter-buffer-substring (match-beginning 1) (match-end 1)))))
836
837 (defun notmuch-folder-show-search (&optional folder)
838   "Show a search window for the search related to the specified folder."
839   (interactive)
840   (if (null folder)
841       (setq folder (notmuch-folder-find-name)))
842   (let ((search (assoc folder notmuch-folders)))
843     (if search
844         (notmuch-search (cdr search) notmuch-search-oldest-first))))
845
846 ;;;###autoload
847 (defun notmuch-folder ()
848   "Show the notmuch folder view and update the displayed counts."
849   (interactive)
850   (let ((buffer (get-buffer-create "*notmuch-folders*")))
851     (switch-to-buffer buffer)
852     (let ((inhibit-read-only t)
853           (n (line-number-at-pos)))
854       (erase-buffer)
855       (notmuch-folder-mode)
856       (notmuch-folder-add notmuch-folders)
857       (goto-char (point-min))
858       (goto-line n))))
859
860 (provide 'notmuch)