]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch.el
emacs: Match entire saved-search when computing search-view buffer name
[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 (require 'notmuch-maildir-fcc)
59
60 (defcustom notmuch-search-result-format
61   `(("date" . "%s ")
62     ("count" . "%-7s ")
63     ("authors" . "%-20s ")
64     ("subject" . "%s ")
65     ("tags" . "(%s)"))
66   "Search result formating. Supported fields are:
67         date, count, authors, subject, tags
68 For example:
69         (setq notmuch-search-result-format \(\(\"authors\" . \"%-40s\"\)
70                                              \(\"subject\" . \"%s\"\)\)\)"
71   :type '(alist :key-type (string) :value-type (string))
72   :group 'notmuch)
73
74 (defun notmuch-select-tag-with-completion (prompt &rest search-terms)
75   (let ((tag-list
76          (with-output-to-string
77            (with-current-buffer standard-output
78              (apply 'call-process notmuch-command nil t nil "search-tags" search-terms)))))
79     (completing-read prompt (split-string tag-list "\n+" t) nil nil nil)))
80
81 (defun notmuch-foreach-mime-part (function mm-handle)
82   (cond ((stringp (car mm-handle))
83          (dolist (part (cdr mm-handle))
84            (notmuch-foreach-mime-part function part)))
85         ((bufferp (car mm-handle))
86          (funcall function mm-handle))
87         (t (dolist (part mm-handle)
88              (notmuch-foreach-mime-part function part)))))
89
90 (defun notmuch-count-attachments (mm-handle)
91   (let ((count 0))
92     (notmuch-foreach-mime-part
93      (lambda (p)
94        (let ((disposition (mm-handle-disposition p)))
95          (and (listp disposition)
96               (or (equal (car disposition) "attachment")
97                   (and (equal (car disposition) "inline")
98                        (assq 'filename disposition)))
99               (incf count))))
100      mm-handle)
101     count))
102
103 (defun notmuch-save-attachments (mm-handle &optional queryp)
104   (notmuch-foreach-mime-part
105    (lambda (p)
106      (let ((disposition (mm-handle-disposition p)))
107        (and (listp disposition)
108             (or (equal (car disposition) "attachment")
109                 (and (equal (car disposition) "inline")
110                      (assq 'filename disposition)))
111             (or (not queryp)
112                 (y-or-n-p
113                  (concat "Save '" (cdr (assq 'filename disposition)) "' ")))
114             (mm-save-part p))))
115    mm-handle))
116
117 (defun notmuch-documentation-first-line (symbol)
118   "Return the first line of the documentation string for SYMBOL."
119   (let ((doc (documentation symbol)))
120     (if doc
121         (with-temp-buffer
122           (insert (documentation symbol t))
123           (goto-char (point-min))
124           (let ((beg (point)))
125             (end-of-line)
126             (buffer-substring beg (point))))
127       "")))
128
129 (defun notmuch-prefix-key-description (key)
130   "Given a prefix key code, return a human-readable string representation.
131
132 This is basically just `format-kbd-macro' but we also convert ESC to M-."
133   (let ((desc (format-kbd-macro (vector key))))
134     (if (string= desc "ESC")
135         "M-"
136       (concat desc " "))))
137
138 ; I would think that emacs would have code handy for walking a keymap
139 ; and generating strings for each key, and I would prefer to just call
140 ; that. But I couldn't find any (could be all implemented in C I
141 ; suppose), so I wrote my own here.
142 (defun notmuch-substitute-one-command-key-with-prefix (prefix binding)
143   "For a key binding, return a string showing a human-readable
144 representation of the prefixed key as well as the first line of
145 documentation from the bound function.
146
147 For a mouse binding, return nil."
148   (let ((key (car binding))
149         (action (cdr binding)))
150     (if (mouse-event-p key)
151         nil
152       (if (keymapp action)
153           (let ((substitute (apply-partially 'notmuch-substitute-one-command-key-with-prefix (notmuch-prefix-key-description key)))
154                 (as-list))
155             (map-keymap (lambda (a b)
156                           (push (cons a b) as-list))
157                         action)
158             (mapconcat substitute as-list "\n"))
159         (concat prefix (format-kbd-macro (vector key))
160                 "\t"
161                 (notmuch-documentation-first-line action))))))
162
163 (defalias 'notmuch-substitute-one-command-key
164   (apply-partially 'notmuch-substitute-one-command-key-with-prefix nil))
165
166 (defun notmuch-substitute-command-keys (doc)
167   "Like `substitute-command-keys' but with documentation, not function names."
168   (let ((beg 0))
169     (while (string-match "\\\\{\\([^}[:space:]]*\\)}" doc beg)
170       (let ((map (substring doc (match-beginning 1) (match-end 1))))
171         (setq doc (replace-match (mapconcat 'notmuch-substitute-one-command-key
172                                             (cdr (symbol-value (intern map))) "\n") 1 1 doc)))
173       (setq beg (match-end 0)))
174     doc))
175
176 (defun notmuch-help ()
177   "Display help for the current notmuch mode."
178   (interactive)
179   (let* ((mode major-mode)
180          (doc (substitute-command-keys (notmuch-substitute-command-keys (documentation mode t)))))
181     (with-current-buffer (generate-new-buffer "*notmuch-help*")
182       (insert doc)
183       (goto-char (point-min))
184       (set-buffer-modified-p nil)
185       (view-buffer (current-buffer) 'kill-buffer-if-not-modified))))
186
187 (defcustom notmuch-search-hook '(hl-line-mode)
188   "List of functions to call when notmuch displays the search results."
189   :type 'hook
190   :options '(hl-line-mode)
191   :group 'notmuch)
192
193 (defvar notmuch-search-mode-map
194   (let ((map (make-sparse-keymap)))
195     (define-key map "?" 'notmuch-help)
196     (define-key map "q" 'notmuch-search-quit)
197     (define-key map "x" 'notmuch-search-quit)
198     (define-key map (kbd "<DEL>") 'notmuch-search-scroll-down)
199     (define-key map "b" 'notmuch-search-scroll-down)
200     (define-key map " " 'notmuch-search-scroll-up)
201     (define-key map "<" 'notmuch-search-first-thread)
202     (define-key map ">" 'notmuch-search-last-thread)
203     (define-key map "p" 'notmuch-search-previous-thread)
204     (define-key map "n" 'notmuch-search-next-thread)
205     (define-key map "r" 'notmuch-search-reply-to-thread)
206     (define-key map "m" 'notmuch-mua-mail)
207     (define-key map "s" 'notmuch-search)
208     (define-key map "o" 'notmuch-search-toggle-order)
209     (define-key map "=" 'notmuch-search-refresh-view)
210     (define-key map "G" 'notmuch-search-poll-and-refresh-view)
211     (define-key map "t" 'notmuch-search-filter-by-tag)
212     (define-key map "f" 'notmuch-search-filter)
213     (define-key map [mouse-1] 'notmuch-search-show-thread)
214     (define-key map "*" 'notmuch-search-operate-all)
215     (define-key map "a" 'notmuch-search-archive-thread)
216     (define-key map "-" 'notmuch-search-remove-tag)
217     (define-key map "+" 'notmuch-search-add-tag)
218     (define-key map (kbd "RET") 'notmuch-search-show-thread)
219     map)
220   "Keymap for \"notmuch search\" buffers.")
221 (fset 'notmuch-search-mode-map notmuch-search-mode-map)
222
223 (defvar notmuch-search-query-string)
224 (defvar notmuch-search-target-thread)
225 (defvar notmuch-search-target-line)
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 (defun notmuch-search-buffer-title (query)
664   "Returns the title for a buffer with notmuch search results."
665   (let* ((folder (rassoc-if (lambda (key)
666                               (string-match (concat "^" (regexp-quote key) "$")
667                                             query))
668                             (notmuch-saved-searches)))
669          (folder-name (car folder))
670          (folder-query (cdr folder)))
671     (cond ((and folder (equal folder-query query))
672            ;; Query is the same as folder search (ignoring case)
673            (concat "*notmuch-folder-" folder-name "*"))
674           (folder
675            (concat "*notmuch-search-"
676                    (replace-regexp-in-string (concat "^" (regexp-quote folder-query))
677                                              (concat "[ " folder-name " ]")
678                                              query)
679                    "*"))
680           (t
681            (concat "*notmuch-search-" query "*"))
682           )))
683
684 ;;;###autoload
685 (defun notmuch-search (query &optional oldest-first target-thread target-line continuation)
686   "Run \"notmuch search\" with the given query string and display results.
687
688 The optional parameters are used as follows:
689
690   oldest-first: A Boolean controlling the sort order of returned threads
691   target-thread: A thread ID (with the thread: prefix) that will be made
692                  current if it appears in the search results.
693   target-line: The line number to move to if the target thread does not
694                appear in the search results."
695   (interactive "sNotmuch search: ")
696   (let ((buffer (get-buffer-create (notmuch-search-buffer-title query))))
697     (switch-to-buffer buffer)
698     (notmuch-search-mode)
699     (set 'notmuch-search-query-string query)
700     (set 'notmuch-search-oldest-first oldest-first)
701     (set 'notmuch-search-target-thread target-thread)
702     (set 'notmuch-search-target-line target-line)
703     (set 'notmuch-search-continuation continuation)
704     (let ((proc (get-buffer-process (current-buffer)))
705           (inhibit-read-only t))
706       (if proc
707           (error "notmuch search process already running for query `%s'" query)
708         )
709       (erase-buffer)
710       (goto-char (point-min))
711       (save-excursion
712         (let ((proc (start-process-shell-command
713                      "notmuch-search" buffer notmuch-command "search"
714                      (if oldest-first "--sort=oldest-first" "--sort=newest-first")
715                      (shell-quote-argument query))))
716           (set-process-sentinel proc 'notmuch-search-process-sentinel)
717           (set-process-filter proc 'notmuch-search-process-filter))))
718     (run-hooks 'notmuch-search-hook)))
719
720 (defun notmuch-search-refresh-view ()
721   "Refresh the current view.
722
723 Kills the current buffer and runs a new search with the same
724 query string as the current search. If the current thread is in
725 the new search results, then point will be placed on the same
726 thread. Otherwise, point will be moved to attempt to be in the
727 same relative position within the new buffer."
728   (interactive)
729   (let ((target-line (line-number-at-pos))
730         (oldest-first notmuch-search-oldest-first)
731         (target-thread (notmuch-search-find-thread-id))
732         (query notmuch-search-query-string)
733         (continuation notmuch-search-continuation))
734     (kill-this-buffer)
735     (notmuch-search query oldest-first target-thread target-line continuation)
736     (goto-char (point-min))))
737
738 (defcustom notmuch-poll-script ""
739   "An external script to incorporate new mail into the notmuch database.
740
741 If this variable is non empty, then it should name a script to be
742 invoked by `notmuch-search-poll-and-refresh-view' and
743 `notmuch-hello-poll-and-update' (each have a default keybinding
744 of 'G'). The script could do any of the following depending on
745 the user's needs:
746
747 1. Invoke a program to transfer mail to the local mail store
748 2. Invoke \"notmuch new\" to incorporate the new mail
749 3. Invoke one or more \"notmuch tag\" commands to classify the mail"
750   :type 'string
751   :group 'notmuch)
752
753 (defun notmuch-poll ()
754   "Run external script to import mail.
755
756 Invokes `notmuch-poll-script' if it is not set to an empty string."
757   (interactive)
758   (if (not (string= notmuch-poll-script ""))
759       (call-process notmuch-poll-script nil nil)))
760
761 (defun notmuch-search-poll-and-refresh-view ()
762   "Invoke `notmuch-poll' to import mail, then refresh the current view."
763   (interactive)
764   (notmuch-poll)
765   (notmuch-search-refresh-view))
766
767 (defun notmuch-search-toggle-order ()
768   "Toggle the current search order.
769
770 By default, the \"inbox\" view created by `notmuch' is displayed
771 in chronological order (oldest thread at the beginning of the
772 buffer), while any global searches created by `notmuch-search'
773 are displayed in reverse-chronological order (newest thread at
774 the beginning of the buffer).
775
776 This command toggles the sort order for the current search.
777
778 Note that any filtered searches created by
779 `notmuch-search-filter' retain the search order of the parent
780 search."
781   (interactive)
782   (set 'notmuch-search-oldest-first (not notmuch-search-oldest-first))
783   (notmuch-search-refresh-view))
784
785 (defun notmuch-search-filter (query)
786   "Filter the current search results based on an additional query string.
787
788 Runs a new search matching only messages that match both the
789 current search results AND the additional query string provided."
790   (interactive "sFilter search: ")
791   (let ((grouped-query (if (string-match-p notmuch-search-disjunctive-regexp query)
792                            (concat "( " query " )")
793                          query)))
794     (notmuch-search (if (string= notmuch-search-query-string "*")
795                         grouped-query
796                       (concat notmuch-search-query-string " and " grouped-query)) notmuch-search-oldest-first)))
797
798 (defun notmuch-search-filter-by-tag (tag)
799   "Filter the current search results based on a single tag.
800
801 Runs a new search matching only messages that match both the
802 current search results AND that are tagged with the given tag."
803   (interactive
804    (list (notmuch-select-tag-with-completion "Filter by tag: ")))
805   (notmuch-search (concat notmuch-search-query-string " and tag:" tag) notmuch-search-oldest-first))
806
807 ;;;###autoload
808 (defun notmuch ()
809   "Run notmuch and display saved searches, known tags, etc."
810   (interactive)
811   (notmuch-hello))
812
813 (setq mail-user-agent 'notmuch-user-agent)
814
815 (provide 'notmuch)