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