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