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 <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")
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 'internal
43 "Determines how address completion candidates are generated.
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 the symbol 'internal, in which case
50 internal completion is used; the variable
51 `notmuch-address-internal-completion` can be used to customize
54 Finally, if this variable is nil then address completion is
57 (const :tag "Use internal address completion" internal)
58 (const :tag "Disable address completion" nil)
59 (string :tag "Use external completion command"))
61 :group 'notmuch-external)
63 (defcustom notmuch-address-internal-completion '(sent nil)
64 "Determines how internal address completion generates candidates.
66 This should be a list of the form '(DIRECTION FILTER), where
67 DIRECTION is either sent or received and specifies whether the
68 candidates are searched in messages sent by the user or received
69 by the user (note received by is much faster), and FILTER is
70 either nil or a filter-string, such as \"date:1y..\" to append
72 :type '(list :tag "Use internal address completion"
74 :tag "Base completion on messages you have"
76 (const :tag "sent (more accurate)" sent)
77 (const :tag "received (faster)" received))
78 (radio :tag "Filter messages used for completion"
79 (const :tag "Use all messages" nil)
80 (string :tag "Filter query")))
81 ;; We override set so that we can clear the cache when this changes
82 :set (lambda (symbol value)
83 (set-default symbol value)
84 (setq notmuch-address-last-harvest 0)
85 (setq notmuch-address-completions (clrhash notmuch-address-completions))
86 (setq notmuch-address-full-harvest-finished nil))
88 :group 'notmuch-external)
90 (defcustom notmuch-address-selection-function 'notmuch-address-selection-function
91 "The function to select address from given list. The function is
92 called with PROMPT, COLLECTION, and INITIAL-INPUT as arguments
93 (subset of what `completing-read' can be called with).
94 While executed the value of `completion-ignore-case' is t.
95 See documentation of function `notmuch-address-selection-function'
96 to know how address selection is made by default."
99 :group 'notmuch-external)
101 (defun notmuch-address-selection-function (prompt collection initial-input)
102 "Call (`completing-read'
103 PROMPT COLLECTION nil nil INITIAL-INPUT 'notmuch-address-history)"
105 prompt collection nil nil initial-input 'notmuch-address-history))
107 (defvar notmuch-address-completion-headers-regexp
108 "^\\(Resent-\\)?\\(To\\|B?Cc\\|Reply-To\\|From\\|Mail-Followup-To\\|Mail-Copies-To\\):")
110 (defvar notmuch-address-history nil)
112 (defun notmuch-address-message-insinuate ()
113 (message "calling notmuch-address-message-insinuate is no longer needed"))
115 (defcustom notmuch-address-use-company t
116 "If available, use company mode for address completion"
118 :group 'notmuch-send)
120 (defun notmuch-address-setup ()
121 (let* ((use-company (and notmuch-address-use-company
122 (eq notmuch-address-command 'internal)
123 (require 'company nil t)))
124 (pair (cons notmuch-address-completion-headers-regexp
125 #'notmuch-address-expand-name)))
127 (notmuch-company-setup))
128 (unless (memq pair message-completion-alist)
129 (setq message-completion-alist
130 (push pair message-completion-alist)))))
132 (defun notmuch-address-matching (substring)
133 "Returns a list of completion candidates matching SUBSTRING.
134 The candidates are taken from `notmuch-address-completions'."
136 (re (regexp-quote substring)))
137 (maphash (lambda (key val)
138 (when (string-match re key)
139 (push key candidates)))
140 notmuch-address-completions)
143 (defun notmuch-address-options (original)
144 "Returns a list of completion candidates. Uses either
145 elisp-based implementation or older implementation requiring
148 ((eq notmuch-address-command 'internal)
149 (when (not notmuch-address-full-harvest-finished)
150 ;; First, run quick synchronous harvest based on what the user
152 (notmuch-address-harvest original t))
153 (prog1 (notmuch-address-matching original)
154 ;; Then start the (potentially long-running) full asynchronous harvest if necessary
155 (notmuch-address-harvest-trigger)))
157 (process-lines notmuch-address-command original))))
159 (defun notmuch-address-expand-name ()
161 ((and (eq notmuch-address-command 'internal)
162 notmuch-address-use-company
163 (bound-and-true-p company-mode))
164 (company-manual-begin))
165 (notmuch-address-command
168 (re-search-backward "\\(\\`\\|[\n:,]\\)[ \t]*")
169 (goto-char (match-end 0))
171 (orig (buffer-substring-no-properties beg end))
172 (completion-ignore-case t)
173 (options (with-temp-message "Looking for completion candidates..."
174 (notmuch-address-options orig)))
175 (num-options (length options))
182 (funcall notmuch-address-selection-function
183 (format "Address (%s matches): " num-options)
184 (cdr options) (car options))))))
187 (push chosen notmuch-address-history)
188 (delete-region beg end)
190 (message "No matches.")
194 ;; Copied from `w3m-which-command'.
195 (defun notmuch-address-locate-command (command)
196 "Return non-nil if `command' is an executable either on
197 `exec-path' or an absolute pathname."
198 (when (stringp command)
199 (if (and (file-name-absolute-p command)
200 (file-executable-p command))
202 (setq command (file-name-nondirectory command))
203 (catch 'found-command
205 (dolist (dir exec-path)
206 (setq bin (expand-file-name command dir))
207 (when (or (and (file-executable-p bin)
208 (not (file-directory-p bin)))
209 (and (file-executable-p (setq bin (concat bin ".exe")))
210 (not (file-directory-p bin))))
211 (throw 'found-command bin))))))))
213 (defun notmuch-address-harvest-addr (result)
214 (let ((name-addr (plist-get result :name-addr)))
215 (puthash name-addr t notmuch-address-completions)))
217 (defun notmuch-address-harvest-handle-result (obj)
218 (notmuch-address-harvest-addr obj))
220 (defun notmuch-address-harvest-filter (proc string)
221 (when (buffer-live-p (process-buffer proc))
222 (with-current-buffer (process-buffer proc)
224 (goto-char (point-max))
226 (notmuch-sexp-parse-partial-list
227 'notmuch-address-harvest-handle-result (process-buffer proc)))))
229 (defvar notmuch-address-harvest-procs '(nil . nil)
230 "The currently running harvests.
232 The car is a partial harvest, and the cdr is a full harvest")
234 (defun notmuch-address-harvest (&optional addr-prefix synchronous callback)
235 "Collect addresses completion candidates.
237 It queries the notmuch database for messages sent/received (as
238 configured with `notmuch-address-command`) by the user, collects
239 destination/source addresses from those messages and stores them
240 in `notmuch-address-completions'.
242 If ADDR-PREFIX is not nil, only messages with to/from addresses
243 matching ADDR-PREFIX*' are queried.
245 Address harvesting may take some time so the address collection runs
246 asynchronously unless SYNCHRONOUS is t. In case of asynchronous
247 execution, CALLBACK is called when harvesting finishes."
249 (let* ((sent (eq (car notmuch-address-internal-completion) 'sent))
250 (config-query (cadr notmuch-address-internal-completion))
251 (prefix-query (when addr-prefix
252 (format "%s:%s*" (if sent "to" "from") addr-prefix)))
254 (mapconcat (lambda (x)
255 (concat (if sent "from:" "to:") x))
256 (notmuch-user-emails) " or "))
257 (query (if (or prefix-query config-query)
258 (concat (format "(%s)" from-or-to-me-query)
260 (format " and (%s)" prefix-query))
262 (format " and (%s)" config-query)))
263 from-or-to-me-query))
264 (args `("address" "--format=sexp" "--format-version=2"
265 ,(if sent "--output=recipients" "--output=sender")
266 "--deduplicate=address"
269 (mapc #'notmuch-address-harvest-addr
270 (apply 'notmuch-call-notmuch-sexp args))
272 (let* ((current-proc (if addr-prefix
273 (car notmuch-address-harvest-procs)
274 (cdr notmuch-address-harvest-procs)))
275 (proc-name (format "notmuch-address-%s-harvest"
276 (if addr-prefix "partial" "full")))
277 (proc-buf (concat " *" proc-name "*")))
278 ;; Kill any existing process
280 (kill-buffer (process-buffer current-proc))) ; this also kills the process
283 (apply 'notmuch-start-notmuch proc-name proc-buf
284 callback ; process sentinel
286 (set-process-filter current-proc 'notmuch-address-harvest-filter)
287 (set-process-query-on-exit-flag current-proc nil)
289 (setcar notmuch-address-harvest-procs current-proc)
290 (setcdr notmuch-address-harvest-procs current-proc)))))
294 (defun notmuch-address-harvest-trigger ()
295 (let ((now (float-time)))
296 (when (> (- now notmuch-address-last-harvest) 86400)
297 (setq notmuch-address-last-harvest now)
298 (notmuch-address-harvest nil nil
300 ;; If harvest fails, we want to try
301 ;; again when the trigger is next
303 (if (string= event "finished\n")
304 (setq notmuch-address-full-harvest-finished t)
305 (setq notmuch-address-last-harvest 0)))))))
309 (defun notmuch-address-from-minibuffer (prompt)
310 (if (not notmuch-address-command)
312 (let ((rmap (copy-keymap minibuffer-local-map))
313 (omap minibuffer-local-map))
314 ;; Configure TAB to start completion when executing read-string.
315 ;; "Original" minibuffer keymap is restored just before calling
316 ;; notmuch-address-expand-name as it may also use minibuffer-local-map
317 ;; (completing-read probably does not but if something else is used there).
318 (define-key rmap (kbd "TAB") (lambda ()
320 (let ((enable-recursive-minibuffers t)
321 (minibuffer-local-map omap))
322 (notmuch-address-expand-name))))
323 (let ((minibuffer-local-map rmap))
324 (read-string prompt)))))
328 (provide 'notmuch-address)
330 ;;; notmuch-address.el ends here