]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch.el
emacs: move search based tree functions to notmuch.el
[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-call-notmuch-process (&rest args)
469   "Synchronously invoke \"notmuch\" with the given list of arguments.
470
471 If notmuch exits with a non-zero status, output from the process
472 will appear in a buffer named \"*Notmuch errors*\" and an error
473 will be signaled."
474   (with-temp-buffer
475     (let ((status (apply #'call-process notmuch-command nil t nil args)))
476       (notmuch-check-exit-status status (cons notmuch-command args)
477                                  (buffer-string)))))
478
479 (defun notmuch-search-set-tags (tags &optional pos)
480   (let ((new-result (plist-put (notmuch-search-get-result pos) :tags tags)))
481     (notmuch-search-update-result new-result pos)))
482
483 (defun notmuch-search-get-tags (&optional pos)
484   (plist-get (notmuch-search-get-result pos) :tags))
485
486 (defun notmuch-search-get-tags-region (beg end)
487   (let (output)
488     (notmuch-search-foreach-result beg end
489       (lambda (pos)
490         (setq output (append output (notmuch-search-get-tags pos)))))
491     output))
492
493 (defun notmuch-search-interactive-region ()
494   "Return the bounds of the current interactive region.
495
496 This returns (BEG END), where BEG and END are the bounds of the
497 region if the region is active, or both `point' otherwise."
498   (if (region-active-p)
499       (list (region-beginning) (region-end))
500     (list (point) (point))))
501
502 (defun notmuch-search-interactive-tag-changes (&optional initial-input)
503   "Prompt for tag changes for the current thread or region.
504
505 Returns (TAG-CHANGES REGION-BEGIN REGION-END)."
506   (let* ((region (notmuch-search-interactive-region))
507          (beg (first region)) (end (second region))
508          (prompt (if (= beg end) "Tag thread" "Tag region")))
509     (cons (notmuch-read-tag-changes
510            (notmuch-search-get-tags-region beg end) prompt initial-input)
511           region)))
512
513 (defun notmuch-search-tag (tag-changes &optional beg end)
514   "Change tags for the currently selected thread or region.
515
516 See `notmuch-tag' for information on the format of TAG-CHANGES.
517 When called interactively, this uses the region if the region is
518 active.  When called directly, BEG and END provide the region.
519 If these are nil or not provided, this applies to the thread at
520 point."
521   (interactive (notmuch-search-interactive-tag-changes))
522   (unless (and beg end) (setq beg (point) end (point)))
523   (let ((search-string (notmuch-search-find-thread-id-region-search beg end)))
524     (notmuch-tag search-string tag-changes)
525     (notmuch-search-foreach-result beg end
526       (lambda (pos)
527         (notmuch-search-set-tags
528          (notmuch-update-tags (notmuch-search-get-tags pos) tag-changes)
529          pos)))))
530
531 (defun notmuch-search-add-tag (tag-changes &optional beg end)
532   "Change tags for the current thread or region (defaulting to add).
533
534 Same as `notmuch-search-tag' but sets initial input to '+'."
535   (interactive (notmuch-search-interactive-tag-changes "+"))
536   (notmuch-search-tag tag-changes beg end))
537
538 (defun notmuch-search-remove-tag (tag-changes &optional beg end)
539   "Change tags for the current thread or region (defaulting to remove).
540
541 Same as `notmuch-search-tag' but sets initial input to '-'."
542   (interactive (notmuch-search-interactive-tag-changes "-"))
543   (notmuch-search-tag tag-changes beg end))
544
545 (put 'notmuch-search-archive-thread 'notmuch-prefix-doc
546      "Un-archive the currently selected thread.")
547 (defun notmuch-search-archive-thread (&optional unarchive beg end)
548   "Archive the currently selected thread or region.
549
550 Archive each message in the currently selected thread by applying
551 the tag changes in `notmuch-archive-tags' to each (remove the
552 \"inbox\" tag by default). If a prefix argument is given, the
553 messages will be \"unarchived\" (i.e. the tag changes in
554 `notmuch-archive-tags' will be reversed).
555
556 This function advances the next thread when finished."
557   (interactive (cons current-prefix-arg (notmuch-search-interactive-region)))
558   (when notmuch-archive-tags
559     (notmuch-search-tag
560      (notmuch-tag-change-list notmuch-archive-tags unarchive) beg end))
561   (notmuch-search-next-thread))
562
563 (defun notmuch-search-update-result (result &optional pos)
564   "Replace the result object of the thread at POS (or point) by
565 RESULT and redraw it.
566
567 This will keep point in a reasonable location.  However, if there
568 are enclosing save-excursions and the saved point is in the
569 result being updated, the point will be restored to the beginning
570 of the result."
571   (let ((start (notmuch-search-result-beginning pos))
572         (end (notmuch-search-result-end pos))
573         (init-point (point))
574         (inhibit-read-only t))
575     ;; Delete the current thread
576     (delete-region start end)
577     ;; Insert the updated thread
578     (notmuch-search-show-result result start)
579     ;; If point was inside the old result, make an educated guess
580     ;; about where to place it now.  Unfortunately, this won't work
581     ;; with save-excursion (or any other markers that would be nice to
582     ;; preserve, such as the window start), but there's nothing we can
583     ;; do about that without a way to retrieve markers in a region.
584     (when (and (>= init-point start) (<= init-point end))
585       (let* ((new-end (notmuch-search-result-end start))
586              (new-point (if (= init-point end)
587                             new-end
588                           (min init-point (- new-end 1)))))
589         (goto-char new-point)))))
590
591 (defun notmuch-search-process-sentinel (proc msg)
592   "Add a message to let user know when \"notmuch search\" exits"
593   (let ((buffer (process-buffer proc))
594         (status (process-status proc))
595         (exit-status (process-exit-status proc))
596         (never-found-target-thread nil))
597     (when (memq status '(exit signal))
598       (catch 'return
599         (kill-buffer (process-get proc 'parse-buf))
600         (if (buffer-live-p buffer)
601             (with-current-buffer buffer
602               (save-excursion
603                 (let ((inhibit-read-only t)
604                       (atbob (bobp)))
605                   (goto-char (point-max))
606                   (if (eq status 'signal)
607                       (insert "Incomplete search results (search process was killed).\n"))
608                   (when (eq status 'exit)
609                     (insert "End of search results.\n")
610                     ;; For version mismatch, there's no point in
611                     ;; showing the search buffer
612                     (when (or (= exit-status 20) (= exit-status 21))
613                       (kill-buffer)
614                       (throw 'return nil))
615                     (if (and atbob
616                              (not (string= notmuch-search-target-thread "found")))
617                         (set 'never-found-target-thread t)))))
618               (when (and never-found-target-thread
619                        notmuch-search-target-line)
620                   (goto-char (point-min))
621                   (forward-line (1- notmuch-search-target-line)))))))))
622
623 (defcustom notmuch-search-line-faces '(("unread" :weight bold)
624                                        ("flagged" :foreground "blue"))
625   "Tag/face mapping for line highlighting in notmuch-search.
626
627 Here is an example of how to color search results based on tags.
628  (the following text would be placed in your ~/.emacs file):
629
630  (setq notmuch-search-line-faces '((\"deleted\" . (:foreground \"red\"
631                                                   :background \"blue\"))
632                                    (\"unread\" . (:foreground \"green\"))))
633
634 The attributes defined for matching tags are merged, with later
635 attributes overriding earlier. A message having both \"deleted\"
636 and \"unread\" tags with the above settings would have a green
637 foreground and blue background."
638   :type '(alist :key-type (string) :value-type (custom-face-edit))
639   :group 'notmuch-search
640   :group 'notmuch-faces)
641
642 (defun notmuch-search-color-line (start end line-tag-list)
643   "Colorize lines in `notmuch-show' based on tags."
644   (mapc (lambda (elem)
645           (let ((tag (car elem))
646                 (attributes (cdr elem)))
647             (when (member tag line-tag-list)
648               (notmuch-combine-face-text-property start end attributes))))
649         ;; Reverse the list so earlier entries take precedence
650         (reverse notmuch-search-line-faces)))
651
652 (defun notmuch-search-author-propertize (authors)
653   "Split `authors' into matching and non-matching authors and
654 propertize appropriately. If no boundary between authors and
655 non-authors is found, assume that all of the authors match."
656   (if (string-match "\\(.*\\)|\\(.*\\)" authors)
657       (concat (propertize (concat (match-string 1 authors) ",")
658                           'face 'notmuch-search-matching-authors)
659               (propertize (match-string 2 authors)
660                           'face 'notmuch-search-non-matching-authors))
661     (propertize authors 'face 'notmuch-search-matching-authors)))
662
663 (defun notmuch-search-insert-authors (format-string authors)
664   ;; Save the match data to avoid interfering with
665   ;; `notmuch-search-process-filter'.
666   (save-match-data
667     (let* ((formatted-authors (format format-string authors))
668            (formatted-sample (format format-string ""))
669            (visible-string formatted-authors)
670            (invisible-string "")
671            (padding ""))
672
673       ;; Truncate the author string to fit the specification.
674       (if (> (length formatted-authors)
675              (length formatted-sample))
676           (let ((visible-length (- (length formatted-sample)
677                                    (length "... "))))
678             ;; Truncate the visible string according to the width of
679             ;; the display string.
680             (setq visible-string (substring formatted-authors 0 visible-length)
681                   invisible-string (substring formatted-authors visible-length))
682             ;; If possible, truncate the visible string at a natural
683             ;; break (comma or pipe), as incremental search doesn't
684             ;; match across the visible/invisible border.
685             (when (string-match "\\(.*\\)\\([,|] \\)\\([^,|]*\\)" visible-string)
686               ;; Second clause is destructive on `visible-string', so
687               ;; order is important.
688               (setq invisible-string (concat (match-string 3 visible-string)
689                                              invisible-string)
690                     visible-string (concat (match-string 1 visible-string)
691                                            (match-string 2 visible-string))))
692             ;; `visible-string' may be shorter than the space allowed
693             ;; by `format-string'. If so we must insert some padding
694             ;; after `invisible-string'.
695             (setq padding (make-string (- (length formatted-sample)
696                                           (length visible-string)
697                                           (length "..."))
698                                        ? ))))
699
700       ;; Use different faces to show matching and non-matching authors.
701       (if (string-match "\\(.*\\)|\\(.*\\)" visible-string)
702           ;; The visible string contains both matching and
703           ;; non-matching authors.
704           (setq visible-string (notmuch-search-author-propertize visible-string)
705                 ;; The invisible string must contain only non-matching
706                 ;; authors, as the visible-string contains both.
707                 invisible-string (propertize invisible-string
708                                              'face 'notmuch-search-non-matching-authors))
709         ;; The visible string contains only matching authors.
710         (setq visible-string (propertize visible-string
711                                          'face 'notmuch-search-matching-authors)
712               ;; The invisible string may contain both matching and
713               ;; non-matching authors.
714               invisible-string (notmuch-search-author-propertize invisible-string)))
715
716       ;; If there is any invisible text, add it as a tooltip to the
717       ;; visible text.
718       (when (not (string= invisible-string ""))
719         (setq visible-string (propertize visible-string 'help-echo (concat "..." invisible-string))))
720
721       ;; Insert the visible and, if present, invisible author strings.
722       (insert visible-string)
723       (when (not (string= invisible-string ""))
724         (let ((start (point))
725               overlay)
726           (insert invisible-string)
727           (setq overlay (make-overlay start (point)))
728           (overlay-put overlay 'invisible 'ellipsis)
729           (overlay-put overlay 'isearch-open-invisible #'delete-overlay)))
730       (insert padding))))
731
732 (defun notmuch-search-insert-field (field format-string result)
733   (cond
734    ((string-equal field "date")
735     (insert (propertize (format format-string (plist-get result :date_relative))
736                         'face 'notmuch-search-date)))
737    ((string-equal field "count")
738     (insert (propertize (format format-string
739                                 (format "[%s/%s]" (plist-get result :matched)
740                                         (plist-get result :total)))
741                         'face 'notmuch-search-count)))
742    ((string-equal field "subject")
743     (insert (propertize (format format-string
744                                 (notmuch-sanitize (plist-get result :subject)))
745                         'face 'notmuch-search-subject)))
746
747    ((string-equal field "authors")
748     (notmuch-search-insert-authors
749      format-string (notmuch-sanitize (plist-get result :authors))))
750
751    ((string-equal field "tags")
752     (let ((tags (plist-get result :tags)))
753       (insert (format format-string (notmuch-tag-format-tags tags)))))))
754
755 (defun notmuch-search-show-result (result &optional pos)
756   "Insert RESULT at POS or the end of the buffer if POS is null."
757   ;; Ignore excluded matches
758   (unless (= (plist-get result :matched) 0)
759     (let ((beg (or pos (point-max))))
760       (save-excursion
761         (goto-char beg)
762         (dolist (spec notmuch-search-result-format)
763           (notmuch-search-insert-field (car spec) (cdr spec) result))
764         (insert "\n")
765         (notmuch-search-color-line beg (point) (plist-get result :tags))
766         (put-text-property beg (point) 'notmuch-search-result result))
767       (when (string= (plist-get result :thread) notmuch-search-target-thread)
768         (setq notmuch-search-target-thread "found")
769         (goto-char beg)))))
770
771 (defun notmuch-search-process-filter (proc string)
772   "Process and filter the output of \"notmuch search\""
773   (let ((results-buf (process-buffer proc))
774         (parse-buf (process-get proc 'parse-buf))
775         (inhibit-read-only t)
776         done)
777     (when (buffer-live-p results-buf)
778       (with-current-buffer parse-buf
779         ;; Insert new data
780         (save-excursion
781           (goto-char (point-max))
782           (insert string))
783         (notmuch-sexp-parse-partial-list 'notmuch-search-show-result
784                                          results-buf)))))
785
786 (defun notmuch-search-tag-all (tag-changes)
787   "Add/remove tags from all messages in current search buffer.
788
789 See `notmuch-tag' for information on the format of TAG-CHANGES."
790   (interactive
791    (list (notmuch-read-tag-changes
792           (notmuch-search-get-tags-region (point-min) (point-max)) "Tag all")))
793   (notmuch-tag notmuch-search-query-string tag-changes))
794
795 (defun notmuch-search-buffer-title (query)
796   "Returns the title for a buffer with notmuch search results."
797   (let* ((saved-search
798           (let (longest
799                 (longest-length 0))
800             (loop for tuple in notmuch-saved-searches
801                   if (let ((quoted-query (regexp-quote (cdr tuple))))
802                        (and (string-match (concat "^" quoted-query) query)
803                             (> (length (match-string 0 query))
804                                longest-length)))
805                   do (setq longest tuple))
806             longest))
807          (saved-search-name (car saved-search))
808          (saved-search-query (cdr saved-search)))
809     (cond ((and saved-search (equal saved-search-query query))
810            ;; Query is the same as saved search (ignoring case)
811            (concat "*notmuch-saved-search-" saved-search-name "*"))
812           (saved-search
813            (concat "*notmuch-search-"
814                    (replace-regexp-in-string (concat "^" (regexp-quote saved-search-query))
815                                              (concat "[ " saved-search-name " ]")
816                                              query)
817                    "*"))
818           (t
819            (concat "*notmuch-search-" query "*"))
820           )))
821
822 (defun notmuch-read-query (prompt)
823   "Read a notmuch-query from the minibuffer with completion.
824
825 PROMPT is the string to prompt with."
826   (lexical-let
827       ((completions
828         (append (list "folder:" "thread:" "id:" "date:" "from:" "to:"
829                       "subject:" "attachment:")
830                 (mapcar (lambda (tag)
831                           (concat "tag:" (notmuch-escape-boolean-term tag)))
832                         (process-lines notmuch-command "search" "--output=tags" "*")))))
833     (let ((keymap (copy-keymap minibuffer-local-map))
834           (minibuffer-completion-table
835            (completion-table-dynamic
836             (lambda (string)
837               ;; generate a list of possible completions for the current input
838               (cond
839                ;; this ugly regexp is used to get the last word of the input
840                ;; possibly preceded by a '('
841                ((string-match "\\(^\\|.* (?\\)\\([^ ]*\\)$" string)
842                 (mapcar (lambda (compl)
843                           (concat (match-string-no-properties 1 string) compl))
844                         (all-completions (match-string-no-properties 2 string)
845                                          completions)))
846                (t (list string)))))))
847       ;; this was simpler than convincing completing-read to accept spaces:
848       (define-key keymap (kbd "TAB") 'minibuffer-complete)
849       (let ((history-delete-duplicates t))
850         (read-from-minibuffer prompt nil keymap nil
851                               'notmuch-search-history nil nil)))))
852
853 ;;;###autoload
854 (put 'notmuch-search 'notmuch-doc "Search for messages.")
855 (defun notmuch-search (&optional query oldest-first target-thread target-line)
856   "Display threads matching QUERY in a notmuch-search buffer.
857
858 If QUERY is nil, it is read interactively from the minibuffer.
859 Other optional parameters are used as follows:
860
861   OLDEST-FIRST: A Boolean controlling the sort order of returned threads
862   TARGET-THREAD: A thread ID (without the thread: prefix) that will be made
863                  current if it appears in the search results.
864   TARGET-LINE: The line number to move to if the target thread does not
865                appear in the search results.
866
867 When called interactively, this will prompt for a query and use
868 the configured default sort order."
869   (interactive
870    (list
871     ;; Prompt for a query
872     nil
873     ;; Use the default search order (if we're doing a search from a
874     ;; search buffer, ignore any buffer-local overrides)
875     (default-value 'notmuch-search-oldest-first)))
876
877   (let* ((query (or query (notmuch-read-query "Notmuch search: ")))
878          (buffer (get-buffer-create (notmuch-search-buffer-title query))))
879     (switch-to-buffer buffer)
880     (notmuch-search-mode)
881     ;; Don't track undo information for this buffer
882     (set 'buffer-undo-list t)
883     (set 'notmuch-search-query-string query)
884     (set 'notmuch-search-oldest-first oldest-first)
885     (set 'notmuch-search-target-thread target-thread)
886     (set 'notmuch-search-target-line target-line)
887     (let ((proc (get-buffer-process (current-buffer)))
888           (inhibit-read-only t))
889       (if proc
890           (error "notmuch search process already running for query `%s'" query)
891         )
892       (erase-buffer)
893       (goto-char (point-min))
894       (save-excursion
895         (let ((proc (notmuch-start-notmuch
896                      "notmuch-search" buffer #'notmuch-search-process-sentinel
897                      "search" "--format=sexp" "--format-version=1"
898                      (if oldest-first
899                          "--sort=oldest-first"
900                        "--sort=newest-first")
901                      query))
902               ;; Use a scratch buffer to accumulate partial output.
903               ;; This buffer will be killed by the sentinel, which
904               ;; should be called no matter how the process dies.
905               (parse-buf (generate-new-buffer " *notmuch search parse*")))
906           (process-put proc 'parse-buf parse-buf)
907           (set-process-filter proc 'notmuch-search-process-filter)
908           (set-process-query-on-exit-flag proc nil))))
909     (run-hooks 'notmuch-search-hook)))
910
911 (defun notmuch-search-refresh-view ()
912   "Refresh the current view.
913
914 Kills the current buffer and runs a new search with the same
915 query string as the current search. If the current thread is in
916 the new search results, then point will be placed on the same
917 thread. Otherwise, point will be moved to attempt to be in the
918 same relative position within the new buffer."
919   (let ((target-line (line-number-at-pos))
920         (oldest-first notmuch-search-oldest-first)
921         (target-thread (notmuch-search-find-thread-id 'bare))
922         (query notmuch-search-query-string))
923     (notmuch-kill-this-buffer)
924     (notmuch-search query oldest-first target-thread target-line)
925     (goto-char (point-min))))
926
927 (defun notmuch-search-toggle-order ()
928   "Toggle the current search order.
929
930 This command toggles the sort order for the current search. The
931 default sort order is defined by `notmuch-search-oldest-first'."
932   (interactive)
933   (set 'notmuch-search-oldest-first (not notmuch-search-oldest-first))
934   (notmuch-search-refresh-view))
935
936 (defun notmuch-search-filter (query)
937   "Filter the current search results based on an additional query string.
938
939 Runs a new search matching only messages that match both the
940 current search results AND the additional query string provided."
941   (interactive (list (notmuch-read-query "Filter search: ")))
942   (let ((grouped-query (if (string-match-p notmuch-search-disjunctive-regexp query)
943                            (concat "( " query " )")
944                          query)))
945     (notmuch-search (if (string= notmuch-search-query-string "*")
946                         grouped-query
947                       (concat notmuch-search-query-string " and " grouped-query)) notmuch-search-oldest-first)))
948
949 (defun notmuch-search-filter-by-tag (tag)
950   "Filter the current search results based on a single tag.
951
952 Runs a new search matching only messages that match both the
953 current search results AND that are tagged with the given tag."
954   (interactive
955    (list (notmuch-select-tag-with-completion "Filter by tag: ")))
956   (notmuch-search (concat notmuch-search-query-string " and tag:" tag) notmuch-search-oldest-first))
957
958 ;;;###autoload
959 (defun notmuch ()
960   "Run notmuch and display saved searches, known tags, etc."
961   (interactive)
962   (notmuch-hello))
963
964 (defun notmuch-interesting-buffer (b)
965   "Is the current buffer of interest to a notmuch user?"
966   (with-current-buffer b
967     (memq major-mode '(notmuch-show-mode
968                        notmuch-search-mode
969                        notmuch-hello-mode
970                        message-mode))))
971
972 ;;;###autoload
973 (defun notmuch-cycle-notmuch-buffers ()
974   "Cycle through any existing notmuch buffers (search, show or hello).
975
976 If the current buffer is the only notmuch buffer, bury it. If no
977 notmuch buffers exist, run `notmuch'."
978   (interactive)
979
980   (let (start first)
981     ;; If the current buffer is a notmuch buffer, remember it and then
982     ;; bury it.
983     (when (notmuch-interesting-buffer (current-buffer))
984       (setq start (current-buffer))
985       (bury-buffer))
986
987     ;; Find the first notmuch buffer.
988     (setq first (loop for buffer in (buffer-list)
989                      if (notmuch-interesting-buffer buffer)
990                      return buffer))
991
992     (if first
993         ;; If the first one we found is any other than the starting
994         ;; buffer, switch to it.
995         (unless (eq first start)
996           (switch-to-buffer first))
997       (notmuch))))
998
999 (setq mail-user-agent 'notmuch-user-agent)
1000
1001 (provide 'notmuch)