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