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