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