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