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