]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch.el
11113fe8ca9d1a2edce1545de0f2ace3352b61f2
[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 (eval-when-compile (require 'cl))
51 (require 'crm)
52 (require 'mm-view)
53 (require 'message)
54
55 (require 'notmuch-lib)
56 (require 'notmuch-show)
57 (require 'notmuch-mua)
58 (require 'notmuch-hello)
59 (require 'notmuch-maildir-fcc)
60 (require 'notmuch-message)
61
62 (defcustom notmuch-search-result-format
63   `(("date" . "%s ")
64     ("count" . "%-7s ")
65     ("authors" . "%-20s ")
66     ("subject" . "%s ")
67     ("tags" . "(%s)"))
68   "Search result formatting. Supported fields are:
69         date, count, authors, subject, tags
70 For example:
71         (setq notmuch-search-result-format \(\(\"authors\" . \"%-40s\"\)
72                                              \(\"subject\" . \"%s\"\)\)\)"
73   :type '(alist :key-type (string) :value-type (string))
74   :group 'notmuch-search)
75
76 (defvar notmuch-query-history nil
77   "Variable to store minibuffer history for notmuch queries")
78
79 (defvar notmuch-select-tag-history nil
80   "Variable to store minibuffer history for
81 `notmuch-select-tag-with-completion' function.")
82
83 (defvar notmuch-read-tag-changes-history nil
84   "Variable to store minibuffer history for
85 `notmuch-read-tag-changes' function.")
86
87 (defun notmuch-tag-completions (&optional search-terms)
88   (split-string
89    (with-output-to-string
90      (with-current-buffer standard-output
91        (apply 'call-process notmuch-command nil t
92               nil "search-tags" search-terms)))
93    "\n+" t))
94
95 (defun notmuch-select-tag-with-completion (prompt &rest search-terms)
96   (let ((tag-list (notmuch-tag-completions search-terms)))
97     (completing-read prompt tag-list nil nil nil 'notmuch-select-tag-history)))
98
99 (defun notmuch-read-tag-changes (&optional initial-input &rest search-terms)
100   (let* ((all-tag-list (notmuch-tag-completions))
101          (add-tag-list (mapcar (apply-partially 'concat "+") all-tag-list))
102          (remove-tag-list (mapcar (apply-partially 'concat "-")
103                                   (if (null search-terms)
104                                       all-tag-list
105                                     (notmuch-tag-completions search-terms))))
106          (tag-list (append add-tag-list remove-tag-list))
107          (crm-separator " ")
108          ;; By default, space is bound to "complete word" function.
109          ;; Re-bind it to insert a space instead.  Note that <tab>
110          ;; still does the completion.
111          (crm-local-completion-map
112           (let ((map (make-sparse-keymap)))
113             (set-keymap-parent map crm-local-completion-map)
114             (define-key map " " 'self-insert-command)
115             map)))
116     (delete "" (completing-read-multiple "Tags (+add -drop): "
117                 tag-list nil nil initial-input
118                 'notmuch-read-tag-changes-history))))
119
120 (defun notmuch-update-tags (tags tag-changes)
121   "Return a copy of TAGS with additions and removals from TAG-CHANGES.
122
123 TAG-CHANGES must be a list of tags names, each prefixed with
124 either a \"+\" to indicate the tag should be added to TAGS if not
125 present or a \"-\" to indicate that the tag should be removed
126 from TAGS if present."
127   (let ((result-tags (copy-sequence tags)))
128     (dolist (tag-change tag-changes)
129       (let ((op (string-to-char tag-change))
130             (tag (unless (string= tag-change "") (substring tag-change 1))))
131         (case op
132           (?+ (unless (member tag result-tags)
133                 (push tag result-tags)))
134           (?- (setq result-tags (delete tag result-tags)))
135           (otherwise
136            (error "Changed tag must be of the form `+this_tag' or `-that_tag'")))))
137     (sort result-tags 'string<)))
138
139 (defun notmuch-foreach-mime-part (function mm-handle)
140   (cond ((stringp (car mm-handle))
141          (dolist (part (cdr mm-handle))
142            (notmuch-foreach-mime-part function part)))
143         ((bufferp (car mm-handle))
144          (funcall function mm-handle))
145         (t (dolist (part mm-handle)
146              (notmuch-foreach-mime-part function part)))))
147
148 (defun notmuch-count-attachments (mm-handle)
149   (let ((count 0))
150     (notmuch-foreach-mime-part
151      (lambda (p)
152        (let ((disposition (mm-handle-disposition p)))
153          (and (listp disposition)
154               (or (equal (car disposition) "attachment")
155                   (and (equal (car disposition) "inline")
156                        (assq 'filename disposition)))
157               (incf count))))
158      mm-handle)
159     count))
160
161 (defun notmuch-save-attachments (mm-handle &optional queryp)
162   (notmuch-foreach-mime-part
163    (lambda (p)
164      (let ((disposition (mm-handle-disposition p)))
165        (and (listp disposition)
166             (or (equal (car disposition) "attachment")
167                 (and (equal (car disposition) "inline")
168                      (assq 'filename disposition)))
169             (or (not queryp)
170                 (y-or-n-p
171                  (concat "Save '" (cdr (assq 'filename disposition)) "' ")))
172             (mm-save-part p))))
173    mm-handle))
174
175 (defun notmuch-documentation-first-line (symbol)
176   "Return the first line of the documentation string for SYMBOL."
177   (let ((doc (documentation symbol)))
178     (if doc
179         (with-temp-buffer
180           (insert (documentation symbol t))
181           (goto-char (point-min))
182           (let ((beg (point)))
183             (end-of-line)
184             (buffer-substring beg (point))))
185       "")))
186
187 (defun notmuch-prefix-key-description (key)
188   "Given a prefix key code, return a human-readable string representation.
189
190 This is basically just `format-kbd-macro' but we also convert ESC to M-."
191   (let ((desc (format-kbd-macro (vector key))))
192     (if (string= desc "ESC")
193         "M-"
194       (concat desc " "))))
195
196 ;; I would think that emacs would have code handy for walking a keymap
197 ;; and generating strings for each key, and I would prefer to just call
198 ;; that. But I couldn't find any (could be all implemented in C I
199 ;; suppose), so I wrote my own here.
200 (defun notmuch-substitute-one-command-key-with-prefix (prefix binding)
201   "For a key binding, return a string showing a human-readable
202 representation of the prefixed key as well as the first line of
203 documentation from the bound function.
204
205 For a mouse binding, return nil."
206   (let ((key (car binding))
207         (action (cdr binding)))
208     (if (mouse-event-p key)
209         nil
210       (if (keymapp action)
211           (let ((substitute (apply-partially 'notmuch-substitute-one-command-key-with-prefix (notmuch-prefix-key-description key)))
212                 (as-list))
213             (map-keymap (lambda (a b)
214                           (push (cons a b) as-list))
215                         action)
216             (mapconcat substitute as-list "\n"))
217         (concat prefix (format-kbd-macro (vector key))
218                 "\t"
219                 (notmuch-documentation-first-line action))))))
220
221 (defun notmuch-substitute-command-keys-one (key)
222   ;; A `keymap' key indicates inheritance from a parent keymap - the
223   ;; inherited mappings follow, so there is nothing to print for
224   ;; `keymap' itself.
225   (when (not (eq key 'keymap))
226     (notmuch-substitute-one-command-key-with-prefix nil key)))
227
228 (defun notmuch-substitute-command-keys (doc)
229   "Like `substitute-command-keys' but with documentation, not function names."
230   (let ((beg 0))
231     (while (string-match "\\\\{\\([^}[:space:]]*\\)}" doc beg)
232       (let* ((keymap-name (substring doc (match-beginning 1) (match-end 1)))
233              (keymap (symbol-value (intern keymap-name))))
234         (setq doc (replace-match
235                    (mapconcat #'notmuch-substitute-command-keys-one
236                               (cdr keymap) "\n")
237                    1 1 doc)))
238       (setq beg (match-end 0)))
239     doc))
240
241 (defun notmuch-help ()
242   "Display help for the current notmuch mode."
243   (interactive)
244   (let* ((mode major-mode)
245          (doc (substitute-command-keys (notmuch-substitute-command-keys (documentation mode t)))))
246     (with-current-buffer (generate-new-buffer "*notmuch-help*")
247       (insert doc)
248       (goto-char (point-min))
249       (set-buffer-modified-p nil)
250       (view-buffer (current-buffer) 'kill-buffer-if-not-modified))))
251
252 (defcustom notmuch-search-hook '(hl-line-mode)
253   "List of functions to call when notmuch displays the search results."
254   :type 'hook
255   :options '(hl-line-mode)
256   :group 'notmuch-search
257   :group 'notmuch-hooks)
258
259 (defvar notmuch-search-mode-map
260   (let ((map (make-sparse-keymap)))
261     (define-key map "?" 'notmuch-help)
262     (define-key map "q" 'notmuch-search-quit)
263     (define-key map "x" 'notmuch-search-quit)
264     (define-key map (kbd "<DEL>") 'notmuch-search-scroll-down)
265     (define-key map "b" 'notmuch-search-scroll-down)
266     (define-key map " " 'notmuch-search-scroll-up)
267     (define-key map "<" 'notmuch-search-first-thread)
268     (define-key map ">" 'notmuch-search-last-thread)
269     (define-key map "p" 'notmuch-search-previous-thread)
270     (define-key map "n" 'notmuch-search-next-thread)
271     (define-key map "r" 'notmuch-search-reply-to-thread-sender)
272     (define-key map "R" 'notmuch-search-reply-to-thread)
273     (define-key map "m" 'notmuch-mua-new-mail)
274     (define-key map "s" 'notmuch-search)
275     (define-key map "o" 'notmuch-search-toggle-order)
276     (define-key map "c" 'notmuch-search-stash-map)
277     (define-key map "=" 'notmuch-search-refresh-view)
278     (define-key map "G" 'notmuch-search-poll-and-refresh-view)
279     (define-key map "t" 'notmuch-search-filter-by-tag)
280     (define-key map "f" 'notmuch-search-filter)
281     (define-key map [mouse-1] 'notmuch-search-show-thread)
282     (define-key map "*" 'notmuch-search-tag-all)
283     (define-key map "a" 'notmuch-search-archive-thread)
284     (define-key map "-" 'notmuch-search-remove-tag)
285     (define-key map "+" 'notmuch-search-add-tag)
286     (define-key map (kbd "RET") 'notmuch-search-show-thread)
287     map)
288   "Keymap for \"notmuch search\" buffers.")
289 (fset 'notmuch-search-mode-map notmuch-search-mode-map)
290
291 (defvar notmuch-search-stash-map
292   (let ((map (make-sparse-keymap)))
293     (define-key map "i" 'notmuch-search-stash-thread-id)
294     map)
295   "Submap for stash commands")
296 (fset 'notmuch-search-stash-map notmuch-search-stash-map)
297
298 (defun notmuch-search-stash-thread-id ()
299   "Copy thread ID of current thread to kill-ring."
300   (interactive)
301   (notmuch-common-do-stash (notmuch-search-find-thread-id)))
302
303 (defvar notmuch-search-query-string)
304 (defvar notmuch-search-target-thread)
305 (defvar notmuch-search-target-line)
306 (defvar notmuch-search-continuation)
307
308 (defvar notmuch-search-disjunctive-regexp      "\\<[oO][rR]\\>")
309
310 (defun notmuch-search-quit ()
311   "Exit the search buffer, calling any defined continuation function."
312   (interactive)
313   (let ((continuation notmuch-search-continuation))
314     (notmuch-kill-this-buffer)
315     (when continuation
316       (funcall continuation))))
317
318 (defun notmuch-search-scroll-up ()
319   "Move forward through search results by one window's worth."
320   (interactive)
321   (condition-case nil
322       (scroll-up nil)
323     ((end-of-buffer) (notmuch-search-last-thread))))
324
325 (defun notmuch-search-scroll-down ()
326   "Move backward through the search results by one window's worth."
327   (interactive)
328   ;; I don't know why scroll-down doesn't signal beginning-of-buffer
329   ;; the way that scroll-up signals end-of-buffer, but c'est la vie.
330   ;;
331   ;; So instead of trapping a signal we instead check whether the
332   ;; window begins on the first line of the buffer and if so, move
333   ;; directly to that position. (We have to count lines since the
334   ;; window-start position is not the same as point-min due to the
335   ;; invisible thread-ID characters on the first line.
336   (if (equal (count-lines (point-min) (window-start)) 0)
337       (goto-char (point-min))
338     (scroll-down nil)))
339
340 (defun notmuch-search-next-thread ()
341   "Select the next thread in the search results."
342   (interactive)
343   (forward-line 1))
344
345 (defun notmuch-search-previous-thread ()
346   "Select the previous thread in the search results."
347   (interactive)
348   (forward-line -1))
349
350 (defun notmuch-search-last-thread ()
351   "Select the last thread in the search results."
352   (interactive)
353   (goto-char (point-max))
354   (forward-line -2))
355
356 (defun notmuch-search-first-thread ()
357   "Select the first thread in the search results."
358   (interactive)
359   (goto-char (point-min)))
360
361 (defface notmuch-message-summary-face
362  '((((class color) (background light)) (:background "#f0f0f0"))
363    (((class color) (background dark)) (:background "#303030")))
364  "Face for the single-line message summary in notmuch-show-mode."
365  :group 'notmuch-show
366  :group 'notmuch-faces)
367
368 (defface notmuch-search-date
369   '((t :inherit default))
370   "Face used in search mode for dates."
371   :group 'notmuch-search
372   :group 'notmuch-faces)
373
374 (defface notmuch-search-count
375   '((t :inherit default))
376   "Face used in search mode for the count matching the query."
377   :group 'notmuch-search
378   :group 'notmuch-faces)
379
380 (defface notmuch-search-subject
381   '((t :inherit default))
382   "Face used in search mode for subjects."
383   :group 'notmuch-search
384   :group 'notmuch-faces)
385
386 (defface notmuch-search-matching-authors
387   '((t :inherit default))
388   "Face used in search mode for authors matching the query."
389   :group 'notmuch-search
390   :group 'notmuch-faces)
391
392 (defface notmuch-search-non-matching-authors
393   '((((class color)
394       (background dark))
395      (:foreground "grey30"))
396     (((class color)
397       (background light))
398      (:foreground "grey60"))
399     (t
400      (:italic t)))
401   "Face used in search mode for authors not matching the query."
402   :group 'notmuch-search
403   :group 'notmuch-faces)
404
405 (defface notmuch-tag-face
406   '((((class color)
407       (background dark))
408      (:foreground "OliveDrab1"))
409     (((class color)
410       (background light))
411      (:foreground "navy blue" :bold t))
412     (t
413      (:bold t)))
414   "Face used in search mode face for tags."
415   :group 'notmuch-search
416   :group 'notmuch-faces)
417
418 (defun notmuch-search-mode ()
419   "Major mode displaying results of a notmuch search.
420
421 This buffer contains the results of a \"notmuch search\" of your
422 email archives. Each line in the buffer represents a single
423 thread giving a summary of the thread (a relative date, the
424 number of matched messages and total messages in the thread,
425 participants in the thread, a representative subject line, and
426 any tags).
427
428 Pressing \\[notmuch-search-show-thread] on any line displays that thread. The '\\[notmuch-search-add-tag]' and '\\[notmuch-search-remove-tag]'
429 keys can be used to add or remove tags from a thread. The '\\[notmuch-search-archive-thread]' key
430 is a convenience for archiving a thread (removing the \"inbox\"
431 tag). The '\\[notmuch-search-tag-all]' key can be used to add or remove a tag from all
432 threads in the current buffer.
433
434 Other useful commands are '\\[notmuch-search-filter]' for filtering the current search
435 based on an additional query string, '\\[notmuch-search-filter-by-tag]' for filtering to include
436 only messages with a given tag, and '\\[notmuch-search]' to execute a new, global
437 search.
438
439 Complete list of currently available key bindings:
440
441 \\{notmuch-search-mode-map}"
442   (interactive)
443   (kill-all-local-variables)
444   (make-local-variable 'notmuch-search-query-string)
445   (make-local-variable 'notmuch-search-oldest-first)
446   (make-local-variable 'notmuch-search-target-thread)
447   (make-local-variable 'notmuch-search-target-line)
448   (set (make-local-variable 'notmuch-search-continuation) nil)
449   (set (make-local-variable 'scroll-preserve-screen-position) t)
450   (add-to-invisibility-spec (cons 'ellipsis t))
451   (use-local-map notmuch-search-mode-map)
452   (setq truncate-lines t)
453   (setq major-mode 'notmuch-search-mode
454         mode-name "notmuch-search")
455   (setq buffer-read-only t))
456
457 (defun notmuch-search-properties-in-region (property beg end)
458   (save-excursion
459     (let ((output nil)
460           (last-line (line-number-at-pos end))
461           (max-line (- (line-number-at-pos (point-max)) 2)))
462       (goto-char beg)
463       (beginning-of-line)
464       (while (<= (line-number-at-pos) (min last-line max-line))
465         (setq output (cons (get-text-property (point) property) output))
466         (forward-line 1))
467       output)))
468
469 (defun notmuch-search-find-thread-id ()
470   "Return the thread for the current thread"
471   (get-text-property (point) 'notmuch-search-thread-id))
472
473 (defun notmuch-search-find-thread-id-region (beg end)
474   "Return a list of threads for the current region"
475   (notmuch-search-properties-in-region 'notmuch-search-thread-id beg end))
476
477 (defun notmuch-search-find-thread-id-region-search (beg end)
478   "Return a search string for threads for the current region"
479   (mapconcat 'identity (notmuch-search-find-thread-id-region beg end) " or "))
480
481 (defun notmuch-search-find-authors ()
482   "Return the authors for the current thread"
483   (get-text-property (point) 'notmuch-search-authors))
484
485 (defun notmuch-search-find-authors-region (beg end)
486   "Return a list of authors for the current region"
487   (notmuch-search-properties-in-region 'notmuch-search-authors beg end))
488
489 (defun notmuch-search-find-subject ()
490   "Return the subject for the current thread"
491   (get-text-property (point) 'notmuch-search-subject))
492
493 (defun notmuch-search-find-subject-region (beg end)
494   "Return a list of authors for the current region"
495   (notmuch-search-properties-in-region 'notmuch-search-subject beg end))
496
497 (defun notmuch-search-show-thread (&optional crypto-switch)
498   "Display the currently selected thread."
499   (interactive "P")
500   (let ((thread-id (notmuch-search-find-thread-id))
501         (subject (notmuch-prettify-subject (notmuch-search-find-subject))))
502     (if (> (length thread-id) 0)
503         (notmuch-show thread-id
504                       (current-buffer)
505                       notmuch-search-query-string
506                       ;; Name the buffer based on the subject.
507                       (concat "*" (truncate-string-to-width subject 30 nil nil t) "*")
508                       crypto-switch)
509       (message "End of search results."))))
510
511 (defun notmuch-search-reply-to-thread (&optional prompt-for-sender)
512   "Begin composing a reply-all to the entire current thread in a new buffer."
513   (interactive "P")
514   (let ((message-id (notmuch-search-find-thread-id)))
515     (notmuch-mua-new-reply message-id prompt-for-sender t)))
516
517 (defun notmuch-search-reply-to-thread-sender (&optional prompt-for-sender)
518   "Begin composing a reply to the entire current thread in a new buffer."
519   (interactive "P")
520   (let ((message-id (notmuch-search-find-thread-id)))
521     (notmuch-mua-new-reply message-id prompt-for-sender nil)))
522
523 (defun notmuch-call-notmuch-process (&rest args)
524   "Synchronously invoke \"notmuch\" with the given list of arguments.
525
526 Output from the process will be presented to the user as an error
527 and will also appear in a buffer named \"*Notmuch errors*\"."
528   (let ((error-buffer (get-buffer-create "*Notmuch errors*")))
529     (with-current-buffer error-buffer
530         (erase-buffer))
531     (if (eq (apply 'call-process notmuch-command nil error-buffer nil args) 0)
532         (point)
533       (progn
534         (with-current-buffer error-buffer
535           (let ((beg (point-min))
536                 (end (- (point-max) 1)))
537             (error (buffer-substring beg end))
538             ))))))
539
540 (defun notmuch-tag (query &rest tag-changes)
541   "Add/remove tags in TAG-CHANGES to messages matching QUERY.
542
543 TAG-CHANGES should be a list of strings of the form \"+tag\" or
544 \"-tag\" and QUERY should be a string containing the
545 search-query.
546
547 Note: Other code should always use this function alter tags of
548 messages instead of running (notmuch-call-notmuch-process \"tag\" ..)
549 directly, so that hooks specified in notmuch-before-tag-hook and
550 notmuch-after-tag-hook will be run."
551   ;; Perform some validation
552   (mapc (lambda (tag-change)
553           (unless (string-match-p "^[-+]\\S-+$" tag-change)
554             (error "Tag must be of the form `+this_tag' or `-that_tag'")))
555         tag-changes)
556   (unless (null tag-changes)
557     (run-hooks 'notmuch-before-tag-hook)
558     (apply 'notmuch-call-notmuch-process "tag"
559            (append tag-changes (list "--" query)))
560     (run-hooks 'notmuch-after-tag-hook)))
561
562 (defcustom notmuch-before-tag-hook nil
563   "Hooks that are run before tags of a message are modified.
564
565 'tags' will contain the tags that are about to be added or removed as
566 a list of strings of the form \"+TAG\" or \"-TAG\".
567 'query' will be a string containing the search query that determines
568 the messages that are about to be tagged"
569
570   :type 'hook
571   :options '(hl-line-mode)
572   :group 'notmuch-hooks)
573
574 (defcustom notmuch-after-tag-hook nil
575   "Hooks that are run after tags of a message are modified.
576
577 'tags' will contain the tags that were added or removed as
578 a list of strings of the form \"+TAG\" or \"-TAG\".
579 'query' will be a string containing the search query that determines
580 the messages that were tagged"
581   :type 'hook
582   :options '(hl-line-mode)
583   :group 'notmuch-hooks)
584
585 (defun notmuch-search-set-tags (tags)
586   (save-excursion
587     (end-of-line)
588     (re-search-backward "(")
589     (forward-char)
590     (let ((beg (point))
591           (inhibit-read-only t))
592       (re-search-forward ")")
593       (backward-char)
594       (let ((end (point)))
595         (delete-region beg end)
596         (insert (propertize (mapconcat  'identity tags " ")
597                             'face 'notmuch-tag-face))))))
598
599 (defun notmuch-search-get-tags ()
600   (save-excursion
601     (end-of-line)
602     (re-search-backward "(")
603     (let ((beg (+ (point) 1)))
604       (re-search-forward ")")
605       (let ((end (- (point) 1)))
606         (split-string (buffer-substring-no-properties beg end))))))
607
608 (defun notmuch-search-get-tags-region (beg end)
609   (save-excursion
610     (let ((output nil)
611           (last-line (line-number-at-pos end))
612           (max-line (- (line-number-at-pos (point-max)) 2)))
613       (goto-char beg)
614       (while (<= (line-number-at-pos) (min last-line max-line))
615         (setq output (append output (notmuch-search-get-tags)))
616         (forward-line 1))
617       output)))
618
619 (defun notmuch-search-tag-thread (&rest tag-changes)
620   "Change tags for the currently selected thread.
621
622 See `notmuch-search-tag-region' for details."
623   (apply 'notmuch-search-tag-region (point) (point) tag-changes))
624
625 (defun notmuch-search-tag-region (beg end &rest tag-changes)
626   "Change tags for threads in the given region.
627
628 TAGS is a list of tag operations for `notmuch-tag'.  The tags are
629 added or removed for all threads in the region from BEG to END."
630   (let ((search-string (notmuch-search-find-thread-id-region-search beg end)))
631     (apply 'notmuch-tag search-string tag-changes)
632     (save-excursion
633       (let ((last-line (line-number-at-pos end))
634             (max-line (- (line-number-at-pos (point-max)) 2)))
635         (goto-char beg)
636         (while (<= (line-number-at-pos) (min last-line max-line))
637           (notmuch-search-set-tags
638            (notmuch-update-tags (notmuch-search-get-tags) tag-changes))
639           (forward-line))))))
640
641 (defun notmuch-search-tag (&optional initial-input)
642   "Change tags for the currently selected thread or region."
643   (interactive)
644   (let* ((beg (if (region-active-p) (region-beginning) (point)))
645          (end (if (region-active-p) (region-end) (point)))
646          (search-string (notmuch-search-find-thread-id-region-search beg end))
647          (tags (notmuch-read-tag-changes initial-input search-string)))
648     (apply 'notmuch-search-tag-region beg end tags)))
649
650 (defun notmuch-search-add-tag ()
651   "Same as `notmuch-search-tag' but sets initial input to '+'."
652   (interactive)
653   (notmuch-search-tag "+"))
654
655 (defun notmuch-search-remove-tag ()
656   "Same as `notmuch-search-tag' but sets initial input to '-'."
657   (interactive)
658   (notmuch-search-tag "-"))
659
660 (defun notmuch-search-archive-thread ()
661   "Archive the currently selected thread (remove its \"inbox\" tag).
662
663 This function advances the next thread when finished."
664   (interactive)
665   (notmuch-search-tag-thread "-inbox")
666   (notmuch-search-next-thread))
667
668 (defvar notmuch-search-process-filter-data nil
669   "Data that has not yet been processed.")
670 (make-variable-buffer-local 'notmuch-search-process-filter-data)
671
672 (defun notmuch-search-process-sentinel (proc msg)
673   "Add a message to let user know when \"notmuch search\" exits"
674   (let ((buffer (process-buffer proc))
675         (status (process-status proc))
676         (exit-status (process-exit-status proc))
677         (never-found-target-thread nil))
678     (if (memq status '(exit signal))
679         (if (buffer-live-p buffer)
680             (with-current-buffer buffer
681               (save-excursion
682                 (let ((inhibit-read-only t)
683                       (atbob (bobp)))
684                   (goto-char (point-max))
685                   (if (eq status 'signal)
686                       (insert "Incomplete search results (search process was killed).\n"))
687                   (when (eq status 'exit)
688                     (if notmuch-search-process-filter-data
689                         (insert (concat "Error: Unexpected output from notmuch search:\n" notmuch-search-process-filter-data)))
690                     (insert "End of search results.")
691                     (unless (= exit-status 0)
692                       (insert (format " (process returned %d)" exit-status)))
693                     (insert "\n")
694                     (if (and atbob
695                              (not (string= notmuch-search-target-thread "found")))
696                         (set 'never-found-target-thread t)))))
697               (when (and never-found-target-thread
698                        notmuch-search-target-line)
699                   (goto-char (point-min))
700                   (forward-line (1- notmuch-search-target-line))))))))
701
702 (defcustom notmuch-search-line-faces '(("unread" :weight bold)
703                                        ("flagged" :foreground "blue"))
704   "Tag/face mapping for line highlighting in notmuch-search.
705
706 Here is an example of how to color search results based on tags.
707  (the following text would be placed in your ~/.emacs file):
708
709  (setq notmuch-search-line-faces '((\"delete\" . (:foreground \"red\"
710                                                   :background \"blue\"))
711                                    (\"unread\" . (:foreground \"green\"))))
712
713 The attributes defined for matching tags are merged, with later
714 attributes overriding earlier. A message having both \"delete\"
715 and \"unread\" tags with the above settings would have a green
716 foreground and blue background."
717   :type '(alist :key-type (string) :value-type (custom-face-edit))
718   :group 'notmuch-search
719   :group 'notmuch-faces)
720
721 (defun notmuch-search-color-line (start end line-tag-list)
722   "Colorize lines in `notmuch-show' based on tags."
723   ;; Create the overlay only if the message has tags which match one
724   ;; of those specified in `notmuch-search-line-faces'.
725   (let (overlay)
726     (mapc (lambda (elem)
727             (let ((tag (car elem))
728                   (attributes (cdr elem)))
729               (when (member tag line-tag-list)
730                 (when (not overlay)
731                   (setq overlay (make-overlay start end)))
732                 ;; Merge the specified properties with any already
733                 ;; applied from an earlier match.
734                 (overlay-put overlay 'face
735                              (append (overlay-get overlay 'face) attributes)))))
736           notmuch-search-line-faces)))
737
738 (defun notmuch-search-author-propertize (authors)
739   "Split `authors' into matching and non-matching authors and
740 propertize appropriately. If no boundary between authors and
741 non-authors is found, assume that all of the authors match."
742   (if (string-match "\\(.*\\)|\\(.*\\)" authors)
743       (concat (propertize (concat (match-string 1 authors) ",")
744                           'face 'notmuch-search-matching-authors)
745               (propertize (match-string 2 authors)
746                           'face 'notmuch-search-non-matching-authors))
747     (propertize authors 'face 'notmuch-search-matching-authors)))
748
749 (defun notmuch-search-insert-authors (format-string authors)
750   ;; Save the match data to avoid interfering with
751   ;; `notmuch-search-process-filter'.
752   (save-match-data
753     (let* ((formatted-authors (format format-string authors))
754            (formatted-sample (format format-string ""))
755            (visible-string formatted-authors)
756            (invisible-string "")
757            (padding ""))
758
759       ;; Truncate the author string to fit the specification.
760       (if (> (length formatted-authors)
761              (length formatted-sample))
762           (let ((visible-length (- (length formatted-sample)
763                                    (length "... "))))
764             ;; Truncate the visible string according to the width of
765             ;; the display string.
766             (setq visible-string (substring formatted-authors 0 visible-length)
767                   invisible-string (substring formatted-authors visible-length))
768             ;; If possible, truncate the visible string at a natural
769             ;; break (comma or pipe), as incremental search doesn't
770             ;; match across the visible/invisible border.
771             (when (string-match "\\(.*\\)\\([,|] \\)\\([^,|]*\\)" visible-string)
772               ;; Second clause is destructive on `visible-string', so
773               ;; order is important.
774               (setq invisible-string (concat (match-string 3 visible-string)
775                                              invisible-string)
776                     visible-string (concat (match-string 1 visible-string)
777                                            (match-string 2 visible-string))))
778             ;; `visible-string' may be shorter than the space allowed
779             ;; by `format-string'. If so we must insert some padding
780             ;; after `invisible-string'.
781             (setq padding (make-string (- (length formatted-sample)
782                                           (length visible-string)
783                                           (length "..."))
784                                        ? ))))
785
786       ;; Use different faces to show matching and non-matching authors.
787       (if (string-match "\\(.*\\)|\\(.*\\)" visible-string)
788           ;; The visible string contains both matching and
789           ;; non-matching authors.
790           (setq visible-string (notmuch-search-author-propertize visible-string)
791                 ;; The invisible string must contain only non-matching
792                 ;; authors, as the visible-string contains both.
793                 invisible-string (propertize invisible-string
794                                              'face 'notmuch-search-non-matching-authors))
795         ;; The visible string contains only matching authors.
796         (setq visible-string (propertize visible-string
797                                          'face 'notmuch-search-matching-authors)
798               ;; The invisible string may contain both matching and
799               ;; non-matching authors.
800               invisible-string (notmuch-search-author-propertize invisible-string)))
801
802       ;; If there is any invisible text, add it as a tooltip to the
803       ;; visible text.
804       (when (not (string= invisible-string ""))
805         (setq visible-string (propertize visible-string 'help-echo (concat "..." invisible-string))))
806
807       ;; Insert the visible and, if present, invisible author strings.
808       (insert visible-string)
809       (when (not (string= invisible-string ""))
810         (let ((start (point))
811               overlay)
812           (insert invisible-string)
813           (setq overlay (make-overlay start (point)))
814           (overlay-put overlay 'invisible 'ellipsis)
815           (overlay-put overlay 'isearch-open-invisible #'delete-overlay)))
816       (insert padding))))
817
818 (defun notmuch-search-insert-field (field date count authors subject tags)
819   (cond
820    ((string-equal field "date")
821     (insert (propertize (format (cdr (assoc field notmuch-search-result-format)) date)
822                         'face 'notmuch-search-date)))
823    ((string-equal field "count")
824     (insert (propertize (format (cdr (assoc field notmuch-search-result-format)) count)
825                         'face 'notmuch-search-count)))
826    ((string-equal field "subject")
827     (insert (propertize (format (cdr (assoc field notmuch-search-result-format)) subject)
828                         'face 'notmuch-search-subject)))
829
830    ((string-equal field "authors")
831     (notmuch-search-insert-authors (cdr (assoc field notmuch-search-result-format)) authors))
832
833    ((string-equal field "tags")
834     (insert (concat "(" (propertize tags 'font-lock-face 'notmuch-tag-face) ")")))))
835
836 (defun notmuch-search-show-result (date count authors subject tags)
837   (let ((fields) (field))
838     (setq fields (mapcar 'car notmuch-search-result-format))
839     (loop for field in fields
840           do (notmuch-search-insert-field field date count authors subject tags)))
841   (insert "\n"))
842
843 (defun notmuch-search-process-filter (proc string)
844   "Process and filter the output of \"notmuch search\""
845   (let ((buffer (process-buffer proc))
846         (found-target nil))
847     (if (buffer-live-p buffer)
848         (with-current-buffer buffer
849           (save-excursion
850             (let ((line 0)
851                   (more t)
852                   (inhibit-read-only t)
853                   (string (concat notmuch-search-process-filter-data string)))
854               (setq notmuch-search-process-filter-data nil)
855               (while more
856                 (while (and (< line (length string)) (= (elt string line) ?\n))
857                   (setq line (1+ line)))
858                 (if (string-match "^\\(thread:[0-9A-Fa-f]*\\) \\([^][]*\\) \\(\\[[0-9/]*\\]\\) \\([^;]*\\); \\(.*\\) (\\([^()]*\\))$" string line)
859                     (let* ((thread-id (match-string 1 string))
860                            (date (match-string 2 string))
861                            (count (match-string 3 string))
862                            (authors (match-string 4 string))
863                            (subject (match-string 5 string))
864                            (tags (match-string 6 string))
865                            (tag-list (if tags (save-match-data (split-string tags)))))
866                       (goto-char (point-max))
867                       (if (/= (match-beginning 1) line)
868                           (insert (concat "Error: Unexpected output from notmuch search:\n" (substring string line (match-beginning 1)) "\n")))
869                       (let ((beg (point)))
870                         (notmuch-search-show-result date count authors
871                                                     (notmuch-prettify-subject subject) tags)
872                         (notmuch-search-color-line beg (point) tag-list)
873                         (put-text-property beg (point) 'notmuch-search-thread-id thread-id)
874                         (put-text-property beg (point) 'notmuch-search-authors authors)
875                         (put-text-property beg (point) 'notmuch-search-subject subject)
876                         (when (string= thread-id notmuch-search-target-thread)
877                           (set 'found-target beg)
878                           (set 'notmuch-search-target-thread "found")))
879                       (set 'line (match-end 0)))
880                   (set 'more nil)
881                   (while (and (< line (length string)) (= (elt string line) ?\n))
882                     (setq line (1+ line)))
883                   (if (< line (length string))
884                       (setq notmuch-search-process-filter-data (substring string line)))
885                   ))))
886           (if found-target
887               (goto-char found-target)))
888       (delete-process proc))))
889
890 (defun notmuch-search-tag-all (&rest tag-changes)
891   "Add/remove tags from all matching messages.
892
893 This command adds or removes tags from all messages matching the
894 current search terms. When called interactively, this command
895 will prompt for tags to be added or removed. Tags prefixed with
896 '+' will be added and tags prefixed with '-' will be removed.
897
898 Each character of the tag name may consist of alphanumeric
899 characters as well as `_.+-'.
900 "
901   (interactive (notmuch-read-tag-changes))
902   (apply 'notmuch-tag notmuch-search-query-string tag-changes))
903
904 (defun notmuch-search-buffer-title (query)
905   "Returns the title for a buffer with notmuch search results."
906   (let* ((saved-search
907           (let (longest
908                 (longest-length 0))
909             (loop for tuple in notmuch-saved-searches
910                   if (let ((quoted-query (regexp-quote (cdr tuple))))
911                        (and (string-match (concat "^" quoted-query) query)
912                             (> (length (match-string 0 query))
913                                longest-length)))
914                   do (setq longest tuple))
915             longest))
916          (saved-search-name (car saved-search))
917          (saved-search-query (cdr saved-search)))
918     (cond ((and saved-search (equal saved-search-query query))
919            ;; Query is the same as saved search (ignoring case)
920            (concat "*notmuch-saved-search-" saved-search-name "*"))
921           (saved-search
922            (concat "*notmuch-search-"
923                    (replace-regexp-in-string (concat "^" (regexp-quote saved-search-query))
924                                              (concat "[ " saved-search-name " ]")
925                                              query)
926                    "*"))
927           (t
928            (concat "*notmuch-search-" query "*"))
929           )))
930
931 (defun notmuch-read-query (prompt)
932   "Read a notmuch-query from the minibuffer with completion.
933
934 PROMPT is the string to prompt with."
935   (lexical-let
936       ((completions
937         (append (list "folder:" "thread:" "id:" "date:" "from:" "to:"
938                       "subject:" "attachment:")
939                 (mapcar (lambda (tag)
940                           (concat "tag:" tag))
941                         (process-lines notmuch-command "search" "--output=tags" "*")))))
942     (let ((keymap (copy-keymap minibuffer-local-map))
943           (minibuffer-completion-table
944            (completion-table-dynamic
945             (lambda (string)
946               ;; generate a list of possible completions for the current input
947               (cond
948                ;; this ugly regexp is used to get the last word of the input
949                ;; possibly preceded by a '('
950                ((string-match "\\(^\\|.* (?\\)\\([^ ]*\\)$" string)
951                 (mapcar (lambda (compl)
952                           (concat (match-string-no-properties 1 string) compl))
953                         (all-completions (match-string-no-properties 2 string)
954                                          completions)))
955                (t (list string)))))))
956       ;; this was simpler than convincing completing-read to accept spaces:
957       (define-key keymap (kbd "<tab>") 'minibuffer-complete)
958       (let ((history-delete-duplicates t))
959         (read-from-minibuffer prompt nil keymap nil
960                               'notmuch-search-history nil nil)))))
961
962 ;;;###autoload
963 (defun notmuch-search (&optional query oldest-first target-thread target-line continuation)
964   "Run \"notmuch search\" with the given `query' and display results.
965
966 If `query' is nil, it is read interactively from the minibuffer.
967 Other optional parameters are used as follows:
968
969   oldest-first: A Boolean controlling the sort order of returned threads
970   target-thread: A thread ID (with the thread: prefix) that will be made
971                  current if it appears in the search results.
972   target-line: The line number to move to if the target thread does not
973                appear in the search results."
974   (interactive)
975   (if (null query)
976       (setq query (notmuch-read-query "Notmuch search: ")))
977   (let ((buffer (get-buffer-create (notmuch-search-buffer-title query))))
978     (switch-to-buffer buffer)
979     (notmuch-search-mode)
980     ;; Don't track undo information for this buffer
981     (set 'buffer-undo-list t)
982     (set 'notmuch-search-query-string query)
983     (set 'notmuch-search-oldest-first oldest-first)
984     (set 'notmuch-search-target-thread target-thread)
985     (set 'notmuch-search-target-line target-line)
986     (set 'notmuch-search-continuation continuation)
987     (let ((proc (get-buffer-process (current-buffer)))
988           (inhibit-read-only t))
989       (if proc
990           (error "notmuch search process already running for query `%s'" query)
991         )
992       (erase-buffer)
993       (goto-char (point-min))
994       (save-excursion
995         (let ((proc (start-process
996                      "notmuch-search" buffer
997                      notmuch-command "search"
998                      (if oldest-first
999                          "--sort=oldest-first"
1000                        "--sort=newest-first")
1001                      query)))
1002           (set-process-sentinel proc 'notmuch-search-process-sentinel)
1003           (set-process-filter proc 'notmuch-search-process-filter)
1004           (set-process-query-on-exit-flag proc nil))))
1005     (run-hooks 'notmuch-search-hook)))
1006
1007 (defun notmuch-search-refresh-view ()
1008   "Refresh the current view.
1009
1010 Kills the current buffer and runs a new search with the same
1011 query string as the current search. If the current thread is in
1012 the new search results, then point will be placed on the same
1013 thread. Otherwise, point will be moved to attempt to be in the
1014 same relative position within the new buffer."
1015   (interactive)
1016   (let ((target-line (line-number-at-pos))
1017         (oldest-first notmuch-search-oldest-first)
1018         (target-thread (notmuch-search-find-thread-id))
1019         (query notmuch-search-query-string)
1020         (continuation notmuch-search-continuation))
1021     (notmuch-kill-this-buffer)
1022     (notmuch-search query oldest-first target-thread target-line continuation)
1023     (goto-char (point-min))))
1024
1025 (defcustom notmuch-poll-script nil
1026   "An external script to incorporate new mail into the notmuch database.
1027
1028 This variable controls the action invoked by
1029 `notmuch-search-poll-and-refresh-view' and
1030 `notmuch-hello-poll-and-update' (each have a default keybinding
1031 of 'G') to incorporate new mail into the notmuch database.
1032
1033 If set to nil (the default), new mail is processed by invoking
1034 \"notmuch new\". Otherwise, this should be set to a string that
1035 gives the name of an external script that processes new mail. If
1036 set to the empty string, no command will be run.
1037
1038 The external script could do any of the following depending on
1039 the user's needs:
1040
1041 1. Invoke a program to transfer mail to the local mail store
1042 2. Invoke \"notmuch new\" to incorporate the new mail
1043 3. Invoke one or more \"notmuch tag\" commands to classify the mail
1044
1045 Note that the recommended way of achieving the same is using
1046 \"notmuch new\" hooks."
1047   :type '(choice (const :tag "notmuch new" nil)
1048                  (const :tag "Disabled" "")
1049                  (string :tag "Custom script"))
1050   :group 'notmuch-external)
1051
1052 (defun notmuch-poll ()
1053   "Run \"notmuch new\" or an external script to import mail.
1054
1055 Invokes `notmuch-poll-script', \"notmuch new\", or does nothing
1056 depending on the value of `notmuch-poll-script'."
1057   (interactive)
1058   (if (stringp notmuch-poll-script)
1059       (unless (string= notmuch-poll-script "")
1060         (call-process notmuch-poll-script nil nil))
1061     (call-process notmuch-command nil nil nil "new")))
1062
1063 (defun notmuch-search-poll-and-refresh-view ()
1064   "Invoke `notmuch-poll' to import mail, then refresh the current view."
1065   (interactive)
1066   (notmuch-poll)
1067   (notmuch-search-refresh-view))
1068
1069 (defun notmuch-search-toggle-order ()
1070   "Toggle the current search order.
1071
1072 By default, the \"inbox\" view created by `notmuch' is displayed
1073 in chronological order (oldest thread at the beginning of the
1074 buffer), while any global searches created by `notmuch-search'
1075 are displayed in reverse-chronological order (newest thread at
1076 the beginning of the buffer).
1077
1078 This command toggles the sort order for the current search.
1079
1080 Note that any filtered searches created by
1081 `notmuch-search-filter' retain the search order of the parent
1082 search."
1083   (interactive)
1084   (set 'notmuch-search-oldest-first (not notmuch-search-oldest-first))
1085   (notmuch-search-refresh-view))
1086
1087 (defun notmuch-search-filter (query)
1088   "Filter the current search results based on an additional query string.
1089
1090 Runs a new search matching only messages that match both the
1091 current search results AND the additional query string provided."
1092   (interactive (list (notmuch-read-query "Filter search: ")))
1093   (let ((grouped-query (if (string-match-p notmuch-search-disjunctive-regexp query)
1094                            (concat "( " query " )")
1095                          query)))
1096     (notmuch-search (if (string= notmuch-search-query-string "*")
1097                         grouped-query
1098                       (concat notmuch-search-query-string " and " grouped-query)) notmuch-search-oldest-first)))
1099
1100 (defun notmuch-search-filter-by-tag (tag)
1101   "Filter the current search results based on a single tag.
1102
1103 Runs a new search matching only messages that match both the
1104 current search results AND that are tagged with the given tag."
1105   (interactive
1106    (list (notmuch-select-tag-with-completion "Filter by tag: ")))
1107   (notmuch-search (concat notmuch-search-query-string " and tag:" tag) notmuch-search-oldest-first))
1108
1109 ;;;###autoload
1110 (defun notmuch ()
1111   "Run notmuch and display saved searches, known tags, etc."
1112   (interactive)
1113   (notmuch-hello))
1114
1115 (defun notmuch-interesting-buffer (b)
1116   "Is the current buffer of interest to a notmuch user?"
1117   (with-current-buffer b
1118     (memq major-mode '(notmuch-show-mode
1119                        notmuch-search-mode
1120                        notmuch-hello-mode
1121                        message-mode))))
1122
1123 ;;;###autoload
1124 (defun notmuch-cycle-notmuch-buffers ()
1125   "Cycle through any existing notmuch buffers (search, show or hello).
1126
1127 If the current buffer is the only notmuch buffer, bury it. If no
1128 notmuch buffers exist, run `notmuch'."
1129   (interactive)
1130
1131   (let (start first)
1132     ;; If the current buffer is a notmuch buffer, remember it and then
1133     ;; bury it.
1134     (when (notmuch-interesting-buffer (current-buffer))
1135       (setq start (current-buffer))
1136       (bury-buffer))
1137
1138     ;; Find the first notmuch buffer.
1139     (setq first (loop for buffer in (buffer-list)
1140                      if (notmuch-interesting-buffer buffer)
1141                      return buffer))
1142
1143     (if first
1144         ;; If the first one we found is any other than the starting
1145         ;; buffer, switch to it.
1146         (unless (eq first start)
1147           (switch-to-buffer first))
1148       (notmuch))))
1149
1150 (setq mail-user-agent 'notmuch-user-agent)
1151
1152 (provide 'notmuch)