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