]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch.el
emacs: Re-arrange message sending code
[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 ((sample (format (cdr (assoc field notmuch-search-result-format)) "")))
586               (if (> (length authors)
587                      (length sample))
588                   (concat (substring authors 0 (- (length sample) 4)) "... ")
589                 (format (cdr (assoc field notmuch-search-result-format)) authors)))))
590    ((string-equal field "subject")
591     (insert (format (cdr (assoc field notmuch-search-result-format)) subject)))
592    ((string-equal field "tags")
593     (insert (concat "(" (propertize tags 'font-lock-face 'notmuch-tag-face) ")")))))
594
595 (defun notmuch-search-show-result (date count authors subject tags)
596   (let ((fields) (field))
597     (setq fields (mapcar 'car notmuch-search-result-format))
598     (loop for field in fields
599           do (notmuch-search-insert-field field date count authors subject tags)))
600   (insert "\n"))
601
602 (defun notmuch-search-process-filter (proc string)
603   "Process and filter the output of \"notmuch search\""
604   (let ((buffer (process-buffer proc))
605         (found-target nil))
606     (if (buffer-live-p buffer)
607         (with-current-buffer buffer
608           (save-excursion
609             (let ((line 0)
610                   (more t)
611                   (inhibit-read-only t))
612               (while more
613                 (if (string-match "^\\(thread:[0-9A-Fa-f]*\\) \\(.*\\) \\(\\[[0-9/]*\\]\\) \\([^;]*\\); \\(.*\\) (\\([^()]*\\))$" string line)
614                     (let* ((thread-id (match-string 1 string))
615                            (date (match-string 2 string))
616                            (count (match-string 3 string))
617                            (authors (match-string 4 string))
618                            (subject (match-string 5 string))
619                            (tags (match-string 6 string))
620                            (tag-list (if tags (save-match-data (split-string tags)))))
621                       (goto-char (point-max))
622                       (let ((beg (point-marker)))
623                         (notmuch-search-show-result date count authors subject tags)
624                         (notmuch-search-color-line beg (point-marker) tag-list)
625                         (put-text-property beg (point-marker) 'notmuch-search-thread-id thread-id)
626                         (put-text-property beg (point-marker) 'notmuch-search-authors authors)
627                         (put-text-property beg (point-marker) 'notmuch-search-subject subject)
628                         (if (string= thread-id notmuch-search-target-thread)
629                             (progn
630                               (set 'found-target beg)
631                               (set 'notmuch-search-target-thread "found"))))
632                       (set 'line (match-end 0)))
633                   (set 'more nil)))))
634           (if found-target
635               (goto-char found-target)))
636       (delete-process proc))))
637
638 (defun notmuch-search-operate-all (action)
639   "Add/remove tags from all matching messages.
640
641 Tis command adds or removes tags from all messages matching the
642 current search terms. When called interactively, this command
643 will prompt for tags to be added or removed. Tags prefixed with
644 '+' will be added and tags prefixed with '-' will be removed.
645
646 Each character of the tag name may consist of alphanumeric
647 characters as well as `_.+-'.
648 "
649   (interactive "sOperation (+add -drop): notmuch tag ")
650   (let ((action-split (split-string action " +")))
651     ;; Perform some validation
652     (let ((words action-split))
653       (when (null words) (error "No operation given"))
654       (while words
655         (unless (string-match-p "^[-+][-+_.[:word:]]+$" (car words))
656           (error "Action must be of the form `+thistag -that_tag'"))
657         (setq words (cdr words))))
658     (apply 'notmuch-call-notmuch-process "tag"
659            (append action-split (list notmuch-search-query-string) nil))))
660
661 (defcustom notmuch-folders (quote (("inbox" . "tag:inbox") ("unread" . "tag:unread")))
662   "List of searches for the notmuch folder view"
663   :type '(alist :key-type (string) :value-type (string))
664   :group 'notmuch)
665
666 (defun notmuch-search-buffer-title (query)
667   "Returns the title for a buffer with notmuch search results."
668   (let* ((folder (rassoc-if (lambda (key)
669                               (string-match (concat "^" (regexp-quote key))
670                                             query))
671                             notmuch-folders))
672          (folder-name (car folder))
673          (folder-query (cdr folder)))
674     (cond ((and folder (equal folder-query query))
675            ;; Query is the same as folder search (ignoring case)
676            (concat "*notmuch-folder-" folder-name "*"))
677           (folder
678            (concat "*notmuch-search-"
679                    (replace-regexp-in-string (concat "^" (regexp-quote folder-query))
680                                              (concat "[ " folder-name " ]")
681                                              query)
682                    "*"))
683           (t
684            (concat "*notmuch-search-" query "*"))
685           )))
686
687 ;;;###autoload
688 (defun notmuch-search (query &optional oldest-first target-thread target-line continuation)
689   "Run \"notmuch search\" with the given query string and display results.
690
691 The optional parameters are used as follows:
692
693   oldest-first: A Boolean controlling the sort order of returned threads
694   target-thread: A thread ID (with the thread: prefix) that will be made
695                  current if it appears in the search results.
696   target-line: The line number to move to if the target thread does not
697                appear in the search results."
698   (interactive "sNotmuch search: ")
699   (let ((buffer (get-buffer-create (notmuch-search-buffer-title query))))
700     (switch-to-buffer buffer)
701     (notmuch-search-mode)
702     (set 'notmuch-search-query-string query)
703     (set 'notmuch-search-oldest-first oldest-first)
704     (set 'notmuch-search-target-thread target-thread)
705     (set 'notmuch-search-target-line target-line)
706     (set 'notmuch-search-continuation continuation)
707     (let ((proc (get-buffer-process (current-buffer)))
708           (inhibit-read-only t))
709       (if proc
710           (error "notmuch search process already running for query `%s'" query)
711         )
712       (erase-buffer)
713       (goto-char (point-min))
714       (save-excursion
715         (let ((proc (start-process-shell-command
716                      "notmuch-search" buffer notmuch-command "search"
717                      (if oldest-first "--sort=oldest-first" "--sort=newest-first")
718                      (shell-quote-argument query))))
719           (set-process-sentinel proc 'notmuch-search-process-sentinel)
720           (set-process-filter proc 'notmuch-search-process-filter))))
721     (run-hooks 'notmuch-search-hook)))
722
723 (defun notmuch-search-refresh-view ()
724   "Refresh the current view.
725
726 Kills the current buffer and runs a new search with the same
727 query string as the current search. If the current thread is in
728 the new search results, then point will be placed on the same
729 thread. Otherwise, point will be moved to attempt to be in the
730 same relative position within the new buffer."
731   (interactive)
732   (let ((target-line (line-number-at-pos))
733         (oldest-first notmuch-search-oldest-first)
734         (target-thread (notmuch-search-find-thread-id))
735         (query notmuch-search-query-string)
736         (continuation notmuch-search-continuation))
737     (kill-this-buffer)
738     (notmuch-search query oldest-first target-thread target-line continuation)
739     (goto-char (point-min))))
740
741 (defcustom notmuch-poll-script ""
742   "An external script to incorporate new mail into the notmuch database.
743
744 If this variable is non empty, then it should name a script to be
745 invoked by `notmuch-search-poll-and-refresh-view' and
746 `notmuch-folder-poll-and-refresh-view' (each have a default
747 keybinding of 'G'). The script could do any of the following
748 depending on the user's needs:
749
750 1. Invoke a program to transfer mail to the local mail store
751 2. Invoke \"notmuch new\" to incorporate the new mail
752 3. Invoke one or more \"notmuch tag\" commands to classify the mail"
753   :type 'string
754   :group 'notmuch)
755
756 (defun notmuch-poll ()
757   "Run external script to import mail.
758
759 Invokes `notmuch-poll-script' if it is not set to an empty string."
760   (interactive)
761   (if (not (string= notmuch-poll-script ""))
762       (call-process notmuch-poll-script nil nil)))
763
764 (defun notmuch-search-poll-and-refresh-view ()
765   "Invoke `notmuch-poll' to import mail, then refresh the current view."
766   (interactive)
767   (notmuch-poll)
768   (notmuch-search-refresh-view))
769
770 (defun notmuch-search-toggle-order ()
771   "Toggle the current search order.
772
773 By default, the \"inbox\" view created by `notmuch' is displayed
774 in chronological order (oldest thread at the beginning of the
775 buffer), while any global searches created by `notmuch-search'
776 are displayed in reverse-chronological order (newest thread at
777 the beginning of the buffer).
778
779 This command toggles the sort order for the current search.
780
781 Note that any filtered searches created by
782 `notmuch-search-filter' retain the search order of the parent
783 search."
784   (interactive)
785   (set 'notmuch-search-oldest-first (not notmuch-search-oldest-first))
786   (notmuch-search-refresh-view))
787
788 (defun notmuch-search-filter (query)
789   "Filter the current search results based on an additional query string.
790
791 Runs a new search matching only messages that match both the
792 current search results AND the additional query string provided."
793   (interactive "sFilter search: ")
794   (let ((grouped-query (if (string-match-p notmuch-search-disjunctive-regexp query)
795                            (concat "( " query " )")
796                          query)))
797     (notmuch-search (if (string= notmuch-search-query-string "*")
798                         grouped-query
799                       (concat notmuch-search-query-string " and " grouped-query)) notmuch-search-oldest-first)))
800
801 (defun notmuch-search-filter-by-tag (tag)
802   "Filter the current search results based on a single tag.
803
804 Runs a new search matching only messages that match both the
805 current search results AND that are tagged with the given tag."
806   (interactive
807    (list (notmuch-select-tag-with-completion "Filter by tag: ")))
808   (notmuch-search (concat notmuch-search-query-string " and tag:" tag) notmuch-search-oldest-first))
809
810 ;;;###autoload
811 (defun notmuch ()
812   "Run notmuch to display all mail with tag of 'inbox'"
813   (interactive)
814   (notmuch-search "tag:inbox" notmuch-search-oldest-first))
815
816 (setq mail-user-agent 'notmuch-user-agent)
817
818 (defvar notmuch-folder-mode-map
819   (let ((map (make-sparse-keymap)))
820     (define-key map "?" 'notmuch-help)
821     (define-key map "x" 'kill-this-buffer)
822     (define-key map "q" 'kill-this-buffer)
823     (define-key map "m" 'notmuch-mua-mail)
824     (define-key map "e" 'notmuch-folder-show-empty-toggle)
825     (define-key map ">" 'notmuch-folder-last)
826     (define-key map "<" 'notmuch-folder-first)
827     (define-key map "=" 'notmuch-folder)
828     (define-key map "G" 'notmuch-folder-poll-and-refresh-view)
829     (define-key map "s" 'notmuch-search)
830     (define-key map [mouse-1] 'notmuch-folder-show-search)
831     (define-key map (kbd "RET") 'notmuch-folder-show-search)
832     (define-key map " " 'notmuch-folder-show-search)
833     (define-key map "p" 'notmuch-folder-previous)
834     (define-key map "n" 'notmuch-folder-next)
835     map)
836   "Keymap for \"notmuch folder\" buffers.")
837
838 (fset 'notmuch-folder-mode-map notmuch-folder-mode-map)
839
840 (defun notmuch-folder-mode ()
841   "Major mode for showing notmuch 'folders'.
842
843 This buffer contains a list of message counts returned by a
844 customizable set of searches of your email archives. Each line in
845 the buffer shows the name of a saved search and the resulting
846 message count.
847
848 Pressing RET on any line opens a search window containing the
849 results for the saved search on that line.
850
851 Here is an example of how the search list could be
852 customized, (the following text would be placed in your ~/.emacs
853 file):
854
855 (setq notmuch-folders '((\"inbox\" . \"tag:inbox\")
856                         (\"unread\" . \"tag:inbox AND tag:unread\")
857                         (\"notmuch\" . \"tag:inbox AND to:notmuchmail.org\")))
858
859 Of course, you can have any number of folders, each configured
860 with any supported search terms (see \"notmuch help search-terms\").
861
862 Currently available key bindings:
863
864 \\{notmuch-folder-mode-map}"
865   (interactive)
866   (kill-all-local-variables)
867   (use-local-map 'notmuch-folder-mode-map)
868   (setq truncate-lines t)
869   (hl-line-mode 1)
870   (setq major-mode 'notmuch-folder-mode
871         mode-name "notmuch-folder")
872   (setq buffer-read-only t))
873
874 (defun notmuch-folder-next ()
875   "Select the next folder in the list."
876   (interactive)
877   (forward-line 1)
878   (if (eobp)
879       (forward-line -1)))
880
881 (defun notmuch-folder-previous ()
882   "Select the previous folder in the list."
883   (interactive)
884   (forward-line -1))
885
886 (defun notmuch-folder-first ()
887   "Select the first folder in the list."
888   (interactive)
889   (goto-char (point-min)))
890
891 (defun notmuch-folder-last ()
892   "Select the last folder in the list."
893   (interactive)
894   (goto-char (point-max))
895   (forward-line -1))
896
897 (defun notmuch-folder-count (search)
898   (car (process-lines notmuch-command "count" search)))
899
900 (defvar notmuch-folder-show-empty t
901   "Whether `notmuch-folder-mode' should display empty folders.")
902
903 (defun notmuch-folder-show-empty-toggle ()
904   "Toggle the listing of empty folders"
905   (interactive)
906   (setq notmuch-folder-show-empty (not notmuch-folder-show-empty))
907   (notmuch-folder))
908
909 (defun notmuch-folder-add (folders)
910   (if folders
911       (let* ((name (car (car folders)))
912             (inhibit-read-only t)
913             (search (cdr (car folders)))
914             (count (notmuch-folder-count search)))
915         (if (or notmuch-folder-show-empty
916                 (not (equal count "0")))
917             (progn
918               (insert name)
919               (indent-to 16 1)
920               (insert count)
921               (insert "\n")
922               )
923           )
924         (notmuch-folder-add (cdr folders)))))
925
926 (defun notmuch-folder-find-name ()
927   (save-excursion
928     (beginning-of-line)
929     (let ((beg (point)))
930       (re-search-forward "\\([ \t]*[^ \t]+\\)")
931       (filter-buffer-substring (match-beginning 1) (match-end 1)))))
932
933 (defun notmuch-folder-show-search (&optional folder)
934   "Show a search window for the search related to the specified folder."
935   (interactive)
936   (if (null folder)
937       (setq folder (notmuch-folder-find-name)))
938   (let ((search (assoc folder notmuch-folders)))
939     (if search
940         (notmuch-search (cdr search) notmuch-search-oldest-first))))
941
942 (defun notmuch-folder-poll-and-refresh-view ()
943   "Invoke `notmuch-poll' to import mail, then refresh the folder view."
944   (interactive)
945   (notmuch-poll)
946   (notmuch-folder))
947
948 ;;;###autoload
949 (defun notmuch-folder ()
950   "Show the notmuch folder view and update the displayed counts."
951   (interactive)
952   (let ((buffer (get-buffer-create "*notmuch-folders*")))
953     (switch-to-buffer buffer)
954     (let ((inhibit-read-only t)
955           (n (line-number-at-pos)))
956       (erase-buffer)
957       (notmuch-folder-mode)
958       (notmuch-folder-add notmuch-folders)
959       (goto-char (point-min))
960       (goto-line n))))
961
962 (provide 'notmuch)