]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch.el
emacs: Remove duplicate declaration of `notmuch-folders'
[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 (defun notmuch-search-buffer-title (query)
663   "Returns the title for a buffer with notmuch search results."
664   (let* ((folder (rassoc-if (lambda (key)
665                               (string-match (concat "^" (regexp-quote key))
666                                             query))
667                             notmuch-folders))
668          (folder-name (car folder))
669          (folder-query (cdr folder)))
670     (cond ((and folder (equal folder-query query))
671            ;; Query is the same as folder search (ignoring case)
672            (concat "*notmuch-folder-" folder-name "*"))
673           (folder
674            (concat "*notmuch-search-"
675                    (replace-regexp-in-string (concat "^" (regexp-quote folder-query))
676                                              (concat "[ " folder-name " ]")
677                                              query)
678                    "*"))
679           (t
680            (concat "*notmuch-search-" query "*"))
681           )))
682
683 ;;;###autoload
684 (defun notmuch-search (query &optional oldest-first target-thread target-line continuation)
685   "Run \"notmuch search\" with the given query string and display results.
686
687 The optional parameters are used as follows:
688
689   oldest-first: A Boolean controlling the sort order of returned threads
690   target-thread: A thread ID (with the thread: prefix) that will be made
691                  current if it appears in the search results.
692   target-line: The line number to move to if the target thread does not
693                appear in the search results."
694   (interactive "sNotmuch search: ")
695   (let ((buffer (get-buffer-create (notmuch-search-buffer-title query))))
696     (switch-to-buffer buffer)
697     (notmuch-search-mode)
698     (set 'notmuch-search-query-string query)
699     (set 'notmuch-search-oldest-first oldest-first)
700     (set 'notmuch-search-target-thread target-thread)
701     (set 'notmuch-search-target-line target-line)
702     (set 'notmuch-search-continuation continuation)
703     (let ((proc (get-buffer-process (current-buffer)))
704           (inhibit-read-only t))
705       (if proc
706           (error "notmuch search process already running for query `%s'" query)
707         )
708       (erase-buffer)
709       (goto-char (point-min))
710       (save-excursion
711         (let ((proc (start-process-shell-command
712                      "notmuch-search" buffer notmuch-command "search"
713                      (if oldest-first "--sort=oldest-first" "--sort=newest-first")
714                      (shell-quote-argument query))))
715           (set-process-sentinel proc 'notmuch-search-process-sentinel)
716           (set-process-filter proc 'notmuch-search-process-filter))))
717     (run-hooks 'notmuch-search-hook)))
718
719 (defun notmuch-search-refresh-view ()
720   "Refresh the current view.
721
722 Kills the current buffer and runs a new search with the same
723 query string as the current search. If the current thread is in
724 the new search results, then point will be placed on the same
725 thread. Otherwise, point will be moved to attempt to be in the
726 same relative position within the new buffer."
727   (interactive)
728   (let ((target-line (line-number-at-pos))
729         (oldest-first notmuch-search-oldest-first)
730         (target-thread (notmuch-search-find-thread-id))
731         (query notmuch-search-query-string)
732         (continuation notmuch-search-continuation))
733     (kill-this-buffer)
734     (notmuch-search query oldest-first target-thread target-line continuation)
735     (goto-char (point-min))))
736
737 (defcustom notmuch-poll-script ""
738   "An external script to incorporate new mail into the notmuch database.
739
740 If this variable is non empty, then it should name a script to be
741 invoked by `notmuch-search-poll-and-refresh-view' and
742 `notmuch-folder-poll-and-refresh-view' (each have a default
743 keybinding of 'G'). The script could do any of the following
744 depending on the user's needs:
745
746 1. Invoke a program to transfer mail to the local mail store
747 2. Invoke \"notmuch new\" to incorporate the new mail
748 3. Invoke one or more \"notmuch tag\" commands to classify the mail"
749   :type 'string
750   :group 'notmuch)
751
752 (defun notmuch-poll ()
753   "Run external script to import mail.
754
755 Invokes `notmuch-poll-script' if it is not set to an empty string."
756   (interactive)
757   (if (not (string= notmuch-poll-script ""))
758       (call-process notmuch-poll-script nil nil)))
759
760 (defun notmuch-search-poll-and-refresh-view ()
761   "Invoke `notmuch-poll' to import mail, then refresh the current view."
762   (interactive)
763   (notmuch-poll)
764   (notmuch-search-refresh-view))
765
766 (defun notmuch-search-toggle-order ()
767   "Toggle the current search order.
768
769 By default, the \"inbox\" view created by `notmuch' is displayed
770 in chronological order (oldest thread at the beginning of the
771 buffer), while any global searches created by `notmuch-search'
772 are displayed in reverse-chronological order (newest thread at
773 the beginning of the buffer).
774
775 This command toggles the sort order for the current search.
776
777 Note that any filtered searches created by
778 `notmuch-search-filter' retain the search order of the parent
779 search."
780   (interactive)
781   (set 'notmuch-search-oldest-first (not notmuch-search-oldest-first))
782   (notmuch-search-refresh-view))
783
784 (defun notmuch-search-filter (query)
785   "Filter the current search results based on an additional query string.
786
787 Runs a new search matching only messages that match both the
788 current search results AND the additional query string provided."
789   (interactive "sFilter search: ")
790   (let ((grouped-query (if (string-match-p notmuch-search-disjunctive-regexp query)
791                            (concat "( " query " )")
792                          query)))
793     (notmuch-search (if (string= notmuch-search-query-string "*")
794                         grouped-query
795                       (concat notmuch-search-query-string " and " grouped-query)) notmuch-search-oldest-first)))
796
797 (defun notmuch-search-filter-by-tag (tag)
798   "Filter the current search results based on a single tag.
799
800 Runs a new search matching only messages that match both the
801 current search results AND that are tagged with the given tag."
802   (interactive
803    (list (notmuch-select-tag-with-completion "Filter by tag: ")))
804   (notmuch-search (concat notmuch-search-query-string " and tag:" tag) notmuch-search-oldest-first))
805
806 ;;;###autoload
807 (defun notmuch ()
808   "Run notmuch and display saved searches, known tags, etc."
809   (interactive)
810   (notmuch-hello))
811
812 (setq mail-user-agent 'notmuch-user-agent)
813
814 (defvar notmuch-folder-mode-map
815   (let ((map (make-sparse-keymap)))
816     (define-key map "?" 'notmuch-help)
817     (define-key map "x" 'kill-this-buffer)
818     (define-key map "q" 'kill-this-buffer)
819     (define-key map "m" 'notmuch-mua-mail)
820     (define-key map "e" 'notmuch-folder-show-empty-toggle)
821     (define-key map ">" 'notmuch-folder-last)
822     (define-key map "<" 'notmuch-folder-first)
823     (define-key map "=" 'notmuch-folder)
824     (define-key map "G" 'notmuch-folder-poll-and-refresh-view)
825     (define-key map "s" 'notmuch-search)
826     (define-key map [mouse-1] 'notmuch-folder-show-search)
827     (define-key map (kbd "RET") 'notmuch-folder-show-search)
828     (define-key map " " 'notmuch-folder-show-search)
829     (define-key map "p" 'notmuch-folder-previous)
830     (define-key map "n" 'notmuch-folder-next)
831     map)
832   "Keymap for \"notmuch folder\" buffers.")
833
834 (fset 'notmuch-folder-mode-map notmuch-folder-mode-map)
835
836 (defun notmuch-folder-mode ()
837   "Major mode for showing notmuch 'folders'.
838
839 This buffer contains a list of message counts returned by a
840 customizable set of searches of your email archives. Each line in
841 the buffer shows the name of a saved search and the resulting
842 message count.
843
844 Pressing RET on any line opens a search window containing the
845 results for the saved search on that line.
846
847 Here is an example of how the search list could be
848 customized, (the following text would be placed in your ~/.emacs
849 file):
850
851 (setq notmuch-folders '((\"inbox\" . \"tag:inbox\")
852                         (\"unread\" . \"tag:inbox AND tag:unread\")
853                         (\"notmuch\" . \"tag:inbox AND to:notmuchmail.org\")))
854
855 Of course, you can have any number of folders, each configured
856 with any supported search terms (see \"notmuch help search-terms\").
857
858 Currently available key bindings:
859
860 \\{notmuch-folder-mode-map}"
861   (interactive)
862   (kill-all-local-variables)
863   (use-local-map 'notmuch-folder-mode-map)
864   (setq truncate-lines t)
865   (hl-line-mode 1)
866   (setq major-mode 'notmuch-folder-mode
867         mode-name "notmuch-folder")
868   (setq buffer-read-only t))
869
870 (defun notmuch-folder-next ()
871   "Select the next folder in the list."
872   (interactive)
873   (forward-line 1)
874   (if (eobp)
875       (forward-line -1)))
876
877 (defun notmuch-folder-previous ()
878   "Select the previous folder in the list."
879   (interactive)
880   (forward-line -1))
881
882 (defun notmuch-folder-first ()
883   "Select the first folder in the list."
884   (interactive)
885   (goto-char (point-min)))
886
887 (defun notmuch-folder-last ()
888   "Select the last folder in the list."
889   (interactive)
890   (goto-char (point-max))
891   (forward-line -1))
892
893 (defun notmuch-folder-count (search)
894   (car (process-lines notmuch-command "count" search)))
895
896 (defvar notmuch-folder-show-empty t
897   "Whether `notmuch-folder-mode' should display empty folders.")
898
899 (defun notmuch-folder-show-empty-toggle ()
900   "Toggle the listing of empty folders"
901   (interactive)
902   (setq notmuch-folder-show-empty (not notmuch-folder-show-empty))
903   (notmuch-folder))
904
905 (defun notmuch-folder-add (folders)
906   (if folders
907       (let* ((name (car (car folders)))
908             (inhibit-read-only t)
909             (search (cdr (car folders)))
910             (count (notmuch-folder-count search)))
911         (if (or notmuch-folder-show-empty
912                 (not (equal count "0")))
913             (progn
914               (insert name)
915               (indent-to 16 1)
916               (insert count)
917               (insert "\n")
918               )
919           )
920         (notmuch-folder-add (cdr folders)))))
921
922 (defun notmuch-folder-find-name ()
923   (save-excursion
924     (beginning-of-line)
925     (let ((beg (point)))
926       (re-search-forward "\\([ \t]*[^ \t]+\\)")
927       (filter-buffer-substring (match-beginning 1) (match-end 1)))))
928
929 (defun notmuch-folder-show-search (&optional folder)
930   "Show a search window for the search related to the specified folder."
931   (interactive)
932   (if (null folder)
933       (setq folder (notmuch-folder-find-name)))
934   (let ((search (assoc folder notmuch-folders)))
935     (if search
936         (notmuch-search (cdr search) notmuch-search-oldest-first))))
937
938 (defun notmuch-folder-poll-and-refresh-view ()
939   "Invoke `notmuch-poll' to import mail, then refresh the folder view."
940   (interactive)
941   (notmuch-poll)
942   (notmuch-folder))
943
944 ;;;###autoload
945 (defun notmuch-folder ()
946   "Show the notmuch folder view and update the displayed counts."
947   (interactive)
948   (let ((buffer (get-buffer-create "*notmuch-folders*")))
949     (switch-to-buffer buffer)
950     (let ((inhibit-read-only t)
951           (n (line-number-at-pos)))
952       (erase-buffer)
953       (notmuch-folder-mode)
954       (notmuch-folder-add notmuch-folders)
955       (goto-char (point-min))
956       (goto-line n))))
957
958 (provide 'notmuch)