1 ;;; notmuch-address.el --- address completion with notmuch -*- lexical-binding: t -*-
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 <https://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")
33 (defvar notmuch-address-last-harvest 0
34 "Time of last address harvest.")
36 (defvar notmuch-address-completions (make-hash-table :test 'equal)
37 "Hash of email addresses for completion during email composition.
38 This variable is set by calling `notmuch-address-harvest'.")
40 (defvar notmuch-address-full-harvest-finished nil
41 "Whether full completion address harvesting has finished.
42 Use `notmuch-address--harvest-ready' to access as that will load
43 a saved hash if necessary (and available).")
45 (defun notmuch-address--harvest-ready ()
46 "Return t if there is a full address hash available.
48 If the hash is not present it attempts to load a saved hash."
49 (or notmuch-address-full-harvest-finished
50 (notmuch-address--load-address-hash)))
54 (defcustom notmuch-address-command 'internal
55 "Determines how address completion candidates are generated.
57 If it is a string then that string should be an external program
58 which must take a single argument (searched string) and output a
59 list of completion candidates, one per line.
61 Alternatively, it can be the symbol `internal', in which case
62 internal completion is used; the variable
63 `notmuch-address-internal-completion' can be used to customize
66 Finally, if this variable is nil then address completion is
69 (const :tag "Use internal address completion" internal)
70 (const :tag "Disable address completion" nil)
71 (string :tag "Use external completion command"))
73 :group 'notmuch-address
74 :group 'notmuch-external)
76 (defcustom notmuch-address-internal-completion '(sent nil)
77 "Determines how internal address completion generates candidates.
79 This should be a list of the form (DIRECTION FILTER), where
80 DIRECTION is either sent or received and specifies whether the
81 candidates are searched in messages sent by the user or received
82 by the user (note received by is much faster), and FILTER is
83 either nil or a filter-string, such as \"date:1y..\" to append to
85 :type '(list :tag "Use internal address completion"
87 :tag "Base completion on messages you have"
89 (const :tag "sent (more accurate)" sent)
90 (const :tag "received (faster)" received))
91 (radio :tag "Filter messages used for completion"
92 (const :tag "Use all messages" nil)
93 (string :tag "Filter query")))
94 ;; We override set so that we can clear the cache when this changes
95 :set (lambda (symbol value)
96 (set-default symbol value)
97 (setq notmuch-address-last-harvest 0)
98 (setq notmuch-address-completions (clrhash notmuch-address-completions))
99 (setq notmuch-address-full-harvest-finished nil))
101 :group 'notmuch-address
102 :group 'notmuch-external)
104 (defcustom notmuch-address-save-filename nil
105 "Filename to save the cached completion addresses.
107 All the addresses notmuch uses for address completion will be
108 cached in this file. This has obvious privacy implications so
109 you should make sure it is not somewhere publicly readable."
110 :type '(choice (const :tag "Off" nil)
111 (file :tag "Filename"))
113 :group 'notmuch-address
114 :group 'notmuch-external)
116 (defcustom notmuch-address-selection-function 'notmuch-address-selection-function
117 "The function to select address from given list.
119 The function is called with PROMPT, COLLECTION, and INITIAL-INPUT
120 as arguments (subset of what `completing-read' can be called
121 with). While executed the value of `completion-ignore-case'
122 is t. See documentation of function
123 `notmuch-address-selection-function' to know how address
124 selection is made by default."
127 :group 'notmuch-address
128 :group 'notmuch-external)
130 (defcustom notmuch-address-post-completion-functions nil
131 "Functions called after completing address.
133 The completed address is passed as an argument to each function.
134 Note that this hook will be invoked for completion in headers
135 matching `notmuch-address-completion-headers-regexp'."
137 :group 'notmuch-address
138 :group 'notmuch-hooks)
140 (defcustom notmuch-address-use-company t
141 "If available, use company mode for address completion."
144 :group 'notmuch-address)
148 (defun notmuch-address-selection-function (prompt collection initial-input)
149 "Call (`completing-read'
150 PROMPT COLLECTION nil nil INITIAL-INPUT 'notmuch-address-history)"
152 prompt collection nil nil initial-input 'notmuch-address-history))
154 (defvar notmuch-address-completion-headers-regexp
155 "^\\(Resent-\\)?\\(To\\|B?Cc\\|Reply-To\\|From\\|Mail-Followup-To\\|Mail-Copies-To\\):")
157 (defvar notmuch-address-history nil)
159 (defun notmuch-address-message-insinuate ()
160 (message "calling notmuch-address-message-insinuate is no longer needed"))
162 (defun notmuch-address-setup ()
163 (when (and notmuch-address-use-company
164 (require 'company nil t))
165 (notmuch-company-setup))
166 (cl-pushnew (cons notmuch-address-completion-headers-regexp
167 #'notmuch-address-expand-name)
168 message-completion-alist :test #'equal))
170 (defun notmuch-address-toggle-internal-completion ()
171 "Toggle use of internal completion for current buffer.
173 This overrides the global setting for address completion and
174 toggles the setting in this buffer."
176 (if (local-variable-p 'notmuch-address-command)
177 (kill-local-variable 'notmuch-address-command)
178 (setq-local notmuch-address-command 'internal))
179 (when (boundp 'company-idle-delay)
180 (if (local-variable-p 'company-idle-delay)
181 (kill-local-variable 'company-idle-delay)
182 (setq-local company-idle-delay nil))))
186 (defun notmuch-address-matching (substring)
187 "Returns a list of completion candidates matching SUBSTRING.
188 The candidates are taken from `notmuch-address-completions'."
190 (re (regexp-quote substring)))
191 (maphash (lambda (key _val)
192 (when (string-match re key)
193 (push key candidates)))
194 notmuch-address-completions)
197 (defun notmuch-address-options (original)
198 "Return a list of completion candidates.
199 Use either elisp-based implementation or older implementation
200 requiring external commands."
202 ((eq notmuch-address-command 'internal)
203 (unless (notmuch-address--harvest-ready)
204 ;; First, run quick synchronous harvest based on what the user
206 (notmuch-address-harvest original t))
207 (prog1 (notmuch-address-matching original)
208 ;; Then start the (potentially long-running) full asynchronous
209 ;; harvest if necessary.
210 (notmuch-address-harvest-trigger)))
212 (process-lines notmuch-address-command original))))
214 (defun notmuch-address-expand-name ()
216 ((and (eq notmuch-address-command 'internal)
217 notmuch-address-use-company
218 (bound-and-true-p company-mode))
219 (company-manual-begin))
220 (notmuch-address-command
223 (re-search-backward "\\(\\`\\|[\n:,]\\)[ \t]*")
224 (goto-char (match-end 0))
226 (orig (buffer-substring-no-properties beg end))
227 (completion-ignore-case t)
228 (options (with-temp-message "Looking for completion candidates..."
229 (notmuch-address-options orig)))
230 (num-options (length options))
237 (funcall notmuch-address-selection-function
238 (format "Address (%s matches): " num-options)
239 ;; We put the first match as the initial
240 ;; input; we put all the matches as
241 ;; possible completions, moving the
242 ;; first match to the end of the list
243 ;; makes cursor up/down in the list work
245 (append (cdr options) (list (car options)))
249 (push chosen notmuch-address-history)
250 (delete-region beg end)
252 (run-hook-with-args 'notmuch-address-post-completion-functions
254 (message "No matches.")
260 (defun notmuch-address-harvest-addr (result)
261 (puthash (plist-get result :name-addr)
262 t notmuch-address-completions))
264 (defun notmuch-address-harvest-filter (proc string)
265 (when (buffer-live-p (process-buffer proc))
266 (with-current-buffer (process-buffer proc)
268 (goto-char (point-max))
270 (notmuch-sexp-parse-partial-list
271 'notmuch-address-harvest-addr (process-buffer proc)))))
273 (defvar notmuch-address-harvest-procs '(nil . nil)
274 "The currently running harvests.
276 The car is a partial harvest, and the cdr is a full harvest.")
278 (defun notmuch-address-harvest (&optional addr-prefix synchronous callback)
279 "Collect addresses completion candidates.
281 It queries the notmuch database for messages sent/received (as
282 configured with `notmuch-address-command') by the user, collects
283 destination/source addresses from those messages and stores them
284 in `notmuch-address-completions'.
286 If ADDR-PREFIX is not nil, only messages with to/from addresses
287 matching ADDR-PREFIX*' are queried.
289 Address harvesting may take some time so the address collection runs
290 asynchronously unless SYNCHRONOUS is t. In case of asynchronous
291 execution, CALLBACK is called when harvesting finishes."
292 (let* ((sent (eq (car notmuch-address-internal-completion) 'sent))
293 (config-query (cadr notmuch-address-internal-completion))
294 (prefix-query (and addr-prefix
296 (if sent "to" "from")
299 (mapconcat (lambda (x)
300 (concat (if sent "from:" "to:") x))
301 (notmuch-user-emails) " or "))
302 (query (if (or prefix-query config-query)
303 (concat (format "(%s)" from-or-to-me-query)
305 (format " and (%s)" prefix-query))
307 (format " and (%s)" config-query)))
308 from-or-to-me-query))
309 (args `("address" "--format=sexp" "--format-version=4"
310 ,(if sent "--output=recipients" "--output=sender")
311 "--deduplicate=address"
314 (mapc #'notmuch-address-harvest-addr
315 (apply 'notmuch-call-notmuch-sexp args))
317 (let* ((current-proc (if addr-prefix
318 (car notmuch-address-harvest-procs)
319 (cdr notmuch-address-harvest-procs)))
320 (proc-name (format "notmuch-address-%s-harvest"
321 (if addr-prefix "partial" "full")))
322 (proc-buf (concat " *" proc-name "*")))
323 ;; Kill any existing process
325 (kill-buffer (process-buffer current-proc))) ; this also kills the process
327 (apply 'notmuch-start-notmuch proc-name proc-buf
328 callback ; process sentinel
330 (set-process-filter current-proc 'notmuch-address-harvest-filter)
331 (set-process-query-on-exit-flag current-proc nil)
333 (setcar notmuch-address-harvest-procs current-proc)
334 (setcdr notmuch-address-harvest-procs current-proc)))))
338 (defvar notmuch-address--save-hash-version 1
339 "Version format of the save hash.")
341 (defun notmuch-address--get-address-hash ()
342 "Return the saved address hash as a plist.
344 Returns nil if the save file does not exist, or it does not seem
345 to be a saved address hash."
346 (and notmuch-address-save-filename
349 (insert-file-contents notmuch-address-save-filename)
350 (let ((name (read (current-buffer)))
351 (plist (read (current-buffer))))
352 ;; We do two simple sanity checks on the loaded file.
353 ;; We just check a version is specified, not that
354 ;; it is the current version, as we are allowed to
355 ;; over-write and a save-file with an older version.
356 (and (string= name "notmuch-address-hash")
357 (plist-get plist :version)
359 ;; The error case catches any of the reads failing.
362 (defun notmuch-address--load-address-hash ()
363 "Read the saved address hash and set the corresponding variables."
364 (let ((load-plist (notmuch-address--get-address-hash)))
365 (when (and load-plist
366 ;; If the user's setting have changed, or the version
367 ;; has changed, return nil to make sure the new settings
369 (equal (plist-get load-plist :completion-settings)
370 notmuch-address-internal-completion)
371 (equal (plist-get load-plist :version)
372 notmuch-address--save-hash-version))
373 (setq notmuch-address-last-harvest (plist-get load-plist :last-harvest))
374 (setq notmuch-address-completions (plist-get load-plist :completions))
375 (setq notmuch-address-full-harvest-finished t)
376 ;; Return t to say load was successful.
379 (defun notmuch-address--save-address-hash ()
380 (when notmuch-address-save-filename
381 (if (or (not (file-exists-p notmuch-address-save-filename))
382 ;; The file exists, check it is a file we saved.
383 (notmuch-address--get-address-hash))
384 (with-temp-file notmuch-address-save-filename
386 (list :version notmuch-address--save-hash-version
387 :completion-settings notmuch-address-internal-completion
388 :last-harvest notmuch-address-last-harvest
389 :completions notmuch-address-completions)))
390 (print "notmuch-address-hash" (current-buffer))
391 (print save-plist (current-buffer))))
393 Warning: notmuch-address-save-filename %s exists but doesn't
394 appear to be an address savefile. Not overwriting."
395 notmuch-address-save-filename))))
397 (defun notmuch-address-harvest-trigger ()
398 (let ((now (float-time)))
399 (when (> (- now notmuch-address-last-harvest) 86400)
400 (setq notmuch-address-last-harvest now)
401 (notmuch-address-harvest
403 (lambda (_proc event)
404 ;; If harvest fails, we want to try
405 ;; again when the trigger is next called.
406 (if (string= event "finished\n")
408 (notmuch-address--save-address-hash)
409 (setq notmuch-address-full-harvest-finished t))
410 (setq notmuch-address-last-harvest 0)))))))
412 ;;; Standalone completion
414 (defun notmuch-address-from-minibuffer (prompt)
415 (if (not notmuch-address-command)
417 (let ((rmap (copy-keymap minibuffer-local-map))
418 (omap minibuffer-local-map))
419 ;; Configure TAB to start completion when executing read-string.
420 ;; "Original" minibuffer keymap is restored just before calling
421 ;; notmuch-address-expand-name as it may also use minibuffer-local-map
422 ;; (completing-read probably does not but if something else is used there).
423 (define-key rmap (kbd "TAB") (lambda ()
425 (let ((enable-recursive-minibuffers t)
426 (minibuffer-local-map omap))
427 (notmuch-address-expand-name))))
428 (let ((minibuffer-local-map rmap))
429 (read-string prompt)))))
433 (provide 'notmuch-address)
435 ;;; notmuch-address.el ends here