]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch.el
emacs: Replace other search text properties with result property
[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 (plist-get (notmuch-search-get-result pos) property) output)))
469     output))
470
471 (defun notmuch-search-find-thread-id ()
472   "Return the thread for the current thread"
473   (let ((thread (plist-get (notmuch-search-get-result) :thread)))
474     (when thread (concat "thread:" thread))))
475
476 (defun notmuch-search-find-thread-id-region (beg end)
477   "Return a list of threads for the current region"
478   (mapcar (lambda (thread) (concat "thread:" thread))
479           (notmuch-search-properties-in-region :thread beg end)))
480
481 (defun notmuch-search-find-thread-id-region-search (beg end)
482   "Return a search string for threads for the current region"
483   (mapconcat 'identity (notmuch-search-find-thread-id-region beg end) " or "))
484
485 (defun notmuch-search-find-authors ()
486   "Return the authors for the current thread"
487   (plist-get (notmuch-search-get-result) :authors))
488
489 (defun notmuch-search-find-authors-region (beg end)
490   "Return a list of authors for the current region"
491   (notmuch-search-properties-in-region :authors beg end))
492
493 (defun notmuch-search-find-subject ()
494   "Return the subject for the current thread"
495   (plist-get (notmuch-search-get-result) :subject))
496
497 (defun notmuch-search-find-subject-region (beg end)
498   "Return a list of authors for the current region"
499   (notmuch-search-properties-in-region :subject beg end))
500
501 (defun notmuch-search-show-thread ()
502   "Display the currently selected thread."
503   (interactive)
504   (let ((thread-id (notmuch-search-find-thread-id))
505         (subject (notmuch-search-find-subject)))
506     (if (> (length thread-id) 0)
507         (notmuch-show thread-id
508                       (current-buffer)
509                       notmuch-search-query-string
510                       ;; Name the buffer based on the subject.
511                       (concat "*" (truncate-string-to-width subject 30 nil nil t) "*"))
512       (message "End of search results."))))
513
514 (defun notmuch-search-reply-to-thread (&optional prompt-for-sender)
515   "Begin composing a reply-all to the entire current thread in a new buffer."
516   (interactive "P")
517   (let ((message-id (notmuch-search-find-thread-id)))
518     (notmuch-mua-new-reply message-id prompt-for-sender t)))
519
520 (defun notmuch-search-reply-to-thread-sender (&optional prompt-for-sender)
521   "Begin composing a reply to the entire current thread in a new buffer."
522   (interactive "P")
523   (let ((message-id (notmuch-search-find-thread-id)))
524     (notmuch-mua-new-reply message-id prompt-for-sender nil)))
525
526 (defun notmuch-call-notmuch-process (&rest args)
527   "Synchronously invoke \"notmuch\" with the given list of arguments.
528
529 Output from the process will be presented to the user as an error
530 and will also appear in a buffer named \"*Notmuch errors*\"."
531   (let ((error-buffer (get-buffer-create "*Notmuch errors*")))
532     (with-current-buffer error-buffer
533         (erase-buffer))
534     (if (eq (apply 'call-process notmuch-command nil error-buffer nil args) 0)
535         (point)
536       (progn
537         (with-current-buffer error-buffer
538           (let ((beg (point-min))
539                 (end (- (point-max) 1)))
540             (error (buffer-substring beg end))
541             ))))))
542
543 (defun notmuch-search-set-tags (tags &optional pos)
544   (let ((new-result (plist-put (notmuch-search-get-result pos) :tags tags)))
545     (notmuch-search-update-result new-result pos)))
546
547 (defun notmuch-search-get-tags (&optional pos)
548   (plist-get (notmuch-search-get-result pos) :tags))
549
550 (defun notmuch-search-get-tags-region (beg end)
551   (let (output)
552     (notmuch-search-foreach-result beg end
553       (lambda (pos)
554         (setq output (append output (notmuch-search-get-tags pos)))))
555     output))
556
557 (defun notmuch-search-tag-region (beg end &optional tag-changes)
558   "Change tags for threads in the given region."
559   (let ((search-string (notmuch-search-find-thread-id-region-search beg end)))
560     (setq tag-changes (funcall 'notmuch-tag search-string tag-changes))
561     (notmuch-search-foreach-result beg end
562       (lambda (pos)
563         (notmuch-search-set-tags
564          (notmuch-update-tags (notmuch-search-get-tags pos) tag-changes)
565          pos)))))
566
567 (defun notmuch-search-tag (&optional tag-changes)
568   "Change tags for the currently selected thread or region.
569
570 See `notmuch-tag' for information on the format of TAG-CHANGES."
571   (interactive)
572   (let* ((beg (if (region-active-p) (region-beginning) (point)))
573          (end (if (region-active-p) (region-end) (point))))
574     (funcall 'notmuch-search-tag-region beg end tag-changes)))
575
576 (defun notmuch-search-add-tag ()
577   "Same as `notmuch-search-tag' but sets initial input to '+'."
578   (interactive)
579   (notmuch-search-tag "+"))
580
581 (defun notmuch-search-remove-tag ()
582   "Same as `notmuch-search-tag' but sets initial input to '-'."
583   (interactive)
584   (notmuch-search-tag "-"))
585
586 (defun notmuch-search-archive-thread ()
587   "Archive the currently selected thread (remove its \"inbox\" tag).
588
589 This function advances the next thread when finished."
590   (interactive)
591   (notmuch-search-tag '("-inbox"))
592   (notmuch-search-next-thread))
593
594 (defun notmuch-search-update-result (result &optional pos)
595   "Replace the result object of the thread at POS (or point) by
596 RESULT and redraw it.
597
598 This will keep point in a reasonable location.  However, if there
599 are enclosing save-excursions and the saved point is in the
600 result being updated, the point will be restored to the beginning
601 of the result."
602   (let ((start (notmuch-search-result-beginning pos))
603         (end (notmuch-search-result-end pos))
604         (init-point (point))
605         (inhibit-read-only t))
606     ;; Delete the current thread
607     (delete-region start end)
608     ;; Insert the updated thread
609     (notmuch-search-show-result result start)
610     ;; If point was inside the old result, make an educated guess
611     ;; about where to place it now.  Unfortunately, this won't work
612     ;; with save-excursion (or any other markers that would be nice to
613     ;; preserve, such as the window start), but there's nothing we can
614     ;; do about that without a way to retrieve markers in a region.
615     (when (and (>= init-point start) (<= init-point end))
616       (let* ((new-end (notmuch-search-result-end start))
617              (new-point (if (= init-point end)
618                             new-end
619                           (min init-point (- new-end 1)))))
620         (goto-char new-point)))))
621
622 (defun notmuch-search-process-sentinel (proc msg)
623   "Add a message to let user know when \"notmuch search\" exits"
624   (let ((buffer (process-buffer proc))
625         (status (process-status proc))
626         (exit-status (process-exit-status proc))
627         (never-found-target-thread nil))
628     (when (memq status '(exit signal))
629         (kill-buffer (process-get proc 'parse-buf))
630         (if (buffer-live-p buffer)
631             (with-current-buffer buffer
632               (save-excursion
633                 (let ((inhibit-read-only t)
634                       (atbob (bobp)))
635                   (goto-char (point-max))
636                   (if (eq status 'signal)
637                       (insert "Incomplete search results (search process was killed).\n"))
638                   (when (eq status 'exit)
639                     (insert "End of search results.")
640                     (unless (= exit-status 0)
641                       (insert (format " (process returned %d)" exit-status)))
642                     (insert "\n")
643                     (if (and atbob
644                              (not (string= notmuch-search-target-thread "found")))
645                         (set 'never-found-target-thread t)))))
646               (when (and never-found-target-thread
647                        notmuch-search-target-line)
648                   (goto-char (point-min))
649                   (forward-line (1- notmuch-search-target-line))))))))
650
651 (defcustom notmuch-search-line-faces '(("unread" :weight bold)
652                                        ("flagged" :foreground "blue"))
653   "Tag/face mapping for line highlighting in notmuch-search.
654
655 Here is an example of how to color search results based on tags.
656  (the following text would be placed in your ~/.emacs file):
657
658  (setq notmuch-search-line-faces '((\"deleted\" . (:foreground \"red\"
659                                                   :background \"blue\"))
660                                    (\"unread\" . (:foreground \"green\"))))
661
662 The attributes defined for matching tags are merged, with later
663 attributes overriding earlier. A message having both \"deleted\"
664 and \"unread\" tags with the above settings would have a green
665 foreground and blue background."
666   :type '(alist :key-type (string) :value-type (custom-face-edit))
667   :group 'notmuch-search
668   :group 'notmuch-faces)
669
670 (defun notmuch-search-color-line (start end line-tag-list)
671   "Colorize lines in `notmuch-show' based on tags."
672   (mapc (lambda (elem)
673           (let ((tag (car elem))
674                 (attributes (cdr elem)))
675             (when (member tag line-tag-list)
676               (notmuch-combine-face-text-property start end attributes))))
677         ;; Reverse the list so earlier entries take precedence
678         (reverse notmuch-search-line-faces)))
679
680 (defun notmuch-search-author-propertize (authors)
681   "Split `authors' into matching and non-matching authors and
682 propertize appropriately. If no boundary between authors and
683 non-authors is found, assume that all of the authors match."
684   (if (string-match "\\(.*\\)|\\(.*\\)" authors)
685       (concat (propertize (concat (match-string 1 authors) ",")
686                           'face 'notmuch-search-matching-authors)
687               (propertize (match-string 2 authors)
688                           'face 'notmuch-search-non-matching-authors))
689     (propertize authors 'face 'notmuch-search-matching-authors)))
690
691 (defun notmuch-search-insert-authors (format-string authors)
692   ;; Save the match data to avoid interfering with
693   ;; `notmuch-search-process-filter'.
694   (save-match-data
695     (let* ((formatted-authors (format format-string authors))
696            (formatted-sample (format format-string ""))
697            (visible-string formatted-authors)
698            (invisible-string "")
699            (padding ""))
700
701       ;; Truncate the author string to fit the specification.
702       (if (> (length formatted-authors)
703              (length formatted-sample))
704           (let ((visible-length (- (length formatted-sample)
705                                    (length "... "))))
706             ;; Truncate the visible string according to the width of
707             ;; the display string.
708             (setq visible-string (substring formatted-authors 0 visible-length)
709                   invisible-string (substring formatted-authors visible-length))
710             ;; If possible, truncate the visible string at a natural
711             ;; break (comma or pipe), as incremental search doesn't
712             ;; match across the visible/invisible border.
713             (when (string-match "\\(.*\\)\\([,|] \\)\\([^,|]*\\)" visible-string)
714               ;; Second clause is destructive on `visible-string', so
715               ;; order is important.
716               (setq invisible-string (concat (match-string 3 visible-string)
717                                              invisible-string)
718                     visible-string (concat (match-string 1 visible-string)
719                                            (match-string 2 visible-string))))
720             ;; `visible-string' may be shorter than the space allowed
721             ;; by `format-string'. If so we must insert some padding
722             ;; after `invisible-string'.
723             (setq padding (make-string (- (length formatted-sample)
724                                           (length visible-string)
725                                           (length "..."))
726                                        ? ))))
727
728       ;; Use different faces to show matching and non-matching authors.
729       (if (string-match "\\(.*\\)|\\(.*\\)" visible-string)
730           ;; The visible string contains both matching and
731           ;; non-matching authors.
732           (setq visible-string (notmuch-search-author-propertize visible-string)
733                 ;; The invisible string must contain only non-matching
734                 ;; authors, as the visible-string contains both.
735                 invisible-string (propertize invisible-string
736                                              'face 'notmuch-search-non-matching-authors))
737         ;; The visible string contains only matching authors.
738         (setq visible-string (propertize visible-string
739                                          'face 'notmuch-search-matching-authors)
740               ;; The invisible string may contain both matching and
741               ;; non-matching authors.
742               invisible-string (notmuch-search-author-propertize invisible-string)))
743
744       ;; If there is any invisible text, add it as a tooltip to the
745       ;; visible text.
746       (when (not (string= invisible-string ""))
747         (setq visible-string (propertize visible-string 'help-echo (concat "..." invisible-string))))
748
749       ;; Insert the visible and, if present, invisible author strings.
750       (insert visible-string)
751       (when (not (string= invisible-string ""))
752         (let ((start (point))
753               overlay)
754           (insert invisible-string)
755           (setq overlay (make-overlay start (point)))
756           (overlay-put overlay 'invisible 'ellipsis)
757           (overlay-put overlay 'isearch-open-invisible #'delete-overlay)))
758       (insert padding))))
759
760 (defun notmuch-search-insert-field (field format-string result)
761   (cond
762    ((string-equal field "date")
763     (insert (propertize (format format-string (plist-get result :date_relative))
764                         'face 'notmuch-search-date)))
765    ((string-equal field "count")
766     (insert (propertize (format format-string
767                                 (format "[%s/%s]" (plist-get result :matched)
768                                         (plist-get result :total)))
769                         'face 'notmuch-search-count)))
770    ((string-equal field "subject")
771     (insert (propertize (format format-string (plist-get result :subject))
772                         'face 'notmuch-search-subject)))
773
774    ((string-equal field "authors")
775     (notmuch-search-insert-authors format-string (plist-get result :authors)))
776
777    ((string-equal field "tags")
778     ;; Ignore format-string here because notmuch-search-set-tags
779     ;; depends on the format of this
780     (insert (concat "(" (propertize
781                          (mapconcat 'identity (plist-get result :tags) " ")
782                          'font-lock-face 'notmuch-tag-face) ")")))))
783
784 (defun notmuch-search-show-result (result &optional pos)
785   "Insert RESULT at POS or the end of the buffer if POS is null."
786   ;; Ignore excluded matches
787   (unless (= (plist-get result :matched) 0)
788     (let ((beg (or pos (point-max))))
789       (save-excursion
790         (goto-char beg)
791         (dolist (spec notmuch-search-result-format)
792           (notmuch-search-insert-field (car spec) (cdr spec) result))
793         (insert "\n")
794         (notmuch-search-color-line beg (point) (plist-get result :tags))
795         (put-text-property beg (point) 'notmuch-search-result result))
796       (when (string= (plist-get result :thread) notmuch-search-target-thread)
797         (setq notmuch-search-target-thread "found")
798         (goto-char beg)))))
799
800 (defun notmuch-search-show-error (string &rest objects)
801   (save-excursion
802     (goto-char (point-max))
803     (insert "Error: Unexpected output from notmuch search:\n")
804     (insert (apply #'format string objects))
805     (insert "\n")))
806
807 (defvar notmuch-search-process-state nil
808   "Parsing state of the search process filter.")
809
810 (defvar notmuch-search-json-parser nil
811   "Incremental JSON parser for the search process filter.")
812
813 (defun notmuch-search-process-filter (proc string)
814   "Process and filter the output of \"notmuch search\""
815   (let ((results-buf (process-buffer proc))
816         (parse-buf (process-get proc 'parse-buf))
817         (inhibit-read-only t)
818         done)
819     (if (not (buffer-live-p results-buf))
820         (delete-process proc)
821       (with-current-buffer parse-buf
822         ;; Insert new data
823         (save-excursion
824           (goto-char (point-max))
825           (insert string)))
826       (with-current-buffer results-buf
827         (while (not done)
828           (condition-case nil
829               (case notmuch-search-process-state
830                 ((begin)
831                  ;; Enter the results list
832                  (if (eq (notmuch-json-begin-compound
833                           notmuch-search-json-parser) 'retry)
834                      (setq done t)
835                    (setq notmuch-search-process-state 'result)))
836                 ((result)
837                  ;; Parse a result
838                  (let ((result (notmuch-json-read notmuch-search-json-parser)))
839                    (case result
840                      ((retry) (setq done t))
841                      ((end) (setq notmuch-search-process-state 'end))
842                      (otherwise (notmuch-search-show-result result)))))
843                 ((end)
844                  ;; Any trailing data is unexpected
845                  (notmuch-json-eof notmuch-search-json-parser)
846                  (setq done t)))
847             (json-error
848              ;; Do our best to resynchronize and ensure forward
849              ;; progress
850              (notmuch-search-show-error
851               "%s"
852               (with-current-buffer parse-buf
853                 (let ((bad (buffer-substring (line-beginning-position)
854                                              (line-end-position))))
855                   (forward-line)
856                   bad))))))
857         ;; Clear out what we've parsed
858         (with-current-buffer parse-buf
859           (delete-region (point-min) (point)))))))
860
861 (defun notmuch-search-tag-all (&optional tag-changes)
862   "Add/remove tags from all messages in current search buffer.
863
864 See `notmuch-tag' for information on the format of TAG-CHANGES."
865   (interactive)
866   (apply 'notmuch-tag notmuch-search-query-string tag-changes))
867
868 (defun notmuch-search-buffer-title (query)
869   "Returns the title for a buffer with notmuch search results."
870   (let* ((saved-search
871           (let (longest
872                 (longest-length 0))
873             (loop for tuple in notmuch-saved-searches
874                   if (let ((quoted-query (regexp-quote (cdr tuple))))
875                        (and (string-match (concat "^" quoted-query) query)
876                             (> (length (match-string 0 query))
877                                longest-length)))
878                   do (setq longest tuple))
879             longest))
880          (saved-search-name (car saved-search))
881          (saved-search-query (cdr saved-search)))
882     (cond ((and saved-search (equal saved-search-query query))
883            ;; Query is the same as saved search (ignoring case)
884            (concat "*notmuch-saved-search-" saved-search-name "*"))
885           (saved-search
886            (concat "*notmuch-search-"
887                    (replace-regexp-in-string (concat "^" (regexp-quote saved-search-query))
888                                              (concat "[ " saved-search-name " ]")
889                                              query)
890                    "*"))
891           (t
892            (concat "*notmuch-search-" query "*"))
893           )))
894
895 (defun notmuch-read-query (prompt)
896   "Read a notmuch-query from the minibuffer with completion.
897
898 PROMPT is the string to prompt with."
899   (lexical-let
900       ((completions
901         (append (list "folder:" "thread:" "id:" "date:" "from:" "to:"
902                       "subject:" "attachment:")
903                 (mapcar (lambda (tag)
904                           (concat "tag:" tag))
905                         (process-lines notmuch-command "search" "--output=tags" "*")))))
906     (let ((keymap (copy-keymap minibuffer-local-map))
907           (minibuffer-completion-table
908            (completion-table-dynamic
909             (lambda (string)
910               ;; generate a list of possible completions for the current input
911               (cond
912                ;; this ugly regexp is used to get the last word of the input
913                ;; possibly preceded by a '('
914                ((string-match "\\(^\\|.* (?\\)\\([^ ]*\\)$" string)
915                 (mapcar (lambda (compl)
916                           (concat (match-string-no-properties 1 string) compl))
917                         (all-completions (match-string-no-properties 2 string)
918                                          completions)))
919                (t (list string)))))))
920       ;; this was simpler than convincing completing-read to accept spaces:
921       (define-key keymap (kbd "TAB") 'minibuffer-complete)
922       (let ((history-delete-duplicates t))
923         (read-from-minibuffer prompt nil keymap nil
924                               'notmuch-search-history nil nil)))))
925
926 ;;;###autoload
927 (defun notmuch-search (&optional query oldest-first target-thread target-line continuation)
928   "Run \"notmuch search\" with the given `query' and display results.
929
930 If `query' is nil, it is read interactively from the minibuffer.
931 Other optional parameters are used as follows:
932
933   oldest-first: A Boolean controlling the sort order of returned threads
934   target-thread: A thread ID (with the thread: prefix) that will be made
935                  current if it appears in the search results.
936   target-line: The line number to move to if the target thread does not
937                appear in the search results."
938   (interactive)
939   (if (null query)
940       (setq query (notmuch-read-query "Notmuch search: ")))
941   (let ((buffer (get-buffer-create (notmuch-search-buffer-title query))))
942     (switch-to-buffer buffer)
943     (notmuch-search-mode)
944     ;; Don't track undo information for this buffer
945     (set 'buffer-undo-list t)
946     (set 'notmuch-search-query-string query)
947     (set 'notmuch-search-oldest-first oldest-first)
948     (set 'notmuch-search-target-thread target-thread)
949     (set 'notmuch-search-target-line target-line)
950     (set 'notmuch-search-continuation continuation)
951     (let ((proc (get-buffer-process (current-buffer)))
952           (inhibit-read-only t))
953       (if proc
954           (error "notmuch search process already running for query `%s'" query)
955         )
956       (erase-buffer)
957       (goto-char (point-min))
958       (save-excursion
959         (let ((proc (start-process
960                      "notmuch-search" buffer
961                      notmuch-command "search"
962                      "--format=json"
963                      (if oldest-first
964                          "--sort=oldest-first"
965                        "--sort=newest-first")
966                      query))
967               ;; Use a scratch buffer to accumulate partial output.
968               ;; This buffer will be killed by the sentinel, which
969               ;; should be called no matter how the process dies.
970               (parse-buf (generate-new-buffer " *notmuch search parse*")))
971           (set (make-local-variable 'notmuch-search-process-state) 'begin)
972           (set (make-local-variable 'notmuch-search-json-parser)
973                (notmuch-json-create-parser parse-buf))
974           (process-put proc 'parse-buf parse-buf)
975           (set-process-sentinel proc 'notmuch-search-process-sentinel)
976           (set-process-filter proc 'notmuch-search-process-filter)
977           (set-process-query-on-exit-flag proc nil))))
978     (run-hooks 'notmuch-search-hook)))
979
980 (defun notmuch-search-refresh-view ()
981   "Refresh the current view.
982
983 Kills the current buffer and runs a new search with the same
984 query string as the current search. If the current thread is in
985 the new search results, then point will be placed on the same
986 thread. Otherwise, point will be moved to attempt to be in the
987 same relative position within the new buffer."
988   (interactive)
989   (let ((target-line (line-number-at-pos))
990         (oldest-first notmuch-search-oldest-first)
991         (target-thread (notmuch-search-find-thread-id))
992         (query notmuch-search-query-string)
993         (continuation notmuch-search-continuation))
994     (notmuch-kill-this-buffer)
995     (notmuch-search query oldest-first target-thread target-line continuation)
996     (goto-char (point-min))))
997
998 (defcustom notmuch-poll-script nil
999   "An external script to incorporate new mail into the notmuch database.
1000
1001 This variable controls the action invoked by
1002 `notmuch-search-poll-and-refresh-view' and
1003 `notmuch-hello-poll-and-update' (each have a default keybinding
1004 of 'G') to incorporate new mail into the notmuch database.
1005
1006 If set to nil (the default), new mail is processed by invoking
1007 \"notmuch new\". Otherwise, this should be set to a string that
1008 gives the name of an external script that processes new mail. If
1009 set to the empty string, no command will be run.
1010
1011 The external script could do any of the following depending on
1012 the user's needs:
1013
1014 1. Invoke a program to transfer mail to the local mail store
1015 2. Invoke \"notmuch new\" to incorporate the new mail
1016 3. Invoke one or more \"notmuch tag\" commands to classify the mail
1017
1018 Note that the recommended way of achieving the same is using
1019 \"notmuch new\" hooks."
1020   :type '(choice (const :tag "notmuch new" nil)
1021                  (const :tag "Disabled" "")
1022                  (string :tag "Custom script"))
1023   :group 'notmuch-external)
1024
1025 (defun notmuch-poll ()
1026   "Run \"notmuch new\" or an external script to import mail.
1027
1028 Invokes `notmuch-poll-script', \"notmuch new\", or does nothing
1029 depending on the value of `notmuch-poll-script'."
1030   (interactive)
1031   (if (stringp notmuch-poll-script)
1032       (unless (string= notmuch-poll-script "")
1033         (call-process notmuch-poll-script nil nil))
1034     (call-process notmuch-command nil nil nil "new")))
1035
1036 (defun notmuch-search-poll-and-refresh-view ()
1037   "Invoke `notmuch-poll' to import mail, then refresh the current view."
1038   (interactive)
1039   (notmuch-poll)
1040   (notmuch-search-refresh-view))
1041
1042 (defun notmuch-search-toggle-order ()
1043   "Toggle the current search order.
1044
1045 By default, the \"inbox\" view created by `notmuch' is displayed
1046 in chronological order (oldest thread at the beginning of the
1047 buffer), while any global searches created by `notmuch-search'
1048 are displayed in reverse-chronological order (newest thread at
1049 the beginning of the buffer).
1050
1051 This command toggles the sort order for the current search.
1052
1053 Note that any filtered searches created by
1054 `notmuch-search-filter' retain the search order of the parent
1055 search."
1056   (interactive)
1057   (set 'notmuch-search-oldest-first (not notmuch-search-oldest-first))
1058   (notmuch-search-refresh-view))
1059
1060 (defun notmuch-search-filter (query)
1061   "Filter the current search results based on an additional query string.
1062
1063 Runs a new search matching only messages that match both the
1064 current search results AND the additional query string provided."
1065   (interactive (list (notmuch-read-query "Filter search: ")))
1066   (let ((grouped-query (if (string-match-p notmuch-search-disjunctive-regexp query)
1067                            (concat "( " query " )")
1068                          query)))
1069     (notmuch-search (if (string= notmuch-search-query-string "*")
1070                         grouped-query
1071                       (concat notmuch-search-query-string " and " grouped-query)) notmuch-search-oldest-first)))
1072
1073 (defun notmuch-search-filter-by-tag (tag)
1074   "Filter the current search results based on a single tag.
1075
1076 Runs a new search matching only messages that match both the
1077 current search results AND that are tagged with the given tag."
1078   (interactive
1079    (list (notmuch-select-tag-with-completion "Filter by tag: ")))
1080   (notmuch-search (concat notmuch-search-query-string " and tag:" tag) notmuch-search-oldest-first))
1081
1082 ;;;###autoload
1083 (defun notmuch ()
1084   "Run notmuch and display saved searches, known tags, etc."
1085   (interactive)
1086   (notmuch-hello))
1087
1088 (defun notmuch-interesting-buffer (b)
1089   "Is the current buffer of interest to a notmuch user?"
1090   (with-current-buffer b
1091     (memq major-mode '(notmuch-show-mode
1092                        notmuch-search-mode
1093                        notmuch-hello-mode
1094                        message-mode))))
1095
1096 ;;;###autoload
1097 (defun notmuch-cycle-notmuch-buffers ()
1098   "Cycle through any existing notmuch buffers (search, show or hello).
1099
1100 If the current buffer is the only notmuch buffer, bury it. If no
1101 notmuch buffers exist, run `notmuch'."
1102   (interactive)
1103
1104   (let (start first)
1105     ;; If the current buffer is a notmuch buffer, remember it and then
1106     ;; bury it.
1107     (when (notmuch-interesting-buffer (current-buffer))
1108       (setq start (current-buffer))
1109       (bury-buffer))
1110
1111     ;; Find the first notmuch buffer.
1112     (setq first (loop for buffer in (buffer-list)
1113                      if (notmuch-interesting-buffer buffer)
1114                      return buffer))
1115
1116     (if first
1117         ;; If the first one we found is any other than the starting
1118         ;; buffer, switch to it.
1119         (unless (eq first start)
1120           (switch-to-buffer first))
1121       (notmuch))))
1122
1123 (setq mail-user-agent 'notmuch-user-agent)
1124
1125 (provide 'notmuch)