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