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