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