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