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