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