]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch.el
emacs/notmuch.el: Enable `hl-line-mode' in `notmuch-search-mode'
[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 '(hl-line-mode)
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     map)
272   "Keymap for \"notmuch search\" buffers.")
273 (fset 'notmuch-search-mode-map notmuch-search-mode-map)
274
275 (defvar notmuch-search-query-string)
276 (defvar notmuch-search-target-thread)
277 (defvar notmuch-search-target-line)
278 (defvar notmuch-search-oldest-first t
279   "Show the oldest mail first in the search-mode")
280
281 (defvar notmuch-search-disjunctive-regexp      "\\<[oO][rR]\\>")
282
283 (defun notmuch-search-scroll-up ()
284   "Move forward through search results by one window's worth."
285   (interactive)
286   (condition-case nil
287       (scroll-up nil)
288     ((end-of-buffer) (notmuch-search-last-thread))))
289
290 (defun notmuch-search-scroll-down ()
291   "Move backward through the search results by one window's worth."
292   (interactive)
293   ; I don't know why scroll-down doesn't signal beginning-of-buffer
294   ; the way that scroll-up signals end-of-buffer, but c'est la vie.
295   ;
296   ; So instead of trapping a signal we instead check whether the
297   ; window begins on the first line of the buffer and if so, move
298   ; directly to that position. (We have to count lines since the
299   ; window-start position is not the same as point-min due to the
300   ; invisible thread-ID characters on the first line.
301   (if (equal (count-lines (point-min) (window-start)) 0)
302       (goto-char (point-min))
303     (scroll-down nil)))
304
305 (defun notmuch-search-next-thread ()
306   "Select the next thread in the search results."
307   (interactive)
308   (forward-line 1))
309
310 (defun notmuch-search-previous-thread ()
311   "Select the previous thread in the search results."
312   (interactive)
313   (forward-line -1))
314
315 (defun notmuch-search-last-thread ()
316   "Select the last thread in the search results."
317   (interactive)
318   (goto-char (point-max))
319   (forward-line -2))
320
321 (defun notmuch-search-first-thread ()
322   "Select the first thread in the search results."
323   (interactive)
324   (goto-char (point-min)))
325
326 (defface notmuch-message-summary-face
327  '((((class color) (background light)) (:background "#f0f0f0"))
328    (((class color) (background dark)) (:background "#303030")))
329  "Face for the single-line message summary in notmuch-show-mode."
330  :group 'notmuch)
331
332 (defface notmuch-tag-face
333   '((((class color)
334       (background dark))
335      (:foreground "OliveDrab1"))
336     (((class color)
337       (background light))
338      (:foreground "navy blue" :bold t))
339     (t
340      (:bold t)))
341   "Notmuch search mode face used to highligh tags."
342   :group 'notmuch)
343
344 (defvar notmuch-tag-face-alist nil
345   "List containing the tag list that need to be highlighed")
346
347 (defvar notmuch-search-font-lock-keywords  nil)
348
349 ;;;###autoload
350 (defun notmuch-search-mode ()
351   "Major mode displaying results of a notmuch search.
352
353 This buffer contains the results of a \"notmuch search\" of your
354 email archives. Each line in the buffer represents a single
355 thread giving a summary of the thread (a relative date, the
356 number of matched messages and total messages in the thread,
357 participants in the thread, a representative subject line, and
358 any tags).
359
360 Pressing \\[notmuch-search-show-thread] on any line displays that thread. The '\\[notmuch-search-add-tag]' and '\\[notmuch-search-remove-tag]'
361 keys can be used to add or remove tags from a thread. The '\\[notmuch-search-archive-thread]' key
362 is a convenience for archiving a thread (removing the \"inbox\"
363 tag). The '\\[notmuch-search-operate-all]' key can be used to add or remove a tag from all
364 threads in the current buffer.
365
366 Other useful commands are '\\[notmuch-search-filter]' for filtering the current search
367 based on an additional query string, '\\[notmuch-search-filter-by-tag]' for filtering to include
368 only messages with a given tag, and '\\[notmuch-search]' to execute a new, global
369 search.
370
371 Complete list of currently available key bindings:
372
373 \\{notmuch-search-mode-map}"
374   (interactive)
375   (kill-all-local-variables)
376   (make-local-variable 'notmuch-search-query-string)
377   (make-local-variable 'notmuch-search-oldest-first)
378   (make-local-variable 'notmuch-search-target-thread)
379   (make-local-variable 'notmuch-search-target-line)
380   (set (make-local-variable 'scroll-preserve-screen-position) t)
381   (add-to-invisibility-spec 'notmuch-search)
382   (use-local-map notmuch-search-mode-map)
383   (setq truncate-lines t)
384   (setq major-mode 'notmuch-search-mode
385         mode-name "notmuch-search")
386   (setq buffer-read-only t)
387   (if (not notmuch-tag-face-alist)
388       (add-to-list 'notmuch-search-font-lock-keywords (list
389                 "(\\([^()]*\\))$" '(1  'notmuch-tag-face)))
390     (let ((notmuch-search-tags (mapcar 'car notmuch-tag-face-alist)))
391       (loop for notmuch-search-tag  in notmuch-search-tags
392             do (add-to-list 'notmuch-search-font-lock-keywords (list
393                         (concat "([^)]*\\(" notmuch-search-tag "\\)[^)]*)$")
394                         `(1  ,(cdr (assoc notmuch-search-tag notmuch-tag-face-alist))))))))
395   (set (make-local-variable 'font-lock-defaults)
396          '(notmuch-search-font-lock-keywords t)))
397
398 (defun notmuch-search-properties-in-region (property beg end)
399   (save-excursion
400     (let ((output nil)
401           (last-line (line-number-at-pos end))
402           (max-line (- (line-number-at-pos (point-max)) 2)))
403       (goto-char beg)
404       (beginning-of-line)
405       (while (<= (line-number-at-pos) (min last-line max-line))
406         (setq output (cons (get-text-property (point) property) output))
407         (forward-line 1))
408       output)))
409
410 (defun notmuch-search-find-thread-id ()
411   "Return the thread for the current thread"
412   (get-text-property (point) 'notmuch-search-thread-id))
413
414 (defun notmuch-search-find-thread-id-region (beg end)
415   "Return a list of threads for the current region"
416   (notmuch-search-properties-in-region 'notmuch-search-thread-id beg end))
417
418 (defun notmuch-search-find-authors ()
419   "Return the authors for the current thread"
420   (get-text-property (point) 'notmuch-search-authors))
421
422 (defun notmuch-search-find-authors-region (beg end)
423   "Return a list of authors for the current region"
424   (notmuch-search-properties-in-region 'notmuch-search-authors beg end))
425
426 (defun notmuch-search-find-subject ()
427   "Return the subject for the current thread"
428   (get-text-property (point) 'notmuch-search-subject))
429
430 (defun notmuch-search-find-subject-region (beg end)
431   "Return a list of authors for the current region"
432   (notmuch-search-properties-in-region 'notmuch-search-subject beg end))
433
434 (defun notmuch-search-show-thread ()
435   "Display the currently selected thread."
436   (interactive)
437   (let ((thread-id (notmuch-search-find-thread-id))
438         (subject (notmuch-search-find-subject))
439         buffer-name)
440     (when (string-match "^[ \t]*$" subject)
441       (setq subject "[No Subject]"))
442     (setq buffer-name (concat "*"
443                               (truncate-string-to-width subject 32 nil nil t)
444                               "*"))
445     (if (> (length thread-id) 0)
446         (notmuch-show thread-id
447                       (current-buffer)
448                       notmuch-search-query-string
449                       buffer-name)
450       (error "End of search results"))))
451
452 (defun notmuch-search-reply-to-thread ()
453   "Begin composing a reply to the entire current thread in a new buffer."
454   (interactive)
455   (let ((message-id (notmuch-search-find-thread-id)))
456     (notmuch-reply message-id)))
457
458 (defun notmuch-call-notmuch-process (&rest args)
459   "Synchronously invoke \"notmuch\" with the given list of arguments.
460
461 Output from the process will be presented to the user as an error
462 and will also appear in a buffer named \"*Notmuch errors*\"."
463   (let ((error-buffer (get-buffer-create "*Notmuch errors*")))
464     (with-current-buffer error-buffer
465         (erase-buffer))
466     (if (eq (apply 'call-process notmuch-command nil error-buffer nil args) 0)
467         (point)
468       (progn
469         (with-current-buffer error-buffer
470           (let ((beg (point-min))
471                 (end (- (point-max) 1)))
472             (error (buffer-substring beg end))
473             ))))))
474
475 (defun notmuch-search-set-tags (tags)
476   (save-excursion
477     (end-of-line)
478     (re-search-backward "(")
479     (forward-char)
480     (let ((beg (point))
481           (inhibit-read-only t))
482       (re-search-forward ")")
483       (backward-char)
484       (let ((end (point)))
485         (delete-region beg end)
486         (insert (mapconcat  'identity tags " "))))))
487
488 (defun notmuch-search-get-tags ()
489   (save-excursion
490     (end-of-line)
491     (re-search-backward "(")
492     (let ((beg (+ (point) 1)))
493       (re-search-forward ")")
494       (let ((end (- (point) 1)))
495         (split-string (buffer-substring beg end))))))
496
497 (defun notmuch-search-get-tags-region (beg end)
498   (save-excursion
499     (let ((output nil)
500           (last-line (line-number-at-pos end))
501           (max-line (- (line-number-at-pos (point-max)) 2)))
502       (goto-char beg)
503       (while (<= (line-number-at-pos) (min last-line max-line))
504         (setq output (append output (notmuch-search-get-tags)))
505         (forward-line 1))
506       output)))
507
508 (defun notmuch-search-add-tag-thread (tag)
509   (notmuch-search-add-tag-region tag (point) (point)))
510
511 (defun notmuch-search-add-tag-region (tag beg end)
512   (let ((search-id-string (mapconcat 'identity (notmuch-search-find-thread-id-region beg end) " or ")))
513     (notmuch-call-notmuch-process "tag" (concat "+" tag) search-id-string)
514     (save-excursion
515       (let ((last-line (line-number-at-pos end))
516             (max-line (- (line-number-at-pos (point-max)) 2)))
517         (goto-char beg)
518         (while (<= (line-number-at-pos) (min last-line max-line))
519           (notmuch-search-set-tags (delete-dups (sort (cons tag (notmuch-search-get-tags)) 'string<)))
520           (forward-line))))))
521
522 (defun notmuch-search-remove-tag-thread (tag)
523   (notmuch-search-remove-tag-region tag (point) (point)))
524
525 (defun notmuch-search-remove-tag-region (tag beg end)
526   (let ((search-id-string (mapconcat 'identity (notmuch-search-find-thread-id-region beg end) " or ")))
527     (notmuch-call-notmuch-process "tag" (concat "-" tag) search-id-string)
528     (save-excursion
529       (let ((last-line (line-number-at-pos end))
530             (max-line (- (line-number-at-pos (point-max)) 2)))
531         (goto-char beg)
532         (while (<= (line-number-at-pos) (min last-line max-line))
533           (notmuch-search-set-tags (delete tag (notmuch-search-get-tags)))
534           (forward-line))))))
535
536 (defun notmuch-search-add-tag (tag)
537   "Add a tag to the currently selected thread or region.
538
539 The tag is added to all messages in the currently selected thread
540 or threads in the current region."
541   (interactive
542    (list (notmuch-select-tag-with-completion "Tag to add: ")))
543   (save-excursion
544     (if (region-active-p)
545         (let* ((beg (region-beginning))
546                (end (region-end)))
547           (notmuch-search-add-tag-region tag beg end))
548       (notmuch-search-add-tag-thread tag))))
549
550 (defun notmuch-search-remove-tag (tag)
551   "Remove a tag from the currently selected thread or region.
552
553 The tag is removed from all messages in the currently selected
554 thread or threads in the current region."
555   (interactive
556    (list (notmuch-select-tag-with-completion
557           "Tag to remove: "
558           (if (region-active-p)
559               (mapconcat 'identity
560                          (notmuch-search-find-thread-id-region (region-beginning) (region-end))
561                          " ")
562             (notmuch-search-find-thread-id)))))
563   (save-excursion
564     (if (region-active-p)
565         (let* ((beg (region-beginning))
566                (end (region-end)))
567           (notmuch-search-remove-tag-region tag beg end))
568       (notmuch-search-remove-tag-thread tag))))
569
570 (defun notmuch-search-archive-thread ()
571   "Archive the currently selected thread (remove its \"inbox\" tag).
572
573 This function advances the next thread when finished."
574   (interactive)
575   (notmuch-search-remove-tag-thread "inbox")
576   (forward-line))
577
578 (defun notmuch-search-process-sentinel (proc msg)
579   "Add a message to let user know when \"notmuch search\" exits"
580   (let ((buffer (process-buffer proc))
581         (status (process-status proc))
582         (exit-status (process-exit-status proc))
583         (never-found-target-thread nil))
584     (if (memq status '(exit signal))
585         (if (buffer-live-p buffer)
586             (with-current-buffer buffer
587               (save-excursion
588                 (let ((inhibit-read-only t)
589                       (atbob (bobp)))
590                   (goto-char (point-max))
591                   (if (eq status 'signal)
592                       (insert "Incomplete search results (search process was killed).\n"))
593                   (if (eq status 'exit)
594                       (progn
595                         (insert "End of search results.")
596                         (if (not (= exit-status 0))
597                             (insert (format " (process returned %d)" exit-status)))
598                         (insert "\n")
599                         (if (and atbob
600                                  (not (string= notmuch-search-target-thread "found")))
601                             (set 'never-found-target-thread t))))))
602               (if (and never-found-target-thread
603                        notmuch-search-target-line)
604                   (goto-line notmuch-search-target-line)))))))
605
606 (defcustom notmuch-search-line-faces nil
607   "Tag/face mapping for line highlighting in notmuch-search.
608
609 Here is an example of how to color search results based on tags.
610 (the following text would be placed in your ~/.emacs file):
611
612 (setq notmuch-search-line-faces '((\"delete\" . '(:foreground \"red\"))
613                                  (\"unread\" . '(:foreground \"green\"))))
614
615 Order matters: for lines with multiple tags, the the first
616 matching will be applied."
617   :type '(alist :key-type (string) :value-type (list))
618   :group 'notmuch)
619
620 (defun notmuch-search-color-line (start end line-tag-list)
621   "Colorize lines in notmuch-show based on tags"
622   (if notmuch-search-line-faces
623       (let ((overlay (make-overlay start end))
624             (tags-faces (copy-alist notmuch-search-line-faces)))
625         (while tags-faces
626           (let* ((tag-face (car tags-faces))
627                  (tag (car tag-face))
628                  (face (cdr tag-face)))
629             (cond ((member tag line-tag-list)
630                    (overlay-put overlay 'face face)
631                    (setq tags-faces nil))
632                   (t
633                    (setq tags-faces (cdr tags-faces)))))))))
634
635 (defun notmuch-search-process-filter (proc string)
636   "Process and filter the output of \"notmuch search\""
637   (let ((buffer (process-buffer proc))
638         (found-target nil))
639     (if (buffer-live-p buffer)
640         (with-current-buffer buffer
641           (save-excursion
642             (let ((line 0)
643                   (more t)
644                   (inhibit-read-only t))
645               (while more
646                 (if (string-match "^\\(thread:[0-9A-Fa-f]*\\) \\(.*\\) \\(\\[[0-9/]*\\]\\) \\([^;]*\\); \\(.*\\) (\\([^()]*\\))$" string line)
647                     (let* ((thread-id (match-string 1 string))
648                            (date (match-string 2 string))
649                            (count (match-string 3 string))
650                            (authors (match-string 4 string))
651                            (authors-length (length authors))
652                            (subject (match-string 5 string))
653                            (tags (match-string 6 string))
654                            (tag-list (if tags (save-match-data (split-string tags)))))
655                       (if (> authors-length notmuch-search-authors-width)
656                           (set 'authors (concat (substring authors 0 (- notmuch-search-authors-width 3)) "...")))
657                       (goto-char (point-max))
658                       (let ((beg (point-marker))
659                             (format-string (format "%%s %%-7s %%-%ds %%s (%%s)\n" notmuch-search-authors-width)))
660                         (insert (format format-string date count authors subject tags))
661                         (notmuch-search-color-line beg (point-marker) tag-list)
662                         (put-text-property beg (point-marker) 'notmuch-search-thread-id thread-id)
663                         (put-text-property beg (point-marker) 'notmuch-search-authors authors)
664                         (put-text-property beg (point-marker) 'notmuch-search-subject subject)
665                         (if (string= thread-id notmuch-search-target-thread)
666                             (progn
667                               (set 'found-target beg)
668                               (set 'notmuch-search-target-thread "found"))))
669                       (set 'line (match-end 0)))
670                   (set 'more nil)))))
671           (if found-target
672               (goto-char found-target)))
673       (delete-process proc))))
674
675 (defun notmuch-search-operate-all (action)
676   "Add/remove tags from all matching messages.
677
678 Tis command adds or removes tags from all messages matching the
679 current search terms. When called interactively, this command
680 will prompt for tags to be added or removed. Tags prefixed with
681 '+' will be added and tags prefixed with '-' will be removed.
682
683 Each character of the tag name may consist of alphanumeric
684 characters as well as `_.+-'.
685 "
686   (interactive "sOperation (+add -drop): notmuch tag ")
687   (let ((action-split (split-string action " +")))
688     ;; Perform some validation
689     (let ((words action-split))
690       (when (null words) (error "No operation given"))
691       (while words
692         (unless (string-match-p "^[-+][-+_.[:word:]]+$" (car words))
693           (error "Action must be of the form `+thistag -that_tag'"))
694         (setq words (cdr words))))
695     (apply 'notmuch-call-notmuch-process "tag"
696            (append action-split (list notmuch-search-query-string) nil))))
697
698 ;;;###autoload
699 (defun notmuch-search (query &optional oldest-first target-thread target-line)
700   "Run \"notmuch search\" with the given query string and display results.
701
702 The optional parameters are used as follows:
703
704   oldest-first: A Boolean controlling the sort order of returned threads
705   target-thread: A thread ID (with the thread: prefix) that will be made
706                  current if it appears in the search results.
707   target-line: The line number to move to if the target thread does not
708                appear in the search results."
709   (interactive "sNotmuch search: ")
710   (let ((buffer (get-buffer-create (concat "*notmuch-search-" query "*"))))
711     (switch-to-buffer buffer)
712     (notmuch-search-mode)
713     (set 'notmuch-search-query-string query)
714     (set 'notmuch-search-oldest-first oldest-first)
715     (set 'notmuch-search-target-thread target-thread)
716     (set 'notmuch-search-target-line target-line)
717     (let ((proc (get-buffer-process (current-buffer)))
718           (inhibit-read-only t))
719       (if proc
720           (error "notmuch search process already running for query `%s'" query)
721         )
722       (erase-buffer)
723       (goto-char (point-min))
724       (save-excursion
725         (let ((proc (start-process-shell-command
726                      "notmuch-search" buffer notmuch-command "search"
727                      (if oldest-first "--sort=oldest-first" "--sort=newest-first")
728                      (shell-quote-argument query))))
729           (set-process-sentinel proc 'notmuch-search-process-sentinel)
730           (set-process-filter proc 'notmuch-search-process-filter))))
731     (run-hooks 'notmuch-search-hook)))
732
733 (defun notmuch-search-refresh-view ()
734   "Refresh the current view.
735
736 Kills the current buffer and runs a new search with the same
737 query string as the current search. If the current thread is in
738 the new search results, then point will be placed on the same
739 thread. Otherwise, point will be moved to attempt to be in the
740 same relative position within the new buffer."
741   (interactive)
742   (let ((target-line (line-number-at-pos))
743         (oldest-first notmuch-search-oldest-first)
744         (target-thread (notmuch-search-find-thread-id))
745         (query notmuch-search-query-string))
746     (kill-this-buffer)
747     (notmuch-search query oldest-first target-thread target-line)
748     (goto-char (point-min))
749     ))
750
751 (defun notmuch-search-toggle-order ()
752   "Toggle the current search order.
753
754 By default, the \"inbox\" view created by `notmuch' is displayed
755 in chronological order (oldest thread at the beginning of the
756 buffer), while any global searches created by `notmuch-search'
757 are displayed in reverse-chronological order (newest thread at
758 the beginning of the buffer).
759
760 This command toggles the sort order for the current search.
761
762 Note that any filtered searches created by
763 `notmuch-search-filter' retain the search order of the parent
764 search."
765   (interactive)
766   (set 'notmuch-search-oldest-first (not notmuch-search-oldest-first))
767   (notmuch-search-refresh-view))
768
769 (defun notmuch-search-filter (query)
770   "Filter the current search results based on an additional query string.
771
772 Runs a new search matching only messages that match both the
773 current search results AND the additional query string provided."
774   (interactive "sFilter search: ")
775   (let ((grouped-query (if (string-match-p notmuch-search-disjunctive-regexp query)
776                            (concat "( " query " )")
777                          query)))
778     (notmuch-search (if (string= notmuch-search-query-string "*")
779                         grouped-query
780                       (concat notmuch-search-query-string " and " grouped-query)) notmuch-search-oldest-first)))
781
782 (defun notmuch-search-filter-by-tag (tag)
783   "Filter the current search results based on a single tag.
784
785 Runs a new search matching only messages that match both the
786 current search results AND that are tagged with the given tag."
787   (interactive
788    (list (notmuch-select-tag-with-completion "Filter by tag: ")))
789   (notmuch-search (concat notmuch-search-query-string " and tag:" tag) notmuch-search-oldest-first))
790
791 ;;;###autoload
792 (defun notmuch ()
793   "Run notmuch to display all mail with tag of 'inbox'"
794   (interactive)
795   (notmuch-search "tag:inbox" notmuch-search-oldest-first))
796
797 (setq mail-user-agent 'message-user-agent)
798
799 (defvar notmuch-folder-mode-map
800   (let ((map (make-sparse-keymap)))
801     (define-key map "?" 'notmuch-help)
802     (define-key map "x" 'kill-this-buffer)
803     (define-key map "q" 'kill-this-buffer)
804     (define-key map "m" 'message-mail)
805     (define-key map "e" 'notmuch-folder-show-empty-toggle)
806     (define-key map ">" 'notmuch-folder-last)
807     (define-key map "<" 'notmuch-folder-first)
808     (define-key map "=" 'notmuch-folder)
809     (define-key map "s" 'notmuch-search)
810     (define-key map [mouse-1] 'notmuch-folder-show-search)
811     (define-key map (kbd "RET") 'notmuch-folder-show-search)
812     (define-key map " " 'notmuch-folder-show-search)
813     (define-key map "p" 'notmuch-folder-previous)
814     (define-key map "n" 'notmuch-folder-next)
815     map)
816   "Keymap for \"notmuch folder\" buffers.")
817
818 (fset 'notmuch-folder-mode-map notmuch-folder-mode-map)
819
820 (defcustom notmuch-folders (quote (("inbox" . "tag:inbox") ("unread" . "tag:unread")))
821   "List of searches for the notmuch folder view"
822   :type '(alist :key-type (string) :value-type (string))
823   :group 'notmuch)
824
825 (defun notmuch-folder-mode ()
826   "Major mode for showing notmuch 'folders'.
827
828 This buffer contains a list of message counts returned by a
829 customizable set of searches of your email archives. Each line in
830 the buffer shows the name of a saved search and the resulting
831 message count.
832
833 Pressing RET on any line opens a search window containing the
834 results for the saved search on that line.
835
836 Here is an example of how the search list could be
837 customized, (the following text would be placed in your ~/.emacs
838 file):
839
840 (setq notmuch-folders '((\"inbox\" . \"tag:inbox\")
841                         (\"unread\" . \"tag:inbox AND tag:unread\")
842                         (\"notmuch\" . \"tag:inbox AND to:notmuchmail.org\")))
843
844 Of course, you can have any number of folders, each configured
845 with any supported search terms (see \"notmuch help search-terms\").
846
847 Currently available key bindings:
848
849 \\{notmuch-folder-mode-map}"
850   (interactive)
851   (kill-all-local-variables)
852   (use-local-map 'notmuch-folder-mode-map)
853   (setq truncate-lines t)
854   (hl-line-mode 1)
855   (setq major-mode 'notmuch-folder-mode
856         mode-name "notmuch-folder")
857   (setq buffer-read-only t))
858
859 (defun notmuch-folder-next ()
860   "Select the next folder in the list."
861   (interactive)
862   (forward-line 1)
863   (if (eobp)
864       (forward-line -1)))
865
866 (defun notmuch-folder-previous ()
867   "Select the previous folder in the list."
868   (interactive)
869   (forward-line -1))
870
871 (defun notmuch-folder-first ()
872   "Select the first folder in the list."
873   (interactive)
874   (goto-char (point-min)))
875
876 (defun notmuch-folder-last ()
877   "Select the last folder in the list."
878   (interactive)
879   (goto-char (point-max))
880   (forward-line -1))
881
882 (defun notmuch-folder-count (search)
883   (car (process-lines notmuch-command "count" search)))
884
885 (defvar notmuch-folder-show-empty t
886   "Whether `notmuch-folder-mode' should display empty folders.")
887
888 (defun notmuch-folder-show-empty-toggle ()
889   "Toggle the listing of empty folders"
890   (interactive)
891   (setq notmuch-folder-show-empty (not notmuch-folder-show-empty))
892   (notmuch-folder))
893
894 (defun notmuch-folder-add (folders)
895   (if folders
896       (let* ((name (car (car folders)))
897             (inhibit-read-only t)
898             (search (cdr (car folders)))
899             (count (notmuch-folder-count search)))
900         (if (or notmuch-folder-show-empty
901                 (not (equal count "0")))
902             (progn
903               (insert name)
904               (indent-to 16 1)
905               (insert count)
906               (insert "\n")
907               )
908           )
909         (notmuch-folder-add (cdr folders)))))
910
911 (defun notmuch-folder-find-name ()
912   (save-excursion
913     (beginning-of-line)
914     (let ((beg (point)))
915       (re-search-forward "\\([ \t]*[^ \t]+\\)")
916       (filter-buffer-substring (match-beginning 1) (match-end 1)))))
917
918 (defun notmuch-folder-show-search (&optional folder)
919   "Show a search window for the search related to the specified folder."
920   (interactive)
921   (if (null folder)
922       (setq folder (notmuch-folder-find-name)))
923   (let ((search (assoc folder notmuch-folders)))
924     (if search
925         (notmuch-search (cdr search) notmuch-search-oldest-first))))
926
927 ;;;###autoload
928 (defun notmuch-folder ()
929   "Show the notmuch folder view and update the displayed counts."
930   (interactive)
931   (let ((buffer (get-buffer-create "*notmuch-folders*")))
932     (switch-to-buffer buffer)
933     (let ((inhibit-read-only t)
934           (n (line-number-at-pos)))
935       (erase-buffer)
936       (notmuch-folder-mode)
937       (notmuch-folder-add notmuch-folders)
938       (goto-char (point-min))
939       (goto-line n))))
940
941 (provide 'notmuch)