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