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