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