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