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