1 ;;; notmuch-address.el --- address completion with notmuch
3 ;; Copyright © David Edmondson
5 ;; This file is part of Notmuch.
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.
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.
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/>.
20 ;; Authors: David Edmondson <dme@dme.org>
25 (require 'notmuch-parser)
26 (require 'notmuch-lib)
27 (require 'notmuch-company)
29 (declare-function company-manual-begin "company")
31 (defvar notmuch-address-last-harvest 0
32 "Time of last address harvest")
34 (defvar notmuch-address-completions (make-hash-table :test 'equal)
35 "Hash of email addresses for completion during email composition.
36 This variable is set by calling `notmuch-address-harvest'.")
38 (defvar notmuch-address-full-harvest-finished nil
39 "t indicates that full completion address harvesting has been
42 (defcustom notmuch-address-command '(sent nil)
43 "Determines how to generate address completion candidates.
45 If it is a string then that string should be an external program
46 which must take a single argument (searched string) and output a
47 list of completion candidates, one per line.
49 Alternatively, it can be a (non-nil) list, in which case internal
50 completion is used; in this case the list should have form
51 '(DIRECTION FILTER), where DIRECTION is either sent or received
52 and specifies whether the candidates are searched in messages
53 sent by the user or received by the user (note received by is
54 much faster), and FILTER is either nil or a filter-string, such
55 as \"date:1y..\" to append to the query.
57 If this variable is nil then address completion is disabled."
59 (list :tag "Use internal address completion"
61 :tag "Base completion on messages you have"
63 (const :tag "sent (more accurate)" sent)
64 (const :tag "received (faster)" received))
65 (radio :tag "Filter messages used for completion"
66 (const :tag "Use all messages" nil)
67 (string :tag "Filter query")))
68 (const :tag "Disable address completion" nil)
69 (string :tag "Use external completion command"))
70 ;; We override set so that we can clear the cache when this changes
71 :set (lambda (symbol value)
72 (set-default symbol value)
73 (setq notmuch-address-last-harvest 0)
74 (setq notmuch-address-completions (clrhash notmuch-address-completions))
75 (setq notmuch-address-full-harvest-finished nil))
77 :group 'notmuch-external)
79 (defcustom notmuch-address-selection-function 'notmuch-address-selection-function
80 "The function to select address from given list. The function is
81 called with PROMPT, COLLECTION, and INITIAL-INPUT as arguments
82 (subset of what `completing-read' can be called with).
83 While executed the value of `completion-ignore-case' is t.
84 See documentation of function `notmuch-address-selection-function'
85 to know how address selection is made by default."
88 :group 'notmuch-external)
90 (defun notmuch-address-selection-function (prompt collection initial-input)
91 "Call (`completing-read'
92 PROMPT COLLECTION nil nil INITIAL-INPUT 'notmuch-address-history)"
94 prompt collection nil nil initial-input 'notmuch-address-history))
96 (defvar notmuch-address-completion-headers-regexp
97 "^\\(Resent-\\)?\\(To\\|B?Cc\\|Reply-To\\|From\\|Mail-Followup-To\\|Mail-Copies-To\\):")
99 (defvar notmuch-address-history nil)
101 (defun notmuch-address-message-insinuate ()
102 (message "calling notmuch-address-message-insinuate is no longer needed"))
104 (defcustom notmuch-address-use-company t
105 "If available, use company mode for address completion"
107 :group 'notmuch-send)
109 (defun notmuch-address-setup ()
110 (let* ((use-company (and notmuch-address-use-company
111 notmuch-address-command
112 (listp notmuch-address-command)
113 (require 'company nil t)))
114 (pair (cons notmuch-address-completion-headers-regexp
116 #'company-manual-begin
117 #'notmuch-address-expand-name))))
119 (notmuch-company-setup))
120 (unless (memq pair message-completion-alist)
121 (setq message-completion-alist
122 (push pair message-completion-alist)))))
124 (defun notmuch-address-matching (substring)
125 "Returns a list of completion candidates matching SUBSTRING.
126 The candidates are taken from `notmuch-address-completions'."
128 (re (regexp-quote substring)))
129 (maphash (lambda (key val)
130 (when (string-match re key)
131 (push key candidates)))
132 notmuch-address-completions)
135 (defun notmuch-address-options (original)
136 "Returns a list of completion candidates. Uses either
137 elisp-based implementation or older implementation requiring
140 ((and notmuch-address-command (listp notmuch-address-command))
141 (when (not notmuch-address-full-harvest-finished)
142 ;; First, run quick synchronous harvest based on what the user
144 (notmuch-address-harvest original t))
145 (prog1 (notmuch-address-matching original)
146 ;; Then start the (potentially long-running) full asynchronous harvest if necessary
147 (notmuch-address-harvest-trigger)))
149 (process-lines notmuch-address-command original))))
151 (defun notmuch-address-expand-name ()
152 (when notmuch-address-command
155 (re-search-backward "\\(\\`\\|[\n:,]\\)[ \t]*")
156 (goto-char (match-end 0))
158 (orig (buffer-substring-no-properties beg end))
159 (completion-ignore-case t)
160 (options (with-temp-message "Looking for completion candidates..."
161 (notmuch-address-options orig)))
162 (num-options (length options))
169 (funcall notmuch-address-selection-function
170 (format "Address (%s matches): " num-options)
171 (cdr options) (car options))))))
174 (push chosen notmuch-address-history)
175 (delete-region beg end)
177 (message "No matches.")
180 ;; Copied from `w3m-which-command'.
181 (defun notmuch-address-locate-command (command)
182 "Return non-nil if `command' is an executable either on
183 `exec-path' or an absolute pathname."
184 (when (stringp command)
185 (if (and (file-name-absolute-p command)
186 (file-executable-p command))
188 (setq command (file-name-nondirectory command))
189 (catch 'found-command
191 (dolist (dir exec-path)
192 (setq bin (expand-file-name command dir))
193 (when (or (and (file-executable-p bin)
194 (not (file-directory-p bin)))
195 (and (file-executable-p (setq bin (concat bin ".exe")))
196 (not (file-directory-p bin))))
197 (throw 'found-command bin))))))))
199 (defun notmuch-address-harvest-addr (result)
200 (let ((name-addr (plist-get result :name-addr)))
201 (puthash name-addr t notmuch-address-completions)))
203 (defun notmuch-address-harvest-handle-result (obj)
204 (notmuch-address-harvest-addr obj))
206 (defun notmuch-address-harvest-filter (proc string)
207 (when (buffer-live-p (process-buffer proc))
208 (with-current-buffer (process-buffer proc)
210 (goto-char (point-max))
212 (notmuch-sexp-parse-partial-list
213 'notmuch-address-harvest-handle-result (process-buffer proc)))))
215 (defvar notmuch-address-harvest-procs '(nil . nil)
216 "The currently running harvests.
218 The car is a partial harvest, and the cdr is a full harvest")
220 (defun notmuch-address-harvest (&optional addr-prefix synchronous callback)
221 "Collect addresses completion candidates.
223 It queries the notmuch database for messages sent/received (as
224 configured with `notmuch-address-command`) by the user, collects
225 destination/source addresses from those messages and stores them
226 in `notmuch-address-completions'.
228 If ADDR-PREFIX is not nil, only messages with to/from addresses
229 matching ADDR-PREFIX*' are queried.
231 Address harvesting may take some time so the address collection runs
232 asynchronously unless SYNCHRONOUS is t. In case of asynchronous
233 execution, CALLBACK is called when harvesting finishes."
235 (let* ((sent (eq (car notmuch-address-command) 'sent))
236 (config-query (cadr notmuch-address-command))
237 (prefix-query (when addr-prefix
238 (format "%s:%s*" (if sent "to" "from") addr-prefix)))
240 (mapconcat (lambda (x)
241 (concat (if sent "from:" "to:") x))
242 (notmuch-user-emails) " or "))
243 (query (if (or prefix-query config-query)
244 (concat (format "(%s)" from-or-to-me-query)
246 (format " and (%s)" prefix-query))
248 (format " and (%s)" config-query)))
249 from-or-to-me-query))
250 (args `("address" "--format=sexp" "--format-version=2"
251 ,(if sent "--output=recipients" "--output=sender")
252 "--deduplicate=address"
255 (mapc #'notmuch-address-harvest-addr
256 (apply 'notmuch-call-notmuch-sexp args))
258 (let* ((current-proc (if addr-prefix
259 (car notmuch-address-harvest-procs)
260 (cdr notmuch-address-harvest-procs)))
261 (proc-name (format "notmuch-address-%s-harvest"
262 (if addr-prefix "partial" "full")))
263 (proc-buf (concat " *" proc-name "*")))
264 ;; Kill any existing process
266 (kill-buffer (process-buffer current-proc))) ; this also kills the process
269 (apply 'notmuch-start-notmuch proc-name proc-buf
270 callback ; process sentinel
272 (set-process-filter current-proc 'notmuch-address-harvest-filter)
273 (set-process-query-on-exit-flag current-proc nil)
275 (setcar notmuch-address-harvest-procs current-proc)
276 (setcdr notmuch-address-harvest-procs current-proc)))))
280 (defun notmuch-address-harvest-trigger ()
281 (let ((now (float-time)))
282 (when (> (- now notmuch-address-last-harvest) 86400)
283 (setq notmuch-address-last-harvest now)
284 (notmuch-address-harvest nil nil
286 ;; If harvest fails, we want to try
287 ;; again when the trigger is next
289 (if (string= event "finished\n")
290 (setq notmuch-address-full-harvest-finished t)
291 (setq notmuch-address-last-harvest 0)))))))
295 (provide 'notmuch-address)
297 ;;; notmuch-address.el ends here