]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-address.el
emacs: allow opting out of notmuch's address completion
[notmuch] / emacs / notmuch-address.el
1 ;;; notmuch-address.el --- address completion with notmuch  -*- lexical-binding: t -*-
2 ;;
3 ;; Copyright © David Edmondson
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: David Edmondson <dme@dme.org>
21
22 ;;; Code:
23
24 (require 'message)
25 (require 'notmuch-parser)
26 (require 'notmuch-lib)
27 (require 'notmuch-company)
28
29 (declare-function company-manual-begin "company")
30
31 ;;; Cache internals
32
33 (defvar notmuch-address-last-harvest 0
34   "Time of last address harvest.")
35
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'.")
39
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).")
44
45 (defun notmuch-address--harvest-ready ()
46   "Return t if there is a full address hash available.
47
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)))
51
52 ;;; Options
53
54 (defcustom notmuch-address-command 'internal
55   "Determines how address completion candidates are generated.
56
57 If this is a string, then that string should be an external
58 program, which must take a single argument (searched string)
59 and output a list of completion candidates, one per line.
60
61 If this is the symbol `internal', then an implementation is used
62 that relies on the \"notmuch address\" command, but does not use
63 any third-party (i.e. \"external\") programs.
64
65 If this is the symbol `as-is', then Notmuch does not modify the
66 value of `message-completion-alist'. This option has to be set to
67 this value before `notmuch' is loaded, otherwise the modification
68 to `message-completion-alist' may already have taken place. This
69 setting obviously does not prevent `message-completion-alist'
70 from being modified at all; the user or some third-party package
71 may still modify it.
72
73 Finally, if this is nil, then address completion is disabled."
74   :type '(radio
75           (const  :tag "Use internal address completion" internal)
76           (string :tag "Use external completion command")
77           (const  :tag "Disable address completion" nil)
78           (const  :tag "Use default or third-party mechanism" as-is))
79   :group 'notmuch-send
80   :group 'notmuch-address
81   :group 'notmuch-external)
82
83 (defcustom notmuch-address-internal-completion '(sent nil)
84   "Determines how internal address completion generates candidates.
85
86 This should be a list of the form (DIRECTION FILTER), where
87 DIRECTION is either sent or received and specifies whether the
88 candidates are searched in messages sent by the user or received
89 by the user (note received by is much faster), and FILTER is
90 either nil or a filter-string, such as \"date:1y..\" to append to
91 the query."
92   :type '(list :tag "Use internal address completion"
93                (radio
94                 :tag "Base completion on messages you have"
95                 :value sent
96                 (const :tag "sent (more accurate)" sent)
97                 (const :tag "received (faster)" received))
98                (radio :tag "Filter messages used for completion"
99                       (const :tag "Use all messages" nil)
100                       (string :tag "Filter query")))
101   ;; We override set so that we can clear the cache when this changes
102   :set (lambda (symbol value)
103          (set-default symbol value)
104          (setq notmuch-address-last-harvest 0)
105          (setq notmuch-address-completions (clrhash notmuch-address-completions))
106          (setq notmuch-address-full-harvest-finished nil))
107   :group 'notmuch-send
108   :group 'notmuch-address
109   :group 'notmuch-external)
110
111 (defcustom notmuch-address-save-filename nil
112   "Filename to save the cached completion addresses.
113
114 All the addresses notmuch uses for address completion will be
115 cached in this file.  This has obvious privacy implications so
116 you should make sure it is not somewhere publicly readable."
117   :type '(choice (const :tag "Off" nil)
118                  (file :tag "Filename"))
119   :group 'notmuch-send
120   :group 'notmuch-address
121   :group 'notmuch-external)
122
123 (defcustom notmuch-address-selection-function 'notmuch-address-selection-function
124   "The function to select address from given list.
125
126 The function is called with PROMPT, COLLECTION, and INITIAL-INPUT
127 as arguments (subset of what `completing-read' can be called
128 with).  While executed the value of `completion-ignore-case'
129 is t.  See documentation of function
130 `notmuch-address-selection-function' to know how address
131 selection is made by default."
132   :type 'function
133   :group 'notmuch-send
134   :group 'notmuch-address
135   :group 'notmuch-external)
136
137 (defcustom notmuch-address-post-completion-functions nil
138   "Functions called after completing address.
139
140 The completed address is passed as an argument to each function.
141 Note that this hook will be invoked for completion in headers
142 matching `notmuch-address-completion-headers-regexp'."
143   :type 'hook
144   :group 'notmuch-address
145   :group 'notmuch-hooks)
146
147 (defcustom notmuch-address-use-company t
148   "If available, use company mode for address completion."
149   :type 'boolean
150   :group 'notmuch-send
151   :group 'notmuch-address)
152
153 ;;; Setup
154
155 (defun notmuch-address-selection-function (prompt collection initial-input)
156   "Call (`completing-read'
157       PROMPT COLLECTION nil nil INITIAL-INPUT 'notmuch-address-history)"
158   (completing-read
159    prompt collection nil nil initial-input 'notmuch-address-history))
160
161 (defvar notmuch-address-completion-headers-regexp
162   "^\\(Resent-\\)?\\(To\\|B?Cc\\|Reply-To\\|From\\|Mail-Followup-To\\|Mail-Copies-To\\):")
163
164 (defvar notmuch-address-history nil)
165
166 (defun notmuch-address-message-insinuate ()
167   (message "calling notmuch-address-message-insinuate is no longer needed"))
168
169 (defun notmuch-address-setup ()
170   (unless (eq notmuch-address-command 'as-is)
171     (when (and notmuch-address-use-company
172                (require 'company nil t))
173       (notmuch-company-setup))
174     (cl-pushnew (cons notmuch-address-completion-headers-regexp
175                       #'notmuch-address-expand-name)
176                 message-completion-alist :test #'equal)))
177
178 (defun notmuch-address-toggle-internal-completion ()
179   "Toggle use of internal completion for current buffer.
180
181 This overrides the global setting for address completion and
182 toggles the setting in this buffer."
183   (interactive)
184   (if (local-variable-p 'notmuch-address-command)
185       (kill-local-variable 'notmuch-address-command)
186     (setq-local notmuch-address-command 'internal))
187   (when (boundp 'company-idle-delay)
188     (if (local-variable-p 'company-idle-delay)
189         (kill-local-variable 'company-idle-delay)
190       (setq-local company-idle-delay nil))))
191
192 ;;; Completion
193
194 (defun notmuch-address-matching (substring)
195   "Returns a list of completion candidates matching SUBSTRING.
196 The candidates are taken from `notmuch-address-completions'."
197   (let ((candidates)
198         (re (regexp-quote substring)))
199     (maphash (lambda (key _val)
200                (when (string-match re key)
201                  (push key candidates)))
202              notmuch-address-completions)
203     candidates))
204
205 (defun notmuch-address-options (original)
206   "Return a list of completion candidates.
207 Use either elisp-based implementation or older implementation
208 requiring external commands."
209   (cond
210    ((eq notmuch-address-command 'internal)
211     (unless (notmuch-address--harvest-ready)
212       ;; First, run quick synchronous harvest based on what the user
213       ;; entered so far.
214       (notmuch-address-harvest original t))
215     (prog1 (notmuch-address-matching original)
216       ;; Then start the (potentially long-running) full asynchronous
217       ;; harvest if necessary.
218       (notmuch-address-harvest-trigger)))
219    (t
220     (process-lines notmuch-address-command original))))
221
222 (defun notmuch-address-expand-name ()
223   (cond
224    ((and (eq notmuch-address-command 'internal)
225          notmuch-address-use-company
226          (bound-and-true-p company-mode))
227     (company-manual-begin))
228    (notmuch-address-command
229     (let* ((end (point))
230            (beg (save-excursion
231                   (re-search-backward "\\(\\`\\|[\n:,]\\)[ \t]*")
232                   (goto-char (match-end 0))
233                   (point)))
234            (orig (buffer-substring-no-properties beg end))
235            (completion-ignore-case t)
236            (options (with-temp-message "Looking for completion candidates..."
237                       (notmuch-address-options orig)))
238            (num-options (length options))
239            (chosen (cond
240                     ((eq num-options 0)
241                      nil)
242                     ((eq num-options 1)
243                      (car options))
244                     (t
245                      (funcall notmuch-address-selection-function
246                               (format "Address (%s matches): " num-options)
247                               ;; We put the first match as the initial
248                               ;; input; we put all the matches as
249                               ;; possible completions, moving the
250                               ;; first match to the end of the list
251                               ;; makes cursor up/down in the list work
252                               ;; better.
253                               (append (cdr options) (list (car options)))
254                               (car options))))))
255       (if chosen
256           (progn
257             (push chosen notmuch-address-history)
258             (delete-region beg end)
259             (insert chosen)
260             (run-hook-with-args 'notmuch-address-post-completion-functions
261                                 chosen))
262         (message "No matches.")
263         (ding))))
264    (t nil)))
265
266 ;;; Harvest
267
268 (defun notmuch-address-harvest-addr (result)
269   (puthash (plist-get result :name-addr)
270            t notmuch-address-completions))
271
272 (defun notmuch-address-harvest-filter (proc string)
273   (when (buffer-live-p (process-buffer proc))
274     (with-current-buffer (process-buffer proc)
275       (save-excursion
276         (goto-char (point-max))
277         (insert string))
278       (notmuch-sexp-parse-partial-list
279        'notmuch-address-harvest-addr (process-buffer proc)))))
280
281 (defvar notmuch-address-harvest-procs '(nil . nil)
282   "The currently running harvests.
283
284 The car is a partial harvest, and the cdr is a full harvest.")
285
286 (defun notmuch-address-harvest (&optional addr-prefix synchronous callback)
287   "Collect addresses completion candidates.
288
289 It queries the notmuch database for messages sent/received (as
290 configured with `notmuch-address-command') by the user, collects
291 destination/source addresses from those messages and stores them
292 in `notmuch-address-completions'.
293
294 If ADDR-PREFIX is not nil, only messages with to/from addresses
295 matching ADDR-PREFIX*' are queried.
296
297 Address harvesting may take some time so the address collection runs
298 asynchronously unless SYNCHRONOUS is t. In case of asynchronous
299 execution, CALLBACK is called when harvesting finishes."
300   (let* ((sent (eq (car notmuch-address-internal-completion) 'sent))
301          (config-query (cadr notmuch-address-internal-completion))
302          (prefix-query (and addr-prefix
303                             (format "%s:%s*"
304                                     (if sent "to" "from")
305                                     addr-prefix)))
306          (from-or-to-me-query
307           (mapconcat (lambda (x)
308                        (concat (if sent "from:" "to:") x))
309                      (notmuch-user-emails) " or "))
310          (query (if (or prefix-query config-query)
311                     (concat (format "(%s)" from-or-to-me-query)
312                             (and prefix-query
313                                  (format " and (%s)" prefix-query))
314                             (and config-query
315                                  (format " and (%s)" config-query)))
316                   from-or-to-me-query))
317          (args `("address" "--format=sexp" "--format-version=4"
318                  ,(if sent "--output=recipients" "--output=sender")
319                  "--deduplicate=address"
320                  ,query)))
321     (if synchronous
322         (mapc #'notmuch-address-harvest-addr
323               (apply 'notmuch-call-notmuch-sexp args))
324       ;; Asynchronous
325       (let* ((current-proc (if addr-prefix
326                                (car notmuch-address-harvest-procs)
327                              (cdr notmuch-address-harvest-procs)))
328              (proc-name (format "notmuch-address-%s-harvest"
329                                 (if addr-prefix "partial" "full")))
330              (proc-buf (concat " *" proc-name "*")))
331         ;; Kill any existing process
332         (when current-proc
333           (kill-buffer (process-buffer current-proc))) ; this also kills the process
334         (setq current-proc
335               (apply 'notmuch-start-notmuch proc-name proc-buf
336                      callback                           ; process sentinel
337                      args))
338         (set-process-filter current-proc 'notmuch-address-harvest-filter)
339         (set-process-query-on-exit-flag current-proc nil)
340         (if addr-prefix
341             (setcar notmuch-address-harvest-procs current-proc)
342           (setcdr notmuch-address-harvest-procs current-proc)))))
343   ;; return value
344   nil)
345
346 (defvar notmuch-address--save-hash-version 1
347   "Version format of the save hash.")
348
349 (defun notmuch-address--get-address-hash ()
350   "Return the saved address hash as a plist.
351
352 Returns nil if the save file does not exist, or it does not seem
353 to be a saved address hash."
354   (and notmuch-address-save-filename
355        (condition-case nil
356            (with-temp-buffer
357              (insert-file-contents notmuch-address-save-filename)
358              (let ((name (read (current-buffer)))
359                    (plist (read (current-buffer))))
360                ;; We do two simple sanity checks on the loaded file.
361                ;; We just check a version is specified, not that
362                ;; it is the current version, as we are allowed to
363                ;; over-write and a save-file with an older version.
364                (and (string= name "notmuch-address-hash")
365                     (plist-get plist :version)
366                     plist)))
367          ;; The error case catches any of the reads failing.
368          (error nil))))
369
370 (defun notmuch-address--load-address-hash ()
371   "Read the saved address hash and set the corresponding variables."
372   (let ((load-plist (notmuch-address--get-address-hash)))
373     (when (and load-plist
374                ;; If the user's setting have changed, or the version
375                ;; has changed, return nil to make sure the new settings
376                ;; take effect.
377                (equal (plist-get load-plist :completion-settings)
378                       notmuch-address-internal-completion)
379                (equal (plist-get load-plist :version)
380                       notmuch-address--save-hash-version))
381       (setq notmuch-address-last-harvest (plist-get load-plist :last-harvest))
382       (setq notmuch-address-completions (plist-get load-plist :completions))
383       (setq notmuch-address-full-harvest-finished t)
384       ;; Return t to say load was successful.
385       t)))
386
387 (defun notmuch-address--save-address-hash ()
388   (when notmuch-address-save-filename
389     (if (or (not (file-exists-p notmuch-address-save-filename))
390             ;; The file exists, check it is a file we saved.
391             (notmuch-address--get-address-hash))
392         (with-temp-file notmuch-address-save-filename
393           (let ((save-plist
394                  (list :version notmuch-address--save-hash-version
395                        :completion-settings notmuch-address-internal-completion
396                        :last-harvest notmuch-address-last-harvest
397                        :completions notmuch-address-completions)))
398             (print "notmuch-address-hash" (current-buffer))
399             (print save-plist (current-buffer))))
400       (message "\
401 Warning: notmuch-address-save-filename %s exists but doesn't
402 appear to be an address savefile.  Not overwriting."
403                notmuch-address-save-filename))))
404
405 (defun notmuch-address-harvest-trigger ()
406   (let ((now (float-time)))
407     (when (> (- now notmuch-address-last-harvest) 86400)
408       (setq notmuch-address-last-harvest now)
409       (notmuch-address-harvest
410        nil nil
411        (lambda (_proc event)
412          ;; If harvest fails, we want to try
413          ;; again when the trigger is next called.
414          (if (string= event "finished\n")
415              (progn
416                (notmuch-address--save-address-hash)
417                (setq notmuch-address-full-harvest-finished t))
418            (setq notmuch-address-last-harvest 0)))))))
419
420 ;;; Standalone completion
421
422 (defun notmuch-address-from-minibuffer (prompt)
423   (if (not notmuch-address-command)
424       (read-string prompt)
425     (let ((rmap (copy-keymap minibuffer-local-map))
426           (omap minibuffer-local-map))
427       ;; Configure TAB to start completion when executing read-string.
428       ;; "Original" minibuffer keymap is restored just before calling
429       ;; notmuch-address-expand-name as it may also use minibuffer-local-map
430       ;; (completing-read probably does not but if something else is used there).
431       (define-key rmap (kbd "TAB") (lambda ()
432                                      (interactive)
433                                      (let ((enable-recursive-minibuffers t)
434                                            (minibuffer-local-map omap))
435                                        (notmuch-address-expand-name))))
436       (let ((minibuffer-local-map rmap))
437         (read-string prompt)))))
438
439 ;;; _
440
441 (provide 'notmuch-address)
442
443 ;;; notmuch-address.el ends here